Decompiled source of VoiceBox v0.2.0
VoiceBoxModLib.Core.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.ClientModel; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Net.WebSockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CognitiveServices.Speech; using Microsoft.CognitiveServices.Speech.Audio; using Microsoft.Extensions.AI; using Microsoft.Extensions.Logging; using NAudio.CoreAudioApi; using NAudio.Wave; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OllamaSharp; using OpenAI; using TimShaw.VoiceBox.Components; using TimShaw.VoiceBox.Core; using TimShaw.VoiceBox.Data; using TimShaw.VoiceBox.GUI; using TimShaw.VoiceBox.Generics; using TimShaw.VoiceBox.Modding; using UnityEngine; using UnityEngine.Networking; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("VoiceBoxModLib.Core")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+d0da256266f31960f6829b319bf172bf8c96813f")] [assembly: AssemblyProduct("VoiceBoxModLib.Core")] [assembly: AssemblyTitle("VoiceBoxModLib.Core")] [assembly: AssemblyVersion("1.0.0.0")] public class APITester : MonoBehaviour { [CompilerGenerated] private sealed class <>c__DisplayClass15_0 { public bool waitingForTTS; public float clipLength; public APITester <>4__this; internal void <TestTextToSpeech>b__0(string path) { Debug.Log((object)("[Test: Text To Speech 1] Generated audio file at " + path)); waitingForTTS = false; } internal void <TestTextToSpeech>b__2(AudioClip audioClip) { Debug.Log((object)"[Test: Text To Speech 2] Generated audioclip and playing..."); clipLength = audioClip.length; waitingForTTS = false; <>4__this.audioSource.PlayOneShot(audioClip); } internal void <TestTextToSpeech>b__3(string err) { Debug.LogError((object)err); waitingForTTS = false; } } [CompilerGenerated] private sealed class <>c__DisplayClass16_0 { public bool waitingForResponse; public string combinedResponse; internal void <TestChat>b__0(ChatUtils.VoiceBoxChatMessage chatMessage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) ChatRole role = ((ChatMessage)chatMessage).Role; Debug.Log((object)(((object)(ChatRole)(ref role)).ToString() + ": " + chatMessage.Text)); waitingForResponse = false; } internal void <TestChat>b__1(string error) { Debug.LogError((object)error); waitingForResponse = false; } internal void <TestChat>b__2(ChatResponseUpdate chunk) { Debug.Log((object)(chunk.Role.ToString() + ": " + chunk.Text)); combinedResponse += (object)chunk; } internal void <TestChat>b__3() { Debug.Log((object)("Combined response: " + combinedResponse)); waitingForResponse = false; } internal void <TestChat>b__4(string error) { Debug.LogError((object)error); waitingForResponse = false; } internal void <TestChat>b__5(ChatUtils.VoiceBoxChatMessage chatMessage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) ChatRole role = ((ChatMessage)chatMessage).Role; Debug.Log((object)(((object)(ChatRole)(ref role)).ToString() + ": " + chatMessage.Text)); waitingForResponse = false; } internal void <TestChat>b__6(string error) { Debug.LogError((object)error); waitingForResponse = false; } internal void <TestChat>b__7(ChatUtils.VoiceBoxChatMessage chatMessage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) ChatRole role = ((ChatMessage)chatMessage).Role; Debug.Log((object)(((object)(ChatRole)(ref role)).ToString() + ": " + chatMessage.Text)); waitingForResponse = false; } internal void <TestChat>b__8(string error) { Debug.LogError((object)error); waitingForResponse = false; } } [CompilerGenerated] private sealed class <TestChat>d__16 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public APITester <>4__this; private <>c__DisplayClass16_0 <>8__1; private List<ChatUtils.VoiceBoxChatMessage> <chats>5__2; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <TestChat>d__16(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>8__1 = null; <chats>5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Expected O, but got Unknown //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Expected O, but got Unknown int num = <>1__state; APITester aPITester = <>4__this; ChatUtils.VoiceBoxChatMessage item; ChatUtils.VoiceBoxChatMessage item2; ChatUtils.VoiceBoxChatTool item3; ChatUtils.VoiceBoxChatCompletionOptions options; ChatUtils.VoiceBoxChatTool item4; ChatUtils.VoiceBoxChatCompletionOptions voiceBoxChatCompletionOptions; ChatUtils.VoiceBoxChatMessage item5; switch (num) { default: return false; case 0: <>1__state = -1; <>8__1 = new <>c__DisplayClass16_0(); goto IL_0062; case 1: <>1__state = -1; goto IL_0062; case 2: <>1__state = -1; goto IL_0123; case 3: <>1__state = -1; goto IL_01c6; case 4: <>1__state = -1; goto IL_02ad; case 5: { <>1__state = -1; return false; } IL_0062: if (aPITester.testIsRunning) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 1; return true; } aPITester.testIsRunning = true; <>8__1.waitingForResponse = false; Debug.Log((object)"VoiceBox: Testing Chat"); Debug.Log((object)"[Test: Chat 1] Simple chat request"); <chats>5__2 = new List<ChatUtils.VoiceBoxChatMessage>(); item = new ChatUtils.VoiceBoxChatMessage(ChatUtils.VoiceBoxChatRole.User, "Write a 1 paragraph essay about huskies. "); <chats>5__2.Add(item); <>8__1.waitingForResponse = true; AIManager.Instance.SendChatMessage(<chats>5__2, delegate(ChatUtils.VoiceBoxChatMessage chatMessage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) ChatRole role3 = ((ChatMessage)chatMessage).Role; Debug.Log((object)(((object)(ChatRole)(ref role3)).ToString() + ": " + chatMessage.Text)); <>8__1.waitingForResponse = false; }, delegate(string error) { Debug.LogError((object)error); <>8__1.waitingForResponse = false; }); goto IL_0123; IL_0123: if (<>8__1.waitingForResponse) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 2; return true; } <>8__1.combinedResponse = ""; Debug.Log((object)"[Test: Chat 2] Simple streaming chat request"); <>8__1.waitingForResponse = true; AIManager.Instance.StreamChatMessage(<chats>5__2, delegate(ChatResponseUpdate chunk) { Debug.Log((object)(chunk.Role.ToString() + ": " + chunk.Text)); <>8__1.combinedResponse += (object)chunk; }, delegate { Debug.Log((object)("Combined response: " + <>8__1.combinedResponse)); <>8__1.waitingForResponse = false; }, delegate(string error) { Debug.LogError((object)error); <>8__1.waitingForResponse = false; }); goto IL_01c6; IL_02ad: if (<>8__1.waitingForResponse) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 4; return true; } Debug.Log((object)"[Test: Chat 4] Simple chat request with complex tool"); item2 = new ChatUtils.VoiceBoxChatMessage(ChatUtils.VoiceBoxChatRole.User, "Display a Vector2 (1.00, 2.00) and a Quaterion (4.00, 4.00, 4.00) to the console"); <chats>5__2.Clear(); <chats>5__2.Add(item2); item3 = new ChatUtils.VoiceBoxChatTool(aPITester, "SampleTool3", "Displays a provided vector2 and quaternion to the console.", new List<JsonConverter> { new ChatUtils.ColorJsonConverter() }); options = new ChatUtils.VoiceBoxChatCompletionOptions { VoiceBoxTools = { item3 } }; <>8__1.waitingForResponse = true; AIManager.Instance.SendChatMessage(<chats>5__2, delegate(ChatUtils.VoiceBoxChatMessage chatMessage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) ChatRole role2 = ((ChatMessage)chatMessage).Role; Debug.Log((object)(((object)(ChatRole)(ref role2)).ToString() + ": " + chatMessage.Text)); <>8__1.waitingForResponse = false; }, delegate(string error) { Debug.LogError((object)error); <>8__1.waitingForResponse = false; }, options); Debug.Log((object)"VoiceBox: Finished Testing Chat"); <>2__current = null; <>1__state = 5; return true; IL_01c6: if (<>8__1.waitingForResponse) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 3; return true; } Debug.Log((object)"[Test: Chat 3] Simple chat request with tool"); item4 = new ChatUtils.VoiceBoxChatTool(aPITester, "SampleTool1", "Displays provided text in the console"); voiceBoxChatCompletionOptions = new ChatUtils.VoiceBoxChatCompletionOptions { VoiceBoxTools = { item4 } }; Debug.Log((object)((ChatOptions)voiceBoxChatCompletionOptions).Tools.Count); item5 = new ChatUtils.VoiceBoxChatMessage(ChatUtils.VoiceBoxChatRole.User, "Write a 1 paragraph essay about huskies. Then, display the first sentence to the console. Only display one sentence to the console."); <chats>5__2.Clear(); <chats>5__2.Add(item5); <>8__1.waitingForResponse = true; AIManager.Instance.SendChatMessage(<chats>5__2, delegate(ChatUtils.VoiceBoxChatMessage chatMessage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) ChatRole role = ((ChatMessage)chatMessage).Role; Debug.Log((object)(((object)(ChatRole)(ref role)).ToString() + ": " + chatMessage.Text)); <>8__1.waitingForResponse = false; }, delegate(string error) { Debug.LogError((object)error); <>8__1.waitingForResponse = false; }, voiceBoxChatCompletionOptions); goto IL_02ad; } } 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 <TestModdingTools>d__13 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public APITester <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <TestModdingTools>d__13(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown int num = <>1__state; APITester aPITester = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; goto IL_004b; case 1: <>1__state = -1; goto IL_004b; case 2: { <>1__state = -1; return false; } IL_004b: if (aPITester.testIsRunning) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 1; return true; } aPITester.testIsRunning = true; Debug.Log((object)"VoiceBox: Testing Modding Tools"); Debug.Log((object)"[Test: ModdingTools] Create AIManager using ModdingTools"); ModdingTools.CreateAIManagerObject<GeminiServiceConfig, AzureSTTServiceConfig, ElevenlabsTTSServiceConfig>(); Debug.Log((object)"VoiceBox: Finished Testing Modding Tools"); aPITester.testIsRunning = false; <>2__current = null; <>1__state = 2; return true; } } 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 <TestSpeechToText>d__14 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public APITester <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <TestSpeechToText>d__14(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Expected O, but got Unknown //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Expected O, but got Unknown int num = <>1__state; APITester aPITester = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; goto IL_0057; case 1: <>1__state = -1; goto IL_0057; case 2: <>1__state = -1; Debug.Log((object)"[Test: Speech To Text 1] Stop Speech Transcription after 10s..."); AIManager.Instance.StopSpeechTranscription(); Debug.Log((object)"[Test: Speech To Text 2] Wait 2s then Start Speech Transcription for 10s after previous stop..."); <>2__current = (object)new WaitForSeconds(2f); <>1__state = 3; return true; case 3: <>1__state = -1; AIManager.Instance.StartSpeechTranscription(); <>2__current = (object)new WaitForSeconds(10f); <>1__state = 4; return true; case 4: <>1__state = -1; Debug.Log((object)"[Test: Speech To Text 2] Stop Speech Transcription again after 10s..."); AIManager.Instance.StopSpeechTranscription(); Debug.Log((object)"VoiceBox: Finished Testing Speech To Text"); aPITester.testIsRunning = false; <>2__current = null; <>1__state = 5; return true; case 5: { <>1__state = -1; return false; } IL_0057: if (aPITester.testIsRunning) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 1; return true; } aPITester.testIsRunning = true; Debug.Log((object)"VoiceBox: Testing Speech To Text"); Debug.Log((object)"[Test: Speech To Text 1] Start Speech Transcription for 10s..."); AIManager.Instance.SpeechToTextService.OnRecognized += aPITester.LogRecognizedSpeech; AIManager.Instance.StartSpeechTranscription(aPITester.internalCancellationTokenSource.Token); <>2__current = (object)new WaitForSeconds(10f); <>1__state = 2; return true; } } 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 <TestTextToSpeech>d__15 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public APITester <>4__this; private <>c__DisplayClass15_0 <>8__1; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <TestTextToSpeech>d__15(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>8__1 = null; <>1__state = -2; } private bool MoveNext() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Expected O, but got Unknown //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Expected O, but got Unknown int num = <>1__state; APITester aPITester = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>8__1 = new <>c__DisplayClass15_0(); <>8__1.<>4__this = <>4__this; goto IL_0073; case 1: <>1__state = -1; goto IL_0073; case 2: <>1__state = -1; goto IL_0116; case 3: <>1__state = -1; goto IL_019c; case 4: <>1__state = -1; Debug.Log((object)"[Test: Text To Speech 3] Stream audio"); AIManager.Instance.RequestAudioAndStream("This audio is streaming instead of waiting for the full response. This approach reduces first-word latency tremendously.", ((Component)aPITester.audioSource).GetComponent<AudioStreamer>()); Debug.Log((object)"VoiceBox: Finished Testing Text To Speech"); aPITester.testIsRunning = false; <>2__current = null; <>1__state = 5; return true; case 5: { <>1__state = -1; return false; } IL_0073: if (aPITester.testIsRunning) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 1; return true; } aPITester.testIsRunning = true; <>8__1.waitingForTTS = true; Debug.Log((object)"VoiceBox: Testing Text To Speech"); Debug.Log((object)"[Test: Text To Speech 1] Generate audio file"); AIManager.Instance.GenerateSpeechFileFromText("Hello World", "helloworld.wav", Application.dataPath, delegate(string path) { Debug.Log((object)("[Test: Text To Speech 1] Generated audio file at " + path)); <>8__1.waitingForTTS = false; }, delegate(string err) { Debug.LogError((object)err); }); goto IL_0116; IL_0116: if (<>8__1.waitingForTTS) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 2; return true; } Debug.Log((object)"[Test: Text To Speech 2] Generating audioclip"); <>8__1.waitingForTTS = true; <>8__1.clipLength = 0f; AIManager.Instance.GenerateSpeechAudioClipFromText("Hello World!", delegate(AudioClip audioClip) { Debug.Log((object)"[Test: Text To Speech 2] Generated audioclip and playing..."); <>8__1.clipLength = audioClip.length; <>8__1.waitingForTTS = false; <>8__1.<>4__this.audioSource.PlayOneShot(audioClip); }, delegate(string err) { Debug.LogError((object)err); <>8__1.waitingForTTS = false; }); goto IL_019c; IL_019c: if (<>8__1.waitingForTTS) { <>2__current = (object)new WaitForSeconds(0.1f); <>1__state = 3; return true; } <>2__current = (object)new WaitForSeconds(<>8__1.clipLength); <>1__state = 4; return true; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [SerializeField] public bool testSpawnManager; [SerializeField] public bool testGUI; [SerializeField] public bool testSTT; [SerializeField] public bool testTTS; [SerializeField] public bool testChat; [SerializeField] public AudioSource audioSource; private CancellationTokenSource internalCancellationTokenSource = new CancellationTokenSource(); private bool testIsRunning; private void LogRecognizedSpeech(object s, STTUtils.VoiceBoxSpeechRecognitionEventArgs e) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 if ((int)e.Result.Reason == 3 && e.Result.Text.Length > 0) { Debug.Log((object)("API Tester: Recognized: " + e.Result.Text)); } } public void SampleTool1(string textToDisplay) { Debug.Log((object)("AI is displaying text! --> " + textToDisplay)); } public void SampleTool2(Color color) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) Color val = color; Debug.Log((object)("AI is displaying a color! --> " + ((object)(Color)(ref val)).ToString())); } public void SampleTool3(Vector2 dir, Quaternion rot) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: 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_001a: Unknown result type (might be due to invalid IL or missing references) Vector2 val = dir; string? text = ((object)(Vector2)(ref val)).ToString(); Quaternion val2 = rot; Debug.Log((object)("AI is displaying a Vector2 and a Quaternion! --> " + text + " -- " + ((object)(Quaternion)(ref val2)).ToString())); } private void Start() { if (testSpawnManager) { ((MonoBehaviour)this).StartCoroutine(TestModdingTools()); } if (testGUI && (Object)(object)GUIManager.Instance != (Object)null) { GUIManager.Instance.visible = true; GUIManager instance = GUIManager.Instance; instance.onApiKeysLoaded = (EventHandler)Delegate.Combine(instance.onApiKeysLoaded, (EventHandler)delegate { Debug.Log((object)"Api keys loaded!"); }); GUIManager instance2 = GUIManager.Instance; instance2.onMicrophoneSelected = (EventHandler<string>)Delegate.Combine(instance2.onMicrophoneSelected, (EventHandler<string>)delegate(object obj, string mic) { Debug.Log((object)("Mic selected: " + mic)); }); GUIManager instance3 = GUIManager.Instance; instance3.onRecordingStopped = (EventHandler<AudioClip>)Delegate.Combine(instance3.onRecordingStopped, (EventHandler<AudioClip>)delegate { Debug.Log((object)"Clip recorded!"); }); } if (testSTT) { ((MonoBehaviour)this).StartCoroutine(TestSpeechToText()); } if (testTTS) { ((MonoBehaviour)this).StartCoroutine(TestTextToSpeech()); } if (testChat) { ((MonoBehaviour)this).StartCoroutine(TestChat()); } } [IteratorStateMachine(typeof(<TestModdingTools>d__13))] private IEnumerator TestModdingTools() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <TestModdingTools>d__13(0) { <>4__this = this }; } [IteratorStateMachine(typeof(<TestSpeechToText>d__14))] private IEnumerator TestSpeechToText() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <TestSpeechToText>d__14(0) { <>4__this = this }; } [IteratorStateMachine(typeof(<TestTextToSpeech>d__15))] private IEnumerator TestTextToSpeech() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <TestTextToSpeech>d__15(0) { <>4__this = this }; } [IteratorStateMachine(typeof(<TestChat>d__16))] private IEnumerator TestChat() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <TestChat>d__16(0) { <>4__this = this }; } private void OnDestroy() { internalCancellationTokenSource.Cancel(); } } namespace TimShaw.VoiceBox.Modding { public static class ModdingTools { public static T CreateChatServiceConfig<T>() where T : GenericChatServiceConfig { return ScriptableObject.CreateInstance<T>(); } public static T CreateSTTServiceConfig<T>() where T : GenericSTTServiceConfig { return ScriptableObject.CreateInstance<T>(); } public static T CreateTTSServiceConfig<T>() where T : GenericTTSServiceConfig { return ScriptableObject.CreateInstance<T>(); } public static GameObject CreateAIManagerObject<ChatConfigType, STTConfigType, TTSConfigType>(string keysFile = "", string chatKey = null, string sttKey = null, string ttsKey = null) where ChatConfigType : GenericChatServiceConfig where STTConfigType : GenericSTTServiceConfig where TTSConfigType : GenericTTSServiceConfig { return CreateAIManagerObject(CreateChatServiceConfig<ChatConfigType>(), CreateSTTServiceConfig<STTConfigType>(), CreateTTSServiceConfig<TTSConfigType>(), keysFile, chatKey, sttKey, ttsKey); } public static GameObject CreateAIManagerObject(GenericChatServiceConfig genericChatServiceConfig, GenericSTTServiceConfig genericSTTServiceConfig, GenericTTSServiceConfig genericTTSServiceConfig, string keysFile = "", string chatKey = null, string sttKey = null, string ttsKey = null) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown if ((Object)(object)AIManager.Instance == (Object)null) { GameObject val = new GameObject("_AIManager"); AIManager aIManager = val.AddComponent<AIManager>(); aIManager.chatServiceConfig = genericChatServiceConfig; aIManager.speechToTextConfig = genericSTTServiceConfig; aIManager.textToSpeechConfig = genericTTSServiceConfig; AIManager.Instance.LoadAPIKeys(keysFile, chatKey, sttKey, ttsKey); aIManager.ChatService = ServiceFactory.CreateChatService(aIManager.chatServiceConfig); aIManager.SpeechToTextService = ServiceFactory.CreateSttService(aIManager.speechToTextConfig); aIManager.TextToSpeechService = ServiceFactory.CreateTtsService(aIManager.textToSpeechConfig); return val; } Debug.LogWarning((object)"AI Manager already exists, no new object will be created."); return ((Component)AIManager.Instance).gameObject; } public static void InitChatManagerObject(ChatManager manager, GenericChatServiceConfig config, string apiKeysJsonPath = "", string chatKey = null) { manager.chatServiceConfig = config; if (apiKeysJsonPath.Length > 0) { manager.LoadAPIKey(apiKeysJsonPath); } else if (chatKey != null) { manager.LoadAPIKey(null, chatKey); } else { manager.LoadAPIKey(); } manager.ChatService = ServiceFactory.CreateChatService(manager.chatServiceConfig); } public static void InitTTSManagerObject(TTSManager manager, GenericTTSServiceConfig config, string apiKeysJsonPath = "", string ttsKey = null) { manager.textToSpeechConfig = config; if (apiKeysJsonPath.Length > 0) { manager.LoadAPIKey(apiKeysJsonPath); } else if (ttsKey != null) { manager.LoadAPIKey(null, ttsKey); } else { manager.LoadAPIKey(); } manager.TextToSpeechService = ServiceFactory.CreateTtsService(manager.textToSpeechConfig); } } } namespace TimShaw.VoiceBox.GUI { public class GUIManager : MonoBehaviour { [Header("GUI Settings")] [Tooltip("The global scale for all GUI elements.")] public float guiScale = 1.5f; [Tooltip("Pixel padding from the screen edges (before scaling).")] public float padding = 10f; [Tooltip("The color for our background.")] public Color backgroundColor = new Color(0.2f, 0.2f, 0.2f, 0.75f); [Header("API Keys")] private string chatApiKey = ""; private string sttApiKey = ""; private string ttsApiKey = ""; [Header("Microphone")] [Tooltip("How sensitive the audio indicator is. Increase this if the bar is too low.")] public float audioSensitivity = 8.5f; [Tooltip("The height of the audio level bar in scaled pixels.")] public float audioBarHeight = 20f; [Tooltip("The max height of the microphone selection box in scaled pixels.")] public float micListMaxHeight = 100f; private float sliderValue = 60f; private DateTime recordingStartTime = DateTime.Now; private static string[] micDevices; private static int selectedMicIndex; private static bool isRecording; private static AudioClip recordingClip; private float currentAudioLevel; private float[] audioSampleData; private int sampleWindow = 256; public bool enableKeyboardShortcut = true; public bool visible; private Vector2 windowScrollPosition; private Vector2 micScrollPosition; private GUIStyle indicatorBoxStyle; private GUIStyle titleStyle; private GUIStyle subtitleStyle; private GenericChatServiceConfig chatServiceConfig; private GenericSTTServiceConfig sttServiceConfig; private GenericTTSServiceConfig ttsServiceConfig; private ChatManager[] chatManagers; private TTSManager[] tTSManagers; private HashSet<KeyCode> currentlyPressedKeys = new HashSet<KeyCode>(); public EventHandler<AudioClip> onRecordingStopped; public EventHandler onApiKeysLoaded; public EventHandler<string> onMicrophoneSelected; public static GUIManager Instance { get; private set; } public static GameObject CreateGUIManagerObject() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown if ((Object)(object)Instance != (Object)null) { return ((Component)Instance).gameObject; } GameObject val = new GameObject("_VoiceBoxGUIManager"); val.AddComponent<GUIManager>(); return val; } private void Awake() { if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this) { Object.Destroy((Object)(object)((Component)this).gameObject); } else { Instance = this; } } private void OnDestroy() { if ((Object)(object)Instance == (Object)(object)this) { Instance = null; } } private void Start() { micDevices = Microphone.devices; audioSampleData = new float[sampleWindow]; if (micDevices.Length == 0) { Debug.LogWarning((object)"No microphone devices found!"); micDevices = new string[1] { "No microphones available" }; } Debug.Log((object)"[GUIManager] GUI Manager created!"); } private void Update() { if (isRecording && (Object)(object)recordingClip != (Object)null) { currentAudioLevel = GetAudioLevel(); } else { currentAudioLevel = 0f; } } private void OnGUI() { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_0109: 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) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Expected O, but got Unknown //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Expected O, but got Unknown //IL_0060: 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_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_069c: Unknown result type (might be due to invalid IL or missing references) //IL_06b5: Unknown result type (might be due to invalid IL or missing references) //IL_06ba: Unknown result type (might be due to invalid IL or missing references) //IL_09af: Unknown result type (might be due to invalid IL or missing references) //IL_08b3: Unknown result type (might be due to invalid IL or missing references) //IL_08b8: Unknown result type (might be due to invalid IL or missing references) //IL_08ba: Unknown result type (might be due to invalid IL or missing references) //IL_08bf: Unknown result type (might be due to invalid IL or missing references) //IL_08d8: Unknown result type (might be due to invalid IL or missing references) //IL_08e2: Unknown result type (might be due to invalid IL or missing references) //IL_0913: Unknown result type (might be due to invalid IL or missing references) //IL_0918: Unknown result type (might be due to invalid IL or missing references) //IL_091d: Unknown result type (might be due to invalid IL or missing references) //IL_0924: Unknown result type (might be due to invalid IL or missing references) if (enableKeyboardShortcut) { if (Event.current.isKey && (int)Event.current.keyCode != 0) { if ((int)Event.current.type == 4) { currentlyPressedKeys.Add(Event.current.keyCode); } else if ((int)Event.current.type == 5) { currentlyPressedKeys.Remove(Event.current.keyCode); } } if (Event.current.shift && currentlyPressedKeys.Contains((KeyCode)118) && currentlyPressedKeys.Contains((KeyCode)98)) { visible = true; } } if (!visible) { return; } Matrix4x4 matrix = GUI.matrix; GUI.matrix = Matrix4x4.Scale(new Vector3(guiScale, guiScale, 1f)); float num = padding / guiScale; float num2 = (float)Screen.width / guiScale; float num3 = (float)Screen.height / guiScale; Rect val = new Rect(num, num, num2 - num * 2f, num3 - num * 2f); Color val2 = GUI.backgroundColor; GUI.backgroundColor = backgroundColor; GUI.Box(val, GUIContent.none); GUI.backgroundColor = val2; if (indicatorBoxStyle == null) { indicatorBoxStyle = new GUIStyle(GUI.skin.box); indicatorBoxStyle.alignment = (TextAnchor)3; } if (titleStyle == null) { titleStyle = new GUIStyle(GUI.skin.label); titleStyle.fontStyle = (FontStyle)1; int num4 = GUI.skin.label.fontSize; if (num4 <= 0) { num4 = 12; } titleStyle.fontSize = num4 * 2; } if (subtitleStyle == null) { subtitleStyle = new GUIStyle(GUI.skin.label); subtitleStyle.fontStyle = (FontStyle)1; int num5 = GUI.skin.label.fontSize; if (num5 <= 0) { num5 = 12; } subtitleStyle.fontSize = Mathf.FloorToInt((float)num5 * 1.2f); } GUILayout.BeginArea(val); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.FlexibleSpace(); if (GUILayout.Button("Hide", (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(60f), GUILayout.Height(25f) })) { visible = false; } GUILayout.EndHorizontal(); windowScrollPosition = GUILayout.BeginScrollView(windowScrollPosition, false, true, Array.Empty<GUILayoutOption>()); GUILayout.Label("VoiceBox Utilities GUI", titleStyle, Array.Empty<GUILayoutOption>()); GUILayout.Label("", Array.Empty<GUILayoutOption>()); GUILayout.Label("API Keys", subtitleStyle, Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Load API Keys", Array.Empty<GUILayoutOption>())) { if ((Object)(object)Object.FindFirstObjectByType<ChatManager>() != (Object)null) { chatManagers = Object.FindObjectsByType<ChatManager>((FindObjectsSortMode)0); chatServiceConfig = chatManagers[0].chatServiceConfig; chatApiKey = chatManagers[0].chatServiceConfig?.apiKey; } if ((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.ChatService != null) { chatServiceConfig = AIManager.Instance.chatServiceConfig; chatApiKey = AIManager.Instance.chatServiceConfig.apiKey; } if ((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.SpeechToTextService != null) { sttServiceConfig = AIManager.Instance.speechToTextConfig; sttApiKey = AIManager.Instance.speechToTextConfig.apiKey; } if ((Object)(object)Object.FindFirstObjectByType<TTSManager>() != (Object)null) { tTSManagers = Object.FindObjectsByType<TTSManager>((FindObjectsSortMode)0); ttsServiceConfig = tTSManagers[0].textToSpeechConfig; ttsApiKey = tTSManagers[0].textToSpeechConfig?.apiKey; } if ((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.TextToSpeechService != null) { ttsServiceConfig = AIManager.Instance.textToSpeechConfig; ttsApiKey = AIManager.Instance.textToSpeechConfig.apiKey; } onApiKeysLoaded?.Invoke(this, null); } if ((Object)(object)chatServiceConfig != (Object)null) { GUILayout.Label("Chat (Type: " + chatServiceConfig.serviceManagerType?.ToString() + ") (Manager Count: " + chatManagers?.Length + ") (" + (((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.ChatService != null) ? "AIManager)" : ")"), Array.Empty<GUILayoutOption>()); } else { GUILayout.Label("Chat (Not Initialized)", Array.Empty<GUILayoutOption>()); } chatApiKey = GUILayout.PasswordField((chatApiKey == null) ? "" : chatApiKey, '*', Array.Empty<GUILayoutOption>()); if ((Object)(object)sttServiceConfig != (Object)null) { GUILayout.Label("Speech to Text (Type: " + sttServiceConfig.serviceManagerType?.ToString() + ") (AIManager)", Array.Empty<GUILayoutOption>()); } else { GUILayout.Label("Speech to Text (Not Initialized)", Array.Empty<GUILayoutOption>()); } sttApiKey = GUILayout.PasswordField((sttApiKey == null) ? "" : sttApiKey, '*', Array.Empty<GUILayoutOption>()); if ((Object)(object)ttsServiceConfig != (Object)null) { GUILayout.Label("Text to Speech (Type: " + ttsServiceConfig.serviceManagerType?.ToString() + ") (Manager Count: " + tTSManagers?.Length + ") (" + (((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.TextToSpeechService != null) ? "AIManager)" : ")"), Array.Empty<GUILayoutOption>()); } else { GUILayout.Label("Text to Speech (Not Initialized)", Array.Empty<GUILayoutOption>()); } ttsApiKey = GUILayout.PasswordField((ttsApiKey == null) ? "" : ttsApiKey, '*', Array.Empty<GUILayoutOption>()); GUILayout.Space(20f); GUILayout.Label("Microphone Utilities", subtitleStyle, Array.Empty<GUILayoutOption>()); if (micDevices.Length != 0) { GUILayout.Label("Select a microphone (does not affect services):", Array.Empty<GUILayoutOption>()); micScrollPosition = GUILayout.BeginScrollView(micScrollPosition, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(micListMaxHeight) }); int num6 = selectedMicIndex; selectedMicIndex = GUILayout.SelectionGrid(selectedMicIndex, micDevices, 1, Array.Empty<GUILayoutOption>()); if (num6 != selectedMicIndex) { onMicrophoneSelected?.Invoke(this, micDevices[selectedMicIndex]); } GUILayout.EndScrollView(); GUILayout.Space(10f); GUILayout.Label("Record an AudioClip", subtitleStyle, Array.Empty<GUILayoutOption>()); GUILayout.Label("Clip length: " + sliderValue + " seconds", Array.Empty<GUILayoutOption>()); sliderValue = (int)Math.Round(GUILayout.HorizontalSlider(sliderValue, 1f, 600f, Array.Empty<GUILayoutOption>()), 0); if (GUILayout.Button(isRecording ? "Stop Recording" : "Start Recording", Array.Empty<GUILayoutOption>())) { if (isRecording) { AudioClip e = StopRecording(); onRecordingStopped?.Invoke(this, e); } else { recordingStartTime = DateTime.Now; StartRecording(); } } GUILayout.Space(5f); if (isRecording && (float)(DateTime.Now - recordingStartTime).Seconds >= sliderValue) { AudioClip e2 = StopRecording(); onRecordingStopped?.Invoke(this, e2); Debug.Log((object)$"[GUIManager] Clip size maximum of {sliderValue} reached. Stopped recording."); } if (isRecording) { float num7 = Mathf.Clamp01(currentAudioLevel * audioSensitivity); if (num7 < 0.02f) { num7 = 0f; } GUILayout.Label("Listening... Level: " + (num7 * 100f).ToString("F0") + "%", Array.Empty<GUILayoutOption>()); Rect rect = GUILayoutUtility.GetRect(GUIContent.none, indicatorBoxStyle, (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Height(audioBarHeight), GUILayout.ExpandWidth(true) }); Color val3 = GUI.backgroundColor; Color color = GUI.color; GUI.backgroundColor = new Color(0.1f, 0.1f, 0.1f, 0.8f); GUI.Box(rect, GUIContent.none, indicatorBoxStyle); Rect val4 = new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width * num7, ((Rect)(ref rect)).height); GUI.color = Color.Lerp(Color.green, Color.red, num7); GUI.DrawTexture(val4, (Texture)(object)Texture2D.whiteTexture); GUI.color = color; GUI.backgroundColor = val3; GUILayout.Label("Recording length: " + (DateTime.Now - recordingStartTime).Seconds + " seconds", Array.Empty<GUILayoutOption>()); } else { GUILayout.Box("Not Recording", indicatorBoxStyle, Array.Empty<GUILayoutOption>()); } } else { GUILayout.Label("No microphone devices found.", Array.Empty<GUILayoutOption>()); } GUILayout.EndScrollView(); GUILayout.EndArea(); GUI.matrix = matrix; } public static void StartRecording() { if (micDevices.Length != 0) { string text = micDevices[selectedMicIndex]; recordingClip = Microphone.Start(text, false, 60, 44100); isRecording = true; Debug.Log((object)("Started recording from: " + text)); } } public static AudioClip StopRecording() { if (micDevices.Length == 0) { return null; } string text = micDevices[selectedMicIndex]; Microphone.End(text); isRecording = false; AudioClip result = recordingClip; recordingClip = null; Debug.Log((object)("Stopped recording from: " + text)); return result; } private float GetAudioLevel() { if ((Object)(object)recordingClip == (Object)null) { return 0f; } int num = Microphone.GetPosition(micDevices[selectedMicIndex]) - sampleWindow; if (num < 0) { num = 0; } recordingClip.GetData(audioSampleData, num); float num2 = 0f; for (int i = 0; i < sampleWindow; i++) { num2 += audioSampleData[i] * audioSampleData[i]; } return Mathf.Sqrt(num2 / (float)sampleWindow); } private void OnDisable() { if (isRecording) { StopRecording(); } } } } namespace TimShaw.VoiceBox.Generics { public class GenericChatServiceConfig : ScriptableObject { public Type serviceManagerType; public string apiKey; public string apiKeyJSONString; public string modelName; public bool useFunctionInvokation = true; } public class GenericSTTServiceConfig : ScriptableObject { public Type serviceManagerType; public string apiKey; public string apiKeyJSONString; } public class GenericTTSServiceConfig : ScriptableObject { public Type serviceManagerType; public string apiKey; public string apiKeyJSONString; } } namespace TimShaw.VoiceBox.Data { [CreateAssetMenu(fileName = "AzureSTTServiceConfig", menuName = "VoiceBox/STT/AzureSTTService Configuration")] public class AzureSTTServiceConfig : GenericSTTServiceConfig { public string region = "canadacentral"; public string language = "en-CA"; public string audioInputDeviceName = "Default"; public string[] audioInputEndpointNames = new string[1] { "Default" }; public AzureSTTServiceConfig() { serviceManagerType = typeof(AzureSTTServiceManager); apiKeyJSONString = "AZURE_SPEECH_API_KEY"; } public void OnValidate() { audioInputEndpointNames = STTUtils.GetAudioInputEndpoints().Keys.ToArray(); } } [CreateAssetMenu(fileName = "ChatGPTServiceConfig", menuName = "VoiceBox/Chat/ChatGPTService Configuration")] public class ChatGPTServiceConfig : GenericChatServiceConfig { public string serviceEndpoint = "https://api.openai.com/v1"; public ChatGPTServiceConfig() { serviceManagerType = typeof(ChatGPTServiceManager); apiKeyJSONString = "OPENAI_API_KEY"; modelName = "gpt-5-nano"; } } [CreateAssetMenu(fileName = "ClaudeServiceConfig", menuName = "VoiceBox/Chat/ClaudeService Configuration")] public class ClaudeServiceConfig : GenericChatServiceConfig { public string serviceEndpoint = "https://api.anthropic.com/v1"; public ClaudeServiceConfig() { serviceManagerType = typeof(ClaudeServiceManager); apiKeyJSONString = "ANTHROPIC_API_KEY"; modelName = "claude-haiku-4-5"; } } [Serializable] public class VoiceSettings { [Tooltip("A float between 0 and 1. Higher values result in more stable speech, but may sound monotonous. Lower values are more expressive, but may be unstable.")] [Range(0f, 1f)] public float stability; [Tooltip("A float between 0 and 1. Higher values boost the similarity to the original voice, but may introduce artifacts. Lower values are more generic, but cleaner.")] [Range(0f, 1f)] public float similarity_boost; [Tooltip("A float between 0 and 1. A higher value will exaggerate the style of the voice.")] [Range(0f, 1f)] public float style; [Tooltip("Whether to use the speaker boost feature, which can enhance voice clarity.")] public bool use_speaker_boost; } [Serializable] public class PronunciationDictionaryLocator { [Tooltip("The ID of the pronunciation dictionary.")] public string pronunciation_dictionary_id; [Tooltip("The version ID of the pronunciation dictionary.")] public string version_id; } [CreateAssetMenu(fileName = "ElevenlabsServiceConfig", menuName = "VoiceBox/TTS/ElevenlabsService Configuration")] public class ElevenlabsTTSServiceConfig : GenericTTSServiceConfig { [Tooltip("The API endpoint for the text-to-speech service.")] public string serviceEndpoint = "https://api.elevenlabs.io/v1/text-to-speech/"; [Tooltip("The ID of the voice you want to use.")] public string voiceId = "JBFqnCBsd6RMkjVDRZzb"; [Tooltip("The ID of the model to be used. Defaults to eleven_multilingual_v2.")] public string modelID = "eleven_multilingual_v2"; [Tooltip("Voice settings that override the stored settings for the given voice.")] public VoiceSettings voiceSettings; [Tooltip("Output format for the generated audio. Currently only mp3 is supported. e.g., mp3_44100_128")] public string output_format = "mp3_44100_128"; public ElevenlabsTTSServiceConfig() { serviceManagerType = typeof(ElevenLabsTTSServiceManager); apiKeyJSONString = "ELEVENLABS_API_KEY"; } } [CreateAssetMenu(fileName = "GeminiServiceConfig", menuName = "VoiceBox/Chat/GeminiService Configuration")] public class GeminiServiceConfig : GenericChatServiceConfig { public string serviceEndpoint = "https://generativelanguage.googleapis.com/v1beta/openai/"; public GeminiServiceConfig() { serviceManagerType = typeof(GeminiServiceManager); apiKeyJSONString = "GEMINI_API_KEY"; modelName = "gemini-2.5-flash"; } } [CreateAssetMenu(fileName = "OllamaServiceConfig", menuName = "VoiceBox/Chat/OllamaService Configuration")] public class OllamaChatServiceConfig : GenericChatServiceConfig { public string serviceEndpoint = "http://localhost:11434/"; public OllamaChatServiceConfig() { serviceManagerType = typeof(OllamaChatServiceManager); apiKeyJSONString = "OLLAMA_API_KEY"; } } [CreateAssetMenu(fileName = "WhisperLiveSTTServiceConfig", menuName = "VoiceBox/STT/WhisperLiveSTTService Configuration")] public class WhisperLiveServiceConfig : GenericSTTServiceConfig { public string audioInputDeviceName = "Default"; public string[] audioInputEndpointNames = new string[1] { "Default" }; public WhisperLiveServiceConfig() { serviceManagerType = typeof(WhisperLiveServiceManager); apiKeyJSONString = ""; } public void OnValidate() { audioInputEndpointNames = STTUtils.GetAudioInputEndpoints().Keys.ToArray(); } } } namespace TimShaw.VoiceBox.Core { public class AIManager : MonoBehaviour { private CancellationTokenSource internalChatCancellationTokenSource = new CancellationTokenSource(); private CancellationTokenSource internalSttCancellationTokenSource = new CancellationTokenSource(); [Tooltip("Path to an api keys json file.")] [SerializeField] public string apiKeysJsonPath = ""; [Header("Service Configurations")] [Tooltip("Configuration asset for the chat service (e.g., GeminiConfig, ChatGPTConfig).")] [SerializeField] public GenericChatServiceConfig chatServiceConfig; [Tooltip("Configuration asset for the STT service (e.g., AzureConfig).")] [SerializeField] public GenericSTTServiceConfig speechToTextConfig; [Tooltip("Configuration asset for the TTS service (e.g., ElevenlabsConfig).")] [SerializeField] public GenericTTSServiceConfig textToSpeechConfig; private IChatService _chatService; private ISpeechToTextService _sttService; private ITextToSpeechService _ttsService; public static AIManager Instance { get; private set; } public IChatService ChatService { get { return _chatService; } set { _chatService = value; } } public ISpeechToTextService SpeechToTextService { get { return _sttService; } set { _sttService = value; } } public ITextToSpeechService TextToSpeechService { get { return _ttsService; } set { _ttsService = value; } } private static void CreateAIManagerObj() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)Object.FindFirstObjectByType<AIManager>())) { Debug.LogError((object)"Error creating AI Manager: only 1 AI manager can exist in a scene at a time."); } else { new GameObject("_AIManager").AddComponent<AIManager>(); } } public void LoadAPIKeys(string keysFile = null, string chatKey = null, string sttKey = null, string ttsKey = null) { Dictionary<string, string> keysFromFile = null; if (!string.IsNullOrEmpty(keysFile)) { keysFromFile = LoadKeysFromFile(keysFile); } if ((Object)(object)chatServiceConfig != (Object)null) { chatServiceConfig.apiKey = GetApiKey(chatKey, chatServiceConfig.apiKeyJSONString, chatServiceConfig.apiKeyJSONString, keysFromFile); if (string.IsNullOrEmpty(chatServiceConfig.apiKey)) { Debug.LogWarning((object)"Chat service API key not found."); } } if ((Object)(object)speechToTextConfig != (Object)null) { speechToTextConfig.apiKey = GetApiKey(sttKey, speechToTextConfig.apiKeyJSONString, speechToTextConfig.apiKeyJSONString, keysFromFile); if (string.IsNullOrEmpty(speechToTextConfig.apiKey)) { Debug.LogWarning((object)"STT service API key not found."); } } if ((Object)(object)textToSpeechConfig != (Object)null) { textToSpeechConfig.apiKey = GetApiKey(ttsKey, textToSpeechConfig.apiKeyJSONString, textToSpeechConfig.apiKeyJSONString, keysFromFile); if (string.IsNullOrEmpty(textToSpeechConfig.apiKey)) { Debug.LogWarning((object)"TTS service API key not found."); } } } private string GetApiKey(string directKey, string envVar, string jsonKey, Dictionary<string, string> keysFromFile) { if (!string.IsNullOrEmpty(directKey)) { return directKey; } if (!string.IsNullOrEmpty(envVar)) { string environmentVariable = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.User); if (!string.IsNullOrEmpty(environmentVariable)) { return environmentVariable; } } if (keysFromFile != null && !string.IsNullOrEmpty(jsonKey) && keysFromFile.ContainsKey(jsonKey)) { return keysFromFile[jsonKey]; } return null; } private Dictionary<string, string> LoadKeysFromFile(string keysFile) { try { return JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(keysFile)); } catch (FileNotFoundException) { Debug.LogWarning((object)("[AI Manager] API keys json file not found at: " + keysFile)); return null; } catch (Exception ex2) { Debug.LogError((object)("[AI Manager] Error reading API keys file: " + ex2.Message)); return null; } } private void UnloadAPIKeys() { if (Object.op_Implicit((Object)(object)chatServiceConfig)) { chatServiceConfig.apiKey = ""; } if (Object.op_Implicit((Object)(object)speechToTextConfig)) { speechToTextConfig.apiKey = ""; } if (Object.op_Implicit((Object)(object)textToSpeechConfig)) { textToSpeechConfig.apiKey = ""; } } private void Awake() { if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this) { Object.Destroy((Object)(object)((Component)this).gameObject); return; } Instance = this; Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject); if (apiKeysJsonPath.Length > 0) { LoadAPIKeys(apiKeysJsonPath); } else { LoadAPIKeys(); } ChatService = ServiceFactory.CreateChatService(chatServiceConfig); SpeechToTextService = ServiceFactory.CreateSttService(speechToTextConfig); TextToSpeechService = ServiceFactory.CreateTtsService(textToSpeechConfig); } private void OnDestroy() { internalChatCancellationTokenSource.Cancel(); internalSttCancellationTokenSource.Cancel(); UnloadAPIKeys(); } public void SendChatMessage(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatUtils.VoiceBoxChatMessage> onSuccess, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options = null, CancellationToken token = default(CancellationToken)) { if (internalChatCancellationTokenSource.IsCancellationRequested) { internalChatCancellationTokenSource = new CancellationTokenSource(); } if (ChatService == null) { onError?.Invoke("Chat service is not initialized. Check AIManager configuration."); return; } token = CancellationTokenSource.CreateLinkedTokenSource(token, internalChatCancellationTokenSource.Token).Token; Task.Run(() => ChatService.SendMessage(messageHistory, onSuccess, onError, options, token)); } public async void StreamChatMessage(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatResponseUpdate> onChunkReceived, Action onComplete, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options = null, CancellationToken token = default(CancellationToken)) { if (internalChatCancellationTokenSource.IsCancellationRequested) { internalChatCancellationTokenSource = new CancellationTokenSource(); } if (ChatService == null) { onError?.Invoke("Chat service is not initialized. Check AIManager configuration."); return; } token = CancellationTokenSource.CreateLinkedTokenSource(token, internalChatCancellationTokenSource.Token).Token; try { await Task.Run(() => ChatService.SendMessageStream(messageHistory, onChunkReceived, onComplete, onError, options, token)); } catch (Exception ex) { Debug.LogException(ex); } } public void StartSpeechTranscription(CancellationToken token = default(CancellationToken)) { if (internalSttCancellationTokenSource.IsCancellationRequested) { internalSttCancellationTokenSource = new CancellationTokenSource(); } if (SpeechToTextService == null) { Debug.Log((object)"STT Service not initialized. Check AIManager configuration."); return; } token = CancellationTokenSource.CreateLinkedTokenSource(token, internalSttCancellationTokenSource.Token).Token; Debug.Log((object)"VoiceBox: Starting speech recognition."); Task.Run(() => SpeechToTextService.TranscribeAudioFromMic(token)); } public void StopSpeechTranscription() { internalSttCancellationTokenSource.Cancel(); } public void GenerateSpeechFileFromText(string prompt, string fileName, string dir, Action<string> onSuccess, Action<string> onError, CancellationToken token = default(CancellationToken)) { Task.Run(() => TextToSpeechService.RequestAudioFile(prompt, fileName, dir, onSuccess, onError, token)); } public async void GenerateSpeechAudioClipFromText(string prompt, Action<AudioClip> onSuccess, Action<string> onError) { try { AudioClip obj = await TextToSpeechService.RequestAudioClip(prompt); onSuccess?.Invoke(obj); } catch (Exception ex) { onError?.Invoke("Failed to generate speech: " + ex.Message); } } public void RequestAudioAndStream(string prompt, AudioStreamer audioStreamer, CancellationToken token = default(CancellationToken)) { if (Object.op_Implicit((Object)(object)audioStreamer)) { audioStreamer.InitStreaming(TextToSpeechService); audioStreamer.ConnectAndStream(prompt, TextToSpeechService, ((MonoBehaviour)this).destroyCancellationToken); } else { Debug.LogError((object)"Audio Streamer is null."); } } public void StartVoiceAgentPipeline(AudioSource audioSource) { throw new NotImplementedException(); } } public static class ChatUtils { public readonly struct VoiceBoxChatRole { public static VoiceBoxChatRole System { get; } = new VoiceBoxChatRole("system"); public static VoiceBoxChatRole Assistant { get; } = new VoiceBoxChatRole("assistant"); public static VoiceBoxChatRole User { get; } = new VoiceBoxChatRole("user"); public static VoiceBoxChatRole Tool { get; } = new VoiceBoxChatRole("tool"); public string Value { get; } public VoiceBoxChatRole(string value) { Value = value; } } public class VoiceBoxChatMessage : ChatMessage { public string Text => ConcatText(((ChatMessage)this).Contents); public VoiceBoxChatMessage(VoiceBoxChatRole role, string content) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown ((ChatMessage)this).Role = new ChatRole(role.Value); ((ChatMessage)this).Contents = ((content == null) ? new List<AIContent>() : new List<AIContent> { (AIContent)new TextContent(content) }); } public VoiceBoxChatMessage(ChatMessage chatMessage) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) ((ChatMessage)this).Role = chatMessage.Role; ((ChatMessage)this).Contents = chatMessage.Contents; ((ChatMessage)this).AdditionalProperties = chatMessage.AdditionalProperties; ((ChatMessage)this).CreatedAt = chatMessage.CreatedAt; ((ChatMessage)this).RawRepresentation = chatMessage.RawRepresentation; ((ChatMessage)this).MessageId = chatMessage.MessageId; ((ChatMessage)this).AuthorName = chatMessage.AuthorName; } private static string ConcatText(IEnumerable<AIContent> contents) { if (contents is IList<AIContent> list) { int count = list.Count; switch (count) { case 0: return string.Empty; case 1: { AIContent obj2 = list[0]; AIContent obj3 = ((obj2 is TextContent) ? obj2 : null); return ((obj3 != null) ? ((TextContent)obj3).Text : null) ?? string.Empty; } default: { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { AIContent obj = list[i]; TextContent val = (TextContent)(object)((obj is TextContent) ? obj : null); if (val != null) { stringBuilder.Append(val.Text); } } return stringBuilder.ToString(); } } } return string.Concat(contents.OfType<TextContent>()); } } public class VoiceBoxList<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable { public Action<T> AddCallback; private readonly List<T> _internalList = new List<T>(); public T this[int index] { get { return _internalList[index]; } set { _internalList[index] = value; } } public int Count => _internalList.Count; public bool IsReadOnly => false; public VoiceBoxList() { } public VoiceBoxList(Action<T> addCallback) { AddCallback = addCallback; } public void Add(T item) { _internalList.Add(item); AddCallback?.Invoke(item); } public void Clear() { _internalList.Clear(); } public bool Contains(T item) { return _internalList.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _internalList.CopyTo(array, arrayIndex); } public IEnumerator<T> GetEnumerator() { return _internalList.GetEnumerator(); } public int IndexOf(T item) { return _internalList.IndexOf(item); } public void Insert(int index, T item) { _internalList.Insert(index, item); } public bool Remove(T item) { return _internalList.Remove(item); } public void RemoveAt(int index) { _internalList.RemoveAt(index); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class VoiceBoxChatCompletionOptions : ChatOptions { public VoiceBoxList<VoiceBoxChatTool> VoiceBoxTools = new VoiceBoxList<VoiceBoxChatTool>(); public VoiceBoxChatCompletionOptions() { if (((ChatOptions)this).Tools == null) { ((ChatOptions)this).Tools = new List<AITool>(); } VoiceBoxTools.AddCallback = delegate(VoiceBoxChatTool tool) { ((ChatOptions)this).Tools.Add((AITool)(object)tool.InternalChatTool); }; } } public class VoiceBoxChatTool { public AIFunction InternalChatTool; public object Caller; public MethodInfo Method; public VoiceBoxChatTool(object caller, string functionName, string functionDescription, IList<JsonConverter> customConverters = null) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown Caller = caller; Method = caller.GetType().GetMethod(functionName); JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions { Converters = { (JsonConverter)new Vector2JsonConverter(), (JsonConverter)new Vector3JsonConverter(), (JsonConverter)new Vector4JsonConverter(), (JsonConverter)new QuaternionJsonConverter() }, TypeInfoResolver = (IJsonTypeInfoResolver)new DefaultJsonTypeInfoResolver() }; if (customConverters != null) { foreach (JsonConverter customConverter in customConverters) { jsonSerializerOptions.Converters.Add(customConverter); } } InternalChatTool = AIFunctionFactory.Create(Method, Caller, functionName, functionDescription, jsonSerializerOptions); } private BinaryData GetBinaryDataFromParameters(ParameterInfo[] parameters) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown JObject val = new JObject(); JArray val2 = new JArray(); foreach (ParameterInfo parameterInfo in parameters) { val.Add(parameterInfo.Name, (JToken)(object)GetJsonSchemaForType(parameterInfo.ParameterType)); if (!parameterInfo.IsOptional) { val2.Add(JToken.op_Implicit(parameterInfo.Name)); } } return BinaryData.FromString(((object)new JObject { ["type"] = JToken.op_Implicit("object"), ["properties"] = (JToken)(object)val, ["required"] = (JToken)(object)val2 }).ToString()); } private JObject GetJsonSchemaForType(Type type) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown //IL_00e1: 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_00fc: Expected O, but got Unknown //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) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Expected O, but got Unknown //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Expected O, but got Unknown //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Expected O, but got Unknown //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Expected O, but got Unknown //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0182: 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_01aa: Expected O, but got Unknown //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Expected O, but got Unknown if (!(type == typeof(string))) { if (!(type == typeof(int)) && !(type == typeof(long)) && !(type == typeof(short))) { if (!(type == typeof(double)) && !(type == typeof(float)) && !(type == typeof(decimal))) { if (!(type == typeof(bool))) { if (!(type == typeof(Guid))) { if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || type.GetGenericTypeDefinition() == typeof(IEnumerable<>))) { Type type2 = type.GetGenericArguments()[0]; return new JObject { ["type"] = JToken.op_Implicit("array"), ["items"] = (JToken)(object)GetJsonSchemaForType(type2) }; } if (type.IsClass) { JObject val = new JObject(); JArray val2 = new JArray(); PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo propertyInfo in properties) { val.Add(propertyInfo.Name, (JToken)(object)GetJsonSchemaForType(propertyInfo.PropertyType)); val2.Add(JToken.op_Implicit(propertyInfo.Name)); } return new JObject { ["type"] = JToken.op_Implicit("object"), ["properties"] = (JToken)(object)val, ["required"] = (JToken)(object)val2 }; } return new JObject { ["type"] = JToken.op_Implicit("string") }; } return new JObject { ["type"] = JToken.op_Implicit("string"), ["format"] = JToken.op_Implicit("uuid") }; } return new JObject { ["type"] = JToken.op_Implicit("boolean") }; } return new JObject { ["type"] = JToken.op_Implicit("number") }; } return new JObject { ["type"] = JToken.op_Implicit("integer") }; } return new JObject { ["type"] = JToken.op_Implicit("string") }; } } public class Vector2JsonConverter : JsonConverter<Vector2> { public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(Vector2); } public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_0057: 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) if (reader.TokenType == JsonTokenType.String) { string[] array = reader.GetString().Trim('(', ')', ' ').Split(','); if (array.Length == 2 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2)) { return new Vector2(result, result2); } } else if (reader.TokenType == JsonTokenType.StartObject) { float num = 0f; float num2 = 0f; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return new Vector2(num, num2); } if (reader.TokenType != JsonTokenType.PropertyName) { continue; } string? @string = reader.GetString(); reader.Read(); string text = @string.ToLower(); if (!(text == "x")) { if (text == "y") { num2 = reader.GetSingle(); } } else { num = reader.GetSingle(); } } } throw new JsonException("Unexpected token or format when parsing Vector2. Value: " + reader.GetString()); } public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) writer.WriteStartObject(); writer.WriteNumber("x", value.x); writer.WriteNumber("y", value.y); writer.WriteEndObject(); } } public class Vector3JsonConverter : JsonConverter<Vector3> { public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(Vector3); } public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (reader.TokenType == JsonTokenType.String) { string[] array = reader.GetString().Trim('(', ')', ' ').Split(','); if (array.Length == 3 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3)) { return new Vector3(result, result2, result3); } } else if (reader.TokenType == JsonTokenType.StartObject) { float num = 0f; float num2 = 0f; float num3 = 0f; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return new Vector3(num, num2, num3); } if (reader.TokenType == JsonTokenType.PropertyName) { string? @string = reader.GetString(); reader.Read(); switch (@string.ToLower()) { case "x": num = reader.GetSingle(); break; case "y": num2 = reader.GetSingle(); break; case "z": num3 = reader.GetSingle(); break; } } } } throw new JsonException("Unexpected token or format when parsing Vector3. Value: " + reader.GetString()); } public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) writer.WriteStartObject(); writer.WriteNumber("x", value.x); writer.WriteNumber("y", value.y); writer.WriteNumber("z", value.z); writer.WriteEndObject(); } } public class Vector4JsonConverter : JsonConverter<Vector4> { public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(Vector4); } public override Vector4 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_00bc: 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) if (reader.TokenType == JsonTokenType.String) { string[] array = reader.GetString().Trim('(', ')', ' ').Split(','); if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4)) { return new Vector4(result, result2, result3, result4); } } else if (reader.TokenType == JsonTokenType.StartObject) { float num = 0f; float num2 = 0f; float num3 = 0f; float num4 = 0f; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return new Vector4(num, num2, num3, num4); } if (reader.TokenType == JsonTokenType.PropertyName) { string? @string = reader.GetString(); reader.Read(); switch (@string.ToLower()) { case "x": num = reader.GetSingle(); break; case "y": num2 = reader.GetSingle(); break; case "z": num3 = reader.GetSingle(); break; case "w": num4 = reader.GetSingle(); break; } } } } throw new JsonException("Unexpected token or format when parsing Vector4. Value: " + reader.GetString()); } public override void Write(Utf8JsonWriter writer, Vector4 value, JsonSerializerOptions options) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) writer.WriteStartObject(); writer.WriteNumber("x", value.x); writer.WriteNumber("y", value.y); writer.WriteNumber("z", value.z); writer.WriteNumber("w", value.w); writer.WriteEndObject(); } } public class QuaternionJsonConverter : JsonConverter<Quaternion> { public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(Quaternion); } public override Quaternion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_00bc: 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) if (reader.TokenType == JsonTokenType.String) { string[] array = reader.GetString().Trim('(', ')', ' ').Split(','); if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4)) { return new Quaternion(result, result2, result3, result4); } } else if (reader.TokenType == JsonTokenType.StartObject) { float num = 0f; float num2 = 0f; float num3 = 0f; float num4 = 0f; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return new Quaternion(num, num2, num3, num4); } if (reader.TokenType == JsonTokenType.PropertyName) { string? @string = reader.GetString(); reader.Read(); switch (@string.ToLower()) { case "x": num = reader.GetSingle(); break; case "y": num2 = reader.GetSingle(); break; case "z": num3 = reader.GetSingle(); break; case "w": num4 = reader.GetSingle(); break; } } } } throw new JsonException("Unexpected token or format when parsing Quaternion. Value: " + reader.GetString()); } public override void Write(Utf8JsonWriter writer, Quaternion value, JsonSerializerOptions options) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) writer.WriteStartObject(); writer.WriteNumber("x", value.x); writer.WriteNumber("y", value.y); writer.WriteNumber("z", value.z); writer.WriteNumber("w", value.w); writer.WriteEndObject(); } } public class ColorJsonConverter : JsonConverter<Color> { public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(Color); } public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) if (reader.TokenType == JsonTokenType.String) { string @string = reader.GetString(); if (string.IsNullOrEmpty(@string)) { return default(Color); } @string = @string.Trim('(', ')', ' '); string[] array = @string.Split(','); if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4)) { return new Color(result, result2, result3, result4); } } else if (reader.TokenType == JsonTokenType.StartObject) { float num = 0f; float num2 = 0f; float num3 = 0f; float num4 = 1f; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return new Color(num, num2, num3, num4); } if (reader.TokenType == JsonTokenType.PropertyName) { string? string2 = reader.GetString(); reader.Read(); switch (string2.ToLower()) { case "r": num = reader.GetSingle(); break; case "g": num2 = reader.GetSingle(); break; case "b": num3 = reader.GetSingle(); break; case "a": num4 = reader.GetSingle(); break; } } } } throw new JsonException($"Unexpected token or format when parsing Color. Token: {reader.TokenType}"); } public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) writer.WriteStartObject(); writer.WriteNumber("r", value.r); writer.WriteNumber("g", value.g); writer.WriteNumber("b", value.b); writer.WriteNumber("a", value.a); writer.WriteEndObject(); } } } public interface IChatService { void Initialize(GenericChatServiceConfig config); Task SendMessage(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatUtils.VoiceBoxChatMessage> onSuccess, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options, CancellationToken token); Task SendMessageStream(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatResponseUpdate> onChunkReceived, Action onComplete, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options, CancellationToken token); } public interface ISpeechToTextService { event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognizing; event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognized; event EventHandler<SpeechRecognitionCanceledEventArgs> OnCanceled; event EventHandler<SessionEventArgs> OnSessionStarted; event EventHandler<SessionEventArgs> OnSessionStopped; event EventHandler<RecognitionEventArgs> OnSpeechStartDetected; event EventHandler<RecognitionEventArgs> OnSpeechEndDetected; void Initialize(GenericSTTServiceConfig config); Task TranscribeAudioFromMic(CancellationToken token); } public interface ITextToSpeechService { void Initialize(GenericTTSServiceConfig config); Task RequestAudioFile(string prompt, string fileName, string dir, Action<string> onSuccess, Action<string> onError, CancellationToken token); Task<AudioClip> RequestAudioClip(string prompt); void InitWebsocket(ClientWebSocket webSocket, StreamingMp3Decoder mp3Decoder, CancellationToken token); Task ConnectAndStream(string text, WebSocket _webSocket, CancellationToken token); } public static class ServiceFactory { public static IChatService CreateChatService(GenericChatServiceConfig config) { try { IChatService obj = Activator.CreateInstance(config.serviceManagerType) as IChatService; obj.Initialize(config); return obj; } catch (Exception ex) { if ((Object)(object)config != (Object)null) { string modelName = config.modelName; if (modelName != null && modelName.Length == 0) { Debug.LogError((object)"[ServiceFactory] No model name specified for chat model."); } if (config.serviceManagerType != null && ex.GetType() == typeof(NullReferenceException)) { Debug.LogError((object)("[ServiceFactory] Unknown chat config type: " + ((object)config).GetType().Name + ". Does it implement IChatService?")); } } else { Debug.LogWarning((object)"[ServiceFactory] Chat service config is null. No chat service will be created."); } return null; } } public static ISpeechToTextService CreateSttService(GenericSTTServiceConfig config) { try { ISpeechToTextService obj = Activator.CreateInstance(config.serviceManagerType) as ISpeechToTextService; obj.Initialize(config); return obj; } catch { if ((Object)(object)config != (Object)null) { if (config.serviceManagerType != null) { Debug.LogError((object)("[ServiceFactory] Unknown STT config type: " + ((object)config).GetType().Name)); } } else { Debug.LogWarning((object)"[ServiceFactory] STT service config is null. No STT service will be created."); } return null; } } public static ITextToSpeechService CreateTtsService(GenericTTSServiceConfig config) { try { ITextToSpeechService obj = Activator.CreateInstance(config.serviceManagerType) as ITextToSpeechService; obj.Initialize(config); return obj; } catch { if ((Object)(object)config != (Object)null) { if (config.serviceManagerType != null) { Debug.LogError((object)("[ServiceFactory] Unknown TTS config type: " + ((object)config).GetType().Name)); } } else { Debug.LogWarning((object)"[ServiceFactory] TTS service config is null. No TTS service will be created."); } return null; } } } public class STTUtils { public class RecognitionResult { public ResultReason Reason { get; set; } public string Text { get; set; } } public class VoiceBoxSpeechRecognitionEventArgs { public RecognitionResult Result { get; set; } public string Text => Result.Text; public VoiceBoxSpeechRecognitionEventArgs() { Result = new RecognitionResult(); } public VoiceBoxSpeechRecognitionEventArgs(ResultReason reason, string text) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) Result = new RecognitionResult(); Result.Reason = reason; Result.Text = text; } public static explicit operator VoiceBoxSpeechRecognitionEventArgs(SpeechRecognitionEventArgs args) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return new VoiceBoxSpeechRecognitionEventArgs(((RecognitionResult)args.Result).Reason, ((RecognitionResult)args.Result).Text); } } public static Dictionary<string, string> GetAudioInputEndpoints() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, string> dictionary = new Dictionary<string, string>(); List<MMDevice> list = ((IEnumerable<MMDevice>)new MMDeviceEnumerator().EnumerateAudioEndPoints((DataFlow)1, (DeviceState)1)).ToList(); dictionary.Add("Default", ""); foreach (MMDevice item in list) { dictionary.Add(item.FriendlyName, item.ID); } return dictionary; } public static int GetAudioInputDeviceNum(string deviceName, Dictionary<string, string> audioInputEndpoints) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (deviceName == "Default") { return 0; } int deviceCount = WaveIn.DeviceCount; for (int i = 0; i < deviceCount; i++) { WaveInCapabilities capabilities = WaveIn.GetCapabilities(i); foreach (string key in audioInputEndpoints.Keys) { if (key.StartsWith(((WaveInCapabilities)(ref capabilities)).ProductName) && key == deviceName) { return i; } } } Debug.LogWarning((object)("Device " + deviceName + " not found.")); return -1; } } public class AzureSTTServiceManager : ISpeechToTextService { public SpeechRecognizer speechRecognizer; private Dictionary<string, string> audioEndpoints; public event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognizing; public event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognized; public event EventHandler<SpeechRecognitionCanceledEventArgs> OnCanceled; public event EventHandler<SessionEventArgs> OnSessionStarted; public event EventHandler<SessionEventArgs> OnSessionStopped; public event EventHandler<RecognitionEventArgs> OnSpeechStartDetected; public event EventHandler<RecognitionEventArgs> OnSpeechEndDetected; public async Task TranscribeAudioFromMic(CancellationToken token) { _ = 2; try { TaskCompletionSource<int> stopRecognition = new TaskCompletionSource<int>(); token.Register(delegate { stopRecognition.TrySetResult(0); }); await speechRecognizer.StartContinuousRecognitionAsync(); await stopRecognition.Task; await speechRecognizer.StopContinuousRecognitionAsync(); Debug.Log((object)"Azure Service Manager: Transcription stopped."); } catch (Exception ex) { Debug.Log((object)"Azure Service Manager: Speech to Text error"); Debug.Log((object)ex.ToString()); } } public void Initialize(GenericSTTServiceConfig config) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown AzureSTTServiceConfig azureSTTServiceConfig = config as AzureSTTServiceConfig; if (azureSTTServiceConfig.apiKey.Length == 0) { Debug.Log((object)"No API key. STT disabled."); return; } audioEndpoints = STTUtils.GetAudioInputEndpoints(); AudioConfig val; try { val = ((azureSTTServiceConfig.audioInputDeviceName == "Default") ? AudioConfig.FromDefaultMicrophoneInput() : AudioConfig.FromMicrophoneInput(audioEndpoints[azureSTTServiceConfig.audioInputDeviceName])); } catch (Exception ex) { Debug.LogWarning((object)("Azure Service Manager: AudioConfig error: " + ex.Message + " -- Using default microphone.")); val = AudioConfig.FromDefaultMicrophoneInput(); } SpeechConfig val2 = SpeechConfig.FromSubscription(azureSTTServiceConfig.apiKey, azureSTTServiceConfig.region); val2.SpeechRecognitionLanguage = azureSTTServiceConfig.language; speechRecognizer = new SpeechRecognizer(val2, val); InitSpeechRecognizer(); } private void InitSpeechRecognizer() { speechRecognizer.Recognizing += delegate(object s, SpeechRecognitionEventArgs e) { Debug.Log((object)("Azure Service Manager: Recognizing: " + ((RecognitionResult)e.Result).Text)); this.OnRecognizing?.Invoke(this, (STTUtils.VoiceBoxSpeechRecognitionEventArgs)e); }; speechRecognizer.Recognized += delegate(object s, SpeechRecognitionEventArgs e) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_0030: Unknown result type (might be due to invalid IL or missing references) if ((int)((RecognitionResult)e.Result).Reason == 3) { Debug.Log((object)("Azure Service Manager: Recognized: " + ((RecognitionResult)e.Result).Text)); } else if ((int)((RecognitionResult)e.Result).Reason == 0) { Debug.Log((object)"Azure Service Manager: No match."); } this.OnRecognized?.Invoke(this, (STTUtils.VoiceBoxSpeechRecognitionEventArgs)e); }; speechRecognizer.Canceled += delegate(object s, SpeechRecognitionCanceledEventArgs e) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) Debug.Log((object)$"Azure Service Manager: CANCELED: Reason={e.Reason}"); this.OnCanceled?.Invoke(this, e); }; ((Recognizer)speechRecognizer).SessionStarted += delegate(object s, SessionEventArgs e) { Debug.Log((object)"Azure Service Manager: Session Started."); this.OnSessionStarted?.Invoke(this, e); }; ((Recognizer)speechRecognizer).SessionStopped += delegate(object s, SessionEventArgs e) { Debug.Log((object)"Azure Service Manager: Session Stopped."); this.OnSessionStopped?.Invoke(this, e); }; ((Recognizer)speechRecognizer).SpeechStartDetected += delegate(object s, RecognitionEventArgs e) { this.OnSpeechStartDetected?.Invoke(this, e); }; ((Recognizer)speechRecognizer).SpeechEndDetected += delegate(object s, RecognitionEventArgs e) { this.OnSpeechEndDetected?.Invoke(this, e); }; } } internal class ChatGPTServiceManager : IChatService { private IChatClient _client; private ChatGPTServiceConfig _config; public void Initialize(GenericChatServiceConfig config) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //IL_009b: 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_005d: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown _config = config as ChatGPTServiceConfig; OpenAIClientOptions val = new OpenAIClientOptions { Endpoint = ((_config.serviceEndpoint.Length > 0) ? new Uri(_config.serviceEndpoint) : null) }; if (_config.useFunctionInvokation) { _client = FunctionInvokingChatClientBuilderExtensions.UseFunctionInvocation(new ChatClientBuilder(OpenAIClientExtensions.AsIChatClient(new OpenAIClient(new ApiKeyCredential(config.apiKey), val).GetChatClient(config.modelName ?? "gpt-4o"))), (ILoggerFactory)null, (Action<FunctionInvokingChatClient>)null).Build((IServiceProvider)null); } else { _client = new ChatClientBuilder(OpenAIClientExtensions.AsIChatClient(new OpenAIClient(new ApiKeyCredential(config.apiKey), val).GetChatClient(config.modelName ?? "gpt-4o"))).Build((IServiceProvider)null); } } public async Task SendMessage(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatUtils.VoiceBoxChatMessage> onSuccess, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options, CancellationToken token) { if (_client == null || (Object)(object)_config == (Object)null) { onError?.Invoke("ChatGPT service is not initialized."); return; } try { ChatResponse val = await _client.GetResponseAsync((IEnumerable<ChatMessage>)messageHistory, (ChatOptions)(object)options, token); onSuccess?.Invoke(new ChatUtils.VoiceBoxChatMessage(val.Messages[0])); } catch (Exception ex) { onError?.Invoke(ex.Message); } } public async Task SendMessageStream(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatResponseUpdate> onChunkReceived, Action onComplete, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options, CancellationToken token) { _ = 1; try { await foreach (ChatResponseUpdate item in _client.GetStreamingResponseAsync((IEnumerable<ChatMessage>)messageHistory, (ChatOptions)(object)options, token)) { onChunkReceived?.Invoke(item); } onComplete?.Invoke(); } catch (Exception ex) { onError?.Invoke(ex.Message); } } } internal class ClaudeServiceManager : IChatService { private IChatClient _client; private ClaudeServiceConfig _config; public void Initialize(GenericChatServiceConfig config) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown _config = config as ClaudeServiceConfig; OpenAIClientOptions val = new OpenAIClientOptions { Endpoint = new Uri(_config.serviceEndpoint) }; if (_config.useFunctionInvokation) { _client = FunctionInvokingChatClientBuilderExtensions.UseFunctionInvocation(new ChatClientBuilder(OpenAIClientExtensions.AsIChatClient(new OpenAIClient(new ApiKeyCredential(config.apiKey), val).GetChatClient(config.modelName ?? "claude-haiku-4-5"))), (ILoggerFactory)null, (Action<FunctionInvokingChatClient>)null).Build((IServiceProvider)null); } else { _client = new ChatClientBuilder(OpenAIClientExtensions.AsIChatClient(new OpenAIClient(new ApiKeyCredential(config.apiKey), val).GetChatClient(config.modelName ?? "claude-haiku-4-5"))).Build((IServiceProvider)null); } } public async Task SendMessage(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatUtils.VoiceBoxChatMessage> onSuccess, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options, CancellationToken token) { if (_client == null || (Object)(object)_config == (Object)null) { onError?.Invoke("Claude service is not initialized."); return; } try { ChatResponse val = await _client.GetResponseAsync((IEnumerable<ChatMessage>)messageHistory, (ChatOptions)(object)options, token); onSuccess?.Invoke(new ChatUtils.VoiceBoxChatMessage(val.Messages[0])); } catch (Exception ex) { onError?.Invoke(ex.Message); } } public async Task SendMessageStream(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatResponseUpdate> onChunkReceived, Action onComplete, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options, CancellationToken token) { _ = 1; try { await foreach (ChatResponseUpdate item in _client.GetStreamingResponseAsync((IEnumerable<ChatMessage>)messageHistory, (ChatOptions)(object)options, token)) { onChunkReceived?.Invoke(item); } onComplete?.Invoke(); } catch (Exception ex) { Debug.LogException(ex); onError?.Invoke(ex.Message); } } } public class ElevenLabsTTSServiceManager : ITextToSpeechService { [Serializable] private class ElevenLabsTTSRequest { public string text; public string model_id; public VoiceSettings voice_settings; public string previous_text = ""; public string next_text = ""; } [Serializable] private class ElevenLabsStreamedResponse { public string audio; public bool isFinal; } private HttpClient client; private ElevenlabsTTSServiceConfig _config; private string fileExtension; private Task _recieveAudioTask; public void Initialize(GenericTTSServiceConfig config) { _config = config as ElevenlabsTTSServiceConfig; if (_config.apiKey.Length == 0) { Debug.LogError((object)"No Elevenlabs API key found."); return; } if (_config.voiceId.Length == 0) { Debug.LogError((object)"No Elevenlabs Voice ID found."); return; } client = new HttpClient(); fileExtension = (_config.output_format.Contains("mp3") ? ".mp3" : ".wav"); client.DefaultRequestHeaders.Add("xi-api-key", _config.apiKey); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/wav")); } private static void ConvertMp3ToWav(string _inPath_, string _outPath_) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown Mp3FileReader val = new Mp3FileReader(_inPath_); try { WaveStream val2 = WaveFormatConversionStream.CreatePcmStream((WaveStream)(object)val); try { WaveFileWriter.CreateWaveFile(_outPath_, (IWaveProvider)(object)val2); } finally { ((IDisposable)val2)?.Dispose(); } } finally { ((IDisposable)val)?.Dispose(); } } private static void IncreaseVolume(string inputPath, string outputPath, double db) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown double num = Math.Pow(10.0, db / 10.0); WaveFileReader val = new WaveFileReader(inputPath); try { new VolumeWaveProvider16((IWave
deps/Accessibility.dll
Decompiled a day agousing System; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Accessibility.dll")] [assembly: AssemblyDescription("Accessibility.dll")] [assembly: AssemblyDefaultAlias("Accessibility.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(true)] [assembly: Guid("1ea4dbf0-3c3b-11cf-810c-00aa00389b71")] [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyDelaySign(true)] [assembly: ImportedFromTypeLib("Accessibility")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: TypeLibVersion(1, 1)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] [assembly: AssemblyVersion("4.0.0.0")] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal interface IAccessibleHandler { } namespace Accessibility; public interface IAccessible { int accChildCount { get; } object accFocus { get; } object accParent { get; } object accSelection { get; } void accDoDefaultAction(object childID); object accHitTest(int xLeft, int yTop); void accLocation(out int pxLeft, out int pyTop, out int pcxWidth, out int pcyHeight, object childID); object accNavigate(int navDir, object childID); void accSelect(int flagsSelect, object childID); object get_accChild(object childID); string get_accDefaultAction(object childID); string get_accDescription(object childID); string get_accHelp(object childID); int get_accHelpTopic(out string pszHelpFile, object childID); string get_accKeyboardShortcut(object childID); string get_accName(object childID); object get_accRole(object childID); object get_accState(object childID); string get_accValue(object childID); void set_accName(object childID, string newName); void set_accValue(object childID, string newValue); }
deps/Azure.Core.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
#define TRACE using System; using System.Buffers; using System.ClientModel; using System.ClientModel.Primitives; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Buffers; using Azure.Core.Diagnostics; using Azure.Core.Json; using Azure.Core.JsonPatch; using Azure.Core.Pipeline; using Azure.Core.Serialization; using Azure.Core.Shared; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Azure.Core.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] [assembly: InternalsVisibleTo("Azure.Core.Perf, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("This is the implementation of the Azure Client Pipeline")] [assembly: AssemblyFileVersion("1.4900.25.47211")] [assembly: AssemblyInformationalVersion("1.49.0+5322cd075cde377e1261fd756b51b2a20df7b819")] [assembly: AssemblyProduct("Azure .NET SDK")] [assembly: AssemblyTitle("Microsoft Azure Client Pipeline")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Azure/azure-sdk-for-net")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ModelReaderWriterContextType(typeof(AzureCoreContext))] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.49.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : 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.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [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.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class ExperimentalAttribute : Attribute { public string DiagnosticId { get; } public string? UrlFormat { get; set; } public ExperimentalAttribute(string diagnosticId) { DiagnosticId = diagnosticId; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed 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; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class DynamicDependencyAttribute : Attribute { public string? MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public Type? Type { get; } public string? TypeName { get; } public string? AssemblyName { get; } public string? Condition { get; set; } public DynamicDependencyAttribute(string memberSignature) { MemberSignature = memberSignature; } public DynamicDependencyAttribute(string memberSignature, Type type) { MemberSignature = memberSignature; Type = type; } public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) { MemberTypes = memberTypes; Type = type; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } } [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 } } namespace Azure { public abstract class AsyncPageable<T> : IAsyncEnumerable<T> where T : notnull { private class StaticPageable : AsyncPageable<T> { private readonly IEnumerable<Page<T>> _pages; public StaticPageable(IEnumerable<Page<T>> pages) { _pages = pages; } public override async IAsyncEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null) { bool shouldReturnPages = continuationToken == null; foreach (Page<T> page in _pages) { if (shouldReturnPages) { yield return page; } else if (continuationToken == page.ContinuationToken) { shouldReturnPages = true; } } } } protected virtual CancellationToken CancellationToken { get; } protected AsyncPageable() { CancellationToken = CancellationToken.None; } protected AsyncPageable(CancellationToken cancellationToken) { CancellationToken = cancellationToken; } public abstract IAsyncEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null); public virtual async IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { await foreach (Page<T> item in AsPages().ConfigureAwait(continueOnCapturedContext: false).WithCancellation(cancellationToken)) { foreach (T value in item.Values) { yield return value; } } } public static AsyncPageable<T> FromPages(IEnumerable<Page<T>> pages) { return new StaticPageable(pages); } [EditorBrowsable(EditorBrowsableState.Never)] public override string? ToString() { return base.ToString(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { return base.Equals(obj); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } } public class AzureKeyCredential : ApiKeyCredential { [EditorBrowsable(EditorBrowsableState.Never)] public string Key { get { string result = default(string); ((ApiKeyCredential)this).Deconstruct(ref result); return result; } private set { ((ApiKeyCredential)this).Update(value); } } public AzureKeyCredential(string key) : base(key) { } } public class AzureNamedKeyCredential { private Tuple<string, string> _namedKey; public string Name => Volatile.Read(ref _namedKey).Item1; public AzureNamedKeyCredential(string name, string key) { Update(name, key); } public void Update(string name, string key) { Argument.AssertNotNullOrEmpty(name, "name"); Argument.AssertNotNullOrEmpty(key, "key"); Volatile.Write(ref _namedKey, Tuple.Create(name, key)); } [EditorBrowsable(EditorBrowsableState.Never)] public void Deconstruct(out string name, out string key) { Tuple<string, string> tuple = Volatile.Read(ref _namedKey); name = tuple.Item1; key = tuple.Item2; } } public class AzureSasCredential { private string _signature; [EditorBrowsable(EditorBrowsableState.Never)] public string Signature { get { return Volatile.Read(ref _signature); } private set { Volatile.Write(ref _signature, value); } } public AzureSasCredential(string signature) { Argument.AssertNotNullOrWhiteSpace(signature, "signature"); Signature = signature; } public void Update(string signature) { Argument.AssertNotNullOrWhiteSpace(signature, "signature"); Signature = signature; } } [Flags] public enum ErrorOptions { Default = 0, NoThrow = 1 } [JsonConverter(typeof(ETagConverter))] public readonly struct ETag : IEquatable<ETag> { private const char QuoteCharacter = '"'; private const string QuoteString = "\""; private const string WeakETagPrefix = "W/\""; private const string DefaultFormat = "G"; private const string HeaderFormat = "H"; private readonly string? _value; public static readonly ETag All = new ETag("*"); public ETag(string etag) { _value = etag; } public static bool operator ==(ETag left, ETag right) { return left.Equals(right); } public static bool operator !=(ETag left, ETag right) { return !left.Equals(right); } public bool Equals(ETag other) { return string.Equals(_value, other._value, StringComparison.Ordinal); } public bool Equals(string? other) { return string.Equals(_value, other, StringComparison.Ordinal); } public override bool Equals(object? obj) { if (obj is ETag other) { return Equals(other); } return false; } public override int GetHashCode() { return _value.GetHashCodeOrdinal(); } [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() { return ToString("G"); } public string ToString(string format) { if (_value == null) { return string.Empty; } if (!(format == "H")) { if (format == "G") { return _value; } throw new ArgumentException("Invalid format string."); } return (!IsValidQuotedFormat(_value)) ? ("\"" + _value + "\"") : _value; } internal static ETag Parse(string value) { if (value == All._value) { return All; } if (!IsValidQuotedFormat(value)) { throw new ArgumentException("The value should be equal to * , be wrapped in quotes, or be wrapped in quotes prefixed by W/", "value"); } if (value.StartsWith("W/\"", StringComparison.Ordinal)) { return new ETag(value); } return new ETag(value.Trim(new char[1] { '"' })); } private static bool IsValidQuotedFormat(string value) { if ((!value.StartsWith("\"", StringComparison.Ordinal) && !value.StartsWith("W/\"", StringComparison.Ordinal)) || !value.EndsWith("\"", StringComparison.Ordinal)) { return value == All._value; } return true; } } internal class ETagConverter : JsonConverter<ETag> { public override ETag Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { string @string = reader.GetString(); if (@string == null) { return default(ETag); } return new ETag(@string); } public override void Write(Utf8JsonWriter writer, ETag value, JsonSerializerOptions options) { if (value == default(ETag)) { writer.WriteNullValue(); } else { writer.WriteStringValue(value.ToString("H")); } } } public class HttpAuthorization { public string Scheme { get; } public string Parameter { get; } public HttpAuthorization(string scheme, string parameter) { Argument.AssertNotNullOrWhiteSpace(scheme, "scheme"); Argument.AssertNotNullOrWhiteSpace(parameter, "parameter"); Scheme = scheme; Parameter = parameter; } public override string ToString() { return Scheme + " " + Parameter; } } public readonly struct HttpRange : IEquatable<HttpRange> { private const string Unit = "bytes"; public long Offset { get; } public long? Length { get; } public HttpRange(long offset = 0L, long? length = null) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset"); } if (length.HasValue && length <= 0) { throw new ArgumentOutOfRangeException("length"); } Offset = offset; Length = length; } public override string ToString() { if (Length.HasValue && Length != 0) { long num = Offset + Length.Value - 1; return FormattableString.Invariant(FormattableStringFactory.Create("{0}={1}-{2}", "bytes", Offset, num)); } return FormattableString.Invariant(FormattableStringFactory.Create("{0}={1}-", "bytes", Offset)); } public static bool operator ==(HttpRange left, HttpRange right) { return left.Equals(right); } public static bool operator !=(HttpRange left, HttpRange right) { return !(left == right); } public bool Equals(HttpRange other) { if (Offset == other.Offset) { return Length == other.Length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { if (obj is HttpRange other) { return Equals(other); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return HashCodeBuilder.Combine(Offset, Length); } } internal class ResponseDebugView<T> { private readonly Response<T> _response; public Response GetRawResponse => _response.GetRawResponse(); public T Value => _response.Value; public ResponseDebugView(Response<T> response) { _response = response; } } internal class ValueResponse<T> : Response<T> { private readonly Response _response; public override T Value { get; } public ValueResponse(Response response, T value) { _response = response; Value = value; } public override Response GetRawResponse() { return _response; } } public class JsonPatchDocument { private readonly ReadOnlyMemory<byte> _rawDocument; private readonly ObjectSerializer _serializer; private readonly Collection<JsonPatchOperation> _operations; [RequiresUnreferencedCode("JsonObjectSerializer uses reflection-based JSON serialization and deserialization that is not compatible with trimming.")] [RequiresDynamicCode("JsonObjectSerializer uses reflection-based JSON serialization and deserialization that is not compatible with trimming.")] public JsonPatchDocument() : this(default(ReadOnlyMemory<byte>)) { } public JsonPatchDocument(ObjectSerializer serializer) : this(default(ReadOnlyMemory<byte>), serializer) { } [RequiresUnreferencedCode("JsonObjectSerializer uses reflection-based JSON serialization and deserialization that is not compatible with trimming.")] [RequiresDynamicCode("JsonObjectSerializer uses reflection-based JSON serialization and deserialization that is not compatible with trimming.")] public JsonPatchDocument(ReadOnlyMemory<byte> rawDocument) : this(rawDocument, new JsonObjectSerializer()) { } public JsonPatchDocument(ReadOnlyMemory<byte> rawDocument, ObjectSerializer serializer) { _operations = new Collection<JsonPatchOperation>(); _rawDocument = rawDocument; _serializer = serializer ?? throw new ArgumentNullException("serializer"); } public void AppendAddRaw(string path, string rawJsonValue) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Add, path, null, rawJsonValue)); } public void AppendAdd<T>(string path, T value) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Add, path, null, Serialize(value))); } public void AppendReplaceRaw(string path, string rawJsonValue) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Replace, path, null, rawJsonValue)); } public void AppendReplace<T>(string path, T value) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Replace, path, null, Serialize(value))); } public void AppendCopy(string from, string path) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Copy, path, from, null)); } public void AppendMove(string from, string path) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Move, path, from, null)); } public void AppendRemove(string path) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Remove, path, null, null)); } public void AppendTestRaw(string path, string rawJsonValue) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Test, path, null, rawJsonValue)); } public void AppendTest<T>(string path, T value) { _operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Test, path, null, Serialize(value))); } public ReadOnlyMemory<byte> ToBytes() { if (!_rawDocument.IsEmpty && _operations.Count == 0) { return _rawDocument; } using MemoryStream memoryStream = new MemoryStream(); using (Utf8JsonWriter writer = new Utf8JsonWriter(memoryStream)) { WriteTo(writer); } return memoryStream.GetBuffer().AsMemory(0, (int)memoryStream.Length); } public override string ToString() { return Encoding.UTF8.GetString(ToBytes().ToArray()); } private void WriteTo(Utf8JsonWriter writer) { writer.WriteStartArray(); if (!_rawDocument.IsEmpty) { using JsonDocument jsonDocument = JsonDocument.Parse(_rawDocument); foreach (JsonElement item in jsonDocument.RootElement.EnumerateArray()) { item.WriteTo(writer); } } foreach (JsonPatchOperation operation in _operations) { writer.WriteStartObject(); writer.WriteString("op", operation.Kind.ToString()); if (operation.From != null) { writer.WriteString("from", operation.From); } writer.WriteString("path", operation.Path); if (operation.RawJsonValue != null) { using JsonDocument jsonDocument2 = JsonDocument.Parse(operation.RawJsonValue); writer.WritePropertyName("value"); jsonDocument2.WriteTo(writer); } writer.WriteEndObject(); } writer.WriteEndArray(); } private string Serialize<T>(T value) { using MemoryStream memoryStream = new MemoryStream(); _serializer.Serialize(memoryStream, value, typeof(T), default(CancellationToken)); return Encoding.UTF8.GetString(memoryStream.ToArray()); } } public class MatchConditions { public ETag? IfMatch { get; set; } public ETag? IfNoneMatch { get; set; } } public abstract class NullableResponse<T> { private const string NoValue = "<null>"; public abstract bool HasValue { get; } public abstract T? Value { get; } public abstract Response GetRawResponse(); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { return base.Equals(obj); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return string.Format("Status: {0}, Value: {1}", GetRawResponse()?.Status, HasValue ? ((object)Value) : "<null>"); } } public abstract class Operation { public abstract string Id { get; } public abstract bool HasCompleted { get; } public static Operation<T> Rehydrate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(HttpPipeline pipeline, RehydrationToken rehydrationToken, ClientOptions? options = null) where T : IPersistableModel<T> { Argument.AssertNotNull(pipeline, "pipeline"); Argument.AssertNotNull(rehydrationToken, "rehydrationToken"); GenericOperationSource<T> operationSource = new GenericOperationSource<T>(); NextLinkOperationImplementation nextLinkOperationImplementation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(pipeline, rehydrationToken); IOperation<T> operation = NextLinkOperationImplementation.Create(operationSource, nextLinkOperationImplementation); OperationState<T> operationState = operation.UpdateStateAsync(async: false, default(CancellationToken)).EnsureCompleted(); return new RehydrationOperation<T>(nextLinkOperationImplementation, operationState, operation, options); } public static Operation Rehydrate(HttpPipeline pipeline, RehydrationToken rehydrationToken, ClientOptions? options = null) { Argument.AssertNotNull(pipeline, "pipeline"); Argument.AssertNotNull(rehydrationToken, "rehydrationToken"); NextLinkOperationImplementation obj = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(pipeline, rehydrationToken); OperationState operationState = obj.UpdateStateAsync(async: false, default(CancellationToken)).EnsureCompleted(); return new RehydrationOperation(obj, operationState); } public static async Task<Operation<T>> RehydrateAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(HttpPipeline pipeline, RehydrationToken rehydrationToken, ClientOptions? options = null) where T : IPersistableModel<T> { Argument.AssertNotNull(pipeline, "pipeline"); Argument.AssertNotNull(rehydrationToken, "rehydrationToken"); IOperationSource<T> operationSource = new GenericOperationSource<T>(); NextLinkOperationImplementation nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(pipeline, rehydrationToken); IOperation<T> operation = NextLinkOperationImplementation.Create(operationSource, nextLinkOperation); return new RehydrationOperation<T>(nextLinkOperation, await operation.UpdateStateAsync(async: true, default(CancellationToken)).ConfigureAwait(continueOnCapturedContext: false), operation, options); } public static async Task<Operation> RehydrateAsync(HttpPipeline pipeline, RehydrationToken rehydrationToken, ClientOptions? options = null) { Argument.AssertNotNull(pipeline, "pipeline"); Argument.AssertNotNull(rehydrationToken, "rehydrationToken"); NextLinkOperationImplementation nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(pipeline, rehydrationToken); return new RehydrationOperation(nextLinkOperation, await nextLinkOperation.UpdateStateAsync(async: true, default(CancellationToken)).ConfigureAwait(continueOnCapturedContext: false)); } public virtual RehydrationToken? GetRehydrationToken() { return null; } public abstract Response GetRawResponse(); public abstract ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default(CancellationToken)); public abstract Response UpdateStatus(CancellationToken cancellationToken = default(CancellationToken)); public virtual async ValueTask<Response> WaitForCompletionResponseAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await new OperationPoller().WaitForCompletionResponseAsync(this, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public virtual async ValueTask<Response> WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default(CancellationToken)) { return await new OperationPoller().WaitForCompletionResponseAsync(this, pollingInterval, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public virtual async ValueTask<Response> WaitForCompletionResponseAsync(DelayStrategy delayStrategy, CancellationToken cancellationToken = default(CancellationToken)) { return await new OperationPoller(delayStrategy).WaitForCompletionResponseAsync(this, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public virtual Response WaitForCompletionResponse(CancellationToken cancellationToken = default(CancellationToken)) { return new OperationPoller().WaitForCompletionResponse(this, null, cancellationToken); } public virtual Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken = default(CancellationToken)) { return new OperationPoller().WaitForCompletionResponse(this, pollingInterval, cancellationToken); } public virtual Response WaitForCompletionResponse(DelayStrategy delayStrategy, CancellationToken cancellationToken = default(CancellationToken)) { return new OperationPoller(delayStrategy).WaitForCompletionResponse(this, null, cancellationToken); } internal static T GetValue<T>(ref T? value) where T : class { if (value == null) { throw new InvalidOperationException("The operation has not completed yet."); } return value; } internal static T GetValue<T>(ref T? value) where T : struct { if (!value.HasValue) { throw new InvalidOperationException("The operation has not completed yet."); } return value.Value; } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { return base.Equals(obj); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } [EditorBrowsable(EditorBrowsableState.Never)] public override string? ToString() { return base.ToString(); } } public abstract class Operation<T> : Operation where T : notnull { public abstract T Value { get; } public abstract bool HasValue { get; } public virtual Response<T> WaitForCompletion(CancellationToken cancellationToken = default(CancellationToken)) { return new OperationPoller().WaitForCompletion(this, null, cancellationToken); } public virtual Response<T> WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken) { return new OperationPoller().WaitForCompletion(this, pollingInterval, cancellationToken); } public virtual async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await new OperationPoller().WaitForCompletionAsync(this, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public virtual async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) { return await new OperationPoller().WaitForCompletionAsync(this, pollingInterval, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public virtual Response<T> WaitForCompletion(DelayStrategy delayStrategy, CancellationToken cancellationToken) { return new OperationPoller(delayStrategy).WaitForCompletion(this, null, cancellationToken); } public virtual async ValueTask<Response<T>> WaitForCompletionAsync(DelayStrategy delayStrategy, CancellationToken cancellationToken) { return await new OperationPoller(delayStrategy).WaitForCompletionAsync(this, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } [EditorBrowsable(EditorBrowsableState.Never)] public override async ValueTask<Response> WaitForCompletionResponseAsync(CancellationToken cancellationToken = default(CancellationToken)) { return (await WaitForCompletionAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetRawResponse(); } [EditorBrowsable(EditorBrowsableState.Never)] public override async ValueTask<Response> WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default(CancellationToken)) { return (await WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetRawResponse(); } } public abstract class Page<T> { private class PageCore : Page<T> { private readonly Response _response; public override IReadOnlyList<T> Values { get; } public override string? ContinuationToken { get; } public PageCore(IReadOnlyList<T> values, string? continuationToken, Response response) { _response = response; Values = values; ContinuationToken = continuationToken; } public override Response GetRawResponse() { return _response; } } public abstract IReadOnlyList<T> Values { get; } public abstract string? ContinuationToken { get; } public abstract Response GetRawResponse(); public static Page<T> FromValues(IReadOnlyList<T> values, string? continuationToken, Response response) { return new PageCore(values, continuationToken, response); } [EditorBrowsable(EditorBrowsableState.Never)] public override string? ToString() { return base.ToString(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { return base.Equals(obj); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } } public abstract class Pageable<T> : IEnumerable<T>, IEnumerable where T : notnull { private class StaticPageable : Pageable<T> { private readonly IEnumerable<Page<T>> _pages; public StaticPageable(IEnumerable<Page<T>> pages) { _pages = pages; } public override IEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null) { bool shouldReturnPages = continuationToken == null; foreach (Page<T> page in _pages) { if (shouldReturnPages) { yield return page; } else if (continuationToken == page.ContinuationToken) { shouldReturnPages = true; } } } } protected virtual CancellationToken CancellationToken { get; } protected Pageable() { CancellationToken = CancellationToken.None; } protected Pageable(CancellationToken cancellationToken) { CancellationToken = cancellationToken; } public abstract IEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null); [EditorBrowsable(EditorBrowsableState.Never)] public override string? ToString() { return base.ToString(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public virtual IEnumerator<T> GetEnumerator() { foreach (Page<T> item in AsPages()) { foreach (T value in item.Values) { yield return value; } } } public static Pageable<T> FromPages(IEnumerable<Page<T>> pages) { return new StaticPageable(pages); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { return base.Equals(obj); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } } public abstract class PageableOperation<T> : Operation<AsyncPageable<T>> where T : notnull { [EditorBrowsable(EditorBrowsableState.Never)] public override AsyncPageable<T> Value => GetValuesAsync(); public abstract AsyncPageable<T> GetValuesAsync(CancellationToken cancellationToken = default(CancellationToken)); public abstract Pageable<T> GetValues(CancellationToken cancellationToken = default(CancellationToken)); } public class RequestConditions : MatchConditions { public DateTimeOffset? IfModifiedSince { get; set; } public DateTimeOffset? IfUnmodifiedSince { get; set; } } public class RequestContext { private bool _frozen; private (int Status, bool IsError)[]? _statusCodes; private ResponseClassificationHandler[]? _handlers; internal (int Status, bool IsError)[]? StatusCodes => _statusCodes; internal ResponseClassificationHandler[]? Handlers => _handlers; internal List<(HttpPipelinePosition Position, HttpPipelinePolicy Policy)>? Policies { get; private set; } public ErrorOptions ErrorOptions { get; set; } public CancellationToken CancellationToken { get; set; } = CancellationToken.None; public static implicit operator RequestContext(ErrorOptions options) { return new RequestContext { ErrorOptions = options }; } public void AddPolicy(HttpPipelinePolicy policy, HttpPipelinePosition position) { if (Policies == null) { List<(HttpPipelinePosition, HttpPipelinePolicy)> list2 = (Policies = new List<(HttpPipelinePosition, HttpPipelinePolicy)>()); } Policies.Add((position, policy)); } public void AddClassifier(int statusCode, bool isError) { Argument.AssertInRange(statusCode, 100, 599, "statusCode"); if (_frozen) { throw new InvalidOperationException("Cannot modify classifiers after this type has been used in a method call."); } int num = ((_statusCodes != null) ? _statusCodes.Length : 0); Array.Resize(ref _statusCodes, num + 1); Array.Copy(_statusCodes, 0, _statusCodes, 1, num); _statusCodes[0] = (statusCode, isError); } public void AddClassifier(ResponseClassificationHandler classifier) { if (_frozen) { throw new InvalidOperationException("Cannot modify classifiers after this type has been used in a method call."); } int num = ((_handlers != null) ? _handlers.Length : 0); Array.Resize(ref _handlers, num + 1); Array.Copy(_handlers, 0, _handlers, 1, num); _handlers[0] = classifier; } internal void Freeze() { _frozen = true; } internal ResponseClassifier Apply(ResponseClassifier classifier) { if (_statusCodes == null && _handlers == null) { return classifier; } if (classifier is StatusCodeClassifier statusCodeClassifier) { StatusCodeClassifier statusCodeClassifier2 = statusCodeClassifier.Clone(); statusCodeClassifier2.Handlers = _handlers; if (_statusCodes != null) { (int, bool)[] statusCodes = _statusCodes; for (int i = 0; i < statusCodes.Length; i++) { (int, bool) tuple = statusCodes[i]; statusCodeClassifier2.AddClassifier(tuple.Item1, tuple.Item2); } } return statusCodeClassifier2; } return new ChainingClassifier(_statusCodes, _handlers, classifier); } } [Serializable] public class RequestFailedException : Exception, ISerializable { internal class ErrorResponse { [JsonPropertyName("error")] public ResponseError? Error { get; set; } } private readonly struct ErrorDetails { public string Message { get; } public string? ErrorCode { get; } public IDictionary<string, string>? Data { get; } public ErrorDetails(string message, string? errorCode, IDictionary<string, string>? data) { Message = message; ErrorCode = errorCode; Data = data; } } private const string DefaultMessage = "Service request failed."; internal const string NoContentOnSuccessMessage = "Service request succeeded. Response content and headers are not included to avoid logging sensitive data."; private readonly Response? _response; public int Status { get; } public string? ErrorCode { get; } public RequestFailedException(string message) : this(0, message) { } public RequestFailedException(string message, Exception? innerException) : this(0, message, innerException) { } [EditorBrowsable(EditorBrowsableState.Never)] public RequestFailedException(int status, string message) : this(status, message, null) { } [EditorBrowsable(EditorBrowsableState.Never)] public RequestFailedException(int status, string message, Exception? innerException) : this(status, message, null, innerException) { } [EditorBrowsable(EditorBrowsableState.Never)] public RequestFailedException(int status, string message, string? errorCode, Exception? innerException) : base(message, innerException) { Status = status; ErrorCode = errorCode; } private RequestFailedException(int status, (string Message, ResponseError? Error) details) : this(status, details.Message, details.Error?.Code, null) { } private RequestFailedException(int status, ErrorDetails details, Exception? innerException) : this(status, details.Message, details.ErrorCode, innerException) { if (details.Data == null) { return; } foreach (KeyValuePair<string, string> datum in details.Data) { Data.Add(datum.Key, datum.Value); } } public RequestFailedException(Response response) : this(response, null) { } public RequestFailedException(Response response, Exception? innerException) : this(response, innerException, null) { } public RequestFailedException(Response response, Exception? innerException, RequestFailedDetailsParser? detailsParser) : this(response.Status, CreateExceptionDetails(response, detailsParser), innerException) { _response = response; } protected RequestFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { Status = info.GetInt32("Status"); ErrorCode = info.GetString("ErrorCode"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { Argument.AssertNotNull(info, "info"); info.AddValue("Status", Status); info.AddValue("ErrorCode", ErrorCode); base.GetObjectData(info, context); } public Response? GetRawResponse() { return _response; } private static ErrorDetails CreateExceptionDetails(Response response, RequestFailedDetailsParser? parser) { BufferResponseIfNeeded(response); if (parser == null) { parser = response.RequestFailedDetailsParser; } if (!(parser?.TryParse(response, out ResponseError error, out IDictionary<string, string> data) ?? DefaultRequestFailedDetailsParser.TryParseDetails(response, out error, out data))) { error = null; data = null; } StringBuilder stringBuilder = new StringBuilder(); AppendStatusAndReason(response, error, stringBuilder); AppendErrorCodeAndAdditionalInfo(error, data, stringBuilder); if (response.IsError) { AppendContentAndHeaders(response, stringBuilder); } else { stringBuilder.AppendLine().AppendLine("Service request succeeded. Response content and headers are not included to avoid logging sensitive data."); } return new ErrorDetails(stringBuilder.ToString(), error?.Code, data); } private static void AppendContentAndHeaders(Response response, StringBuilder messageBuilder) { if (response.ContentStream is MemoryStream && ContentTypeUtilities.TryGetTextEncoding(response.Headers.ContentType, out var _)) { messageBuilder.AppendLine().AppendLine("Content:").AppendLine(((object)response.Content).ToString()); } messageBuilder.AppendLine().AppendLine("Headers:"); foreach (HttpHeader header in response.Headers) { string text = response.Sanitizer.SanitizeHeader(header.Name, header.Value); string value = header.Name + ": " + text; messageBuilder.AppendLine(value); } } private static void AppendErrorCodeAndAdditionalInfo(ResponseError? error, IDictionary<string, string>? additionalInfo, StringBuilder messageBuilder) { if (!string.IsNullOrWhiteSpace(error?.Code)) { messageBuilder.Append("ErrorCode: ").Append(error?.Code).AppendLine(); } if (additionalInfo == null || additionalInfo.Count <= 0) { return; } messageBuilder.AppendLine().AppendLine("Additional Information:"); foreach (KeyValuePair<string, string> item in additionalInfo) { messageBuilder.Append(item.Key).Append(": ").AppendLine(item.Value); } } private static void AppendStatusAndReason(Response response, ResponseError? error, StringBuilder messageBuilder) { messageBuilder.AppendLine(error?.Message ?? "Service request failed.").Append("Status: ").Append(response.Status.ToString(CultureInfo.InvariantCulture)); if (!string.IsNullOrEmpty(response.ReasonPhrase)) { messageBuilder.Append(" (").Append(response.ReasonPhrase).AppendLine(")"); } else { messageBuilder.AppendLine(); } } private static void BufferResponseIfNeeded(Response response) { Stream contentStream = response.ContentStream; if ((contentStream != null && !(contentStream is MemoryStream)) || 1 == 0) { MemoryStream memoryStream = new MemoryStream(); response.ContentStream.CopyTo(memoryStream); response.ContentStream.Dispose(); memoryStream.Position = 0L; response.ContentStream = memoryStream; } } } public abstract class Response : IDisposable { public abstract int Status { get; } public abstract string ReasonPhrase { get; } public abstract Stream? ContentStream { get; set; } public abstract string ClientRequestId { get; set; } public virtual ResponseHeaders Headers => new ResponseHeaders(this); public virtual BinaryData Content { get { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown if (ContentStream == null) { return BinaryData.Empty; } if (!(ContentStream is MemoryStream memoryStream)) { throw new InvalidOperationException("The response is not fully buffered."); } if (!memoryStream.TryGetBuffer(out var buffer)) { return new BinaryData(memoryStream.ToArray()); } return new BinaryData((ReadOnlyMemory<byte>)buffer.AsMemory()); } } public virtual bool IsError { get; internal set; } internal HttpMessageSanitizer Sanitizer { get; set; } = HttpMessageSanitizer.Default; internal RequestFailedDetailsParser? RequestFailedDetailsParser { get; set; } public abstract void Dispose(); protected internal abstract bool TryGetHeader(string name, [NotNullWhen(true)] out string? value); protected internal abstract bool TryGetHeaderValues(string name, [NotNullWhen(true)] out IEnumerable<string>? values); protected internal abstract bool ContainsHeader(string name); protected internal abstract IEnumerable<HttpHeader> EnumerateHeaders(); public static Response<T> FromValue<T>(T value, Response response) { return new ValueResponse<T>(response, value); } public override string ToString() { return $"Status: {Status}, ReasonPhrase: {ReasonPhrase}"; } internal static void DisposeStreamIfNotBuffered(ref Stream? stream) { if (!(stream is MemoryStream)) { stream?.Dispose(); stream = null; } } } [JsonConverter(typeof(Converter))] [TypeReferenceType(true, new string[] { "Target", "Details" })] public sealed class ResponseError : IJsonModel<ResponseError>, IPersistableModel<ResponseError> { internal class Converter : JsonConverter<ResponseError?> { public override ResponseError? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader); return ReadFromJson(jsonDocument.RootElement); } public override void Write(Utf8JsonWriter writer, ResponseError? value, JsonSerializerOptions options) { throw new NotImplementedException(); } } private readonly JsonElement _element; public string? Code { get; } public string? Message { get; } internal ResponseInnerError? InnerError { get; } internal string? Target { get; } internal IReadOnlyList<ResponseError> Details { get; } public ResponseError() : this(null, null) { } [InitializationConstructor] public ResponseError(string? code, string? message) : this(code, message, null, default(JsonElement)) { } [SerializationConstructor] internal ResponseError(string? code, string? message, string? target, JsonElement element, ResponseInnerError? innerError = null, IReadOnlyList<ResponseError>? details = null) { _element = element; Code = code; Message = message; InnerError = innerError; Target = target; Details = details ?? Array.Empty<ResponseError>(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); Append(stringBuilder, includeRaw: true); return stringBuilder.ToString(); } internal void Append(StringBuilder builder, bool includeRaw) { builder.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}{2}", Code, Message, Environment.NewLine); if (Target != null) { builder.AppendFormat(CultureInfo.InvariantCulture, "Target: {0}{1}", Target, Environment.NewLine); } ResponseInnerError innerError = InnerError; if (innerError != null) { builder.AppendLine(); builder.AppendLine("Inner Errors:"); while (innerError != null) { builder.AppendLine(innerError.Code); innerError = innerError.InnerError; } } if (Details.Count > 0) { builder.AppendLine(); builder.AppendLine("Details:"); foreach (ResponseError detail in Details) { detail.Append(builder, includeRaw: false); } } if (includeRaw && _element.ValueKind != 0) { builder.AppendLine(); builder.AppendLine("Raw:"); builder.Append(_element.GetRawText()); } } private void Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Code != null) { writer.WritePropertyName("code"); writer.WriteStringValue(Code); } if (Message != null) { writer.WritePropertyName("message"); writer.WriteStringValue(Message); } if (Target != null) { writer.WritePropertyName("target"); writer.WriteStringValue(Target); } if (InnerError != null) { writer.WritePropertyName("innererror"); InnerError.Write(writer, ModelReaderWriterOptions.Json); } if (Details.Count > 0) { writer.WritePropertyName("details"); writer.WriteStartArray(); foreach (ResponseError detail in Details) { if (detail == null) { writer.WriteNullValue(); } else { detail.Write(writer); } } writer.WriteEndArray(); } writer.WriteEndObject(); } private static ResponseError? ReadFromJson(JsonElement element) { if (element.ValueKind == JsonValueKind.Null) { return null; } string code = null; if (element.TryGetProperty("code", out var value)) { code = value.GetString(); } string message = null; if (element.TryGetProperty("message", out value)) { message = value.GetString(); } string target = null; if (element.TryGetProperty("target", out value)) { target = value.GetString(); } ResponseInnerError innerError = null; if (element.TryGetProperty("innererror", out value)) { innerError = ResponseInnerError.ReadFromJson(value); } List<ResponseError> list = null; if (element.TryGetProperty("details", out value) && value.ValueKind == JsonValueKind.Array) { foreach (JsonElement item in value.EnumerateArray()) { ResponseError responseError = ReadFromJson(item); if (responseError != null) { if (list == null) { list = new List<ResponseError>(); } list.Add(responseError); } } } return new ResponseError(code, message, target, element.Clone(), innerError, list); } void IJsonModel<ResponseError>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { string text = ((options.Format == "W") ? ((IPersistableModel<ResponseError>)(object)this).GetFormatFromOptions(options) : options.Format); if (text != "J") { throw new FormatException("The model ResponseError does not support '" + text + "' format."); } writer.WriteStartObject(); if (Code != null) { writer.WritePropertyName("code"); writer.WriteStringValue(Code); } if (Message != null) { writer.WritePropertyName("message"); writer.WriteStringValue(Message); } if (Target != null) { writer.WritePropertyName("target"); writer.WriteStringValue(Target); } if (InnerError != null) { writer.WritePropertyName("innererror"); InnerError.Write(writer, ModelReaderWriterOptions.Json); } if (Details.Count > 0) { writer.WritePropertyName("details"); writer.WriteStartArray(); foreach (ResponseError detail in Details) { if (detail == null) { writer.WriteNullValue(); } else { detail.Write(writer); } } writer.WriteEndArray(); } writer.WriteEndObject(); } ResponseError IJsonModel<ResponseError>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { string text = ((options.Format == "W") ? ((IPersistableModel<ResponseError>)(object)this).GetFormatFromOptions(options) : options.Format); if (text != "J") { throw new FormatException("The model ResponseError does not support '" + text + "' format."); } using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader); return ReadFromJson(jsonDocument.RootElement) ?? new ResponseError(); } BinaryData IPersistableModel<ResponseError>.Write(ModelReaderWriterOptions options) { string text = ((options.Format == "W") ? ((IPersistableModel<ResponseError>)(object)this).GetFormatFromOptions(options) : options.Format); if (text != "J") { throw new FormatException("The model ResponseError does not support '" + text + "' format."); } return ModelReaderWriter.Write<ResponseError>(this, options, (ModelReaderWriterContext)(object)AzureCoreContext.Default); } ResponseError IPersistableModel<ResponseError>.Create(BinaryData data, ModelReaderWriterOptions options) { string text = ((options.Format == "W") ? ((IPersistableModel<ResponseError>)(object)this).GetFormatFromOptions(options) : options.Format); if (text != "J") { throw new FormatException("The model ResponseError does not support '" + text + "' format."); } using JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(data)); return ReadFromJson(jsonDocument.RootElement) ?? new ResponseError(); } string IPersistableModel<ResponseError>.GetFormatFromOptions(ModelReaderWriterOptions options) { return "J"; } } [JsonConverter(typeof(ResponseInnerErrorConverter))] internal sealed class ResponseInnerError : IJsonModel<ResponseInnerError>, IPersistableModel<ResponseInnerError> { internal class ResponseInnerErrorConverter : JsonConverter<ResponseInnerError?> { public override ResponseInnerError? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader); return ReadFromJson(jsonDocument.RootElement); } public override void Write(Utf8JsonWriter writer, ResponseInnerError? value, JsonSerializerOptions options) { throw new NotImplementedException(); } } private readonly JsonElement _innerErrorElement; public string? Code { get; } public ResponseInnerError? InnerError { get; } internal ResponseInnerError() { } internal ResponseInnerError(string? code, ResponseInnerError? innerError, JsonElement innerErrorElement) { _innerErrorElement = innerErrorElement; Code = code; InnerError = innerError; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); Append(stringBuilder); return stringBuilder.ToString(); } internal void Append(StringBuilder builder) { builder.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}", Code, Environment.NewLine); if (InnerError != null) { builder.AppendLine("Inner Error:"); builder.Append(InnerError); } } private static void WriteInnerError(Utf8JsonWriter writer, ResponseInnerError innerError) { writer.WriteStartObject(); if (innerError.Code != null) { writer.WritePropertyName("code"); writer.WriteStringValue(innerError.Code); } if (innerError.InnerError != null) { writer.WritePropertyName("innererror"); WriteInnerError(writer, innerError.InnerError); } writer.WriteEndObject(); } public void Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { string text = ((options.Format == "W") ? GetFormatFromOptions(options) : options.Format); if (text != "J") { throw new FormatException("The model ResponseInnerError does not support '" + text + "' format."); } WriteInnerError(writer, this); } public ResponseInnerError Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { string text = ((options.Format == "W") ? GetFormatFromOptions(options) : options.Format); if (text != "J") { throw new FormatException("The model ResponseInnerError does not support '" + text + "' format."); } using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader); return ReadFromJson(jsonDocument.RootElement) ?? new ResponseInnerError(null, null, default(JsonElement)); } public BinaryData Write(ModelReaderWriterOptions options) { string text = ((options.Format == "W") ? GetFormatFromOptions(options) : options.Format); if (text != "J") { throw new FormatException("The model ResponseInnerError does not support '" + text + "' format."); } return ModelReaderWriter.Write<ResponseInnerError>(this, options, (ModelReaderWriterContext)(object)AzureCoreContext.Default); } public ResponseInnerError Create(BinaryData data, ModelReaderWriterOptions options) { string text = ((options.Format == "W") ? GetFormatFromOptions(options) : options.Format); if (text != "J") { throw new FormatException("The model ResponseInnerError does not support '" + text + "' format."); } using JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(data)); return ReadFromJson(jsonDocument.RootElement) ?? new ResponseInnerError(null, null, default(JsonElement)); } string IPersistableModel<ResponseInnerError>.GetFormatFromOptions(ModelReaderWriterOptions options) { return "J"; } private string GetFormatFromOptions(ModelReaderWriterOptions options) { return "J"; } internal static ResponseInnerError? ReadFromJson(JsonElement element) { if (element.ValueKind == JsonValueKind.Null) { return null; } string code = null; if (element.TryGetProperty("code", out var value)) { code = value.GetString(); } ResponseInnerError innerError = null; if (element.TryGetProperty("innererror", out value)) { innerError = ReadFromJson(value); } return new ResponseInnerError(code, innerError, element.Clone()); } } [DebuggerTypeProxy(typeof(ResponseDebugView<>))] public abstract class Response<T> : NullableResponse<T> { [EditorBrowsable(EditorBrowsableState.Never)] public override bool HasValue => true; public override T Value => Value; public static implicit operator T(Response<T> response) { if (response == null) { throw new ArgumentNullException("response", $"The implicit cast from Response<{typeof(T)}> to {typeof(T)} failed because the Response<{typeof(T)}> was null."); } return response.Value; } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { return base.Equals(obj); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } } public static class AzureCoreExtensions { public static T? ToObject<T>(this BinaryData data, ObjectSerializer serializer, CancellationToken cancellationToken = default(CancellationToken)) { return (T)serializer.Deserialize(data.ToStream(), typeof(T), cancellationToken); } public static async ValueTask<T?> ToObjectAsync<T>(this BinaryData data, ObjectSerializer serializer, CancellationToken cancellationToken = default(CancellationToken)) { return (T)(await serializer.DeserializeAsync(data.ToStream(), typeof(T), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); } [RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] [RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] public static object? ToObjectFromJson(this BinaryData data) { JsonElement element = data.ToObjectFromJson<JsonElement>((JsonSerializerOptions)null); return element.GetObject(); } [RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] [RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] public static dynamic ToDynamicFromJson(this BinaryData utf8Json) { DynamicDataOptions options = new DynamicDataOptions(); return utf8Json.ToDynamicFromJson(options); } [RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] [RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] public static dynamic ToDynamicFromJson(this BinaryData utf8Json, JsonPropertyNames propertyNameFormat, string dateTimeFormat = "o") { DynamicDataOptions options = new DynamicDataOptions { PropertyNameFormat = propertyNameFormat, DateTimeFormat = dateTimeFormat }; return utf8Json.ToDynamicFromJson(options); } [RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] [RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] internal static dynamic ToDynamicFromJson(this BinaryData utf8Json, DynamicDataOptions options) { return new DynamicData(MutableJsonDocument.Parse(utf8Json, DynamicDataOptions.ToSerializerOptions(options)).RootElement, options); } private static object? GetObject(this in JsonElement element) { switch (element.ValueKind) { case JsonValueKind.String: return element.GetString(); case JsonValueKind.Number: { if (element.TryGetInt32(out var value)) { return value; } if (element.TryGetInt64(out var value2)) { return value2; } return element.GetDouble(); } case JsonValueKind.True: return true; case JsonValueKind.False: return false; case JsonValueKind.Undefined: case JsonValueKind.Null: return null; case JsonValueKind.Object: { Dictionary<string, object> dictionary = new Dictionary<string, object>(); { foreach (JsonProperty item in element.EnumerateObject()) { string name = item.Name; JsonElement element3 = item.Value; dictionary.Add(name, element3.GetObject()); } return dictionary; } } case JsonValueKind.Array: { List<object> list = new List<object>(); foreach (JsonElement item2 in element.EnumerateArray()) { JsonElement element2 = item2; list.Add(element2.GetObject()); } return list.ToArray(); } default: throw new NotSupportedException("Not supported value kind " + element.ValueKind); } } } public class SyncAsyncEventArgs : EventArgs { public bool IsRunningSynchronously { get; } public CancellationToken CancellationToken { get; } public SyncAsyncEventArgs(bool isRunningSynchronously, CancellationToken cancellationToken = default(CancellationToken)) { IsRunningSynchronously = isRunningSynchronously; CancellationToken = cancellationToken; } } public enum WaitUntil { Completed, Started } internal class ResponseError_Builder : ModelReaderWriterTypeBuilder { protected override Type BuilderType => typeof(ResponseError); protected override object CreateInstance() { return new ResponseError(); } } internal class ResponseInnerError_Builder : ModelReaderWriterTypeBuilder { protected override Type BuilderType => typeof(ResponseInnerError); protected override object CreateInstance() { return new ResponseInnerError(); } } } namespace Azure.Messaging { [JsonConverter(typeof(CloudEventConverter))] [RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] [RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] public class CloudEvent { private string? _id; private string? _source; private string? _type; public BinaryData? Data { get; set; } public string Id { get { return _id; } set { Argument.AssertNotNull(value, "value"); _id = value; } } internal CloudEventDataFormat DataFormat { get; set; } public string Source { get { return _source; } set { Argument.AssertNotNull(value, "value"); _source = value; } } public string Type { get { return _type; } set { Argument.AssertNotNull(value, "value"); _type = value; } } internal string? SpecVersion { get; set; } public DateTimeOffset? Time { get; set; } = DateTimeOffset.UtcNow; public string? DataSchema { get; set; } public string? DataContentType { get; set; } internal Type? DataSerializationType { get; } public string? Subject { get; set; } public IDictionary<string, object> ExtensionAttributes { get; } = new CloudEventExtensionAttributes<string, object>(); public CloudEvent(string source, string type, object? jsonSerializableData, Type? dataSerializationType = null) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown if (jsonSerializableData is BinaryData) { throw new InvalidOperationException("This constructor does not support BinaryData. Use the constructor that takes a BinaryData instance."); } Source = source; Type = type; Id = Guid.NewGuid().ToString(); DataFormat = CloudEventDataFormat.Json; Data = new BinaryData(jsonSerializableData, (JsonSerializerOptions)null, dataSerializationType ?? jsonSerializableData?.GetType()); SpecVersion = "1.0"; } public CloudEvent(string source, string type, BinaryData? data, string? dataContentType, CloudEventDataFormat dataFormat = CloudEventDataFormat.Binary) { Source = source; Type = type; DataContentType = dataContentType; Id = Guid.NewGuid().ToString(); DataFormat = dataFormat; Data = data; SpecVersion = "1.0"; } internal CloudEvent() { } public static CloudEvent[] ParseMany(BinaryData json, bool skipValidation = false) { Argument.AssertNotNull<BinaryData>(json, "json"); CloudEvent[] array = null; JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(json)); if (jsonDocument.RootElement.ValueKind == JsonValueKind.Object) { array = new CloudEvent[1] { CloudEventConverter.DeserializeCloudEvent(jsonDocument.RootElement, skipValidation) }; } else if (jsonDocument.RootElement.ValueKind == JsonValueKind.Array) { array = new CloudEvent[jsonDocument.RootElement.GetArrayLength()]; int num = 0; foreach (JsonElement item in jsonDocument.RootElement.EnumerateArray()) { array[num++] = CloudEventConverter.DeserializeCloudEvent(item, skipValidation); } } return array ?? Array.Empty<CloudEvent>(); } public static CloudEvent? Parse(BinaryData json, bool skipValidation = false) { Argument.AssertNotNull<BinaryData>(json, "json"); using JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(json)); CloudEvent result = null; if (jsonDocument.RootElement.ValueKind == JsonValueKind.Object) { result = CloudEventConverter.DeserializeCloudEvent(jsonDocument.RootElement, skipValidation); } else if (jsonDocument.RootElement.ValueKind == JsonValueKind.Array) { if (jsonDocument.RootElement.GetArrayLength() > 1) { throw new ArgumentException("The BinaryData instance contains JSON from multiple cloud events. This method should only be used with BinaryData containing a single cloud event. " + Environment.NewLine + "To parse multiple events, use the ParseMany overload."); } using JsonElement.ArrayEnumerator arrayEnumerator = jsonDocument.RootElement.EnumerateArray().GetEnumerator(); if (arrayEnumerator.MoveNext()) { result = CloudEventConverter.DeserializeCloudEvent(arrayEnumerator.Current, skipValidation); } } return result; } } internal class CloudEventConstants { public const string SpecVersion = "specversion"; public const string Id = "id"; public const string Source = "source"; public const string Type = "type"; public const string DataContentType = "datacontenttype"; public const string DataSchema = "dataschema"; public const string Subject = "subject"; public const string Time = "time"; public const string Data = "data"; public const string DataBase64 = "data_base64"; public const string ErrorSkipValidationSuggestion = "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation."; } [RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] [RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")] internal class CloudEventConverter : JsonConverter<CloudEvent> { public override CloudEvent Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader); return DeserializeCloudEvent(jsonDocument.RootElement, skipValidation: false); } internal static CloudEvent DeserializeCloudEvent(JsonElement element, bool skipValidation) { //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown CloudEvent cloudEvent = new CloudEvent(); foreach (JsonProperty item in element.EnumerateObject()) { if (item.NameEquals("id")) { if (item.Value.ValueKind != JsonValueKind.Null) { cloudEvent.Id = item.Value.GetString(); } } else if (item.NameEquals("source")) { if (item.Value.ValueKind != JsonValueKind.Null) { cloudEvent.Source = item.Value.GetString(); } } else if (item.NameEquals("data")) { cloudEvent.Data = new BinaryData((object)item.Value, (JsonSerializerOptions)null, (Type)null); cloudEvent.DataFormat = CloudEventDataFormat.Json; } else if (item.NameEquals("data_base64")) { if (item.Value.ValueKind != JsonValueKind.Null) { cloudEvent.Data = BinaryData.FromBytes(item.Value.GetBytesFromBase64()); cloudEvent.DataFormat = CloudEventDataFormat.Binary; } } else if (item.NameEquals("type")) { if (item.Value.ValueKind != JsonValueKind.Null) { cloudEvent.Type = item.Value.GetString(); } } else if (item.NameEquals("time")) { if (item.Value.ValueKind != JsonValueKind.Null) { cloudEvent.Time = item.Value.GetDateTimeOffset(); } } else if (item.NameEquals("specversion")) { cloudEvent.SpecVersion = item.Value.GetString(); } else if (item.NameEquals("dataschema")) { cloudEvent.DataSchema = item.Value.GetString(); } else if (item.NameEquals("datacontenttype")) { cloudEvent.DataContentType = item.Value.GetString(); } else if (item.NameEquals("subject")) { cloudEvent.Subject = item.Value.GetString(); } else if (!skipValidation) { IDictionary<string, object> extensionAttributes = cloudEvent.ExtensionAttributes; string name = item.Name; JsonElement element2 = item.Value; extensionAttributes.Add(name, GetObject(in element2)); } else { CloudEventExtensionAttributes<string, object> obj = (CloudEventExtensionAttributes<string, object>)cloudEvent.ExtensionAttributes; string name2 = item.Name; JsonElement element2 = item.Value; obj.AddWithoutValidation(name2, GetObject(in element2)); } } if (!skipValidation) { if (cloudEvent.Source == null) { throw new ArgumentException("The source property must be specified in each CloudEvent. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation."); } if (cloudEvent.Type == null) { throw new ArgumentException("The type property must be specified in each CloudEvent. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation."); } if (cloudEvent.Id == null) { throw new ArgumentException("The Id property must be specified in each CloudEvent. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation."); } if (cloudEvent.SpecVersion != "1.0") { if (cloudEvent.SpecVersion == null) { throw new ArgumentException("The specverion was not set in at least one of the events in the payload. This type only supports specversion '1.0', which must be set for each event. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation." + Environment.NewLine + element, "element"); } throw new ArgumentException("The specverion value of '" + cloudEvent.SpecVersion + "' is not supported by CloudEvent. This type only supports specversion '1.0'. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation." + Environment.NewLine + element, "element"); } } return cloudEvent; } public override void Write(Utf8JsonWriter writer, CloudEvent value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WritePropertyName("id"); writer.WriteStringValue(value.Id); writer.WritePropertyName("source"); writer.WriteStringValue(value.Source); writer.WritePropertyName("type"); writer.WriteStringValue(value.Type); if (value.Data != null) { switch (value.DataFormat) { case CloudEventDataFormat.Binary: writer.WritePropertyName("data_base64"); writer.WriteBase64StringValue(value.Data.ToArray()); break; case CloudEventDataFormat.Json: { using (JsonDocument jsonDocument = JsonDocument.Parse(value.Data.ToMemory())) { writer.WritePropertyName("data"); jsonDocument.RootElement.WriteTo(writer); } break; } } } if (value.Time.HasValue) { writer.WritePropertyName("time"); writer.WriteStringValue(value.Time.Value); } writer.WritePropertyName("specversion"); writer.WriteStringValue(value.SpecVersion); if (value.DataSchema != null) { writer.WritePropertyName("dataschema"); writer.WriteStringValue(value.DataSchema); } if (value.DataContentType != null) { writer.WritePropertyName("datacontenttype"); writer.WriteStringValue(value.DataContentType); } if (value.Subject != null) { writer.WritePropertyName("subject"); writer.WriteStringValue(value.Subject); } foreach (KeyValuePair<string, object> extensionAttribute in value.ExtensionAttributes) { writer.WritePropertyName(extensionAttribute.Key); WriteObjectValue(writer, extensionAttribute.Value); } writer.WriteEndObject(); } private static void WriteObjectValue(Utf8JsonWriter writer, object? value) { if (value != null) { if (!(value is byte[] inArray)) { if (!(value is ReadOnlyMemory<byte> readOnlyMemory)) { if (!(value is int value2)) { if (!(value is string value3)) { if (!(value is bool value4)) { if (!(value is Guid value5)) { if (!(value is Uri uri)) { if (!(value is DateTimeOffset value6)) { if (!(value is DateTime value7)) { if (!(value is IEnumerable<KeyValuePair<string, object>> enumerable)) { if (value is IEnumerable<object> enumerable2) { writer.WriteStartArray(); foreach (object item in enumerable2) { WriteObjectValue(writer, item); } writer.WriteEndArray(); return; } throw new NotSupportedException("Not supported type " + value.GetType()); } writer.WriteStartObject(); foreach (KeyValuePair<string, object> item2 in enumerable) { writer.WritePropertyName(item2.Key); WriteObjectValue(writer, item2.Value); } writer.WriteEndObject(); } else { writer.WriteStringValue(value7); } } else { writer.WriteStringValue(value6); } } else { writer.WriteStringValue(uri.ToString()); } } else { writer.WriteStringValue(value5); } } else { writer.WriteBooleanValue(value4); } } else { writer.WriteStringValue(value3); } } else { writer.WriteNumberValue(value2); } } else { writer.WriteStringValue(Convert.ToBase64String(readOnlyMemory.ToArray())); } } else { writer.WriteStringValue(Convert.ToBase64String(inArray)); } } else { writer.WriteNullValue(); } } private static object? GetObject(in JsonElement element) { switch (element.ValueKind) { case JsonValueKind.String: return element.GetString(); case JsonValueKind.Number: { if (element.TryGetInt32(out var value)) { return value; } if (element.TryGetInt64(out var value2)) { return value2; } return element.GetDouble(); } case JsonValueKind.True: return true; case JsonValueKind.False: return false; case JsonValueKind.Undefined: case JsonValueKind.Null: return null; case JsonValueKind.Object: { Dictionary<string, object> dictionary = new Dictionary<string, object>(); { foreach (JsonProperty item in element.EnumerateObject()) { string name = item.Name; JsonElement element3 = item.Value; dictionary.Add(name, GetObject(in element3)); } return dictionary; } } case JsonValueKind.Array: { List<object> list = new List<object>(); foreach (JsonElement item2 in element.EnumerateArray()) { JsonElement element2 = item2; list.Add(GetObject(in element2)); } return list.ToArray(); } default: throw new NotSupportedException("Not supported value kind " + element.ValueKind); } } } public enum CloudEventDataFormat { Binary, Json } internal class CloudEventExtensionAttributes<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable where TKey : class { private readonly Dictionary<TKey, TValue> _backingDictionary; private static readonly HashSet<string> s_reservedAttributes = new HashSet<string> { "specversion", "id", "source", "type", "datacontenttype", "dataschema", "subject", "time", "data", "data_base64" }; public TValue this[TKey key] { get { return _backingDictionary[key]; } set { ValidateAttribute(key as string, value); _backingDictionary[key] = value; } } public ICollection<TKey> Keys => _backingDictionary.Keys; public ICollection<TValue> Values => _backingDictionary.Values; public int Count => _backingDictionary.Count; public bool IsReadOnly => ((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).IsReadOnly; public CloudEventExtensionAttributes() { _backingDictionary = new Dictionary<TKey, TValue>(); } public void Add(TKey key, TValue value) { ValidateAttribute(key as string, value); _backingDictionary.Add(key, value); } public void AddWithoutValidation(TKey key, TValue value) { _backingDictionary.Add(key, value); } public void Add(KeyValuePair<TKey, TValue> item) { ValidateAttribute(item.Key as string, item.Value); ((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).Add(item); } public void Clear() { _backingDictionary.Clear(); } public bool Contains(KeyValuePair<TKey, TValue> item) { return ((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).Contains(item); } public bool ContainsKey(TKey key) { return _backingDictionary.ContainsKey(key); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { ((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).CopyTo(array, arrayIndex); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _backingDictionary.GetEnumerator(); } public bool Remove(TKey key) { return _backingDictionary.Remove(key); } public bool Remove(KeyValuePair<TKey, TValue> item) { return ((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).Remove(item); } public bool TryGetValue(TKey key, out TValue value) { return _backingDictionary.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return _backingDictionary.GetEnumerator(); } private static void ValidateAttribute(string? name, object? value) { Argument.AssertNotNullOrEmpty(name, "name"); Argument.AssertNotNull(value, "value"); if (s_reservedAttributes.Contains(name)) { throw new ArgumentException("Attribute name cannot use the reserved attribute: '" + name + "'", "name"); } foreach (char c in name) { if ((c < '0' || c > '9') && (c < 'a' || c > 'z')) { throw new ArgumentException($"Invalid character in extension attribute name: '{c}'. " + "CloudEvent attribute names must consist of lower-case letters ('a' to 'z') or digits ('0' to '9') from the ASCII character set.", "name"); } } if (value is string || value is byte[] || value is ReadOnlyMemory<byte> || value is int || value is bool || value is Uri || value is DateTime || value is DateTimeOffset) { return; } throw new ArgumentException($"Values of type {value.GetType()} are not supported. " + "Attribute values must be of type string, bool, byte, int, Uri, DateTime, or DateTimeOffset."); } } public class MessageContent { public virtual BinaryData? Data { get; set; } public virtual ContentType? ContentType { get { return ContentTypeCore; } set { ContentTypeCore = value; } } [EditorBrowsable(EditorBrowsableState.Never)] protected virtual ContentType? ContentTypeCore { get; set; } public virtual bool IsReadOnly { get; } } } namespace Azure.Core { public struct AccessToken { public string Token { get; } public DateTimeOffset ExpiresOn { get; } public DateTimeOffset? RefreshOn { get; } public string TokenType { get; } public AccessToken(string accessToken, DateTimeOffset expiresOn) { RefreshOn = null; Token = accessToken; ExpiresOn = expiresOn; TokenType = "Bearer"; } public AccessToken(string accessToken, DateTimeOffset expiresOn, DateTimeOffset? refreshOn) { Token = accessToken; ExpiresOn = expiresOn; RefreshOn = refreshOn; TokenType = "Bearer"; } public AccessToken(string accessToken, DateTimeOffset expiresOn, DateTimeOffset? refreshOn, string tokenType) { Token = accessToken; ExpiresOn = expiresOn; RefreshOn = refreshOn; TokenType = tokenType; } public override bool Equals(object? obj) { if (obj is AccessToken accessToken) { if (accessToken.ExpiresOn == ExpiresOn && accessToken.Token == Token) { return accessToken.TokenType == TokenType; } return false; } return false; } public override int GetHashCode() { return HashCodeBuilder.Combine(Token, ExpiresOn, TokenType); } internal AuthenticationToken ToAuthenticationToken() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown return new AuthenticationToken(Token, TokenType, ExpiresOn, RefreshOn); } } [ModelReaderWriterBuildable(typeof(ResponseError))] [ModelReaderWriterBuildable(typeof(RehydrationToken))] [ModelReaderWriterBuildable(typeof(ResponseInnerError))] public class AzureCoreContext : ModelReaderWriterContext { private readonly Dictionary<Type, Func<ModelReaderWriterTypeBuilder>> _typeBuilderFactories = new Dictionary<Type, Func<ModelReaderWriterTypeBuilder>>(); private readonly ConcurrentDictionary<Type, ModelReaderWriterTypeBuilder> _typeBuilders = new ConcurrentDictionary<Type, ModelReaderWriterTypeBuilder>(); private static AzureCoreContext _azureCoreContext; public static AzureCoreContext Default => _azureCoreContext ?? (_azureCoreContext = new AzureCoreContext()); private AzureCoreContext() { _typeBuilderFactories.Add(typeof(ResponseError), () => (ModelReaderWriterTypeBuilder)(object)new ResponseError_Builder()); _typeBuilderFactories.Add(typeof(RehydrationToken), () => (ModelReaderWriterTypeBuilder)(object)new RehydrationToken_Builder()); _typeBuilderFactories.Add(typeof(ResponseInnerError), () => (ModelReaderWriterTypeBuilder)(object)new ResponseInnerError_Builder()); } protected override bool TryGetTypeBuilderCore(Type type, out ModelReaderWriterTypeBuilder builder) { if (_typeBuilders.TryGetValue(type, out builder)) { return true; } if (_typeBuilderFactories.TryGetValue(type, out var value)) { builder = value(); _typeBuilders.TryAdd(type, builder); return true; } builder = null; return false; } } public readonly struct AzureLocation : IEquatable<AzureLocation> { private const char Space = ' '; private static Dictionary<string, AzureLocation> PublicCloudLocations { get; } = new Dictionary<string, AzureLocation>(); public static AzureLocation EastAsia { get; } = CreateStaticReference("eastasia", "East Asia"); public static AzureLocation SoutheastAsia { get; } = CreateStaticReference("southeastasia", "Southeast Asia"); public static AzureLocation CentralUS { get; } = CreateStaticReference("centralus", "Central US"); public static AzureLocation EastUS { get; } = CreateStaticReference("eastus", "East US"); public static AzureLocation EastUS2 { get; } = CreateStaticReference("eastus2", "East US 2"); public static AzureLocation WestUS { get; } = CreateStaticReference("westus", "West US"); public static AzureLocation WestUS2 { get; } = CreateStaticReference("westus2", "West US 2"); public static AzureLocation WestUS3 { get; } = CreateStaticReference("westus3", "West US 3"); public static AzureLocation NorthCentralUS { get; } = CreateStaticReference("northcentralus", "North Central US"); public static AzureLocation SouthCentralUS { get; } = CreateStaticReference("southcentralus", "South Central US"); public static AzureLocation NorthEurope { get; } = CreateStaticReference("northeurope", "North Europe"); public static AzureLocation WestEurope { get; } = CreateStaticReference("westeurope", "West Europe"); public static AzureLocation JapanWest { get; } = CreateStaticReference("japanwest", "Japan West"); public static AzureLocation JapanEast { get; } = CreateStaticReference("japaneast", "Japan East"); public static AzureLocation BrazilSouth { get; } = CreateStaticReference("brazilsouth", "Brazil South"); public static AzureLocation AustraliaEast { get; } = CreateStaticReference("australiaeast", "Australia East"); public static AzureLocation AustraliaSoutheast { get; } = CreateStaticReference("australiasoutheast", "Australia Southeast"); public static AzureLocation SouthIndia { get; } = CreateStaticReference("southindia", "South India"); public static AzureLocation CentralIndia { get; } = CreateStaticReference("centralindia", "Central India"); public static AzureLocation WestIndia { get; } = CreateStaticReference("westindia", "West India"); public static AzureLocation CanadaCentral { get; } = CreateStaticReference("canadacentral", "Canada Central"); public static AzureLocation CanadaEast { get; } = CreateStaticReference("canadaeast", "Canada East"); public static AzureLocation UKSouth { get; } = CreateStaticReference("uksouth", "UK South"); public static AzureLocation UKWest { get; } = CreateStaticReference("ukwest", "UK West"); public static AzureLocation WestCentralUS { get; } = CreateStaticReference("westcentralus", "West Central US"); public static AzureLocation KoreaCentral { get; } = CreateStaticReference("koreacentral", "Korea Central"); public static AzureLocation KoreaSouth { get; } = CreateStaticReference("koreasouth", "Korea South"); public static AzureLocation FranceCentral { get; } = CreateStaticReference("francecentral", "France Central"); public static AzureLocation FranceSouth { get; } = CreateStaticReference("francesouth", "France South"); public static AzureLocation AustraliaCentral { get; } = CreateStaticReference("australiacentral", "Australia Central"); public static AzureLocation AustraliaCentral2 { get; } = CreateStaticReference("australiacentral2", "Australia Central 2"); public static AzureLocation UAECentral { get; } = CreateStaticReference("uaecentral", "UAE Central"); public static AzureLocation UAENorth { get; } = CreateStaticReference("uaenorth", "UAE North"); public static AzureLocation SouthAfricaNorth { get; } = CreateStaticReference("southafricanorth", "South Africa North"); public static AzureLocation SouthAfricaWest { get; } = CreateStaticReference("southafricawest", "South Africa West"); public static AzureLocation SwedenCentral { get; } = CreateStaticReference("swedencentral", "Sweden Central"); public static AzureLocation SwedenSouth { get; } = CreateStaticReference("swedensouth", "Sweden South"); public static AzureLocation SwitzerlandNorth { get; } = CreateStaticReference("switzerlandnorth", "Switzerland North"); public static AzureLocation SwitzerlandWest { get; } = CreateStaticReference("switzerlandwest", "Switzerland West"); public static AzureLocation GermanyNorth { get; } = CreateStaticReference("germanynorth", "Germany North"); public static AzureLocation GermanyWestCentral { get; } = CreateStaticReference("germanywestcentral", "Germany West Central"); public static AzureLocation GermanyCentral { get; } = CreateStaticReference("germanycentral", "Germany Central"); public static AzureLocation GermanyNorthEast { get; } = CreateStaticReference("germanynortheast", "Germany Northeast"); public static AzureLocation NorwayWest { get; } = CreateStaticReference("norwaywest", "Norway West"); public static AzureLocation NorwayEast { get; } = CreateStaticReference("norwayeast", "Norway East"); public static AzureLocation BrazilSoutheast { get; } = CreateStaticReference("brazilsoutheast", "Brazil Southeast"); public static AzureLocation ChinaNorth { get; } = CreateStaticReference("chinanorth", "China North"); public static AzureLocation ChinaEast { get; } = CreateStaticReference("chinaeast", "China East"); public static AzureLocation ChinaNorth2 { get; } = CreateStaticReference("chinanorth2", "China North 2"); public static AzureLocation ChinaNorth3 { get; } = CreateStaticReference("chinanorth3", "China North 3"); public static AzureLocation ChinaEast2 { get; } = CreateStaticReference("chinaeast2", "China East 2"); public static AzureLocation ChinaEast3 { get; } = CreateStaticReference("chinaeast3", "China East 3"); public static AzureLocation QatarCentral { get; } = CreateStaticReference("qatarcentral", "Qatar Central"); public static AzureLocation USDoDCentral { get; } = CreateStaticReference("usdodcentral", "US DoD Central"); public static AzureLocation USDoDEast { get; } = CreateStaticReference("usdodeast", "US DoD East"); public static AzureLocation USGovArizona { get; } = CreateStaticReference("usgovarizona", "US Gov Arizona"); public static AzureLocation USGovTexas { get; } = CreateStaticReference("usgovtexas", "US Gov Texas"); public static AzureLocation USGovVirginia { get; } = CreateStaticReference("usgovvirginia", "US Gov Virginia"); public static AzureLocation USGovIowa { get; } = CreateStaticReference("usgoviowa", "US Gov Iowa"); public static AzureLocation IsraelCentral { get; } = CreateStaticReference("israelcentral", "Israel Central"); public static AzureLocation ItalyNorth { get; } = CreateStaticReference("italynorth", "Italy North"); public static AzureLocation PolandCentral { get; } = CreateStaticReference("polandcentral", "Poland Central"); public static AzureLocation MexicoCentral { get; } = CreateStaticReference("mexicocentral", "Mexico Central"); public static AzureLocation SpainCentral { get; } = CreateStaticReference("spaincentral", "Spain Central"); public string Name { get; } public string? DisplayName { get; } public AzureLocation(string location) { if (location == null) { throw new ArgumentNullException("location"); } Name = GetNameFromDisplayName(location, out var foundSpace); string key = (foundSpace ? Name : location.ToLowerInvariant()); if (PublicCloudLocations.TryGetValue(key, out var value)) { Name = value.Name; DisplayName = value.DisplayName; } else { DisplayName = (foundSpace ? location : null); } } public AzureLocation(string name, string displayName) { if (name == null) { throw new ArgumentNullException("name"); } Name = name; DisplayName = displayName; } private static string GetNameFromDisplayName(string name, out bool foundSpace) { foundSpace = false; StringBuilder stringBuilder = new StringBuilder(); foreach (char c in name) { if (c == ' ') { foundSpace = true; } else { stringBuilder.Append(char.ToLowerInvariant(c)); } } if (!foundSpace) { return name; } return stringBuilder.ToString(); } private static AzureLocation CreateStaticReference(string name, string displayName) { AzureLocation azureLocation = new AzureLocation(name, displayName); PublicCloudLocations.Add(name, azureLocation); return azureLocation; } public override string ToString() { return Name; } public static implicit operator AzureLocation(string location) { if (location != null && PublicCloudLocations.TryGetValue(location, out var value)) { return value; } return new AzureLocation(location); } public bool Equals(AzureLocation other) { return Name == other.Name; } public static implicit operator string(AzureLocation location) { return location.ToString(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { if (obj == null) { return false; } if (!(obj is AzureLocation other)) { return false; } return Equals(other); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return Name.GetHashCode(); } public static bool operator ==(AzureLocation left, AzureLocation right) { return left.Equals(right); } public static bool operator !=(AzureLocation left, AzureLocation right) { return !left.Equals(right); } } internal class ChainingClassifier : ResponseClassifier { private class StatusCodeHandler : ResponseClassificationHandler { private (int Status, bool IsError)[] _statusCodes; public StatusCodeHandler((int Status, bool IsError)[] statusCodes) { _statusCodes = statusCodes; } public override bool TryClassify(HttpMessage message, out bool isError) { (int, bool)[] statusCodes = _statusCodes; for (int i = 0; i < statusCodes.Length; i++) { (int, bool) tuple = statusCodes[i]; if (tuple.Item1 == message.Response.Status) { isError = tuple.Item2; return true; } } isError = false; return false; } } private ResponseClassificationHandler[]? _handlers; private ResponseClassifier _endOfChain; public ChainingClassifier((int Status, bool IsError)[]? statusCodes, ResponseClassificationHandler[]? handlers, ResponseClassifier endOfChain) { if (handlers != null) { AddClassifiers(handlers); } if (statusCodes != null) { StatusCodeHandler[] array = new StatusCodeHandler[1] { new StatusCodeHandler(statusCodes) }; ResponseClassificationHandler[] array2 = array; AddClassifiers(new ReadOnlySpan<ResponseClassificationHandler>(array2)); } _endOfChain = endOfChain; } public override bool IsErrorResponse(HttpMessage message) { if (_handlers != null) { ResponseClassificationHandler[] handlers = _handlers; for (int i = 0; i < handlers.Length; i++) { if (handlers[i].TryClassify(message, out var isError)) { return isError; } } } return _endOfChain.IsErrorResponse(message); } private void AddClassifiers(ReadOnlySpan<ResponseClassificationHandler> handlers) { int num = ((_handlers != null) ? _handlers.Length : 0); Array.Resize(ref _handlers, num + handlers.Length); Span<ResponseClassificationHandler> destination = new Span<ResponseClassificationHandler>(_handlers, num, handlers.Length); handlers.CopyTo(destination); } } public abstract class ClientOptions { private HttpPipelineTransport _transport; internal bool IsCustomTransportSet { get; private set; } public static ClientOptions Default { get; private set; } = new DefaultClientOptions(); public HttpPipelineTransport Transport { get { return _transport; } set { _transport = value ?? throw new ArgumentNullException("value"); IsCustomTransportSet = true; } } public DiagnosticsOptions Diagnostics { get; } public RetryOptions Retry { get; } public HttpPipelinePolicy? RetryPolicy { get; set; } internal List<(HttpPipelinePosition Position, HttpPipelinePolicy Policy)>? Policies { get; private set; } internal static void ResetDefaultOptions() { Default = new DefaultClientOptions(); } protected ClientOptions() : this(Default, null) { } protected ClientOptions(DiagnosticsOptions? diagnostics) : this(Default, diagnostics) { } internal ClientOptions(ClientOptions? clientOptions, DiagnosticsOptions? diagnostics) { if (clientOptions != null) { Retry = new RetryOptions(clientOptions.Retry); RetryPolicy = clientOptions.RetryPolicy; Diagnostics = diagnostics ?? new DiagnosticsOptions(clientOptions.Diagnostics); _transport = clientOptions.Transport; if (clientOptions.Policies != null) { Policies = new List<(HttpPipelinePosition, HttpPipelinePolicy)>(clientOptions.Policies); } } else { _transport = HttpPipelineTransport.Create(); Diagnostics = new DiagnosticsOptions(null); Retry = new RetryOptions(null); } } public void AddPolicy(HttpPipelinePolicy policy, HttpPipelinePosition position) { if (position != 0 && position != HttpPipelinePosition.PerRetry && position != HttpPipelinePosition.BeforeTransport) { throw new ArgumentOutOfRangeException("position", position, null); } if (Policies == null) { List<(HttpPipelinePosition, HttpPipelinePolicy)> list2 = (Policies = new List<(HttpPipelinePosition, HttpPipelinePolicy)>()); } Policies.Add((position, policy));
deps/Microsoft.Bcl.AsyncInterfaces.dll
Decompiled a day agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Bcl.AsyncInterfaces")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides the IAsyncEnumerable<T> and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.\r\n\r\nCommonly Used Types:\r\nSystem.IAsyncDisposable\r\nSystem.Collections.Generic.IAsyncEnumerable\r\nSystem.Collections.Generic.IAsyncEnumerator")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("8.0.0.0")] [assembly: TypeForwardedTo(typeof(IAsyncEnumerable<>))] [assembly: TypeForwardedTo(typeof(IAsyncEnumerator<>))] [assembly: TypeForwardedTo(typeof(IAsyncDisposable))] [assembly: TypeForwardedTo(typeof(AsyncIteratorMethodBuilder))] [assembly: TypeForwardedTo(typeof(AsyncIteratorStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(ConfiguredAsyncDisposable))] [assembly: TypeForwardedTo(typeof(ConfiguredCancelableAsyncEnumerable<>))] [assembly: TypeForwardedTo(typeof(EnumeratorCancellationAttribute))] [assembly: TypeForwardedTo(typeof(ManualResetValueTaskSourceCore<>))] [assembly: TypeForwardedTo(typeof(TaskAsyncEnumerableExtensions))] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } }
deps/Microsoft.CognitiveServices.Speech.csharp.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Azure.AI.Common.Internal; using Azure.Core; using Microsoft.CognitiveServices.Speech.Audio; using Microsoft.CognitiveServices.Speech.Diagnostics.Logging; using Microsoft.CognitiveServices.Speech.Dialog; using Microsoft.CognitiveServices.Speech.Dialog.Internal; using Microsoft.CognitiveServices.Speech.Intent; using Microsoft.CognitiveServices.Speech.Internal; using Microsoft.CognitiveServices.Speech.Transcription; using Microsoft.CognitiveServices.Speech.Translation; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyConfiguration("ReleaseUnity")] [assembly: AssemblyCopyright("\ufffd Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Microsoft Cognitive Services Speech SDK")] [assembly: AssemblyFileVersion("1.44.0.28")] [assembly: AssemblyInformationalVersion("1.44.0+eaf8ce5f789cd9b50e1b7c3afd8ab6c9c521d29e")] [assembly: AssemblyProduct("Microsoft Cognitive Services Speech SDK")] [assembly: AssemblyTitle("Microsoft Cognitive Services Speech SDK")] [assembly: AssemblyVersion("1.44.0.28")] namespace Azure.AI.Common.Internal { public enum ValueKind { Error = -1, End = 0, Object = 123, Array = 91, String = 34, Number = 49, Boolean = 98, Null = 110, Unspecified = 63 } public class JsonValue : DisposableBase { [CompilerGenerated] private sealed class <get_Items>d__16 : IEnumerable<JsonValue>, IEnumerable, IEnumerator<JsonValue>, IDisposable, IEnumerator { private int <>1__state; private JsonValue <>2__current; private int <>l__initialThreadId; public JsonValue <>4__this; private int <i>5__1; JsonValue IEnumerator<JsonValue>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <get_Items>d__16(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <i>5__1 = 0; break; case 1: <>1__state = -1; <i>5__1++; break; } if (<i>5__1 < <>4__this.Count) { <>2__current = <>4__this[<i>5__1]; <>1__state = 1; return true; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<JsonValue> IEnumerable<JsonValue>.GetEnumerator() { <get_Items>d__16 result; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; result = this; } else { result = new <get_Items>d__16(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<JsonValue>)this).GetEnumerator(); } } private Func<InteropSafeHandle> _getHandle; private InteropSafeHandle _parser; private int _item; public int Count { get; } public ValueKind Kind { get; } public string Name { get; } public IEnumerable<JsonValue> Items { [IteratorStateMachine(typeof(<get_Items>d__16))] get { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() <get_Items>d__16 <get_Items>d__ = new <get_Items>d__16(-2); <get_Items>d__.<>4__this = this; return <get_Items>d__; } } public JsonValue this[int index] { get { int num = ai_core_json.ai_core_json_item_at(Handle, _item, index, null); IfFalseThrowHr(num < 0, SpxError.NotFound); return new JsonValue(_getHandle ?? ((Func<InteropSafeHandle>)(() => _parser)), num); } } public JsonValue this[string key] { get { int num = ai_core_json.ai_core_json_item_at(Handle, _item, 0, key); IfFalseThrowHr(num < 0, SpxError.NotFound); return new JsonValue(_getHandle ?? ((Func<InteropSafeHandle>)(() => _parser)), num); } } internal InteropSafeHandle Handle { get { CheckDisposed(); return _getHandle?.Invoke() ?? _parser; } } public static JsonValue Parse(string json) { InteropSafeHandle parser; int num = ai_core_json.ai_core_json_parser_create(out parser, json); IfFalseThrowHr(num < 0, SpxError.InvalidArgument, "Unable to parse json: " + ((json == null || json.Length <= 31) ? (json + "...") : json?.Substring(0, 32))); return new JsonValue(parser, null, num); } private JsonValue(InteropSafeHandle parser, Func<InteropSafeHandle> getHandle, int item) { _parser = parser; _getHandle = getHandle; _item = item; Count = ai_core_json.native.ai_core_json_item_count(Handle, _item); Kind = (ValueKind)ai_core_json.native.ai_core_json_value_kind(Handle, _item); Name = ai_core_json.ai_core_json_value_as_string_ptr(Handle, ai_core_json.native.ai_core_json_item_name(Handle, _item), null); } private JsonValue(Func<InteropSafeHandle> getHandle, int item) : this(null, getHandle ?? throw new ArgumentNullException("getHandle"), item) { } public bool HasValue(int index) { return ai_core_json.ai_core_json_item_at(Handle, _item, index, null) > 0; } public bool HasValue(string key) { return ai_core_json.ai_core_json_item_at(Handle, _item, 0, key) > 0; } public string AsString() { string text = ai_core_json.ai_core_json_value_as_string_ptr(Handle, _item, null); IfFalseThrowHr(text == null, SpxError.InvalidArgument, "Unable to get string value for json pair with name {Name}."); return text; } public string AsStringCopy() { string text = ai_core_json.ai_core_json_value_as_string_copy(Handle, _item, null); IfFalseThrowHr(text == null, SpxError.InvalidArgument, "Unable to get string value for json pair with name {Name}."); return text; } public long AsLong() { IfFalseThrowHr(Kind != ValueKind.Number, SpxError.InvalidArgument); return ai_core_json.native.ai_core_json_value_as_int(Handle, _item, 0L); } public ulong AsULong() { IfFalseThrowHr(Kind != ValueKind.Number, SpxError.InvalidArgument); return ai_core_json.native.ai_core_json_value_as_uint(Handle, _item, 0uL); } public double AsDouble() { IfFalseThrowHr(Kind != ValueKind.Number, SpxError.InvalidArgument); return ai_core_json.native.ai_core_json_value_as_double(Handle, _item, 0.0); } public float AsFloat() { return (float)AsDouble(); } public bool AsBool() { IfFalseThrowHr(Kind != ValueKind.Boolean, SpxError.InvalidArgument); return ai_core_json.native.ai_core_json_value_as_bool(Handle, _item, defaultValue: false); } public string AsJson() { return ai_core_json.ai_core_json_value_as_json_copy(Handle, _item); } public JsonValue[] AsArray() { IfFalseThrowHr(Kind != ValueKind.Array, SpxError.InvalidArgument); if (Count == 0) { return Array.Empty<JsonValue>(); } JsonValue[] array = new JsonValue[Count]; for (int i = 0; i < Count; i++) { array[i] = this[i]; } return array; } protected override void Dispose(bool disposeManaged) { if (disposeManaged) { _parser?.Dispose(); _parser = null; _getHandle = null; } } private static void IfFalseThrowHr(bool cond, IntPtr error, string errorMessage) { if (cond) { string message = string.Format(CultureInfo.CurrentCulture, "Exception with an error code: 0x{0:x} \n{errorMessage}", error); throw new ApplicationException(message); } } private static void IfFalseThrowHr(bool cond, IntPtr error) { IfFalseThrowHr(cond, error, string.Empty); } } public class JsonBuilder : DisposableBase { private Func<InteropSafeHandle> _getHandle; private InteropSafeHandle _builder; public int root { get; } internal InteropSafeHandle Handle { get { CheckDisposed(); return _getHandle?.Invoke() ?? _builder; } } public JsonBuilder() { root = ai_core_json.ai_core_json_builder_create(out _builder); } public int AddItem(int item, int index, string find) { return ai_core_json.ai_core_json_builder_add(_builder, item, index, find); } public void SetString(int item, string value) { using Utf8StringHandle str = new Utf8StringHandle(value); using Utf8StringHandle json = new Utf8StringHandle(null); int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, json, (UIntPtr)0uL, 34, str, (UIntPtr)(ulong)value.Length, boolean: false, 0, 0.0); IfTrueThrowHr(num != 0, (IntPtr)num); } public void SetJson(int item, string value) { using Utf8StringHandle json = new Utf8StringHandle(value); using Utf8StringHandle str = new Utf8StringHandle(null); int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, json, (UIntPtr)(ulong)value.Length, 123, str, (UIntPtr)0uL, boolean: false, 0, 0.0); IfTrueThrowHr(num != 0, (IntPtr)num); } public void SetBoolean(int item, bool value) { using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(null); int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, utf8StringHandle, (UIntPtr)0uL, 98, utf8StringHandle, (UIntPtr)0uL, value, 0, 0.0); IfTrueThrowHr(num != 0, (IntPtr)num); } public void SetInteger(int item, int value) { using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(null); int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, utf8StringHandle, (UIntPtr)0uL, 49, utf8StringHandle, (UIntPtr)0uL, boolean: false, value, 0.0); IfTrueThrowHr(num != 0, (IntPtr)num); } public void SetDouble(int item, double value) { using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(null); int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, utf8StringHandle, (UIntPtr)0uL, 49, utf8StringHandle, (UIntPtr)0uL, boolean: false, 0, value); IfTrueThrowHr(num != 0, (IntPtr)num); } public override string ToString() { return ai_core_json.ai_core_json_value_as_json_copy(Handle, root); } protected override void Dispose(bool disposeManaged) { if (disposeManaged) { _builder?.Dispose(); _builder = null; _getHandle = null; } } private static void IfTrueThrowHr(bool cond, IntPtr error, string errorMessage) { if (cond) { string message = string.Format(CultureInfo.CurrentCulture, "Exception with an error code: 0x{0:x} \n{errorMessage}", error); throw new ApplicationException(message); } } private static void IfTrueThrowHr(bool cond, IntPtr error) { IfTrueThrowHr(cond, error, string.Empty); } } internal static class ai_core_json { internal static class native { static native() { DotNetFrameworkAnyCpuSupport.Initialize(); } [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern IntPtr ai_core_string_create(Utf8StringHandle str, UIntPtr size); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern void ai_core_string_free(IntPtr str); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_parser_create(out IntPtr parser, Utf8StringHandle json, UIntPtr jsize); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] [return: MarshalAs(UnmanagedType.U1)] internal static extern bool ai_core_json_parser_handle_is_valid(InteropSafeHandle parser); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern IntPtr ai_core_json_parser_handle_release(IntPtr parser); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_item_count(InteropSafeHandle parserOrBuildder, int item); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_item_at(InteropSafeHandle parserOrBuilder, int item, int index, Utf8StringHandle find); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_item_next(InteropSafeHandle parserOrBuilder, int item); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_item_name(InteropSafeHandle parserOrBuilder, int item); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_value_kind(InteropSafeHandle parserOrBuilder, int item); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] [return: MarshalAs(UnmanagedType.U1)] internal static extern bool ai_core_json_value_as_bool(InteropSafeHandle parserOrBuilder, int item, bool defaultValue); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern double ai_core_json_value_as_double(InteropSafeHandle parserOrBuilder, int item, double defaultValue); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern long ai_core_json_value_as_int(InteropSafeHandle parserOrBuilder, int item, long defaultValue); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern ulong ai_core_json_value_as_uint(InteropSafeHandle parserOrBuilder, int item, ulong defaultValue); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern IntPtr ai_core_json_value_as_string_ptr(InteropSafeHandle parserOrBuilder, int item, out IntPtr size); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern IntPtr ai_core_json_value_as_string_copy(InteropSafeHandle parserOrBuilder, int item, Utf8StringHandle defaultValue); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern IntPtr ai_core_json_value_as_json_copy(InteropSafeHandle parserOrBuilder, int item); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_builder_create(out IntPtr builder, Utf8StringHandle json, UIntPtr jsize); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_builder_item_add(InteropSafeHandle builder, int item, int index, Utf8StringHandle find); [DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)] internal static extern int ai_core_json_builder_item_set(InteropSafeHandle builder, int item, Utf8StringHandle json, UIntPtr jsize, int kind, Utf8StringHandle str, UIntPtr ssize, bool boolean, int integer, double number); } internal static int ai_core_json_parser_create(out InteropSafeHandle parser, string json) { using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(json); IntPtr parser2; int result = native.ai_core_json_parser_create(out parser2, utf8StringHandle, (UIntPtr)utf8StringHandle.Length); parser = new InteropSafeHandle(parser2, (HandleRelease)native.ai_core_json_parser_handle_release); return result; } internal static int ai_core_json_builder_create(out InteropSafeHandle builder) { using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(""); IntPtr builder2; int result = native.ai_core_json_builder_create(out builder2, utf8StringHandle, (UIntPtr)utf8StringHandle.Length); builder = new InteropSafeHandle(builder2, (HandleRelease)native.ai_core_json_parser_handle_release); return result; } internal static int ai_core_json_builder_add(InteropSafeHandle builder, int item, int index, string find) { using Utf8StringHandle find2 = new Utf8StringHandle(find); return native.ai_core_json_builder_item_add(builder, item, index, find2); } internal static int ai_core_json_item_at(InteropSafeHandle parserOrBuilder, int item, int index, string find) { using Utf8StringHandle find2 = new Utf8StringHandle(find); return native.ai_core_json_item_at(parserOrBuilder, item, index, find2); } internal static string ai_core_json_value_as_string_ptr(InteropSafeHandle parserOrBuilder, int item, string defaultValue) { using (new Utf8StringHandle(defaultValue)) { IntPtr size; IntPtr native = ai_core_json.native.ai_core_json_value_as_string_ptr(parserOrBuilder, item, out size); return Utf8StringMarshaler.MarshalNativeToManaged(native, size.ToInt32()); } } internal static string ai_core_json_value_as_string_copy(InteropSafeHandle parserOrBuilder, int item, string defaultValue) { using Utf8StringHandle defaultValue2 = new Utf8StringHandle(defaultValue); using InteropSafeHandle interopSafeHandle = new InteropSafeHandle(native.ai_core_json_value_as_string_copy(parserOrBuilder, item, defaultValue2), (Action<IntPtr>)native.ai_core_string_free); return Utf8StringMarshaler.MarshalNativeToManaged(interopSafeHandle.DangerousGetHandle()); } internal static string ai_core_json_value_as_json_copy(InteropSafeHandle parserOrBuilder, int item) { using InteropSafeHandle interopSafeHandle = new InteropSafeHandle(native.ai_core_json_value_as_json_copy(parserOrBuilder, item), (Action<IntPtr>)native.ai_core_string_free); return Utf8StringMarshaler.MarshalNativeToManaged(interopSafeHandle.DangerousGetHandle()); } } } namespace Microsoft.CognitiveServices.Speech { public class AudioDataStream : IDisposable { internal volatile bool disposed = false; internal InteropSafeHandle streamHandle; public PropertyCollection Properties { get; private set; } public static AudioDataStream FromWavFileInput(string fileName) { IntPtr audioStream = IntPtr.Zero; IntPtr fileName2 = Utf8StringMarshaler.MarshalManagedToNative(fileName); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_create_from_file(out audioStream, fileName2)); return new AudioDataStream(audioStream); } public static AudioDataStream FromResult(SpeechSynthesisResult result) { SpxExceptionThrower.ThrowIfNull(result); IntPtr audioStream = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_create_from_result(out audioStream, result.resultHandle)); return new AudioDataStream(audioStream); } public static AudioDataStream FromResult(KeywordRecognitionResult result) { SpxExceptionThrower.ThrowIfNull(result); IntPtr audioStream = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_create_from_keyword_result(out audioStream, result.resultHandle)); return new AudioDataStream(audioStream); } internal AudioDataStream(IntPtr streamHandlePtr) { SpxExceptionThrower.ThrowIfNull(streamHandlePtr); streamHandle = new InteropSafeHandle(streamHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_release); IntPtr propbag = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_get_property_bag(streamHandle, out propbag)); Properties = new PropertyCollection(propbag); } public StreamStatus GetStatus() { SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_get_status(streamHandle, out var status)); return status; } public bool CanReadData(uint bytesRequested) { SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); return Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_can_read_data(streamHandle, bytesRequested); } public bool CanReadData(uint pos, uint bytesRequested) { SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); return Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_can_read_data_from_position(streamHandle, bytesRequested, pos); } public uint ReadData(byte[] buffer) { SpxExceptionThrower.ThrowIfNull(buffer, "buffer can not be Null."); SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); IntPtr intPtr = Marshal.AllocHGlobal(buffer.Length); uint filledSize; try { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_read(streamHandle, intPtr, (uint)buffer.Length, out filledSize)); filledSize %= int.MaxValue; Marshal.Copy(intPtr, buffer, 0, (int)filledSize); } finally { Marshal.FreeHGlobal(intPtr); } return filledSize; } public uint ReadData(uint pos, byte[] buffer) { SpxExceptionThrower.ThrowIfNull(buffer, "buffer can not be Null."); SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); IntPtr intPtr = Marshal.AllocHGlobal(buffer.Length); uint filledSize; try { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_read_from_position(streamHandle, intPtr, (uint)buffer.Length, pos, out filledSize)); filledSize %= int.MaxValue; Marshal.Copy(intPtr, buffer, 0, (int)filledSize); } finally { Marshal.FreeHGlobal(intPtr); } return filledSize; } public Task SaveToWaveFileAsync(string fileName) { SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); return Task.Run(delegate { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_save_to_wave_file(streamHandle, fileName)); }); } public void SetPosition(uint pos) { SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_set_position(streamHandle, pos)); } public uint GetPosition() { SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_get_position(streamHandle, out var position)); return position; } public void DetachInput() { SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle."); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_detach_input(streamHandle)); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { Properties?.Close(); streamHandle?.Dispose(); } disposed = true; } } } public class AutoDetectSourceLanguageConfig { internal InteropSafeHandle configHandle; internal AutoDetectSourceLanguageConfig(IntPtr configPtr) { SpxExceptionThrower.ThrowIfNull(configPtr); configHandle = new InteropSafeHandle(configPtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.auto_detect_source_lang_config_release); } public static AutoDetectSourceLanguageConfig FromOpenRange() { IntPtr hAutoDetectSourceLanguageconfig = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.create_auto_detect_source_lang_config_from_open_range(out hAutoDetectSourceLanguageconfig)); return new AutoDetectSourceLanguageConfig(hAutoDetectSourceLanguageconfig); } public static AutoDetectSourceLanguageConfig FromLanguages(string[] languages) { if (languages == null || languages.Length == 0) { throw new ArgumentNullException("languages"); } foreach (string text in languages) { if (string.IsNullOrEmpty(text)) { throw new ArgumentNullException(text, "language in languages cannot be null or empty"); } } IntPtr hAutoDetectSourceLanguageconfig = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.create_auto_detect_source_lang_config_from_languages(out hAutoDetectSourceLanguageconfig, string.Join(",", languages))); return new AutoDetectSourceLanguageConfig(hAutoDetectSourceLanguageconfig); } public static AutoDetectSourceLanguageConfig FromSourceLanguageConfigs(SourceLanguageConfig[] sourceLanguageConfigs) { if (sourceLanguageConfigs == null || sourceLanguageConfigs.Length == 0) { throw new ArgumentNullException("sourceLanguageConfigs"); } IntPtr hAutoDetectSourceLanguageconfig = IntPtr.Zero; bool flag = true; foreach (SourceLanguageConfig sourceLanguageConfig in sourceLanguageConfigs) { if (sourceLanguageConfig == null) { throw new ArgumentNullException("sourceLanguageConfig in sourceLanguageConfigs cannot be null"); } if (flag) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.create_auto_detect_source_lang_config_from_source_lang_config(out hAutoDetectSourceLanguageconfig, sourceLanguageConfig.configHandle)); flag = false; } else { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.add_source_lang_config_to_auto_detect_source_lang_config(hAutoDetectSourceLanguageconfig, sourceLanguageConfig.configHandle)); } } return new AutoDetectSourceLanguageConfig(hAutoDetectSourceLanguageconfig); } } public class AutoDetectSourceLanguageResult { public string Language { get; } public static AutoDetectSourceLanguageResult FromResult(SpeechRecognitionResult result) { return new AutoDetectSourceLanguageResult(result); } public static AutoDetectSourceLanguageResult FromResult(TranslationRecognitionResult result) { return new AutoDetectSourceLanguageResult(result); } internal AutoDetectSourceLanguageResult(RecognitionResult result) { SpxExceptionThrower.ThrowIfNull(result); Language = result.Properties.GetProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguageResult); } } public sealed class Connection : IDisposable { private GCHandle gch; private volatile bool disposed = false; private volatile bool isDisposing = false; private InteropSafeHandle connectionHandle; private ConnectionCallbackFunctionDelegate connectedCallbackDelegate; private ConnectionCallbackFunctionDelegate disconnectedCallbackDelegate; private ConnectionCallbackFunctionDelegate messageReceivedCallbackDelegate; private object connectionLock = new object(); private int activeAsyncConnectionCounter = 0; private PropertyCollection Properties { get; set; } private event EventHandler<ConnectionEventArgs> _Connected; private event EventHandler<ConnectionEventArgs> _Disconnected; private event EventHandler<ConnectionMessageEventArgs> _MessageReceived; public event EventHandler<ConnectionEventArgs> Connected { add { if (this._Connected == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_connected_set_callback(connectionHandle, connectedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _Connected += value; } remove { _Connected -= value; if (this._Connected == null && connectionHandle != null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_connected_set_callback(connectionHandle, null, IntPtr.Zero)); } } } public event EventHandler<ConnectionEventArgs> Disconnected { add { if (this._Disconnected == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_disconnected_set_callback(connectionHandle, disconnectedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _Disconnected += value; } remove { _Disconnected -= value; if (this._Disconnected == null && connectionHandle != null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_disconnected_set_callback(connectionHandle, null, IntPtr.Zero)); } } } public event EventHandler<ConnectionMessageEventArgs> MessageReceived { add { if (this._MessageReceived == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_set_callback(connectionHandle, messageReceivedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _MessageReceived += value; } remove { _MessageReceived -= value; if (this._MessageReceived == null && connectionHandle != null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_set_callback(connectionHandle, null, IntPtr.Zero)); } } } public static Connection FromRecognizer(Recognizer recognizer) { SpxExceptionThrower.ThrowIfNull(recognizer, "null recognizer"); IntPtr zero = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_from_recognizer(recognizer.recoHandle, out zero)); return new Connection(zero); } public static Connection FromConversationTranslator(Microsoft.CognitiveServices.Speech.Transcription.ConversationTranslator convTrans) { SpxExceptionThrower.ThrowIfNull(convTrans, "null conversation translator"); IntPtr zero = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_from_conversation_translator(convTrans._nativeHandle, out zero)); return new Connection(zero); } public static Connection FromDialogServiceConnector(Microsoft.CognitiveServices.Speech.Dialog.DialogServiceConnector dialogServiceConnector) { SpxExceptionThrower.ThrowIfNull(dialogServiceConnector, "null dialog service connector"); IntPtr zero = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_from_dialog_service_connector(dialogServiceConnector.dialogServiceConnectorHandle, out zero)); return new Connection(zero); } public static Connection FromSpeechSynthesizer(SpeechSynthesizer speechSynthesizer) { SpxExceptionThrower.ThrowIfNull(speechSynthesizer, "null speech synthesizer"); IntPtr zero = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_from_speech_synthesizer(speechSynthesizer.synthHandle, out zero)); return new Connection(zero); } ~Connection() { isDisposing = true; Dispose(disposing: false); } public void Dispose() { try { isDisposing = true; lock (connectionLock) { if (activeAsyncConnectionCounter != 0) { throw new InvalidOperationException("Cannot dispose a connection while async operation is running. Await async connections to avoid unexpected disposals."); } } } finally { Dispose(disposing: true); GC.SuppressFinalize(this); } } private void Dispose(bool disposing) { if (!disposed) { if (connectionHandle != null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_connected_set_callback(connectionHandle, null, IntPtr.Zero)); SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_disconnected_set_callback(connectionHandle, null, IntPtr.Zero)); SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_set_callback(connectionHandle, null, IntPtr.Zero)); } if (disposing) { connectionHandle?.Dispose(); Properties?.Close(); } if (gch.IsAllocated) { gch.Free(); } disposed = true; connectedCallbackDelegate = null; disconnectedCallbackDelegate = null; messageReceivedCallbackDelegate = null; } } internal Connection(IntPtr connectionPtr) { SpxExceptionThrower.ThrowIfNull(connectionPtr, "Invalid connectionPtr."); connectionHandle = new InteropSafeHandle(connectionPtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_handle_release); connectedCallbackDelegate = FireEvent_Connected; disconnectedCallbackDelegate = FireEvent_Disconnected; messageReceivedCallbackDelegate = FireEvent_MessageReceived; IntPtr propbag = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_get_property_bag(connectionHandle, out propbag)); if (propbag != IntPtr.Zero) { Properties = new PropertyCollection(propbag); } gch = GCHandle.Alloc(this, GCHandleType.Weak); } public void Open(bool forContinuousRecognition) { bool item = connectionHandle != null; IntPtr invalidHandle = SpxError.InvalidHandle; SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32()); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_open(connectionHandle, forContinuousRecognition)); } public void Close() { bool item = connectionHandle != null; IntPtr invalidHandle = SpxError.InvalidHandle; SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32()); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_close(connectionHandle)); } public Task SendMessageAsync(string path, string payload) { InteropSafeHandle asyncHandle = null; Utf8StringHandle payloadString = new Utf8StringHandle(payload); DoAsyncConnectionAction(delegate { asyncHandle = SendMessage(path, payloadString); }); string s = Properties?.GetProperty("SPEECH-SendMessageTimeout"); if (!uint.TryParse(s, out var timeout)) { timeout = 90000u; } return Task.Run(delegate { DoAsyncConnectionAction(delegate { try { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_send_message_wait_for(asyncHandle, timeout)); } finally { payloadString.Dispose(); asyncHandle.Dispose(); } }); }); } public Task SendMessageAsync(string path, byte[] payload, uint size) { InteropSafeHandle asyncHandle = null; DoAsyncConnectionAction(delegate { asyncHandle = SendMessageData(path, payload, size); }); string s = Properties?.GetProperty("SPEECH-SendMessageTimeout"); if (!uint.TryParse(s, out var timeout)) { timeout = 90000u; } return Task.Run(delegate { DoAsyncConnectionAction(delegate { try { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_send_message_wait_for(asyncHandle, timeout)); } finally { asyncHandle.Dispose(); } }); }); } public void SetMessageProperty(string path, string propertyName, string propertyValue) { bool item = connectionHandle != null; IntPtr invalidHandle = SpxError.InvalidHandle; SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32()); IntPtr name = Utf8StringMarshaler.MarshalManagedToNative(propertyName); IntPtr value = Utf8StringMarshaler.MarshalManagedToNative(propertyValue); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_set_message_property(connectionHandle, path, name, value)); } [MonoPInvokeCallback(typeof(ConnectionCallbackFunctionDelegate))] private static void FireEvent_Connected(IntPtr hevent, IntPtr pvContext) { try { Connection objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Connection>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { ConnectionEventArgs e = new ConnectionEventArgs(hevent); objectFromWeakHandle._Connected?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } [MonoPInvokeCallback(typeof(ConnectionCallbackFunctionDelegate))] private static void FireEvent_Disconnected(IntPtr hevent, IntPtr pvContext) { try { Connection objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Connection>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { ConnectionEventArgs e = new ConnectionEventArgs(hevent); objectFromWeakHandle._Disconnected?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } [MonoPInvokeCallback(typeof(ConnectionCallbackFunctionDelegate))] private static void FireEvent_MessageReceived(IntPtr hevent, IntPtr pvContext) { try { Connection objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Connection>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { ConnectionMessageEventArgs e = new ConnectionMessageEventArgs(hevent); objectFromWeakHandle._MessageReceived?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } private void DoAsyncConnectionAction(Action connectionImplAction) { lock (connectionLock) { activeAsyncConnectionCounter++; } if (disposed || isDisposing) { throw new ObjectDisposedException(GetType().Name); } try { connectionImplAction(); } finally { lock (connectionLock) { activeAsyncConnectionCounter--; } } } internal InteropSafeHandle SendMessage(string path, Utf8StringHandle payload) { IntPtr asyncHandle = IntPtr.Zero; bool item = connectionHandle != null; IntPtr invalidHandle = SpxError.InvalidHandle; SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32()); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_send_message_async(connectionHandle, path, payload, out asyncHandle)); return new InteropSafeHandle(asyncHandle, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_async_handle_release); } internal InteropSafeHandle SendMessageData(string path, byte[] payload, uint size) { IntPtr asyncHandle = IntPtr.Zero; bool item = connectionHandle != null; IntPtr invalidHandle = SpxError.InvalidHandle; SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32()); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_send_message_data_async(connectionHandle, path, payload, size, out asyncHandle)); return new InteropSafeHandle(asyncHandle, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_async_handle_release); } } public sealed class ConnectionEventArgs : SessionEventArgs { internal ConnectionEventArgs(IntPtr eventHandlePtr) : base(eventHandlePtr) { } } internal enum ConnectionEventType { ConnectedEvent, DisconnectedEvent } public class ConnectionMessage { internal InteropSafeHandle connectionMessageHandle; public string Path { get; } public PropertyCollection Properties { get; private set; } internal ConnectionMessage(IntPtr connectionMessageHandlePtr) { SpxExceptionThrower.ThrowIfNull(connectionMessageHandlePtr); connectionMessageHandle = new InteropSafeHandle(connectionMessageHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_handle_release); IntPtr propbag = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_get_property_bag(connectionMessageHandle, out propbag)); Properties = new PropertyCollection(propbag); Path = Properties.GetProperty("connection.message.path"); } public bool IsTextMessage() { SpxExceptionThrower.ThrowIfNull(connectionMessageHandle); return Properties.GetProperty("connection.message.type") == "text"; } public bool IsBinaryMessage() { SpxExceptionThrower.ThrowIfNull(connectionMessageHandle); return Properties.GetProperty("connection.message.type") == "binary"; } public string GetTextMessage() { SpxExceptionThrower.ThrowIfNull(connectionMessageHandle); return Properties.GetProperty("connection.message.text.message"); } public byte[] GetBinaryMessage() { SpxExceptionThrower.ThrowIfNull(connectionMessageHandle); uint num = Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_get_data_size(connectionMessageHandle); IntPtr intPtr = Marshal.AllocHGlobal((int)num); try { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_get_data(connectionMessageHandle, intPtr, num)); byte[] array = new byte[num]; Marshal.Copy(intPtr, array, 0, (int)num); return array; } finally { Marshal.FreeHGlobal(intPtr); } } public override string ToString() { return IsTextMessage() ? string.Format(CultureInfo.InvariantCulture, "Path:{0} Type:text Message:{1}", Path, GetTextMessage()) : string.Format(CultureInfo.InvariantCulture, "Path:{0} Type:binary Size:{1}", Path, GetBinaryMessage().Length); } } public sealed class ConnectionMessageEventArgs : System.EventArgs { internal InteropSafeHandle eventHandle; public ConnectionMessage Message { get; } internal ConnectionMessageEventArgs(IntPtr eventHandlePtr) { SpxExceptionThrower.ThrowIfNull(eventHandlePtr); eventHandle = new InteropSafeHandle(eventHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_event_handle_release); IntPtr hcm = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_event_get_message(eventHandle, out hcm)); Message = new ConnectionMessage(hcm); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Message: {0}.", Message.ToString()); } } [DataContract] internal sealed class DetailedSpeechRecognitionResultCollection { [DataMember] public IEnumerable<DetailedSpeechRecognitionResult> NBest { get; set; } } [DataContract] public sealed class DetailedSpeechRecognitionResult { [DataMember] public double Confidence { get; private set; } [DataMember(Name = "Display")] public string Text { get; private set; } [DataMember(Name = "Lexical")] public string LexicalForm { get; private set; } [DataMember(Name = "ITN")] public string NormalizedForm { get; private set; } [DataMember(Name = "MaskedITN")] public string MaskedNormalizedForm { get; private set; } [DataMember(Name = "PronunciationAssessment")] internal SentenceLevelPronunciationAssessmentResult PronunciationAssessment { get; private set; } [DataMember(Name = "ContentAssessment")] internal ContentAssessmentResult ContentAssessmentResult { get; private set; } [DataMember(Name = "Words")] public IEnumerable<WordLevelTimingResult> Words { get; private set; } [DataMember(Name = "DisplayWords")] public IEnumerable<WordLevelTimingResult> DisplayWords { get; private set; } internal DetailedSpeechRecognitionResult() { } internal DetailedSpeechRecognitionResult(double confidence, string text, string lexicalForm, string normalizedForm) { Confidence = confidence; Text = text; LexicalForm = lexicalForm; NormalizedForm = normalizedForm; MaskedNormalizedForm = normalizedForm; } } [DataContract] public sealed class WordLevelTimingResult { [DataMember] public double Confidence { get; private set; } [DataMember] public int Duration { get; private set; } [DataMember] public long Offset { get; private set; } [DataMember] public string Word { get; private set; } [DataMember(Name = "PronunciationAssessment")] internal WordLevelPronunciationAssessmentResult PronunciationAssessment { get; private set; } [DataMember(Name = "Phonemes")] internal IEnumerable<PhonemeLevelTimingResult> Phonemes { get; private set; } [DataMember(Name = "Syllables")] internal IEnumerable<SyllableLevelTimingResult> Syllables { get; private set; } internal WordLevelTimingResult() { } internal WordLevelTimingResult(int duration, long offset, string word) { Duration = duration; Offset = offset; Word = word; } } [DataContract] public sealed class PhonemeLevelTimingResult { [DataMember] public int Duration { get; private set; } [DataMember] public long Offset { get; private set; } [DataMember] public string Phoneme { get; private set; } public double AccuracyScore => PronunciationAssessment?.AccuracyScore ?? 0.0; public IEnumerable<PronunciationAssessmentNBestPhoneme> NBestPhonemes => PronunciationAssessment?.NBestPhonemes; [DataMember(Name = "PronunciationAssessment")] private PronunciationAssessmentPhonemeResult PronunciationAssessment { get; set; } internal PhonemeLevelTimingResult() { } } [DataContract] public sealed class SyllableLevelTimingResult { [DataMember] public int Duration { get; private set; } [DataMember] public long Offset { get; private set; } [DataMember] public string Syllable { get; private set; } [DataMember] public string Grapheme { get; private set; } public double AccuracyScore => PronunciationAssessment?.AccuracyScore ?? 0.0; [DataMember(Name = "PronunciationAssessment")] private PronunciationAssessmentAccuracyScore PronunciationAssessment { get; set; } internal SyllableLevelTimingResult() { } } [DataContract] internal sealed class SentenceLevelPronunciationAssessmentResult { [DataMember] public double AccuracyScore { get; private set; } [DataMember(Name = "PronScore")] public double PronunciationScore { get; private set; } [DataMember] public double CompletenessScore { get; private set; } [DataMember] public double FluencyScore { get; private set; } [DataMember] public double ProsodyScore { get; private set; } } [DataContract] internal sealed class WordLevelPronunciationAssessmentResult { [DataMember] public double AccuracyScore { get; private set; } [DataMember] public string ErrorType { get; private set; } } [DataContract] internal class PronunciationAssessmentAccuracyScore { [DataMember] public double AccuracyScore { get; private set; } } [DataContract] public sealed class PronunciationAssessmentNBestPhoneme { [DataMember] public string Phoneme { get; private set; } [DataMember] public double Score { get; private set; } } [DataContract] internal sealed class PronunciationAssessmentPhonemeResult : PronunciationAssessmentAccuracyScore { [DataMember] public IEnumerable<PronunciationAssessmentNBestPhoneme> NBestPhonemes { get; private set; } } [DataContract] public sealed class ContentAssessmentResult { [DataMember] public double GrammarScore { get; private set; } [DataMember] public double VocabularyScore { get; private set; } [DataMember] public double TopicScore { get; private set; } } public sealed class EmbeddedSpeechConfig { private SpeechConfig config; internal InteropSafeHandle configHandle => config.configHandle; public string SpeechRecognitionModelName => GetProperty(PropertyId.SpeechServiceConnection_RecoModelName); public OutputFormat SpeechRecognitionOutputFormat { get { return config.OutputFormat; } set { config.OutputFormat = value; } } public string SpeechSynthesisVoiceName => GetProperty(PropertyId.SpeechServiceConnection_SynthOfflineVoice); public string SpeechSynthesisOutputFormat => config.SpeechSynthesisOutputFormat; public string SpeechTranslationModelName => GetProperty(PropertyId.SpeechTranslation_ModelName); public string KeywordRecognitionModelName => GetProperty(PropertyId.KeywordRecognition_ModelName); internal EmbeddedSpeechConfig(IntPtr handle) { config = new SpeechConfig(handle); } public static EmbeddedSpeechConfig FromPath(string path) { IntPtr zero = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_create(out zero)); if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(path, "path cannot be null or empty"); } SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_add_path(zero, path)); return new EmbeddedSpeechConfig(zero); } public static EmbeddedSpeechConfig FromPaths(string[] paths) { if (paths == null || paths.Length == 0) { throw new ArgumentNullException("paths"); } IntPtr zero = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_create(out zero)); foreach (string text in paths) { if (string.IsNullOrWhiteSpace(text)) { throw new ArgumentNullException(text, "path cannot be null or empty"); } SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_add_path(zero, text)); } return new EmbeddedSpeechConfig(zero); } public ReadOnlyCollection<SpeechRecognitionModel> GetSpeechRecognitionModels() { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_get_num_speech_reco_models(configHandle, out var numModels)); List<SpeechRecognitionModel> list = new List<SpeechRecognitionModel>(); IntPtr model = IntPtr.Zero; try { for (uint num = 0u; num < numModels; num++) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_get_speech_reco_model(configHandle, num, out model)); if (model != Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.SPXHANDLE_INVALID) { list.Add(new SpeechRecognitionModel(model)); model = IntPtr.Zero; } } } catch { foreach (SpeechRecognitionModel item in list) { item.Dispose(); } throw; } finally { if (model != Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.SPXHANDLE_INVALID && model != IntPtr.Zero) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.SpeechRecognitionModel.speech_recognition_model_handle_release(model)); } } return new ReadOnlyCollection<SpeechRecognitionModel>(list); } public void SetProperty(string name, string value) { config.SetProperty(name, value); } public void SetProperty(PropertyId id, string value) { config.SetProperty(id, value); } public string GetProperty(string name) { return config.GetProperty(name); } public string GetProperty(PropertyId id) { return config.GetProperty(id); } public void SetSpeechRecognitionModel(string name, string license) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_set_speech_recognition_model(configHandle, name, license)); } public void SetProfanity(ProfanityOption profanity) { config.SetProfanity(profanity); } public void SetSpeechSynthesisVoice(string name, string license) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_set_speech_synthesis_voice(configHandle, name, license)); } public void SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat format) { config.SetSpeechSynthesisOutputFormat(format); } public ReadOnlyCollection<SpeechTranslationModel> GetSpeechTranslationModels() { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_get_num_speech_translation_models(configHandle, out var numModels)); List<SpeechTranslationModel> list = new List<SpeechTranslationModel>(); IntPtr model = IntPtr.Zero; try { for (uint num = 0u; num < numModels; num++) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_get_speech_translation_model(configHandle, num, out model)); if (model != Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.SPXHANDLE_INVALID) { list.Add(new SpeechTranslationModel(model)); model = IntPtr.Zero; } } } catch { foreach (SpeechTranslationModel item in list) { item.Dispose(); } throw; } finally { if (model != Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.SPXHANDLE_INVALID && model != IntPtr.Zero) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.SpeechTranslationModel.speech_translation_model_handle_release(model)); } } return new ReadOnlyCollection<SpeechTranslationModel>(list); } public void SetSpeechTranslationModel(string name, string license) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_set_speech_translation_model(configHandle, name, license)); } public void SetKeywordRecognitionModel(string name, string license) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_set_keyword_recognition_model(configHandle, name, license)); } } public sealed class HybridSpeechConfig { private SpeechConfig config; internal InteropSafeHandle configHandle => config.configHandle; public OutputFormat SpeechRecognitionOutputFormat { get { return config.OutputFormat; } set { config.OutputFormat = value; } } public string SpeechSynthesisOutputFormat => config.SpeechSynthesisOutputFormat; internal HybridSpeechConfig(IntPtr handle) { config = new SpeechConfig(handle); } public static HybridSpeechConfig FromConfigs(SpeechConfig cloudSpeechConfig, EmbeddedSpeechConfig embeddedSpeechConfig) { if (cloudSpeechConfig == null) { throw new ArgumentNullException("cloudSpeechConfig"); } if (embeddedSpeechConfig == null) { throw new ArgumentNullException("embeddedSpeechConfig"); } IntPtr zero = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.HybridSpeechConfig.hybrid_speech_config_create(out zero, cloudSpeechConfig.configHandle, embeddedSpeechConfig.configHandle)); return new HybridSpeechConfig(zero); } public void SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat format) { config.SetSpeechSynthesisOutputFormat(format); } public void SetProperty(string name, string value) { config.SetProperty(name, value); } public void SetProperty(PropertyId id, string value) { config.SetProperty(id, value); } public string GetProperty(string name) { return config.GetProperty(name); } public string GetProperty(PropertyId id) { return config.GetProperty(id); } } public sealed class KeywordRecognitionModel : IDisposable { private bool disposed = false; internal InteropSafeHandle keywordHandle; public static KeywordRecognitionModel FromFile(string fileName) { IntPtr kwmodel = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_create_from_file(fileName, out kwmodel)); return new KeywordRecognitionModel(kwmodel); } public static KeywordRecognitionModel FromConfig(EmbeddedSpeechConfig embeddedSpeechConfig) { if (embeddedSpeechConfig == null) { throw new ArgumentNullException("embeddedSpeechConfig"); } IntPtr keywordModel = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_create_from_config(embeddedSpeechConfig.configHandle, out keywordModel)); return new KeywordRecognitionModel(keywordModel); } public static KeywordRecognitionModel FromConfig(EmbeddedSpeechConfig embeddedSpeechConfig, string[] userDefinedWakeWords) { if (embeddedSpeechConfig == null) { throw new ArgumentNullException("embeddedSpeechConfig"); } IntPtr keywordModel = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_create_from_config(embeddedSpeechConfig.configHandle, out keywordModel)); foreach (string text in userDefinedWakeWords) { if (string.IsNullOrWhiteSpace(text)) { throw new ArgumentNullException(text, "wake word cannot be null or empty"); } SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_add_user_defined_wake_word(keywordModel, text)); } return new KeywordRecognitionModel(keywordModel); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (!disposed) { if (disposing) { keywordHandle?.Dispose(); } disposed = true; } } private KeywordRecognitionModel(IntPtr keywordHandlePtr) { keywordHandle = new InteropSafeHandle(keywordHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_handle_release); } } public class KeywordRecognitionEventArgs : RecognitionEventArgs { public KeywordRecognitionResult Result { get; } internal KeywordRecognitionEventArgs(IntPtr eventHandlePtr) : base(eventHandlePtr) { IntPtr result = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognition_event_get_result(eventHandle, out result)); Result = new KeywordRecognitionResult(result); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "SessionId:{0} ResultId:{1} Reason:{2} Recognized text:<{3}>.", base.SessionId, Result.ResultId, Result.Reason, Result.Text); } } public class KeywordRecognitionResult : RecognitionResult { internal KeywordRecognitionResult(IntPtr resultPtr) : base(resultPtr) { } } public sealed class KeywordRecognizer : IDisposable { private GCHandle gch; private SpeechRecognizer recognizer; private Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioInputKeepAlive; private volatile bool isDisposing = false; private CallbackFunctionDelegate recognizedCallbackDelegate; public PropertyCollection Properties => recognizer.Properties; public event EventHandler<KeywordRecognitionEventArgs> Recognized { add { if (this._Recognized == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognized_set_callback(recognizer.recoHandle, recognizedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _Recognized += value; } remove { _Recognized -= value; if (this._Recognized == null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognized_set_callback(recognizer.recoHandle, null, IntPtr.Zero)); } } } public event EventHandler<SpeechRecognitionCanceledEventArgs> Canceled { add { recognizer.Canceled += value; } remove { recognizer.Canceled -= value; } } private event EventHandler<KeywordRecognitionEventArgs> _Recognized; public KeywordRecognizer(Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig) { Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig2 = ((audioConfig == null) ? Microsoft.CognitiveServices.Speech.Audio.AudioConfig.FromDefaultMicrophoneInput() : audioConfig); try { recognizer = new SpeechRecognizer(Recognizer.FromConfig(SpxFactory.recognizer_create_keyword_recognizer_from_audio_config, audioConfig2)); recognizedCallbackDelegate = FireEvent_Recognized; gch = GCHandle.Alloc(this, GCHandleType.Weak); } finally { if (audioConfig == null) { audioConfig2.Dispose(); audioConfig2 = null; } audioInputKeepAlive = audioConfig; } } public Task<KeywordRecognitionResult> RecognizeOnceAsync(KeywordRecognitionModel model) { return Task.Run(delegate { KeywordRecognitionResult result = null; recognizer.DoAsyncRecognitionAction(delegate { IntPtr result2 = IntPtr.Zero; SpxExceptionThrower.ThrowIfNull(recognizer.recoHandle, "Invalid recognizer handle"); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognize_keyword_once(recognizer.recoHandle, model.keywordHandle, out result2)); result = new KeywordRecognitionResult(result2); }); return result; }); } public Task StopRecognitionAsync() { return recognizer.StopKeywordRecognitionAsync(); } public void Dispose() { if (!isDisposing) { isDisposing = true; recognizedCallbackDelegate = null; SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognized_set_callback(recognizer.recoHandle, null, IntPtr.Zero)); recognizer.Dispose(); audioInputKeepAlive = null; } } [MonoPInvokeCallback(typeof(CallbackFunctionDelegate))] private static void FireEvent_Recognized(IntPtr hreco, IntPtr hevent, IntPtr pvContext) { try { KeywordRecognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<KeywordRecognizer>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { KeywordRecognitionEventArgs e = new KeywordRecognitionEventArgs(hevent); objectFromWeakHandle._Recognized?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } } public enum NoMatchReason { NotRecognized = 1, InitialSilenceTimeout, InitialBabbleTimeout, KeywordNotRecognized, EndSilenceTimeout } public enum OutputFormat { Simple, Detailed } public enum ProfanityOption { Masked, Removed, Raw } public class PropertyCollection { private InteropSafeHandle propbagHandle; protected internal PropertyCollection(IntPtr propertyBagPtr) { if (propertyBagPtr != IntPtr.Zero) { propbagHandle = new InteropSafeHandle(propertyBagPtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_release); } } public virtual void Close() { propbagHandle.Dispose(); } public virtual string GetProperty(PropertyId id) { SpxExceptionThrower.ThrowIfNull(propbagHandle); return GetPropertyString(propbagHandle, (int)id, null, ""); } public virtual string GetProperty(string propertyName) { SpxExceptionThrower.ThrowIfNull(propbagHandle); return GetPropertyString(propbagHandle, -1, propertyName, ""); } public virtual string GetProperty(PropertyId id, string defaultValue) { SpxExceptionThrower.ThrowIfNull(propbagHandle); return GetPropertyString(propbagHandle, (int)id, null, defaultValue); } public virtual string GetProperty(string propertyName, string defaultValue) { SpxExceptionThrower.ThrowIfNull(propbagHandle); return GetPropertyString(propbagHandle, -1, propertyName, defaultValue); } public virtual void SetProperty(PropertyId id, string value) { SpxExceptionThrower.ThrowIfNull(propbagHandle); IntPtr intPtr = Utf8StringMarshaler.MarshalManagedToNative(value); try { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_set_string(propbagHandle, (int)id, IntPtr.Zero, intPtr)); } finally { Marshal.FreeHGlobal(intPtr); } } public virtual void SetProperty(string propertyName, string value) { SpxExceptionThrower.ThrowIfNull(propbagHandle); IntPtr intPtr = Utf8StringMarshaler.MarshalManagedToNative(value); IntPtr intPtr2 = Utf8StringMarshaler.MarshalManagedToNative(propertyName); try { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_set_string(propbagHandle, -1, intPtr2, intPtr)); } finally { Marshal.FreeHGlobal(intPtr); Marshal.FreeHGlobal(intPtr2); } } private string GetPropertyString(InteropSafeHandle propHandle, int id, string name, string defaultValue) { string result = string.Empty; IntPtr intPtr = Utf8StringMarshaler.MarshalManagedToNative(name); IntPtr intPtr2 = Utf8StringMarshaler.MarshalManagedToNative(defaultValue); try { IntPtr intPtr3 = Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_get_string(propHandle, id, intPtr, intPtr2); if (intPtr3 != IntPtr.Zero) { try { result = Utf8StringMarshaler.MarshalNativeToManaged(intPtr3); } finally { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_free_string(intPtr3)); } } } finally { Marshal.FreeHGlobal(intPtr); Marshal.FreeHGlobal(intPtr2); } return result; } } public enum PropertyId { SpeechServiceConnection_Key = 1000, SpeechServiceConnection_Endpoint = 1001, SpeechServiceConnection_Region = 1002, SpeechServiceAuthorization_Token = 1003, SpeechServiceAuthorization_Type = 1004, SpeechServiceConnection_EndpointId = 1005, SpeechServiceConnection_Host = 1006, SpeechServiceConnection_ProxyHostName = 1100, SpeechServiceConnection_ProxyPort = 1101, SpeechServiceConnection_ProxyUserName = 1102, SpeechServiceConnection_ProxyPassword = 1103, SpeechServiceConnection_Url = 1104, SpeechServiceConnection_ProxyHostBypass = 1105, SpeechServiceConnection_TranslationToLanguages = 2000, SpeechServiceConnection_TranslationVoice = 2001, SpeechServiceConnection_TranslationFeatures = 2002, SpeechServiceConnection_IntentRegion = 2003, SpeechServiceConnection_RecoMode = 3000, SpeechServiceConnection_RecoLanguage = 3001, SpeechServiceConnection_RecoBackend = 3004, SpeechServiceConnection_RecoModelName = 3005, [EditorBrowsable(EditorBrowsableState.Never)] SpeechServiceConnection_RecoModelKey = 3006, Speech_SessionId = 3002, SpeechServiceConnection_SynthLanguage = 3100, SpeechServiceConnection_SynthVoice = 3101, SpeechServiceConnection_SynthOutputFormat = 3102, SpeechServiceConnection_SynthEnableCompressedAudioTransmission = 3103, SpeechServiceConnection_SynthBackend = 3110, SpeechServiceConnection_SynthOfflineDataPath = 3112, SpeechServiceConnection_SynthOfflineVoice = 3113, [EditorBrowsable(EditorBrowsableState.Never)] SpeechServiceConnection_SynthModelKey = 3114, SpeechServiceConnection_VoicesListEndpoint = 3130, SpeechServiceConnection_InitialSilenceTimeoutMs = 3200, SpeechServiceConnection_EndSilenceTimeoutMs = 3201, SpeechServiceConnection_EnableAudioLogging = 3202, SpeechServiceConnection_AutoDetectSourceLanguages = 3300, SpeechServiceConnection_AutoDetectSourceLanguageResult = 3301, SpeechServiceConnection_LanguageIdMode = 3205, SpeechServiceConnection_TranslationCategoryId = 3206, SpeechServiceResponse_RequestDetailedResultTrueFalse = 4000, SpeechServiceResponse_RequestProfanityFilterTrueFalse = 4001, SpeechServiceResponse_ProfanityOption = 4002, SpeechServiceResponse_PostProcessingOption = 4003, SpeechServiceResponse_RequestWordLevelTimestamps = 4004, SpeechServiceResponse_StablePartialResultThreshold = 4005, SpeechServiceResponse_OutputFormatOption = 4006, SpeechServiceResponse_RequestSnr = 4007, SpeechServiceResponse_TranslationRequestStablePartialResult = 4100, SpeechServiceResponse_RequestWordBoundary = 4200, SpeechServiceResponse_RequestPunctuationBoundary = 4201, SpeechServiceResponse_RequestSentenceBoundary = 4202, SpeechServiceResponse_SynthesisEventsSyncToAudio = 4210, SpeechServiceResponse_JsonResult = 5000, SpeechServiceResponse_JsonErrorDetails = 5001, SpeechServiceResponse_RecognitionLatencyMs = 5002, SpeechServiceResponse_RecognitionBackend = 5003, SpeechServiceResponse_SynthesisFirstByteLatencyMs = 5010, SpeechServiceResponse_SynthesisFinishLatencyMs = 5011, SpeechServiceResponse_SynthesisUnderrunTimeMs = 5012, SpeechServiceResponse_SynthesisConnectionLatencyMs = 5013, SpeechServiceResponse_SynthesisNetworkLatencyMs = 5014, SpeechServiceResponse_SynthesisServiceLatencyMs = 5015, SpeechServiceResponse_SynthesisBackend = 5020, SpeechServiceResponse_DiarizeIntermediateResults = 5025, CancellationDetails_Reason = 6000, CancellationDetails_ReasonText = 6001, CancellationDetails_ReasonDetailedText = 6002, LanguageUnderstandingServiceResponse_JsonResult = 7000, AudioConfig_DeviceNameForRender = 8005, AudioConfig_PlaybackBufferLengthInMs = 8006, Speech_LogFilename = 9001, Speech_SegmentationSilenceTimeoutMs = 9002, Speech_SegmentationMaximumTimeMs = 9003, Speech_SegmentationStrategy = 9004, Conversation_ApplicationId = 10000, Conversation_DialogType = 10001, Conversation_Initial_Silence_Timeout = 10002, Conversation_From_Id = 10003, Conversation_Conversation_Id = 10004, Conversation_Custom_Voice_Deployment_Ids = 10005, Conversation_Speech_Activity_Template = 10006, Conversation_Request_Bot_Status_Messages = 10008, Conversation_Connection_Id = 10009, Conversation_ParticipantId = 10007, ConversationTranscribingService_DataBufferUserId = 11002, ConversationTranscribingService_DataBufferTimeStamp = 11001, PronunciationAssessment_ReferenceText = 12001, PronunciationAssessment_GradingSystem = 12002, PronunciationAssessment_Granularity = 12003, PronunciationAssessment_EnableMiscue = 12005, PronunciationAssessment_PhonemeAlphabet = 12006, PronunciationAssessment_NBestPhonemeCount = 12007, PronunciationAssessment_EnableProsodyAssessment = 12008, PronunciationAssessment_Json = 12009, PronunciationAssessment_Params = 12010, PronunciationAssessment_ContentTopic = 12020, SpeakerRecognition_Api_Version = 13001, SpeechTranslation_ModelName = 13100, [EditorBrowsable(EditorBrowsableState.Never)] SpeechTranslation_ModelKey = 13101, KeywordRecognition_ModelName = 13200, [EditorBrowsable(EditorBrowsableState.Never)] KeywordRecognition_ModelKey = 13201, EmbeddedSpeech_EnablePerformanceMetrics = 13300, SpeechSynthesisRequest_Pitch = 14001, SpeechSynthesisRequest_Rate = 14002, SpeechSynthesisRequest_Volume = 14003, SpeechSynthesis_FrameTimeoutInterval = 14101, SpeechSynthesis_RtfTimeoutThreshold = 14102 } public enum ResultReason { NoMatch, Canceled, RecognizingSpeech, RecognizedSpeech, RecognizingIntent, RecognizedIntent, TranslatingSpeech, TranslatedSpeech, SynthesizingAudio, SynthesizingAudioCompleted, RecognizingKeyword, RecognizedKeyword, SynthesizingAudioStarted, TranslatingParticipantSpeech, TranslatedParticipantSpeech, TranslatedInstantMessage, TranslatedParticipantInstantMessage, EnrollingVoiceProfile, EnrolledVoiceProfile, RecognizedSpeakers, RecognizedSpeaker, ResetVoiceProfile, DeletedVoiceProfile, VoicesListRetrieved } public enum CancellationReason { Error = 1, EndOfStream, CancelledByUser } public enum CancellationErrorCode { NoError = 0, AuthenticationFailure = 1, BadRequest = 2, TooManyRequests = 3, Forbidden = 4, ConnectionFailure = 5, ServiceTimeout = 6, ServiceError = 7, ServiceUnavailable = 8, RuntimeError = 9, EmbeddedModelError = 12 } public class RecognitionEventArgs : SessionEventArgs { public ulong Offset { get; } internal RecognitionEventArgs(IntPtr eventHandlePtr) : base(eventHandlePtr) { SpxExceptionThrower.ThrowIfNull(eventHandle); ulong offset = 0uL; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognition_event_get_offset(eventHandle, ref offset)); Offset = offset; } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "SessionId: {0} Offset: {1}", base.SessionId, Offset); } } internal enum RecognitionEventType { SpeechStartDetectedEvent, SpeechEndDetectedEvent } public class RecognitionResult { internal InteropSafeHandle resultHandle; internal const int maxCharCount = 2048; public virtual string ResultId { get; } public virtual ResultReason Reason { get; } public virtual string Text { get; } public virtual TimeSpan Duration => TimeSpan.FromTicks((long)GetDuration()); public virtual long OffsetInTicks => (long)GetOffset(); public virtual int Channel => (int)GetChannel(); public virtual PropertyCollection Properties { get; private set; } internal RecognitionResult(IntPtr resultHandlePtr) { if (resultHandlePtr != IntPtr.Zero) { resultHandle = new InteropSafeHandle(resultHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.recognizer_result_handle_release); ResultId = SpxFactory.GetDataFromHandleUsingDelegate(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_result_id, resultHandle, 2048); Text = SpxFactory.GetDataFromHandleUsingDelegate(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_text, resultHandle, 2048); ResultReason reason = ResultReason.NoMatch; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_reason(resultHandle, ref reason)); Reason = reason; IntPtr hpropbag = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_property_bag(resultHandle, out hpropbag)); Properties = new PropertyCollection(hpropbag); } } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "ResultId:{0} Reason:{1} Recognized text:<{2}>. Json:{3}", ResultId, Reason, Text, Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult)); } private ulong GetDuration() { SpxExceptionThrower.ThrowIfNull(resultHandle); ulong duration = 0uL; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_duration(resultHandle, ref duration)); return duration; } private ulong GetOffset() { SpxExceptionThrower.ThrowIfNull(resultHandle); ulong offset = 0uL; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_offset(resultHandle, ref offset)); return offset; } private uint GetChannel() { SpxExceptionThrower.ThrowIfNull(resultHandle); uint channel = 0u; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_channel(resultHandle, ref channel)); return channel; } } public class CancellationDetails { private RecognitionResult recognitionResult = null; public CancellationReason Reason { get; private set; } public CancellationErrorCode ErrorCode { get; private set; } public string ErrorDetails { get; private set; } public static CancellationDetails FromResult(RecognitionResult result) { return new CancellationDetails(result); } internal CancellationDetails(RecognitionResult result) { SpxExceptionThrower.ThrowIfNull(result); recognitionResult = result; SpxExceptionThrower.ThrowIfNull(recognitionResult.resultHandle, "Invalid result handle."); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.CancellationDetails.result_get_reason_canceled(recognitionResult.resultHandle, out var reason)); Reason = reason; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.CancellationDetails.result_get_canceled_error_code(recognitionResult.resultHandle, out var errorCode)); ErrorCode = errorCode; ErrorDetails = recognitionResult.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonErrorDetails); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Reason:{0} ErrorDetails:<{1}>", Reason, ErrorDetails); } } public class NoMatchDetails { private RecognitionResult recognitionResult = null; public NoMatchReason Reason { get; private set; } public static NoMatchDetails FromResult(RecognitionResult result) { return new NoMatchDetails(result); } internal NoMatchDetails(RecognitionResult result) { SpxExceptionThrower.ThrowIfNull(result); recognitionResult = result; SpxExceptionThrower.ThrowIfNull(recognitionResult.resultHandle, "Invalid result handle."); NoMatchReason reason = NoMatchReason.NotRecognized; SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.NoMatchDetails.result_get_no_match_reason(recognitionResult.resultHandle, ref reason)); Reason = reason; } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "NoMatchReason:{0}", Reason); } } public class Recognizer : IDisposable { internal delegate IntPtr GetRecognizerFromConfigDelegate(out IntPtr phreco, InteropSafeHandle speechconfig, InteropSafeHandle audioInput); internal delegate IntPtr GetRecognizerFromConfigWithLanguageConfigDelegate(out IntPtr phreco, InteropSafeHandle speechconfig, InteropSafeHandle sourceLanguageConfig, InteropSafeHandle audioInput); internal delegate IntPtr GetRecognizerFromAudioConfigDelegate(out IntPtr reco, InteropSafeHandle audioConfig); private const string AuthTokenExpiryProperty = "service.auth.token.expirems"; private const string AuthTokenErrorProperty = "service.auth.token.lasterror"; private const string AuthTokenRefreshIntervalMsProperty = "service.auth.token.refreshintervalms"; private static readonly string[] TokenRequestScopes = new string[1] { "https://cognitiveservices.azure.com/.default" }; protected readonly TokenCredential _tokenCredential; internal InteropSafeHandle recoHandle; protected readonly string pointerHandle; private IntPtr asyncStartContinuousHandle = IntPtr.Zero; private IntPtr asyncStopContinuousHandle = IntPtr.Zero; private IntPtr asyncStartKeywordHandle = IntPtr.Zero; private IntPtr asyncStopKeywordHandle = IntPtr.Zero; private CallbackFunctionDelegate speechStartDetectedCallbackDelegate; private CallbackFunctionDelegate speechEndDetectedCallbackDelegate; private CallbackFunctionDelegate sessionStartedCallbackDelegate; private CallbackFunctionDelegate sessionStoppedCallbackDelegate; private CallbackFunctionDelegate tokenRequestedCallbackDelegate; protected GCHandle gch; protected volatile bool disposed = false; protected volatile bool isDisposing = false; protected object recognizerLock = new object(); private int activeAsyncRecognitionCounter = 0; private event EventHandler<SessionEventArgs> _SessionStarted; private event EventHandler<SessionEventArgs> _SessionStopped; private event EventHandler<SessionEventArgs> _TokenRequested; private event EventHandler<RecognitionEventArgs> _SpeechStartDetected; private event EventHandler<RecognitionEventArgs> _SpeechEndDetected; public event EventHandler<SessionEventArgs> SessionStarted { add { if (this._SessionStarted == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_session_started_set_callback(recoHandle, sessionStartedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _SessionStarted += value; } remove { _SessionStarted -= value; if (this._SessionStarted == null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_session_started_set_callback(recoHandle, null, IntPtr.Zero)); } } } public event EventHandler<SessionEventArgs> SessionStopped { add { if (this._SessionStopped == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_session_stopped_set_callback(recoHandle, sessionStoppedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _SessionStopped += value; } remove { _SessionStopped -= value; if (this._SessionStopped == null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_session_stopped_set_callback(recoHandle, null, IntPtr.Zero)); } } } public event EventHandler<RecognitionEventArgs> SpeechStartDetected { add { if (this._SpeechStartDetected == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_speech_start_detected_set_callback(recoHandle, speechStartDetectedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _SpeechStartDetected += value; } remove { _SpeechStartDetected -= value; if (this._SpeechStartDetected == null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_speech_start_detected_set_callback(recoHandle, null, IntPtr.Zero)); } } } public event EventHandler<RecognitionEventArgs> SpeechEndDetected { add { if (this._SpeechEndDetected == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_speech_end_detected_set_callback(recoHandle, speechEndDetectedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _SpeechEndDetected += value; } remove { _SpeechEndDetected -= value; if (this._SpeechEndDetected == null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_speech_end_detected_set_callback(recoHandle, null, IntPtr.Zero)); } } } protected event EventHandler<SessionEventArgs> TokenRequested { add { if (this._TokenRequested == null) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_token_requested_set_callback(recoHandle, tokenRequestedCallbackDelegate, GCHandle.ToIntPtr(gch))); } _TokenRequested += value; } remove { _TokenRequested -= value; if (this._TokenRequested == null) { SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_token_requested_set_callback(recoHandle, null, IntPtr.Zero)); } } } internal Recognizer(InteropSafeHandle recoPtr, TokenCredential tokenCredential = null) { SpxExceptionThrower.ThrowIfNull(recoPtr); recoHandle = recoPtr; pointerHandle = recoPtr.ToString(); Microsoft.CognitiveServices.Speech.Internal.Diagnostics.SPX_TRACE_VERBOSE("Constructor for " + pointerHandle, 148, ".ctor", "D:\\a\\_work\\1\\s\\source\\bindings\\csharp\\recognizer.cs"); _tokenCredential = tokenCredential; gch = GCHandle.Alloc(this, GCHandleType.Weak); speechStartDetectedCallbackDelegate = FireEvent_SpeechStartDetected; speechEndDetectedCallbackDelegate = FireEvent_SpeechEndDetected; sessionStartedCallbackDelegate = FireEvent_SetSessionStarted; sessionStoppedCallbackDelegate = FireEvent_SetSessionStopped; tokenRequestedCallbackDelegate = FireEvent_TokenRequested; } ~Recognizer() { Microsoft.CognitiveServices.Speech.Internal.Diagnostics.SPX_TRACE_VERBOSE("Finalizer for " + pointerHandle, 161, "Finalize", "D:\\a\\_work\\1\\s\\source\\bindings\\csharp\\recognizer.cs"); isDisposing = true; Dispose(disposing: false); } public void Dispose() { try { isDisposing = true; lock (recognizerLock) { if (activeAsyncRecognitionCounter != 0) { throw new InvalidOperationException("Cannot dispose a recognizer while async recognition is running. Await async recognitions to avoid unexpected disposals."); } } } finally { Dispose(disposing: true); GC.SuppressFinalize(this); } } protected virtual void Dispose(bool disposing) { Microsoft.CognitiveServices.Speech.Internal.Diagnostics.SPX_TRACE_VERBOSE($"Dispose({disposing}) called for {pointerHandle}", 222, "Dispose", "D:\\a\\_work\\1\\s\\source\\bindings\\csharp\\recognizer.cs"); if (!disposed) { speechStartDetectedCallbackDelegate = null; speechEndDetectedCallbackDelegate = null; sessionStartedCallbackDelegate = null; sessionStoppedCallbackDelegate = null; tokenRequestedCallbackDelegate = null; if (gch.IsAllocated) { gch.Free(); } disposed = true; } } protected void SetUpTokenRefreshCallback(PropertyCollection property) { if (_tokenCredential != null && property != null && this._TokenRequested == null) { TokenRequested += delegate { UpdateAuthToken(property); }; property.SetProperty("service.auth.token.expirems", "infinite"); } } private void UpdateAuthToken(PropertyCollection property) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0070: 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) if (property == null || _tokenCredential == null) { return; } string value = property.GetProperty(PropertyId.SpeechServiceAuthorization_Token, string.Empty); string value2 = property.GetProperty("service.auth.token.expirems", string.Empty); string property2 = property.GetProperty("service.auth.token.refreshintervalms", string.Empty); try { AccessToken token = _tokenCredential.GetToken(new TokenRequestContext(TokenRequestScopes, (string)null, (string)null, (string)null, false, false, (string)null, (Uri)null, (string)null), default(CancellationToken)); value = ((AccessToken)(ref token)).Token; value2 = ((!int.TryParse(property2, out var result)) ? $"{((AccessToken)(ref token)).ExpiresOn.ToUnixTimeMilliseconds()}" : $"{new DateTimeOffset(DateTime.UtcNow.AddMilliseconds(result * 2)).ToUnixTimeMilliseconds()}"); property.SetProperty("service.auth.token.lasterror", string.Empty); } catch (Exception ex) { property.SetProperty("service.auth.token.lasterror", ex.ToString()); } finally { property.SetProperty(PropertyId.SpeechServiceAuthorization_Token, value); property.SetProperty("service.auth.token.expirems", value2); } } [MonoPInvokeCallback(typeof(CallbackFunctionDelegate))] private static void FireEvent_SetSessionStarted(IntPtr hreco, IntPtr hevent, IntPtr pvContext) { try { Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { SessionEventArgs e = new SessionEventArgs(hevent); objectFromWeakHandle._SessionStarted?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } [MonoPInvokeCallback(typeof(CallbackFunctionDelegate))] private static void FireEvent_SetSessionStopped(IntPtr hreco, IntPtr hevent, IntPtr pvContext) { try { Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { SessionEventArgs e = new SessionEventArgs(hevent); objectFromWeakHandle._SessionStopped?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } [MonoPInvokeCallback(typeof(CallbackFunctionDelegate))] private static void FireEvent_TokenRequested(IntPtr hreco, IntPtr hevent, IntPtr pvContext) { try { Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { SessionEventArgs e = new SessionEventArgs(hevent); objectFromWeakHandle._TokenRequested?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } [MonoPInvokeCallback(typeof(CallbackFunctionDelegate))] private static void FireEvent_SpeechStartDetected(IntPtr hreco, IntPtr hevent, IntPtr pvContext) { try { Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { RecognitionEventArgs e = new RecognitionEventArgs(hevent); objectFromWeakHandle._SpeechStartDetected?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } [MonoPInvokeCallback(typeof(CallbackFunctionDelegate))] private static void FireEvent_SpeechEndDetected(IntPtr hreco, IntPtr hevent, IntPtr pvContext) { try { Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext); if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing) { RecognitionEventArgs e = new RecognitionEventArgs(hevent); objectFromWeakHandle._SpeechEndDetected?.Invoke(objectFromWeakHandle, e); } } catch (Exception ex) { SpxExceptionThrower.LogError(ex.Message); } } internal void DoAsyncRecognitionAction(Action recoImplAction) { lock (recognizerLock) { activeAsyncRecognitionCounter++; } if (disposed || isDisposing) { throw new ObjectDisposedException(GetType().Name); } try { SpxExceptionThrower.ThrowIfNull(recoImplAction); recoImplAction(); } finally { lock (recognizerLock) { activeAsyncRecognitionCounter--; } } } internal IntPtr RecognizeOnce() { IntPtr result = IntPtr.Zero; SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle"); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognize_once(recoHandle, out result)); return result; } internal void StartContinuousRecognition() { if (asyncStartContinuousHandle != IntPtr.Zero) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStartContinuousHandle)); } SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle"); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_start_continuous_recognition_async(recoHandle, out asyncStartContinuousHandle)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_start_continuous_recognition_async_wait_for(asyncStartContinuousHandle, uint.MaxValue)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStartContinuousHandle)); asyncStartContinuousHandle = IntPtr.Zero; } internal void StopContinuousRecognition() { if (asyncStopContinuousHandle != IntPtr.Zero) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopContinuousHandle)); } SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle"); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_continuous_recognition_async(recoHandle, out asyncStopContinuousHandle)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_continuous_recognition_async_wait_for(asyncStopContinuousHandle, uint.MaxValue)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopContinuousHandle)); asyncStopContinuousHandle = IntPtr.Zero; } internal void StopTranscribing(bool destroyResource) { if (asyncStopContinuousHandle != IntPtr.Zero) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopContinuousHandle)); } SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle"); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_continuous_recognition_async(recoHandle, out asyncStopContinuousHandle)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_continuous_recognition_async_wait_for(asyncStopContinuousHandle, uint.MaxValue)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopContinuousHandle)); asyncStopContinuousHandle = IntPtr.Zero; } internal void StartKeywordRecognition(KeywordRecognitionModel model) { if (asyncStartKeywordHandle != IntPtr.Zero) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStartKeywordHandle)); } SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle"); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_start_keyword_recognition_async(recoHandle, model.keywordHandle, out asyncStartKeywordHandle)); GC.KeepAlive(model); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_start_keyword_recognition_async_wait_for(asyncStartKeywordHandle, uint.MaxValue)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStartKeywordHandle)); asyncStartKeywordHandle = IntPtr.Zero; } internal void StopKeywordRecognition() { if (asyncStopKeywordHandle != IntPtr.Zero) { SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopKeywordHandle)); } SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle"); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_keyword_recognition_async(recoHandle, out asyncStopKeywordHandle)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_keyword_recognition_async_wait_for(asyncStopKeywordHandle, uint.MaxValue)); SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopKeywordHandle)); asyncStopKeywordHandle = IntPtr.Zero; } internal static InteropSafeHandle FromConfig(GetRecognizerFromConfigDelegate fromConfig, SpeechConfig speechConfig, Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig) { if (speechConfig == null) { throw new ArgumentNullException("speechConfig"); } if (audioConfig == null) { throw new ArgumentNullException("audioConfig"); } IntPtr phreco = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioConfig.configHandle)); InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release); GC.KeepAlive(speechConfig); GC.KeepAlive(audioConfig); return result; } internal static InteropSafeHandle FromEmbeddedConfig(GetRecognizerFromConfigDelegate fromConfig, EmbeddedSpeechConfig speechConfig, Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig) { if (speechConfig == null) { throw new ArgumentNullException("speechConfig"); } if (audioConfig == null) { throw new ArgumentNullException("audioConfig"); } IntPtr phreco = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioConfig.configHandle)); InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release); GC.KeepAlive(speechConfig); GC.KeepAlive(audioConfig); return result; } internal static InteropSafeHandle FromHybridConfig(GetRecognizerFromConfigDelegate fromConfig, HybridSpeechConfig speechConfig, Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig) { if (speechConfig == null) { throw new ArgumentNullException("speechConfig"); } if (audioConfig == null) { throw new ArgumentNullException("audioConfig"); } IntPtr phreco = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioConfig.configHandle)); InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release); GC.KeepAlive(speechConfig); GC.KeepAlive(audioConfig); return result; } internal static InteropSafeHandle FromConfig(GetRecognizerFromConfigDelegate fromConfig, SpeechConfig speechConfig) { if (speechConfig == null) { throw new ArgumentNullException("speechConfig"); } IntPtr zero = IntPtr.Zero; using InteropSafeHandle audioInput = new InteropSafeHandle(zero, (HandleRelease)null); IntPtr phreco = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioInput)); InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release); GC.KeepAlive(speechConfig); return result; } internal static InteropSafeHandle FromEmbeddedConfig(GetRecognizerFromConfigDelegate fromConfig, EmbeddedSpeechConfig speechConfig) { if (speechConfig == null) { throw new ArgumentNullException("speechConfig"); } IntPtr zero = IntPtr.Zero; using InteropSafeHandle audioInput = new InteropSafeHandle(zero, (HandleRelease)null); IntPtr phreco = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioInput)); InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release); GC.KeepAlive(speechConfig); return result; } internal static InteropSafeHandle FromHybridConfig(GetRecognizerFromConfigDelegate fromConfig, HybridSpeechConfig speechConfig) { if (speechConfig == null) { throw new ArgumentNullException("speechConfig"); } IntPtr zero = IntPtr.Zero; using InteropSafeHandle audioInput = new InteropSafeHandle(zero, (HandleRelease)null); IntPtr phreco = IntPtr.Zero; SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioInput)); InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release); GC.KeepAlive(speechConfig); return result; } internal static InteropSafeHandle FromConfig(GetRecognizerFromConfigWithLanguageConfigDelegate fromConfig, SpeechConfig speechConfig, SourceLanguageConfig sourceLanguageConfig, Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig) { if (speechConfig == null) { throw new ArgumentNullException("speechConfig"); } if (sourceLanguageConfig == null) { throw new ArgumentNullException("sourceLanguageConfig"); } IntPtr phreco = IntPtr.Zero; InteropSafeHandle audioConfigHandle = getAudioConfigHandle(audioConfig); SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, sourceLanguageConfig.configHandle, audioConfigHandle)); InteropSafeHandle
deps/Microsoft.Extensions.AI.Abstractions.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Schema; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Shared.Collections; using Microsoft.Shared.Diagnostics; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Abstractions representing generative AI components.")] [assembly: AssemblyFileVersion("9.1000.25.51303")] [assembly: AssemblyInformationalVersion("9.10.0+f8f779a6ea004bb1f26649719ca77d63a9d9417c")] [assembly: AssemblyProduct("Microsoft.Extensions.AI.Abstractions")] [assembly: AssemblyTitle("Microsoft.Extensions.AI.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/extensions")] [assembly: AssemblyVersion("9.10.0.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] internal sealed class IsByRefLikeAttribute : 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 Microsoft.Extensions.AI { public sealed class AdditionalPropertiesDictionary : AdditionalPropertiesDictionary<object?> { public AdditionalPropertiesDictionary() { } public AdditionalPropertiesDictionary(IDictionary<string, object?> dictionary) : base(dictionary) { } public AdditionalPropertiesDictionary(IEnumerable<KeyValuePair<string, object?>> collection) : base(collection) { } public new AdditionalPropertiesDictionary Clone() { return new AdditionalPropertiesDictionary(this); } } [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(AdditionalPropertiesDictionary<>.DebugView))] public class AdditionalPropertiesDictionary<TValue> : IDictionary<string, TValue>, ICollection<KeyValuePair<string, TValue>>, IEnumerable<KeyValuePair<string, TValue>>, IEnumerable, IReadOnlyDictionary<string, TValue>, IReadOnlyCollection<KeyValuePair<string, TValue>> { public struct Enumerator : IEnumerator<KeyValuePair<string, TValue>>, IEnumerator, IDisposable { private Dictionary<string, TValue>.Enumerator _dictionaryEnumerator; public KeyValuePair<string, TValue> Current => _dictionaryEnumerator.Current; object IEnumerator.Current => Current; internal Enumerator(Dictionary<string, TValue>.Enumerator dictionaryEnumerator) { _dictionaryEnumerator = dictionaryEnumerator; } public void Dispose() { _dictionaryEnumerator.Dispose(); } public bool MoveNext() { return _dictionaryEnumerator.MoveNext(); } public void Reset() { Reset(ref _dictionaryEnumerator); } private static void Reset<TEnumerator>(ref TEnumerator enumerator) where TEnumerator : struct, IEnumerator { enumerator.Reset(); } } private sealed class DebugView { [DebuggerDisplay("{Value}", Name = "[{Key}]")] public readonly struct AdditionalProperty { [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string Key { get; } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public TValue Value { get; } public AdditionalProperty(string key, TValue value) { Key = key; Value = value; } } private readonly AdditionalPropertiesDictionary<TValue> _properties = Throw.IfNull(properties, "properties"); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public AdditionalProperty[] Items => _properties.Select<KeyValuePair<string, TValue>, AdditionalProperty>(delegate(KeyValuePair<string, TValue> p) { KeyValuePair<string, TValue> keyValuePair = p; string key = keyValuePair.Key; keyValuePair = p; return new AdditionalProperty(key, keyValuePair.Value); }).ToArray(); public DebugView(AdditionalPropertiesDictionary<TValue> properties) { } } private readonly Dictionary<string, TValue> _dictionary; public TValue this[string key] { get { return _dictionary[key]; } set { _dictionary[key] = value; } } public ICollection<string> Keys => _dictionary.Keys; public ICollection<TValue> Values => _dictionary.Values; public int Count => _dictionary.Count; bool ICollection<KeyValuePair<string, TValue>>.IsReadOnly => false; IEnumerable<string> IReadOnlyDictionary<string, TValue>.Keys => _dictionary.Keys; IEnumerable<TValue> IReadOnlyDictionary<string, TValue>.Values => _dictionary.Values; public AdditionalPropertiesDictionary() { _dictionary = new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase); } public AdditionalPropertiesDictionary(IDictionary<string, TValue> dictionary) { _dictionary = new Dictionary<string, TValue>(dictionary, StringComparer.OrdinalIgnoreCase); } public AdditionalPropertiesDictionary(IEnumerable<KeyValuePair<string, TValue>> collection) { _dictionary = new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, TValue> item in collection) { _dictionary.Add(item.Key, item.Value); } } public AdditionalPropertiesDictionary<TValue> Clone() { return new AdditionalPropertiesDictionary<TValue>(_dictionary); } public void Add(string key, TValue value) { _dictionary.Add(key, value); } public bool TryAdd(string key, TValue value) { if (!_dictionary.ContainsKey(key)) { _dictionary.Add(key, value); return true; } return false; } void ICollection<KeyValuePair<string, TValue>>.Add(KeyValuePair<string, TValue> item) { ((ICollection<KeyValuePair<string, TValue>>)_dictionary).Add(item); } public void Clear() { _dictionary.Clear(); } bool ICollection<KeyValuePair<string, TValue>>.Contains(KeyValuePair<string, TValue> item) { return ((ICollection<KeyValuePair<string, TValue>>)_dictionary).Contains(item); } public bool ContainsKey(string key) { return _dictionary.ContainsKey(key); } void ICollection<KeyValuePair<string, TValue>>.CopyTo(KeyValuePair<string, TValue>[] array, int arrayIndex) { ((ICollection<KeyValuePair<string, TValue>>)_dictionary).CopyTo(array, arrayIndex); } public Enumerator GetEnumerator() { return new Enumerator(_dictionary.GetEnumerator()); } IEnumerator<KeyValuePair<string, TValue>> IEnumerable<KeyValuePair<string, TValue>>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool Remove(string key) { return _dictionary.Remove(key); } bool ICollection<KeyValuePair<string, TValue>>.Remove(KeyValuePair<string, TValue> item) { return ((ICollection<KeyValuePair<string, TValue>>)_dictionary).Remove(item); } public bool TryGetValue<T>(string key, [NotNullWhen(true)] out T? value) { if (TryGetValue(key, out var value2)) { if (value2 is T) { object obj = value2; T val = (T)((obj is T) ? obj : null); value = val; return true; } if (value2 is IConvertible) { try { value = (T)Convert.ChangeType(value2, typeof(T), CultureInfo.InvariantCulture); return true; } catch (Exception ex) when (((ex is ArgumentException || ex is FormatException || ex is InvalidCastException || ex is OverflowException) ? 1 : 0) != 0) { } } } value = default(T); return false; } public bool TryGetValue(string key, [MaybeNullWhen(false)] out TValue value) { return _dictionary.TryGetValue(key, out value); } bool IDictionary<string, TValue>.TryGetValue(string key, out TValue value) { return _dictionary.TryGetValue(key, out value); } bool IReadOnlyDictionary<string, TValue>.TryGetValue(string key, out TValue value) { return _dictionary.TryGetValue(key, out value); } internal void SetAll(IEnumerable<KeyValuePair<string, TValue>> items) { Throw.IfNull(items, "items"); foreach (KeyValuePair<string, TValue> item in items) { _dictionary[item.Key] = item.Value; } } } [DebuggerDisplay("Auto")] public sealed class AutoChatToolMode : ChatToolMode { public override bool Equals(object? obj) { return obj is AutoChatToolMode; } public override int GetHashCode() { return typeof(AutoChatToolMode).GetHashCode(); } } public static class ChatClientExtensions { public static TService? GetService<TService>(this IChatClient client, object? serviceKey = null) { Throw.IfNull(client, "client"); object service = client.GetService(typeof(TService), serviceKey); if (service is TService) { return (TService)service; } return default(TService); } public static object GetRequiredService(this IChatClient client, Type serviceType, object? serviceKey = null) { Throw.IfNull(client, "client"); Throw.IfNull(serviceType, "serviceType"); return client.GetService(serviceType, serviceKey) ?? throw Throw.CreateMissingServiceException(serviceType, serviceKey); } public static TService GetRequiredService<TService>(this IChatClient client, object? serviceKey = null) { Throw.IfNull(client, "client"); object service = client.GetService(typeof(TService), serviceKey); if (service is TService) { return (TService)service; } throw Throw.CreateMissingServiceException(typeof(TService), serviceKey); } public static Task<ChatResponse> GetResponseAsync(this IChatClient client, string chatMessage, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(client, "client"); Throw.IfNull(chatMessage, "chatMessage"); return client.GetResponseAsync(new ChatMessage(ChatRole.User, chatMessage), options, cancellationToken); } public static Task<ChatResponse> GetResponseAsync(this IChatClient client, ChatMessage chatMessage, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(client, "client"); Throw.IfNull(chatMessage, "chatMessage"); return client.GetResponseAsync(new <>z__ReadOnlySingleElementList<ChatMessage>(chatMessage), options, cancellationToken); } public static IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(this IChatClient client, string chatMessage, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(client, "client"); Throw.IfNull(chatMessage, "chatMessage"); return client.GetStreamingResponseAsync(new ChatMessage(ChatRole.User, chatMessage), options, cancellationToken); } public static IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(this IChatClient client, ChatMessage chatMessage, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(client, "client"); Throw.IfNull(chatMessage, "chatMessage"); return client.GetStreamingResponseAsync(new <>z__ReadOnlySingleElementList<ChatMessage>(chatMessage), options, cancellationToken); } } public class ChatClientMetadata { public string? ProviderName { get; } public Uri? ProviderUri { get; } public string? DefaultModelId { get; } public ChatClientMetadata(string? providerName = null, Uri? providerUri = null, string? defaultModelId = null) { DefaultModelId = defaultModelId; ProviderName = providerName; ProviderUri = providerUri; } } [JsonConverter(typeof(Converter))] public readonly struct ChatFinishReason : IEquatable<ChatFinishReason> { [EditorBrowsable(EditorBrowsableState.Never)] public sealed class Converter : JsonConverter<ChatFinishReason> { public override ChatFinishReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new ChatFinishReason(reader.GetString()); } public override void Write(Utf8JsonWriter writer, ChatFinishReason value, JsonSerializerOptions options) { Throw.IfNull(writer, "writer").WriteStringValue(value.Value); } } [CompilerGenerated] private readonly string <Value>k__BackingField; public string Value => <Value>k__BackingField ?? Stop.Value; public static ChatFinishReason Stop { get; } = new ChatFinishReason("stop"); public static ChatFinishReason Length { get; } = new ChatFinishReason("length"); public static ChatFinishReason ToolCalls { get; } = new ChatFinishReason("tool_calls"); public static ChatFinishReason ContentFilter { get; } = new ChatFinishReason("content_filter"); [JsonConstructor] public ChatFinishReason(string value) { <Value>k__BackingField = Throw.IfNullOrWhitespace(value, "value"); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ChatFinishReason other) { return Equals(other); } return false; } public bool Equals(ChatFinishReason other) { return StringComparer.OrdinalIgnoreCase.Equals(Value, other.Value); } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Value); } public static bool operator ==(ChatFinishReason left, ChatFinishReason right) { return left.Equals(right); } public static bool operator !=(ChatFinishReason left, ChatFinishReason right) { return !(left == right); } public override string ToString() { return Value; } } [DebuggerDisplay("[{Role}] {ContentForDebuggerDisplay}{EllipsesForDebuggerDisplay,nq}")] public class ChatMessage { private IList<AIContent>? _contents; private string? _authorName; public string? AuthorName { get { return _authorName; } set { _authorName = (string.IsNullOrWhiteSpace(value) ? null : value); } } public DateTimeOffset? CreatedAt { get; set; } public ChatRole Role { get; set; } = ChatRole.User; [JsonIgnore] public string Text => Contents.ConcatText(); public IList<AIContent> Contents { get { return _contents ?? (_contents = new List<AIContent>()); } [param: AllowNull] set { _contents = value; } } public string? MessageId { get; set; } [JsonIgnore] public object? RawRepresentation { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private AIContent? ContentForDebuggerDisplay { get { string text = Text; if (string.IsNullOrWhiteSpace(text)) { IList<AIContent> contents = _contents; if (contents == null || contents.Count <= 0) { return null; } return _contents[0]; } return new TextContent(text); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string EllipsesForDebuggerDisplay { get { IList<AIContent> contents = _contents; if (contents == null || contents.Count <= 1) { return string.Empty; } return ", ..."; } } [JsonConstructor] public ChatMessage() { } public ChatMessage(ChatRole role, string? content) : this(role, (content == null) ? new List<AIContent>() : new List<AIContent>(1) { new TextContent(content) }) { } public ChatMessage(ChatRole role, IList<AIContent>? contents) { Role = role; _contents = contents; } public ChatMessage Clone() { return new ChatMessage { AdditionalProperties = AdditionalProperties, _authorName = _authorName, _contents = _contents, CreatedAt = CreatedAt, RawRepresentation = RawRepresentation, Role = Role, MessageId = MessageId }; } public override string ToString() { return Text; } } public class ChatOptions { public string? ConversationId { get; set; } public string? Instructions { get; set; } public float? Temperature { get; set; } public int? MaxOutputTokens { get; set; } public float? TopP { get; set; } public int? TopK { get; set; } public float? FrequencyPenalty { get; set; } public float? PresencePenalty { get; set; } public long? Seed { get; set; } public ChatResponseFormat? ResponseFormat { get; set; } public string? ModelId { get; set; } public IList<string>? StopSequences { get; set; } public bool? AllowMultipleToolCalls { get; set; } public ChatToolMode? ToolMode { get; set; } [JsonIgnore] public IList<AITool>? Tools { get; set; } [Experimental("MEAI001")] [JsonIgnore] public bool? AllowBackgroundResponses { get; set; } [Experimental("MEAI001")] [JsonIgnore] public object? ContinuationToken { get; set; } [JsonIgnore] public Func<IChatClient, object?>? RawRepresentationFactory { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } public ChatOptions() { } protected ChatOptions(ChatOptions? other) { if (other != null) { AdditionalProperties = other.AdditionalProperties?.Clone(); AllowBackgroundResponses = other.AllowBackgroundResponses; AllowMultipleToolCalls = other.AllowMultipleToolCalls; ConversationId = other.ConversationId; ContinuationToken = other.ContinuationToken; FrequencyPenalty = other.FrequencyPenalty; Instructions = other.Instructions; MaxOutputTokens = other.MaxOutputTokens; ModelId = other.ModelId; PresencePenalty = other.PresencePenalty; RawRepresentationFactory = other.RawRepresentationFactory; ResponseFormat = other.ResponseFormat; Seed = other.Seed; Temperature = other.Temperature; ToolMode = other.ToolMode; TopK = other.TopK; TopP = other.TopP; if (other.StopSequences != null) { IList<string> stopSequences = other.StopSequences; List<string> list = new List<string>(stopSequences.Count); list.AddRange(stopSequences); StopSequences = list; } if (other.Tools != null) { IList<AITool> tools = other.Tools; List<AITool> list2 = new List<AITool>(tools.Count); list2.AddRange(tools); Tools = list2; } } } public virtual ChatOptions Clone() { return new ChatOptions(this); } } public class ChatResponse { private IList<ChatMessage>? _messages; public IList<ChatMessage> Messages { get { return _messages ?? (_messages = new List<ChatMessage>(1)); } [param: AllowNull] set { _messages = value; } } [JsonIgnore] public string Text => _messages?.ConcatText() ?? string.Empty; public string? ResponseId { get; set; } public string? ConversationId { get; set; } public string? ModelId { get; set; } public DateTimeOffset? CreatedAt { get; set; } public ChatFinishReason? FinishReason { get; set; } public UsageDetails? Usage { get; set; } [Experimental("MEAI001")] [JsonIgnore] public object? ContinuationToken { get; set; } [JsonIgnore] public object? RawRepresentation { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } public ChatResponse() { } public ChatResponse(ChatMessage message) { Throw.IfNull(message, "message"); Messages.Add(message); } public ChatResponse(IList<ChatMessage>? messages) { _messages = messages; } public override string ToString() { return Text; } public ChatResponseUpdate[] ToChatResponseUpdates() { ChatResponseUpdate chatResponseUpdate = null; if (AdditionalProperties != null || Usage != null) { chatResponseUpdate = new ChatResponseUpdate { AdditionalProperties = AdditionalProperties }; UsageDetails usage = Usage; if (usage != null) { chatResponseUpdate.Contents.Add(new UsageContent(usage)); } } int num = _messages?.Count ?? 0; ChatResponseUpdate[] array = new ChatResponseUpdate[num + ((chatResponseUpdate != null) ? 1 : 0)]; int i; for (i = 0; i < num; i++) { ChatMessage chatMessage = _messages[i]; array[i] = new ChatResponseUpdate { AdditionalProperties = chatMessage.AdditionalProperties, AuthorName = chatMessage.AuthorName, Contents = chatMessage.Contents, MessageId = chatMessage.MessageId, RawRepresentation = chatMessage.RawRepresentation, Role = chatMessage.Role, ConversationId = ConversationId, FinishReason = FinishReason, ModelId = ModelId, ResponseId = ResponseId, CreatedAt = (chatMessage.CreatedAt ?? CreatedAt), ContinuationToken = ContinuationToken }; } if (chatResponseUpdate != null) { array[i] = chatResponseUpdate; } return array; } } public static class ChatResponseExtensions { public static void AddMessages(this IList<ChatMessage> list, ChatResponse response) { Throw.IfNull(list, "list"); Throw.IfNull(response, "response"); if (list is List<ChatMessage> list2) { list2.AddRange(response.Messages); return; } foreach (ChatMessage message in response.Messages) { list.Add(message); } } public static void AddMessages(this IList<ChatMessage> list, IEnumerable<ChatResponseUpdate> updates) { Throw.IfNull(list, "list"); Throw.IfNull(updates, "updates"); if (!(updates is ICollection<ChatResponseUpdate> collection) || collection.Count != 0) { list.AddMessages(updates.ToChatResponse()); } } public static void AddMessages(this IList<ChatMessage> list, ChatResponseUpdate update, Func<AIContent, bool>? filter = null) { Throw.IfNull(list, "list"); Throw.IfNull(update, "update"); IList<AIContent> list3; if (filter != null) { IList<AIContent> list2 = update.Contents.Where(filter).ToList(); list3 = list2; } else { list3 = update.Contents; } IList<AIContent> list4 = list3; if (list4.Count > 0) { list.Add(new ChatMessage(update.Role ?? ChatRole.Assistant, list4) { AuthorName = update.AuthorName, CreatedAt = update.CreatedAt, RawRepresentation = update.RawRepresentation, AdditionalProperties = update.AdditionalProperties }); } } public static Task AddMessagesAsync(this IList<ChatMessage> list, IAsyncEnumerable<ChatResponseUpdate> updates, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(list, "list"); Throw.IfNull(updates, "updates"); return AddMessagesAsync(list, updates, cancellationToken); static async Task AddMessagesAsync(IList<ChatMessage> list, IAsyncEnumerable<ChatResponseUpdate> updates, CancellationToken cancellationToken) { list.AddMessages(await updates.ToChatResponseAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); } } public static ChatResponse ToChatResponse(this IEnumerable<ChatResponseUpdate> updates) { Throw.IfNull(updates, "updates"); ChatResponse chatResponse = new ChatResponse(); foreach (ChatResponseUpdate update in updates) { ProcessUpdate(update, chatResponse); } FinalizeResponse(chatResponse); return chatResponse; } public static Task<ChatResponse> ToChatResponseAsync(this IAsyncEnumerable<ChatResponseUpdate> updates, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(updates, "updates"); return ToChatResponseAsync(updates, cancellationToken); static async Task<ChatResponse> ToChatResponseAsync(IAsyncEnumerable<ChatResponseUpdate> updates, CancellationToken cancellationToken) { ChatResponse response = new ChatResponse(); await foreach (ChatResponseUpdate item in updates.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { ProcessUpdate(item, response); } FinalizeResponse(response); return response; } } internal static void CoalesceTextContent(IList<AIContent> contents) { Coalesce<TextContent>(contents, mergeSingle: false, null, (IList<AIContent> contents, int start, int end) => new TextContent(MergeText(contents, start, end)) { AdditionalProperties = contents[start].AdditionalProperties?.Clone() }); Coalesce<TextReasoningContent>(contents, mergeSingle: false, (TextReasoningContent r1, TextReasoningContent r2) => string.IsNullOrEmpty(r1.ProtectedData), (IList<AIContent> contents, int start, int end) => new TextReasoningContent(MergeText(contents, start, end)) { AdditionalProperties = contents[start].AdditionalProperties?.Clone() }); static void Coalesce<TContent>(IList<AIContent> contents, bool mergeSingle, Func<TContent, TContent, bool>? canMerge, Func<IList<AIContent>, int, int, TContent> merge) where TContent : notnull, AIContent { int num = 0; while (num < contents.Count) { if (!TryAsCoalescable<TContent>(contents[num], out var coalescable2)) { num++; } else { int num2 = num + 1; TContent arg = coalescable2; TContent coalescable3; while (num2 < contents.Count && TryAsCoalescable<TContent>(contents[num2], out coalescable3) && (canMerge == null || canMerge(arg, coalescable3))) { num2++; arg = coalescable3; } if (num == num2 - 1 && !mergeSingle) { num++; } else { contents[num] = merge(contents, num, num2); num++; while (num < num2) { contents[num++] = null; } } } } if (contents is List<AIContent> list) { list.RemoveAll((AIContent u) => u == null); } else { int num3 = 0; int count = contents.Count; for (int i = 0; i < count; i++) { AIContent aIContent = contents[i]; if (aIContent != null) { contents[num3++] = aIContent; } } for (int num4 = count - 1; num4 >= num3; num4--) { contents.RemoveAt(num4); } } } static string MergeText(IList<AIContent> contents, int start, int end) { StringBuilder stringBuilder = new StringBuilder(); for (int j = start; j < end; j++) { stringBuilder.Append(contents[j]); } return stringBuilder.ToString(); } static bool TryAsCoalescable<TContent>(AIContent content, [NotNullWhen(true)] out TContent? coalescable) where TContent : notnull, AIContent { if (content is TContent val) { IList<AIAnnotation> annotations = val.Annotations; if (annotations == null || annotations.Count <= 0) { coalescable = val; return true; } } coalescable = null; return false; } } private static void FinalizeResponse(ChatResponse response) { int count = response.Messages.Count; for (int i = 0; i < count; i++) { CoalesceTextContent((List<AIContent>)response.Messages[i].Contents); } } private static void ProcessUpdate(ChatResponseUpdate update, ChatResponse response) { bool flag = true; if (response.Messages.Count != 0) { ChatMessage chatMessage = response.Messages[response.Messages.Count - 1]; flag = NotEmptyOrEqual(update.AuthorName, chatMessage.AuthorName) || NotEmptyOrEqual(update.MessageId, chatMessage.MessageId) || NotNullOrEqual(update.Role, chatMessage.Role); } ChatMessage chatMessage2; if (flag) { chatMessage2 = new ChatMessage(ChatRole.Assistant, new List<AIContent>()); response.Messages.Add(chatMessage2); } else { chatMessage2 = response.Messages[response.Messages.Count - 1]; } if (update.AuthorName != null) { chatMessage2.AuthorName = update.AuthorName; } if (!chatMessage2.CreatedAt.HasValue || (update.CreatedAt.HasValue && update.CreatedAt > chatMessage2.CreatedAt)) { chatMessage2.CreatedAt = update.CreatedAt; } ChatRole? role = update.Role; if (role.HasValue) { ChatRole valueOrDefault = role.GetValueOrDefault(); chatMessage2.Role = valueOrDefault; } string messageId = update.MessageId; if (messageId != null && messageId.Length > 0) { chatMessage2.MessageId = update.MessageId; } foreach (AIContent content in update.Contents) { if (content is UsageContent usageContent) { (response.Usage ?? (response.Usage = new UsageDetails())).Add(usageContent.Details); } else { chatMessage2.Contents.Add(content); } } messageId = update.ResponseId; if (messageId != null && messageId.Length > 0) { response.ResponseId = update.ResponseId; } if (update.ConversationId != null) { response.ConversationId = update.ConversationId; } if (!response.CreatedAt.HasValue || (update.CreatedAt.HasValue && update.CreatedAt > response.CreatedAt)) { response.CreatedAt = update.CreatedAt; } if (update.FinishReason.HasValue) { response.FinishReason = update.FinishReason; } if (update.ModelId != null) { response.ModelId = update.ModelId; } if (update.AdditionalProperties != null) { if (response.AdditionalProperties == null) { response.AdditionalProperties = new AdditionalPropertiesDictionary(update.AdditionalProperties); } else { response.AdditionalProperties.SetAll(update.AdditionalProperties); } } } private static bool NotEmptyOrEqual(string? s1, string? s2) { if (s1 != null && s1.Length > 0) { if (s2 != null && s2.Length > 0) { return s1 != s2; } } return false; } private static bool NotNullOrEqual(ChatRole? r1, ChatRole? r2) { if (r1.HasValue && r2.HasValue) { return r1.Value != r2.Value; } return false; } } [JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] [JsonDerivedType(typeof(ChatResponseFormatText), "text")] [JsonDerivedType(typeof(ChatResponseFormatJson), "json")] public class ChatResponseFormat { private static readonly AIJsonSchemaCreateOptions _inferenceOptions = new AIJsonSchemaCreateOptions { IncludeSchemaKeyword = true }; private static readonly Regex _invalidNameCharsRegex = new Regex("[^0-9A-Za-z_]", RegexOptions.Compiled); public static ChatResponseFormatText Text { get; } = new ChatResponseFormatText(); public static ChatResponseFormatJson Json { get; } = new ChatResponseFormatJson(null); private protected ChatResponseFormat() { } public static ChatResponseFormatJson ForJsonSchema(JsonElement schema, string? schemaName = null, string? schemaDescription = null) { return new ChatResponseFormatJson(schema, schemaName, schemaDescription); } public static ChatResponseFormatJson ForJsonSchema<T>(JsonSerializerOptions? serializerOptions = null, string? schemaName = null, string? schemaDescription = null) { return ForJsonSchema(typeof(T), serializerOptions, schemaName, schemaDescription); } public static ChatResponseFormatJson ForJsonSchema(Type schemaType, JsonSerializerOptions? serializerOptions = null, string? schemaName = null, string? schemaDescription = null) { Throw.IfNull(schemaType, "schemaType"); JsonElement schema = AIJsonUtilities.CreateJsonSchema(schemaType, null, hasDefaultValue: false, null, serializerOptions ?? AIJsonUtilities.DefaultOptions, _inferenceOptions); return ForJsonSchema(schema, schemaName ?? InvalidNameCharsRegex().Replace(schemaType.Name, "_"), schemaDescription ?? schemaType.GetCustomAttribute<DescriptionAttribute>()?.Description); } private static Regex InvalidNameCharsRegex() { return _invalidNameCharsRegex; } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public sealed class ChatResponseFormatJson : ChatResponseFormat { public JsonElement? Schema { get; } public string? SchemaName { get; } public string? SchemaDescription { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => Schema?.ToString() ?? "JSON"; [JsonConstructor] public ChatResponseFormatJson(JsonElement? schema, string? schemaName = null, string? schemaDescription = null) { if (!schema.HasValue && (schemaName != null || schemaDescription != null)) { Throw.ArgumentException((schemaName != null) ? "schemaName" : "schemaDescription", "Schema name and description can only be specified if a schema is provided."); } Schema = schema; SchemaName = schemaName; SchemaDescription = schemaDescription; } } [DebuggerDisplay("Text")] public sealed class ChatResponseFormatText : ChatResponseFormat { public override bool Equals(object? obj) { return obj is ChatResponseFormatText; } public override int GetHashCode() { return typeof(ChatResponseFormatText).GetHashCode(); } } [DebuggerDisplay("[{Role}] {ContentForDebuggerDisplay}{EllipsesForDebuggerDisplay,nq}")] public class ChatResponseUpdate { private IList<AIContent>? _contents; [CompilerGenerated] private string? <AuthorName>k__BackingField; public string? AuthorName { [CompilerGenerated] get { return <AuthorName>k__BackingField; } set { <AuthorName>k__BackingField = (string.IsNullOrWhiteSpace(value) ? null : value); } } public ChatRole? Role { get; set; } [JsonIgnore] public string Text { get { if (_contents == null) { return string.Empty; } return _contents.ConcatText(); } } public IList<AIContent> Contents { get { return _contents ?? (_contents = new List<AIContent>()); } [param: AllowNull] set { _contents = value; } } [JsonIgnore] public object? RawRepresentation { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } public string? ResponseId { get; set; } public string? MessageId { get; set; } public string? ConversationId { get; set; } public DateTimeOffset? CreatedAt { get; set; } public ChatFinishReason? FinishReason { get; set; } public string? ModelId { get; set; } [Experimental("MEAI001")] [JsonIgnore] public object? ContinuationToken { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private AIContent? ContentForDebuggerDisplay { get { string text = Text; if (string.IsNullOrWhiteSpace(text)) { IList<AIContent> contents = _contents; if (contents == null || contents.Count <= 0) { return null; } return _contents[0]; } return new TextContent(text); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string EllipsesForDebuggerDisplay { get { IList<AIContent> contents = _contents; if (contents == null || contents.Count <= 1) { return string.Empty; } return ", ..."; } } [JsonConstructor] public ChatResponseUpdate() { } public ChatResponseUpdate(ChatRole? role, string? content) : this(role, (content == null) ? null : new List<AIContent>(1) { new TextContent(content) }) { } public ChatResponseUpdate(ChatRole? role, IList<AIContent>? contents) { Role = role; _contents = contents; } public override string ToString() { return Text; } } [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] public readonly struct ChatRole : IEquatable<ChatRole> { [EditorBrowsable(EditorBrowsableState.Never)] public sealed class Converter : JsonConverter<ChatRole> { public override ChatRole Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new ChatRole(reader.GetString()); } public override void Write(Utf8JsonWriter writer, ChatRole value, JsonSerializerOptions options) { Throw.IfNull(writer, "writer").WriteStringValue(value.Value); } } public static ChatRole System { get; } = new ChatRole("system"); public static ChatRole Assistant { get; } = new ChatRole("assistant"); public static ChatRole User { get; } = new ChatRole("user"); public static ChatRole Tool { get; } = new ChatRole("tool"); public string Value { get; } [JsonConstructor] public ChatRole(string value) { Value = Throw.IfNullOrWhitespace(value, "value"); } public static bool operator ==(ChatRole left, ChatRole right) { return left.Equals(right); } public static bool operator !=(ChatRole left, ChatRole right) { return !(left == right); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ChatRole other) { return Equals(other); } return false; } public bool Equals(ChatRole other) { return string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Value); } public override string ToString() { return Value; } } [JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] [JsonDerivedType(typeof(NoneChatToolMode), "none")] [JsonDerivedType(typeof(AutoChatToolMode), "auto")] [JsonDerivedType(typeof(RequiredChatToolMode), "required")] public class ChatToolMode { public static AutoChatToolMode Auto { get; } = new AutoChatToolMode(); public static NoneChatToolMode None { get; } = new NoneChatToolMode(); public static RequiredChatToolMode RequireAny { get; } = new RequiredChatToolMode(null); private protected ChatToolMode() { } public static RequiredChatToolMode RequireSpecific(string functionName) { return new RequiredChatToolMode(functionName); } } public class DelegatingChatClient : IChatClient, IDisposable { protected IChatClient InnerClient { get; } protected DelegatingChatClient(IChatClient innerClient) { InnerClient = Throw.IfNull(innerClient, "innerClient"); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public virtual Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return InnerClient.GetResponseAsync(messages, options, cancellationToken); } public virtual IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return InnerClient.GetStreamingResponseAsync(messages, options, cancellationToken); } public virtual object? GetService(Type serviceType, object? serviceKey = null) { Throw.IfNull(serviceType, "serviceType"); if (serviceKey != null || !serviceType.IsInstanceOfType(this)) { return InnerClient.GetService(serviceType, serviceKey); } return this; } protected virtual void Dispose(bool disposing) { if (disposing) { InnerClient.Dispose(); } } } public interface IChatClient : IDisposable { Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)); IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)); object? GetService(Type serviceType, object? serviceKey = null); } [DebuggerDisplay("None")] public sealed class NoneChatToolMode : ChatToolMode { public override bool Equals(object? obj) { return obj is NoneChatToolMode; } public override int GetHashCode() { return typeof(NoneChatToolMode).GetHashCode(); } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public sealed class RequiredChatToolMode : ChatToolMode { public string? RequiredFunctionName { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => "Required: " + (RequiredFunctionName ?? "Any"); public RequiredChatToolMode(string? requiredFunctionName) { if (requiredFunctionName != null) { Throw.IfNullOrWhitespace(requiredFunctionName, "requiredFunctionName"); } RequiredFunctionName = requiredFunctionName; } public override bool Equals(object? obj) { if (obj is RequiredChatToolMode requiredChatToolMode) { return RequiredFunctionName == requiredChatToolMode.RequiredFunctionName; } return false; } public override int GetHashCode() { string? requiredFunctionName = RequiredFunctionName; if (requiredFunctionName == null) { return typeof(RequiredChatToolMode).GetHashCode(); } return StringHash.GetHashCode(requiredFunctionName, StringComparison.Ordinal); } } [Experimental("MEAI001")] public interface IChatReducer { Task<IEnumerable<ChatMessage>> ReduceAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken); } [JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] [JsonDerivedType(typeof(CitationAnnotation), "citation")] public class AIAnnotation { public IList<AnnotatedRegion>? AnnotatedRegions { get; set; } [JsonIgnore] public object? RawRepresentation { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } } [JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] [JsonDerivedType(typeof(DataContent), "data")] [JsonDerivedType(typeof(ErrorContent), "error")] [JsonDerivedType(typeof(FunctionCallContent), "functionCall")] [JsonDerivedType(typeof(FunctionResultContent), "functionResult")] [JsonDerivedType(typeof(HostedFileContent), "hostedFile")] [JsonDerivedType(typeof(HostedVectorStoreContent), "hostedVectorStore")] [JsonDerivedType(typeof(TextContent), "text")] [JsonDerivedType(typeof(TextReasoningContent), "reasoning")] [JsonDerivedType(typeof(UriContent), "uri")] [JsonDerivedType(typeof(UsageContent), "usage")] public class AIContent { public IList<AIAnnotation>? Annotations { get; set; } [JsonIgnore] public object? RawRepresentation { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } } internal static class AIContentExtensions { public static string ConcatText(this IEnumerable<AIContent> contents) { if (contents is IList<AIContent> list) { int count = list.Count; switch (count) { case 0: return string.Empty; case 1: return (list[0] as TextContent)?.Text ?? string.Empty; default: { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { if (list[i] is TextContent textContent) { stringBuilder.Append(textContent.Text); } } return stringBuilder.ToString(); } } } return string.Concat(contents.OfType<TextContent>()); } public static string ConcatText(this IList<ChatMessage> messages) { int count = messages.Count; switch (count) { case 0: return string.Empty; case 1: return messages[0].Text; default: { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { string text = messages[i].Text; if (text.Length > 0) { if (stringBuilder.Length > 0) { stringBuilder.AppendLine(); } stringBuilder.Append(text); } } return stringBuilder.ToString(); } } } } [JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] [JsonDerivedType(typeof(TextSpanAnnotatedRegion), "textSpan")] public class AnnotatedRegion { } public class CitationAnnotation : AIAnnotation { public string? Title { get; set; } public Uri? Url { get; set; } public string? FileId { get; set; } public string? ToolName { get; set; } public string? Snippet { get; set; } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public class DataContent : AIContent { private readonly DataUriParser.DataUri? _dataUri; private string? _uri; private ReadOnlyMemory<byte>? _data; [StringSyntax("Uri")] public string Uri { get { if (_uri == null) { ReadOnlyMemory<byte> valueOrDefault = _data.GetValueOrDefault(); ArraySegment<byte> segment; string text = (MemoryMarshal.TryGetArray(valueOrDefault, out segment) ? Convert.ToBase64String(segment.Array, segment.Offset, segment.Count) : Convert.ToBase64String(valueOrDefault.ToArray())); _uri = "data:" + MediaType + ";base64," + text; } return _uri; } } [JsonIgnore] public string MediaType { get; } public string? Name { get; set; } [JsonIgnore] public ReadOnlyMemory<byte> Data { get { ReadOnlyMemory<byte>? data = _data; if (!data.HasValue) { _data = _dataUri.ToByteArray(); } return _data.GetValueOrDefault(); } } [JsonIgnore] public ReadOnlyMemory<char> Base64Data { get { string uri = Uri; int num = uri.IndexOf(','); return uri.AsMemory(num + 1); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { string uri = Uri; if (uri.Length > 80) { return "Data = " + uri.Substring(0, 80) + "..."; } return "Data = " + uri; } } public DataContent(Uri uri, string? mediaType = null) : this(Throw.IfNull(uri, "uri").ToString(), mediaType) { } [JsonConstructor] public DataContent([StringSyntax("Uri")] string uri, string? mediaType = null) { _uri = Throw.IfNullOrWhitespace(uri, "uri"); if (!uri.StartsWith(DataUriParser.Scheme, StringComparison.OrdinalIgnoreCase)) { Throw.ArgumentException("uri", "The provided URI is not a data URI."); } _dataUri = DataUriParser.Parse(uri.AsMemory()); if (mediaType == null) { mediaType = _dataUri.MediaType; } if (mediaType == null) { Throw.ArgumentNullException("mediaType", "uri did not contain a media type, and mediaType was not provided."); } MediaType = DataUriParser.ThrowIfInvalidMediaType(mediaType, "mediaType"); if (!_dataUri.IsBase64 || mediaType != _dataUri.MediaType) { _data = _dataUri.ToByteArray(); _dataUri = null; _uri = null; } } public DataContent(ReadOnlyMemory<byte> data, string mediaType) { MediaType = DataUriParser.ThrowIfInvalidMediaType(mediaType, "mediaType"); _data = data; } public bool HasTopLevelMediaType(string topLevelType) { return DataUriParser.HasTopLevelMediaType(MediaType, topLevelType); } } internal static class DataUriParser { public sealed class DataUri { public string? MediaType { get; } public ReadOnlyMemory<char> Data { get; } public bool IsBase64 { get; } public DataUri(ReadOnlyMemory<char> data, bool isBase64, string? mediaType) { MediaType = mediaType; Data = data; IsBase64 = isBase64; base..ctor(); } public byte[] ToByteArray() { if (!IsBase64) { return Encoding.UTF8.GetBytes(WebUtility.UrlDecode(Data.ToString())); } return Convert.FromBase64String(Data.ToString()); } } public static string Scheme => "data:"; public static DataUri Parse(ReadOnlyMemory<char> dataUri) { if (!dataUri.Span.StartsWith(Scheme.AsSpan(), StringComparison.OrdinalIgnoreCase)) { throw new UriFormatException("Invalid data URI format: the data URI must start with 'data:'."); } dataUri = dataUri.Slice(Scheme.Length); int num = dataUri.Span.IndexOf(','); if (num < 0) { throw new UriFormatException("Invalid data URI format: the data URI must contain a comma separating the metadata and the data."); } ReadOnlyMemory<char> readOnlyMemory = dataUri.Slice(0, num); ReadOnlyMemory<char> data = dataUri.Slice(num + 1); bool isBase = false; if (readOnlyMemory.Span.EndsWith(";base64".AsSpan(), StringComparison.OrdinalIgnoreCase)) { readOnlyMemory = readOnlyMemory.Slice(0, readOnlyMemory.Length - ";base64".Length); isBase = true; if (!IsValidBase64Data(data.Span)) { throw new UriFormatException("Invalid data URI format: the data URI is base64-encoded, but the data is not a valid base64 string."); } } ReadOnlySpan<char> mediaTypeSpan = readOnlyMemory.Span.Trim(); string mediaType = null; if (!mediaTypeSpan.IsEmpty && !IsValidMediaType(mediaTypeSpan, ref mediaType)) { throw new UriFormatException("Invalid data URI format: the media type is not a valid."); } return new DataUri(data, isBase, mediaType); } public static string ThrowIfInvalidMediaType(string mediaType, [CallerArgumentExpression("mediaType")] string parameterName = "") { Throw.IfNullOrWhitespace(mediaType, parameterName); if (!IsValidMediaType(mediaType)) { Throw.ArgumentException(parameterName, "An invalid media type was specified: '" + mediaType + "'"); } return mediaType; } public static bool IsValidMediaType(string mediaType) { return IsValidMediaType(mediaType.AsSpan(), ref mediaType); } public static bool IsValidMediaType(ReadOnlySpan<char> mediaTypeSpan, [NotNull] ref string? mediaType) { string text; switch (mediaTypeSpan.Length) { case 24: { char c = mediaTypeSpan[0]; if (c != 'a') { if (c == 't' && mediaTypeSpan.SequenceEqual("text/plain;charset=UTF-8".AsSpan())) { text = "text/plain;charset=UTF-8"; break; } } else if (mediaTypeSpan.SequenceEqual("application/octet-stream".AsSpan())) { text = "application/octet-stream"; break; } goto IL_045b; } case 15: { char c = mediaTypeSpan[12]; if (c != 'i') { if (c != 'p') { if (c == 'x' && mediaTypeSpan.SequenceEqual("application/xml".AsSpan())) { text = "application/xml"; break; } } else if (mediaTypeSpan.SequenceEqual("application/pdf".AsSpan())) { text = "application/pdf"; break; } } else if (mediaTypeSpan.SequenceEqual("text/javascript".AsSpan())) { text = "text/javascript"; break; } goto IL_045b; } case 10: switch (mediaTypeSpan[6]) { case 'm': break; case 'a': goto IL_01f3; case 'j': goto IL_0222; case 't': goto IL_023c; case 'w': goto IL_0256; case 'l': goto IL_0270; default: goto IL_045b; } if (!mediaTypeSpan.SequenceEqual("audio/mpeg".AsSpan())) { goto IL_045b; } text = "audio/mpeg"; break; case 9: { char c = mediaTypeSpan[6]; if ((uint)c <= 111u) { if (c != 'b') { if (c != 'g') { if (c == 'o' && mediaTypeSpan.SequenceEqual("audio/ogg".AsSpan())) { text = "audio/ogg"; break; } } else if (mediaTypeSpan.SequenceEqual("image/gif".AsSpan())) { text = "image/gif"; break; } } else if (mediaTypeSpan.SequenceEqual("image/bmp".AsSpan())) { text = "image/bmp"; break; } } else if (c != 'p') { if (c != 't') { if (c == 'w' && mediaTypeSpan.SequenceEqual("audio/wav".AsSpan())) { text = "audio/wav"; break; } } else if (mediaTypeSpan.SequenceEqual("text/html".AsSpan())) { text = "text/html"; break; } } else if (mediaTypeSpan.SequenceEqual("image/png".AsSpan())) { text = "image/png"; break; } goto IL_045b; } case 8: { char c = mediaTypeSpan[7]; if (c != 'l') { if (c != 's') { if (c == 'v' && mediaTypeSpan.SequenceEqual("text/csv".AsSpan())) { text = "text/csv"; break; } } else if (mediaTypeSpan.SequenceEqual("text/css".AsSpan())) { text = "text/css"; break; } } else if (mediaTypeSpan.SequenceEqual("text/xml".AsSpan())) { text = "text/xml"; break; } goto IL_045b; } case 16: if (!mediaTypeSpan.SequenceEqual("application/json".AsSpan())) { goto IL_045b; } text = "application/json"; break; case 13: if (!mediaTypeSpan.SequenceEqual("image/svg+xml".AsSpan())) { goto IL_045b; } text = "image/svg+xml"; break; default: goto IL_045b; IL_0270: if (!mediaTypeSpan.SequenceEqual("text/plain".AsSpan())) { goto IL_045b; } text = "text/plain"; break; IL_0256: if (!mediaTypeSpan.SequenceEqual("image/webp".AsSpan())) { goto IL_045b; } text = "image/webp"; break; IL_0222: if (!mediaTypeSpan.SequenceEqual("image/jpeg".AsSpan())) { goto IL_045b; } text = "image/jpeg"; break; IL_045b: text = null; break; IL_023c: if (!mediaTypeSpan.SequenceEqual("image/tiff".AsSpan())) { goto IL_045b; } text = "image/tiff"; break; IL_01f3: if (!mediaTypeSpan.SequenceEqual("image/apng".AsSpan())) { if (!mediaTypeSpan.SequenceEqual("image/avif".AsSpan())) { goto IL_045b; } text = "image/avif"; break; } text = "image/apng"; break; } string text2 = text; if (text2 != null) { mediaType = text2; return true; } if (mediaType == null) { mediaType = mediaTypeSpan.ToString(); } MediaTypeHeaderValue parsedValue; return MediaTypeHeaderValue.TryParse(mediaType, out parsedValue); } public static bool HasTopLevelMediaType(string mediaType, string topLevelMediaType) { int num = mediaType.IndexOf('/'); ReadOnlySpan<char> span = ((num < 0) ? mediaType.AsSpan() : mediaType.AsSpan(0, num)); span = span.Trim(); return MemoryExtensions.Equals(span, topLevelMediaType.AsSpan(), StringComparison.OrdinalIgnoreCase); } private static bool IsValidBase64Data(ReadOnlySpan<char> value) { if (value.IsEmpty) { return true; } if (value.Length % 4 != 0) { return false; } int num = value.Length - 1; if (value[num] == '=') { num--; } if (value[num] == '=') { num--; } for (int i = 0; i <= num; i++) { bool flag; switch (value[i]) { case '+': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': flag = true; break; default: flag = false; break; } if (!flag) { return false; } } return true; } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public class ErrorContent : AIContent { [CompilerGenerated] private string <Message>k__BackingField; public string Message { get { return <Message>k__BackingField ?? string.Empty; } [CompilerGenerated] [param: AllowNull] set { <Message>k__BackingField = value; } } public string? ErrorCode { get; set; } public string? Details { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => "Error = \"" + Message + "\"" + ((!string.IsNullOrWhiteSpace(ErrorCode)) ? (" (" + ErrorCode + ")") : string.Empty) + ((!string.IsNullOrWhiteSpace(Details)) ? (" - \"" + Details + "\"") : string.Empty); public ErrorContent(string? message) { Message = message; } } [Experimental("MEAI001")] public sealed class FunctionApprovalRequestContent : UserInputRequestContent { public FunctionCallContent FunctionCall { get; } public FunctionApprovalRequestContent(string id, FunctionCallContent functionCall) : base(id) { FunctionCall = Throw.IfNull(functionCall, "functionCall"); } public FunctionApprovalResponseContent CreateResponse(bool approved) { return new FunctionApprovalResponseContent(base.Id, approved, FunctionCall); } } [Experimental("MEAI001")] public sealed class FunctionApprovalResponseContent : UserInputResponseContent { public bool Approved { get; } public FunctionCallContent FunctionCall { get; } public FunctionApprovalResponseContent(string id, bool approved, FunctionCallContent functionCall) : base(id) { Approved = approved; FunctionCall = Throw.IfNull(functionCall, "functionCall"); } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public sealed class FunctionCallContent : AIContent { public string CallId { get; } public string Name { get; } public IDictionary<string, object?>? Arguments { get; set; } [JsonIgnore] public Exception? Exception { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { string text = "FunctionCall = "; if (CallId != null) { text = text + CallId + ", "; } return text + ((Arguments != null) ? (Name + "(" + string.Join(", ", Arguments) + ")") : (Name + "()")); } } [JsonConstructor] public FunctionCallContent(string callId, string name, IDictionary<string, object?>? arguments = null) { CallId = Throw.IfNull(callId, "callId"); Name = Throw.IfNull(name, "name"); Arguments = arguments; } public static FunctionCallContent CreateFromParsedArguments<TEncoding>(TEncoding encodedArguments, string callId, string name, Func<TEncoding, IDictionary<string, object?>?> argumentParser) { Throw.IfNull(encodedArguments, "encodedArguments"); Throw.IfNull(callId, "callId"); Throw.IfNull(name, "name"); Throw.IfNull(argumentParser, "argumentParser"); IDictionary<string, object> arguments = null; Exception exception = null; try { arguments = argumentParser(encodedArguments); } catch (Exception innerException) { exception = new InvalidOperationException("Error parsing function call arguments.", innerException); } return new FunctionCallContent(callId, name, arguments) { Exception = exception }; } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public sealed class FunctionResultContent : AIContent { public string CallId { get; } public object? Result { get; set; } [JsonIgnore] public Exception? Exception { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { string text = "FunctionResult = "; if (CallId != null) { text = text + CallId + ", "; } return text + ((Exception != null) ? (Exception.GetType().Name + "(\"" + Exception.Message + "\")") : ((Result?.ToString() ?? "(null)") ?? "")); } } [JsonConstructor] public FunctionResultContent(string callId, object? result) { CallId = Throw.IfNull(callId, "callId"); Result = result; } } [DebuggerDisplay("FileId = {FileId}")] public sealed class HostedFileContent : AIContent { private string _fileId; public string FileId { get { return _fileId; } set { _fileId = Throw.IfNullOrWhitespace(value, "value"); } } public HostedFileContent(string fileId) { _fileId = Throw.IfNullOrWhitespace(fileId, "fileId"); } } [DebuggerDisplay("VectorStoreId = {VectorStoreId}")] public sealed class HostedVectorStoreContent : AIContent { private string _vectorStoreId; public string VectorStoreId { get { return _vectorStoreId; } set { _vectorStoreId = Throw.IfNullOrWhitespace(value, "value"); } } public HostedVectorStoreContent(string vectorStoreId) { _vectorStoreId = Throw.IfNullOrWhitespace(vectorStoreId, "vectorStoreId"); } } [Experimental("MEAI001")] public sealed class McpServerToolApprovalRequestContent : UserInputRequestContent { public McpServerToolCallContent ToolCall { get; } public McpServerToolApprovalRequestContent(string id, McpServerToolCallContent toolCall) : base(id) { ToolCall = Throw.IfNull(toolCall, "toolCall"); } public McpServerToolApprovalResponseContent CreateResponse(bool approved) { return new McpServerToolApprovalResponseContent(base.Id, approved); } } [Experimental("MEAI001")] public sealed class McpServerToolApprovalResponseContent : UserInputResponseContent { public bool Approved { get; } public McpServerToolApprovalResponseContent(string id, bool approved) : base(id) { Approved = approved; } } [Experimental("MEAI001")] public sealed class McpServerToolCallContent : AIContent { public string CallId { get; } public string ToolName { get; } public string ServerName { get; } public IReadOnlyDictionary<string, object?>? Arguments { get; set; } public McpServerToolCallContent(string callId, string toolName, string serverName) { CallId = Throw.IfNullOrWhitespace(callId, "callId"); ToolName = Throw.IfNullOrWhitespace(toolName, "toolName"); ServerName = Throw.IfNullOrWhitespace(serverName, "serverName"); } } [Experimental("MEAI001")] public sealed class McpServerToolResultContent : AIContent { public string CallId { get; } public IList<AIContent>? Output { get; set; } public McpServerToolResultContent(string callId) { CallId = Throw.IfNullOrWhitespace(callId, "callId"); } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public sealed class TextContent : AIContent { [CompilerGenerated] private string <Text>k__BackingField; public string Text { get { return <Text>k__BackingField ?? string.Empty; } [CompilerGenerated] [param: AllowNull] set { <Text>k__BackingField = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => "Text = \"" + Text + "\""; public TextContent(string? text) { Text = text; } public override string ToString() { return Text; } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public sealed class TextReasoningContent : AIContent { [CompilerGenerated] private string <Text>k__BackingField; public string Text { get { return <Text>k__BackingField ?? string.Empty; } [CompilerGenerated] [param: AllowNull] set { <Text>k__BackingField = value; } } public string? ProtectedData { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => "Reasoning = \"" + Text + "\""; public TextReasoningContent(string? text) { Text = text; } public override string ToString() { return Text; } } [DebuggerDisplay("[{StartIndex}, {EndIndex})")] public sealed class TextSpanAnnotatedRegion : AnnotatedRegion { [JsonPropertyName("start")] public int? StartIndex { get; set; } [JsonPropertyName("end")] public int? EndIndex { get; set; } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public class UriContent : AIContent { private Uri _uri; private string _mediaType; public Uri Uri { get { return _uri; } set { _uri = Throw.IfNull(value, "value"); } } public string MediaType { get { return _mediaType; } set { _mediaType = DataUriParser.ThrowIfInvalidMediaType(value, "value"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => $"Uri = {_uri}"; public UriContent(string uri, string mediaType) : this(new Uri(Throw.IfNull(uri, "uri")), mediaType) { } [JsonConstructor] public UriContent(Uri uri, string mediaType) { _uri = Throw.IfNull(uri, "uri"); _mediaType = DataUriParser.ThrowIfInvalidMediaType(mediaType, "mediaType"); } public bool HasTopLevelMediaType(string topLevelType) { return DataUriParser.HasTopLevelMediaType(MediaType, topLevelType); } } [DebuggerDisplay("{DebuggerDisplay,nq}")] public class UsageContent : AIContent { private UsageDetails _details; public UsageDetails Details { get { return _details; } set { _details = Throw.IfNull(value, "value"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => "Usage = " + _details.DebuggerDisplay; public UsageContent() { _details = new UsageDetails(); } [JsonConstructor] public UsageContent(UsageDetails details) { _details = Throw.IfNull(details, "details"); } } [Experimental("MEAI001")] public class UserInputRequestContent : AIContent { public string Id { get; } protected UserInputRequestContent(string id) { Id = Throw.IfNullOrWhitespace(id, "id"); } } [Experimental("MEAI001")] public class UserInputResponseContent : AIContent { public string Id { get; } protected UserInputResponseContent(string id) { Id = Throw.IfNullOrWhitespace(id, "id"); } } public sealed class BinaryEmbedding : Embedding { [EditorBrowsable(EditorBrowsableState.Never)] public sealed class VectorConverter : JsonConverter<BitArray> { public override BitArray Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Throw.IfNull(typeToConvert, "typeToConvert"); Throw.IfNull(options, "options"); if (reader.TokenType != JsonTokenType.String) { throw new JsonException("Expected string property."); } byte[] array = null; ReadOnlySpan<byte> readOnlySpan; if (!reader.HasValueSequence && !reader.ValueIsEscaped) { readOnlySpan = reader.ValueSpan; } else { int minimumLength = (reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length); array = ArrayPool<byte>.Shared.Rent(minimumLength); readOnlySpan = array.AsSpan(0, reader.CopyString((Span<byte>)array)); } BitArray bitArray = new BitArray(readOnlySpan.Length); for (int i = 0; i < readOnlySpan.Length; i++) { BitArray bitArray2 = bitArray; int index = i; bitArray2[index] = readOnlySpan[i] switch { 48 => false, 49 => true, _ => throw new JsonException("Expected binary character sequence."), }; } if (array != null) { ArrayPool<byte>.Shared.Return(array); } return bitArray; } public override void Write(Utf8JsonWriter writer, BitArray value, JsonSerializerOptions options) { Throw.IfNull(writer, "writer"); Throw.IfNull(value, "value"); Throw.IfNull(options, "options"); int length = value.Length; byte[] array = ArrayPool<byte>.Shared.Rent(length); Span<byte> span = array.AsSpan(0, length); for (int i = 0; i < span.Length; i++) { span[i] = (byte)(value[i] ? 49 : 48); } writer.WriteStringValue(span); ArrayPool<byte>.Shared.Return(array); } } private BitArray _vector; [JsonConverter(typeof(VectorConverter))] public BitArray Vector { get { return _vector; } set { _vector = Throw.IfNull(value, "value"); } } [JsonIgnore] public override int Dimensions => _vector.Length; public BinaryEmbedding(BitArray vector) { _vector = Throw.IfNull(vector, "vector"); } } public class DelegatingEmbeddingGenerator<TInput, TEmbedding> : IEmbeddingGenerator<TInput, TEmbedding>, IEmbeddingGenerator, IDisposable where TEmbedding : Embedding { protected IEmbeddingGenerator<TInput, TEmbedding> InnerGenerator { get; } protected DelegatingEmbeddingGenerator(IEmbeddingGenerator<TInput, TEmbedding> innerGenerator) { InnerGenerator = Throw.IfNull(innerGenerator, "innerGenerator"); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public virtual Task<GeneratedEmbeddings<TEmbedding>> GenerateAsync(IEnumerable<TInput> values, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return InnerGenerator.GenerateAsync(values, options, cancellationToken); } public virtual object? GetService(Type serviceType, object? serviceKey = null) { Throw.IfNull(serviceType, "serviceType"); if (serviceKey != null || !serviceType.IsInstanceOfType(this)) { return InnerGenerator.GetService(serviceType, serviceKey); } return this; } protected virtual void Dispose(bool disposing) { if (disposing) { InnerGenerator.Dispose(); } } } [JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] [JsonDerivedType(typeof(BinaryEmbedding), "binary")] [JsonDerivedType(typeof(Embedding<byte>), "uint8")] [JsonDerivedType(typeof(Embedding<sbyte>), "int8")] [JsonDerivedType(typeof(Embedding<float>), "float32")] [JsonDerivedType(typeof(Embedding<double>), "float64")] [DebuggerDisplay("Dimensions = {Dimensions}")] public class Embedding { public DateTimeOffset? CreatedAt { get; set; } [JsonIgnore] public virtual int Dimensions { get; } public string? ModelId { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } protected Embedding() { } } public class EmbeddingGenerationOptions { [CompilerGenerated] private int? <Dimensions>k__BackingField; public int? Dimensions { [CompilerGenerated] get { return <Dimensions>k__BackingField; } set { if (value.HasValue) { Throw.IfLessThan(value.Value, 1, "value"); } <Dimensions>k__BackingField = value; } } public string? ModelId { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } [JsonIgnore] public Func<IEmbeddingGenerator, object?>? RawRepresentationFactory { get; set; } public EmbeddingGenerationOptions() { } protected EmbeddingGenerationOptions(EmbeddingGenerationOptions? other) { if (other != null) { AdditionalProperties = other.AdditionalProperties?.Clone(); Dimensions = other.Dimensions; ModelId = other.ModelId; RawRepresentationFactory = other.RawRepresentationFactory; } } public virtual EmbeddingGenerationOptions Clone() { return new EmbeddingGenerationOptions(this); } } public static class EmbeddingGeneratorExtensions { public static TService? GetService<TService>(this IEmbeddingGenerator generator, object? serviceKey = null) { Throw.IfNull(generator, "generator"); object service = generator.GetService(typeof(TService), serviceKey); if (service is TService) { return (TService)service; } return default(TService); } public static object GetRequiredService(this IEmbeddingGenerator generator, Type serviceType, object? serviceKey = null) { Throw.IfNull(generator, "generator"); Throw.IfNull(serviceType, "serviceType"); return generator.GetService(serviceType, serviceKey) ?? throw Throw.CreateMissingServiceException(serviceType, serviceKey); } public static TService GetRequiredService<TService>(this IEmbeddingGenerator generator, object? serviceKey = null) { Throw.IfNull(generator, "generator"); object service = generator.GetService(typeof(TService), serviceKey); if (service is TService) { return (TService)service; } throw Throw.CreateMissingServiceException(typeof(TService), serviceKey); } public static async Task<ReadOnlyMemory<TEmbeddingElement>> GenerateVectorAsync<TInput, TEmbeddingElement>(this IEmbeddingGenerator<TInput, Embedding<TEmbeddingElement>> generator, TInput value, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return (await generator.GenerateAsync(value, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Vector; } public static async Task<TEmbedding> GenerateAsync<TInput, TEmbedding>(this IEmbeddingGenerator<TInput, TEmbedding> generator, TInput value, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) where TEmbedding : Embedding { Throw.IfNull(generator, "generator"); Throw.IfNull(value, "value"); GeneratedEmbeddings<TEmbedding> generatedEmbeddings = await generator.GenerateAsync(new <>z__ReadOnlySingleElementList<TInput>(value), options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (generatedEmbeddings == null) { Throw.InvalidOperationException("Embedding generator returned a null collection of embeddings."); } if (generatedEmbeddings.Count != 1) { Throw.InvalidOperationException($"Expected the number of embeddings ({generatedEmbeddings.Count}) to match the number of inputs (1)."); } TEmbedding val = generatedEmbeddings[0]; if (val == null) { Throw.InvalidOperationException("Embedding generator generated a null embedding."); } return val; } public static async Task<(TInput Value, TEmbedding Embedding)[]> GenerateAndZipAsync<TInput, TEmbedding>(this IEmbeddingGenerator<TInput, TEmbedding> generator, IEnumerable<TInput> values, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) where TEmbedding : Embedding { Throw.IfNull(generator, "generator"); Throw.IfNull(values, "values"); IList<TInput> inputs = (values as IList<TInput>) ?? values.ToList(); int inputsCount = inputs.Count; if (inputsCount == 0) { return Array.Empty<(TInput, TEmbedding)>(); } GeneratedEmbeddings<TEmbedding> generatedEmbeddings = await generator.GenerateAsync(values, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (generatedEmbeddings.Count != inputsCount) { Throw.InvalidOperationException($"Expected the number of embeddings ({generatedEmbeddings.Count}) to match the number of inputs ({inputsCount})."); } (TInput, TEmbedding)[] array = new(TInput, TEmbedding)[generatedEmbeddings.Count]; for (int i = 0; i < array.Length; i++) { array[i] = (inputs[i], generatedEmbeddings[i]); } return array; } } public class EmbeddingGeneratorMetadata { public string? ProviderName { get; } public Uri? ProviderUri { get; } public string? DefaultModelId { get; } public int? DefaultModelDimensions { get; } public EmbeddingGeneratorMetadata(string? providerName = null, Uri? providerUri = null, string? defaultModelId = null, int? defaultModelDimensions = null) { DefaultModelId = defaultModelId; ProviderName = providerName; ProviderUri = providerUri; DefaultModelDimensions = defaultModelDimensions; } } public sealed class Embedding<T> : Embedding { public ReadOnlyMemory<T> Vector { get; set; } [JsonIgnore] public override int Dimensions => Vector.Length; public Embedding(ReadOnlyMemory<T> vector) { Vector = vector; } } [DebuggerDisplay("Count = {Count}")] public sealed class GeneratedEmbeddings<TEmbedding> : IList<TEmbedding>, ICollection<TEmbedding>, IEnumerable<TEmbedding>, IEnumerable, IReadOnlyList<TEmbedding>, IReadOnlyCollection<TEmbedding> where TEmbedding : Embedding { private List<TEmbedding> _embeddings; public UsageDetails? Usage { get; set; } public AdditionalPropertiesDictionary? AdditionalProperties { get; set; } public TEmbedding this[int index] { get { return _embeddings[index]; } set { _embeddings[index] = value; } } public int Count => _embeddings.Count; bool ICollection<TEmbedding>.IsReadOnly => false; public GeneratedEmbeddings() { _embeddings = new List<TEmbedding>(); } public GeneratedEmbeddings(int capacity) { _embeddings = new List<TEmbedding>(Throw.IfLessThan(capacity, 0, "capacity")); } public GeneratedEmbeddings(IEnumerable<TEmbedding> embeddings) { _embeddings = new List<TEmbedding>(Throw.IfNull(embeddings, "embeddings")); } public void Add(TEmbedding item) { _embeddings.Add(item); } public void AddRange(IEnumerable<TEmbedding> items) { _embeddings.AddRange(items); } public void Clear() { _embeddings.Clear(); } public bool Contains(TEmbedding item) { return _embeddings.Contains(item); } public void CopyTo(TEmbedding[] array, int arrayIndex) { _embeddings.CopyTo(array, arrayIndex); } public IEnumerator<TEmbedding> GetEnumerator() { return _embeddings.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int IndexOf(TEmbedding item) { return _embeddings.IndexOf(item); } public void Insert(int index, TEmbedding item) { _embeddings.Insert(index, item); } public bool Remove(TEmbedding item) { return _embeddings.Remove(item); } public void RemoveAt(int index) { _embeddings.RemoveAt(index); } } public interface IEmbeddingGenerator : IDisposable { object? GetService(Type serviceType, object? serviceKey = null); } public interface IEmbeddingGenerator<in TInput, TEmbedding> : IEmbeddingGenerator, IDisposable where TEmbedding : Embedding { Task<GeneratedEmbeddings<TEmbedding>> GenerateAsync(IEnumerable<TInput> values, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)); } public abstract class AIFunction : AIFunctionDeclaration { private sealed class NonInvocableAIFunction : DelegatingAIFunctionDeclaration { public NonInvocableAIFunction(AIFunction function) : base(function) { } } public virtual MethodInfo? UnderlyingMethod => null; public virtual JsonSerializerOptions JsonSerializerOptions => AIJsonUtilities.DefaultOptions; public ValueTask<object?> InvokeAsync(AIFunctionArguments? arguments = null, CancellationToken cancellationToken = default(CancellationToken)) { return InvokeCoreAsync(arguments ?? new AIFunctionArguments(), cancellationToken); } protected abstract ValueTask<object?> InvokeCoreAsync(AIFunctionArguments arguments, CancellationToken cancellationToken); public AIFunctionDeclaration AsDeclarationOnly() { return new NonInvocableAIFunction(this); } } [DebuggerDisplay("Count = {Count}")] public class AIFunctionArguments : IDictionary<string, object?>, ICollection<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyDictionary<string, object?>, IReadOnlyCollection<KeyValuePair<string, object?>> { private readonly Dictionary<string, object?> _arguments; public IServiceProvider? Services { get; set; } public IDictionary<object, object?>? Context { get; set; } public object? this[string key] { get { return _arguments[key]; } set { _arguments[key] = value; } } public ICollection<string> Keys => _arguments.Keys; public ICollection<object?> Values => _arguments.Values; public int Count => _arguments.Count; bool ICollection<KeyValuePair<string, object>>.IsReadOnly => false; IEnumerable<string> IReadOnlyDictionary<string, object>.Keys => Keys; IEnumerable<object?> IReadOnlyDictionary<string, object>.Values => Values; public AIFunctionArguments() : this(null, null) { } public AIFunctionArguments(IDictionary<string, object?>? arguments) : this(arguments, null) { } public AIFunctionArguments(IEqualityComparer<string>? comparer) : this(null, comparer) { } public AIFunctionArguments(IDictionary<string, object?>? arguments, IEqualityComparer<string>? comparer) { _arguments = ((arguments == null) ? new Dictionary<string, object>(comparer) : ((arguments is Dictionary<string, object> dictionary && (comparer == null || dictionary.Comparer == comparer)) ? dictionary : new Dictionary<string, object>(arguments, comparer))); } public void Add(string key, object? value) { _arguments.Add(key, value); } void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object?> item) { ((ICollection<KeyValuePair<string, object>>)_arguments).Add(item); } public void Clear() { _arguments.Clear(); } bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object?> item) { return ((ICollection<KeyValuePair<string, object>>)_arguments).Contains(item); } public bool ContainsKey(string key) { return _arguments.ContainsKey(key); } public void CopyTo(KeyValuePair<string, object?>[] array, int arrayIndex) { ((ICollection<KeyValuePair<string, object>>)_arguments).CopyTo(array, arrayIndex); } public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() { return _arguments.GetEnumerator(); } public bool Remove(string key) { return _arguments.Remove(key); } bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object?> item) { return ((ICollection<KeyValuePair<string, object>>)_arguments).Remove(item); } public bool TryGetValue(string key, out object? value) { return _arguments.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public abstract class AIFunctionDeclaration : AITool { public virtual JsonElement JsonSchema => AIJsonUtilities.DefaultJsonSchema; public virtual JsonElement? ReturnJsonSchema => null; } public static class AIFunctionFactory { private sealed class DefaultAIFunctionDeclaration : AIFunctionDeclaration { [CompilerGenerated] private string <name>P; [CompilerGenerated] private string <description>P; [CompilerGenerated] private JsonElement <jsonSchema>P; [CompilerGenerated] private JsonElement? <returnJsonSchema>P; public override string Name => <name>P; public override string Description => <description>P; public override JsonElement JsonSchema => <jsonSchema>P; public override JsonElement? ReturnJsonSchema => <returnJsonSchema>P; public DefaultAIFunctionDeclaration(string name, string description, JsonElement jsonSchema, JsonElement? returnJsonSchema) { <name>P = name; <description>P = description; <jsonSchema>P = jsonSchema; <returnJsonSchema>P = returnJsonSchema; base..ctor(); } } private sealed class ReflectionAIFunction : AIFunction { public ReflectionAIFunctionDescriptor FunctionDescriptor { get; } public object? Target { get; } public Func<AIFunctionArguments, object>? CreateInstanceFunc { get; } public override IReadOnlyDictionary<string, object?> AdditionalProperties { get; } public override string Name => FunctionDescriptor.Name; public override string Description => FunctionDescriptor.Description; public override MethodInfo UnderlyingMethod => FunctionDescriptor.Method; public override JsonElement JsonSchema => FunctionDescriptor.JsonSchema; public override JsonElement? ReturnJsonSchema => FunctionDescriptor.ReturnJsonSchema; public override JsonSerializerOptions JsonSerializerOptions => FunctionDescriptor.JsonSerializerOptions; public static ReflectionAIFunction Build(MethodInfo method, object? target, AIFunctionFactoryOptions options) { Throw.IfNull(method, "method"); if (method.ContainsGenericParameters) { Throw.ArgumentException("method", "Open generic methods are not supported"); } if (!method.IsStatic && target == null) { Throw.ArgumentNullException("target", "Target must not be null for an instance method."); } ReflectionAIFunctionDescriptor orCreate = ReflectionAIFunctionDescriptor.GetOrCreate(method, options); if (target == null && options.AdditionalProperties == null) { ReflectionAIFunctionDescriptor reflectionAIFunctionDescriptor = orCreate; return reflectionAIFunctionDescriptor.CachedDefaultInstance ?? (reflectionAIFunctionDescriptor.CachedDefaultInstance = new ReflectionAIFunction(orCreate, target, options)); } return new ReflectionAIFunction(orCreate, target, options); } public static ReflectionAIFunction Build(MethodInfo method, Func<AIFunctionArguments, object> createInstanceFunc, AIFunctionFactoryOptions options) { Throw.IfNull(method, "method"); Throw.IfNull(createInstanceFunc, "createInstanceFunc"); if (method.ContainsGenericParameters) { Throw.ArgumentException("method", "Open generic methods are not supported"); } if (method.IsStatic) { Throw.ArgumentException("method", "The method must be an instance method."); } return new ReflectionAIFunction(ReflectionAIFunctionDescriptor.GetOrCreate(method, options), createInstanceFunc, options); } private ReflectionAIFunction(ReflectionAIFunctionDescriptor functionDescriptor, object? target, AIFunctionFactoryOptions options) { FunctionDescriptor = functionDescriptor; Target = target; AdditionalProperties = options.AdditionalProperties ?? EmptyReadOnlyDictionary<string, object>.Instance; } private ReflectionAIFunction(ReflectionAIFunctionDescriptor functionDescriptor, Func<AIFunctionArguments, object> createInstanceFunc, AIFunctionFactoryOptions options) { FunctionDescriptor = functionDescriptor; CreateInstanceFunc = createInstanceFunc; AdditionalProperties = options.AdditionalProperties ?? EmptyReadOnlyDictionary<string, object>.Instance; } protected override async ValueTask<object?> InvokeCoreAsync(AIFunctionArguments arguments, CancellationToken cancellationToken) { bool disposeTarget = false; object target = Target; object result; try { Func<AIFunctionArguments, object> createInstanceFunc = CreateInstanceFunc; if (createInstanceFunc != null) { target = createInstanceFunc(arguments); if (target == null) { Throw.InvalidOperationException("Unable to create an instance of the target type."); } disposeTarget = true; } Func<AIFunctionArguments, CancellationToken, object>[] parameterMarshallers = FunctionDescriptor.ParameterMarshallers; object[] array = ((parameterMarshallers.Length != 0) ? new object[parameterMarshallers.Length] : Array.Empty<object>()); for (int i = 0; i < array.Length; i++) { array[i] = parameterMarshallers[i](arguments, cancellationToken); } result = await FunctionDescriptor.ReturnParameterMarshaller(ReflectionInvoke(FunctionDescriptor.Method, target, array), cancellationToken).ConfigureAwait(continueOnCapturedContext: true); } finally { if (disposeTarget) { if (target is IAsyncDisposable asyncDisposable) { await asyncDisposable.DisposeAsync().ConfigureAwait(continueOnCapturedContext: true); } else if (target is IDisposable disposable) { disposable.Dispose(); } } } return result; } } private sealed class ReflectionAIFunctionDescriptor { private record struct DescriptorKey(MethodInfo Method, string? Name, string? Description, Func<ParameterInfo, AIFunctionFactoryOptions.ParameterBindingOptions>? GetBindParameterOptions, Func<object?, Type?, CancellationToken, ValueTask<object?>>? MarshalResult, bool ExcludeResultSchema, AIJsonSchemaCreateOptions SchemaOptions); private const int InnerCacheSoftLimit = 512; private static readonly ConditionalWeakTable<JsonSerializerOptions, ConcurrentDictionary<DescriptorKey, ReflectionAIFunctionDescriptor>> _descriptorCache = new ConditionalWeakTable<JsonSerializerOptions, ConcurrentDictionary<DescriptorKey, ReflectionAIFunctionDescriptor>>(); private static readonly object? _boxedDefaultCancellationToken = default(CancellationToken); private static readonly MethodInfo _taskGetResult = typeof(Task<>).GetProperty("Result", BindingFlags.Instance | BindingFlags.Public).GetMethod; private static readonly MethodInfo _valueTaskAsTask = typeof(ValueTask<>).GetMethod("AsTask", BindingFlags.Instance | BindingFlags.Public); public string Name { get; } public string Description { get; } public MethodInfo Method { get; } public JsonSerializerOptions JsonSerializerOptions { get; } public JsonElement JsonSchema { get; } public JsonElement? ReturnJsonSchema { get; } public Func<AIFunctionArguments, CancellationToken, object?>[] ParameterMarshallers { get; } public Func<object?, CancellationToken, ValueTask<object?>> ReturnParameterMarshaller { get; } public ReflectionAIFunction? CachedDefaultInstance { get; set; } public static ReflectionAIFunctionDescriptor GetOrCreate(MethodInfo method, AIFunctionFactoryOptions options) { JsonSerializerOptions jsonSerializerOptions = options.SerializerOptions ?? AIJsonUtilities.DefaultOptions; AIJsonSchemaCreateOptions schemaOptions = options.JsonSchemaCreateOptions ?? AIJsonSchemaCreateOptions.Default; jsonSerializerOptions.MakeReadOnly(); ConcurrentDictionary<DescriptorKey, ReflectionAIFunctionDescriptor> orCreateValue = _descriptorCache.GetOrCreateValue(jsonSerializerOptions); DescriptorKey key = new DescriptorKey(method, options.Name, options.Description, options.ConfigureParameterBinding, options.MarshalResult, options.ExcludeResultSchema, schemaOptions); if (orCreateValue.TryGetValue(key, out var value)) { return value; } value = new ReflectionAIFunctionDescriptor(key, jsonSerializerOptions); if (orCreateValue.Count >= 512) { return value; } return orCreateValue.GetOrAdd(key, value); } private ReflectionAIFunctionDescriptor(DescriptorKey key, JsonSerializerOptions serializerOptions) { ParameterInfo[] parameters = key.Method.GetParameters(); Dictionary<ParameterInfo, AIFunctionFactoryOptions.ParameterBindingOptions> boundParameters = null; if (parameters.Length != 0 && key.GetBindParameterOptions != null) { boundParameters = new Dictionary<ParameterInfo, AIFunctionFactoryOptions.ParameterBindingOptions>(parameters.Length); for (int i = 0; i < parameters.Length; i++) { boundParameters[parameters[i]] = key.GetBindParameterOptions(parameters[i]); } } AIJsonSchemaCreateOptions inferenceOptions = key.SchemaOptions with { IncludeParameter = delegate(ParameterInfo parameterInfo) { if (parameterInfo.ParameterType == typeof(AIFunctionArguments) || parameterInfo.ParameterType == typeof(IServiceProvider)) { return false; } AIFunctionFactoryOptions.ParameterBindingOptions value2 = default(AIFunctionFactoryOptions.ParameterBindingOptions); bool? flag = boundParameters?.TryGetValue(parameterInfo, out value2); return (!flag.HasValue || !flag.GetValueOrDefault() || !value2.ExcludeFromSchema) && (key.SchemaOptions.IncludeParameter?.Invoke(parameterInfo) ?? true); } }; ParameterMarshallers = ((parameters.Length != 0) ? new Func<AIFunctionArguments, CancellationToken, object>[parameters.Length] : Array.Empty<Func<AIFunctionArguments, CancellationToken, object>>()); AIFunctionFactoryOptions.ParameterBindingOptions value = default(AIFunctionFactoryOptions.ParameterBindingOptions); for (int j = 0; j < parameters.Length; j++) { if ((!(boundParameters?.TryGetValue(parameters[j], out value))) ?? true) { value = default(AIFunctionFactoryOptions.ParameterBindingOptions); } ParameterMarshallers[j] = GetParameterMarshaller(serializerOptions, value, parameters[j]); } ReturnParameterMarshaller = GetReturnParameterMarshaller(key, serializerOptions, out Type returnType); Method = key.Method; Name = key.Name ?? GetFunctionName(key.Method); Description = key.Description ?? key.Method.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description ?? string.Empty; JsonSerializerOptions = serializerOptions; ReturnJsonSchema = (((object)returnType == null || key.ExcludeResultSchema) ? null : new JsonElement?(AIJsonUtilities.CreateJsonSchema(returnType, key.Method.ReturnParameter.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description, hasDefaultValue: false, null, serializerOptions, inferenceOptions))); JsonSchema = AIJsonUtilities.CreateFunctionJsonSchema(key.Method, string.Empty, string.Empty, serializerOptions, inferenceOptions); } private static string GetFunctionName(MethodInfo method) { string text = SanitizeMemberName(method.Name); if (IsAsyncMethod(method)) { int num = text.LastIndexOf("Async", StringComparison.Ordinal); if (num > 0 && (num + "Async".Length == text.Length || (num + "Async".Length < text.Length && text[num + "Async".Length] == '_'))) { text = text.Substring(0, num) + text.Substring(num + "Async".Length); } } return text; static bool IsAsyncMethod(MethodInfo method) { Type returnType = method.ReturnType; if (returnType == typeof(Task) || returnType == typeof(ValueTask)) { return true; } if (returnType.IsGenericType) { returnType = returnType.GetGenericTypeDefinition(); if (returnType == typeof(Task<>) || returnType == typeof(ValueTask<>) || returnType == typeof(IAsyncEnumerable<>)) { return true; } } return false; } } private static Func<AIFunctionArguments, CancellationToken, object?> GetParameterMarshaller(JsonSerializerOptions serializerOptions, AIFunctionFactoryOptions.ParameterBindingOptions bindingOptions, ParameterInfo parameter) { ParameterInfo parameter2 = parameter; JsonSerializerOptions serializerOptions2 = serializerOptions; if (string.IsNullOrWhiteSpace(parameter2.Name)) { Throw.ArgumentException("parameter", "Parameter is missing a name."); } Type parameterType = parameter2.ParameterType; if (parameterType == typeof(CancellationToken)) { return (AIFunctionArguments _, CancellationToken cancellationToken) => (!(cancellationToken == default(CancellationToken))) ? ((object)cancellationToken) : _boxedDefaultCancellationToken; } Func<ParameterInfo, AIFunctionArguments, object?> bindParameter = bindingOptions.BindParameter; if (bindParameter != null) { return (AIFunctionArguments arguments, CancellationToken _) => bindParameter(parameter2, arguments); } if (parameterType == typeof(AIFunctionArguments)) { return (AIFunctionArguments arguments, CancellationToken _) => arguments; } if (parameterType == typeof(IServiceProvider)) { return delegate(AIFunctionArguments arguments, CancellationToken _) { IServiceProvider services = arguments.Services; if (!parameter2.HasDefaultValue && services == null) { ThrowNullServices(parameter2.Name); } return services; }; } JsonTypeInfo typeInfo = serializerOptions2.GetTypeInfo(parameterType); return delegate(AIFunctionArguments arguments, CancellationToken _) { if (arguments.TryGetValue(parameter2.Name, out object value2)) { object obj2 = value2; if (obj2 == null) { return null; } if (parameterType.IsInstanceOfType(value2)) { return value2; } if (obj2 is JsonElement jsonElement) { return JsonSerializer.Deserialize(jsonElement, typeInfo); } if (obj2 is JsonDocument jsonDocument) { return JsonSerializer.Deserialize(jsonDocument, typeInfo); } if (obj2 is JsonNode jsonNode) { return JsonSerializer.Deserialize(jsonNode, typeInfo); } return MarshallViaJsonRoundtrip(value2); } if (!parameter2.HasDefaultValue) { Throw.ArgumentException("arguments", "The arguments dictionary is missing a value for the required parameter '" + parameter2.Name + "'."); } return parameter2.DefaultValue; }; object? MarshallViaJsonRoundtrip(object value) { try { if (value is string text && IsPotentiallyJson(text)) { try { return JsonSerializer.Deserialize(text, typeInfo); } catch (JsonException) { } } string text2 = JsonSerializer.Serialize(value, serializerOptions2.GetTypeInfo(value.GetType())); return JsonSerializer.Deserialize(text2, typeInfo); } catch { return value; } } static void ThrowNullServices(string parameterName) { Throw.ArgumentNullException("arguments.Services", "Services are required for parameter '" + parameterName + "'."); } } private static Func<object?, CancellationToken, ValueTask<object?>> GetReturnParameterMarshaller(DescriptorKey key, JsonSerializerOptions serializerOptions, out Type? returnType) { returnType = key.Method.ReturnType; Func<object?, Type?, CancellationToken, ValueTask<object?>> marshalResult = key.MarshalResult; if (returnType == typeof(void)) { returnType = null; if (marshalResult != null) { return (object? result, CancellationToken cancellationToken) => marshalResult(null, null, cancellationToken); } return (object? _, CancellationToken _) => new ValueTask<object>((object)null); } if (returnType == typeof(Task)) { returnType = null; if (marshalResult != null) { return async delegate(object? result, CancellationToken cancellationToken) { await ((Task)ThrowIfNullResult(result)).ConfigureAwait(continueOnCapturedContext: true); return await marshalResult(null, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); }; } return async delegate(object? result, CancellationToken _) { await ((Task)ThrowIfNullResult(result)).ConfigureAwait(continueOnCapturedContext: true); return null; }; } if (returnType == typeof(ValueTask)) { returnType = null; if (marshalResult != null) { return async delegate(object? result, CancellationToken cancellationToken) { await ((ValueTask)ThrowIfNullResult(result)).ConfigureAwait(continueOnCapturedContext: true); return await marshalResult(null, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); }; } return async delegate(object? result, CancellationToken _) { await ((ValueTask)ThrowIfNullResult(result)).ConfigureAwait(continueOnCapturedContext: true); return null; }; } JsonTypeInfo returnTypeInfo2; if (returnType.IsGenericType) { if (returnType.GetGenericTypeDefinition() == typeof(Task<>)) { MethodInfo taskResultGetter = GetMethodFromGenericMethodDefinition(returnType, _taskGetResult); returnType = taskResultGetter.ReturnType; if (marshalResult != null) { return async delegate(object? taskObj, CancellationToken cancellationToken) { await ((Task)ThrowIfNullResult(taskObj)).ConfigureAwait(continueOnCapturedContext: true); object arg2 = ReflectionInvoke(taskResultGetter, taskObj, null); return await marshalResult(arg2, taskResultGetter.ReturnType, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); }; } returnTypeInfo2 = serializerOptions.GetTypeInfo(returnType); return async delegate(object? taskObj, CancellationToken cancellationToken) { await ((Task)ThrowIfNullResult(taskObj)).ConfigureAwait(continueOnCapturedContext: true); object result3 = ReflectionInvoke(taskResultGetter, taskObj, null); return await SerializeResultAsync(result3, returnTypeInfo2, cancellationToken).ConfigureAwait(continueOnCapturedContext: true); }; } if (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)) { MethodInfo valueTaskAsTask = GetMethodFromGenericMethodDefinition(returnType, _valueTaskAsTask); MethodInfo asTaskResultGetter = GetMethodFromGenericMethodDefinition(valueTaskAsTask.ReturnType, _taskGetResult); returnType = asTaskResultGetter.ReturnType; if (marshalResult != null) { return async delegate(object? taskObj, CancellationToken cancellationToken) { Task tas
deps/Microsoft.Extensions.AI.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Metrics; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.Versioning; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.AI; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Shared.Collections; using Microsoft.Shared.Diagnostics; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Utilities for working with generative AI components.")] [assembly: AssemblyFileVersion("9.900.125.47406")] [assembly: AssemblyInformationalVersion("9.9.1+54f611c53feaaecb28108edd16725b7577c8a9aa")] [assembly: AssemblyProduct("Microsoft.Extensions.AI")] [assembly: AssemblyTitle("Microsoft.Extensions.AI")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/extensions")] [assembly: AssemblyVersion("9.9.0.0")] [assembly: TypeForwardedTo(typeof(IChatReducer))] [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] internal sealed class ParamCollectionAttribute : 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.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [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 Microsoft.Extensions.DependencyInjection { public static class ChatClientBuilderServiceCollectionExtensions { public static ChatClientBuilder AddChatClient(this IServiceCollection serviceCollection, IChatClient innerClient, ServiceLifetime lifetime = ServiceLifetime.Singleton) { IChatClient innerClient2 = innerClient; Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull<IChatClient>(innerClient2, "innerClient"); return serviceCollection.AddChatClient((Func<IServiceProvider, IChatClient>)((IServiceProvider _) => innerClient2), lifetime); } public static ChatClientBuilder AddChatClient(this IServiceCollection serviceCollection, Func<IServiceProvider, IChatClient> innerClientFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) { Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull(innerClientFactory, "innerClientFactory"); ChatClientBuilder chatClientBuilder = new ChatClientBuilder(innerClientFactory); serviceCollection.Add(new ServiceDescriptor(typeof(IChatClient), chatClientBuilder.Build, lifetime)); return chatClientBuilder; } public static ChatClientBuilder AddKeyedChatClient(this IServiceCollection serviceCollection, object? serviceKey, IChatClient innerClient, ServiceLifetime lifetime = ServiceLifetime.Singleton) { IChatClient innerClient2 = innerClient; Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull<IChatClient>(innerClient2, "innerClient"); return serviceCollection.AddKeyedChatClient(serviceKey, (Func<IServiceProvider, IChatClient>)((IServiceProvider _) => innerClient2), lifetime); } public static ChatClientBuilder AddKeyedChatClient(this IServiceCollection serviceCollection, object? serviceKey, Func<IServiceProvider, IChatClient> innerClientFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) { Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull(innerClientFactory, "innerClientFactory"); ChatClientBuilder builder = new ChatClientBuilder(innerClientFactory); serviceCollection.Add(new ServiceDescriptor(typeof(IChatClient), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => builder.Build(services)), lifetime)); return builder; } } public static class EmbeddingGeneratorBuilderServiceCollectionExtensions { public static EmbeddingGeneratorBuilder<TInput, TEmbedding> AddEmbeddingGenerator<TInput, TEmbedding>(this IServiceCollection serviceCollection, IEmbeddingGenerator<TInput, TEmbedding> innerGenerator, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TEmbedding : Embedding { IEmbeddingGenerator<TInput, TEmbedding> innerGenerator2 = innerGenerator; Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull<IEmbeddingGenerator<TInput, TEmbedding>>(innerGenerator2, "innerGenerator"); return serviceCollection.AddEmbeddingGenerator((IServiceProvider _) => innerGenerator2, lifetime); } public static EmbeddingGeneratorBuilder<TInput, TEmbedding> AddEmbeddingGenerator<TInput, TEmbedding>(this IServiceCollection serviceCollection, Func<IServiceProvider, IEmbeddingGenerator<TInput, TEmbedding>> innerGeneratorFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TEmbedding : Embedding { Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull(innerGeneratorFactory, "innerGeneratorFactory"); EmbeddingGeneratorBuilder<TInput, TEmbedding> embeddingGeneratorBuilder = new EmbeddingGeneratorBuilder<TInput, TEmbedding>(innerGeneratorFactory); serviceCollection.Add(new ServiceDescriptor(typeof(IEmbeddingGenerator<TInput, TEmbedding>), embeddingGeneratorBuilder.Build, lifetime)); serviceCollection.Add(new ServiceDescriptor(typeof(IEmbeddingGenerator), (IServiceProvider services) => services.GetRequiredService<IEmbeddingGenerator<TInput, TEmbedding>>(), lifetime)); return embeddingGeneratorBuilder; } public static EmbeddingGeneratorBuilder<TInput, TEmbedding> AddKeyedEmbeddingGenerator<TInput, TEmbedding>(this IServiceCollection serviceCollection, object? serviceKey, IEmbeddingGenerator<TInput, TEmbedding> innerGenerator, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TEmbedding : Embedding { IEmbeddingGenerator<TInput, TEmbedding> innerGenerator2 = innerGenerator; Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull<IEmbeddingGenerator<TInput, TEmbedding>>(innerGenerator2, "innerGenerator"); return serviceCollection.AddKeyedEmbeddingGenerator(serviceKey, (IServiceProvider _) => innerGenerator2, lifetime); } public static EmbeddingGeneratorBuilder<TInput, TEmbedding> AddKeyedEmbeddingGenerator<TInput, TEmbedding>(this IServiceCollection serviceCollection, object? serviceKey, Func<IServiceProvider, IEmbeddingGenerator<TInput, TEmbedding>> innerGeneratorFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TEmbedding : Embedding { Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull(innerGeneratorFactory, "innerGeneratorFactory"); EmbeddingGeneratorBuilder<TInput, TEmbedding> builder = new EmbeddingGeneratorBuilder<TInput, TEmbedding>(innerGeneratorFactory); serviceCollection.Add(new ServiceDescriptor(typeof(IEmbeddingGenerator<TInput, TEmbedding>), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => builder.Build(services)), lifetime)); serviceCollection.Add(new ServiceDescriptor(typeof(IEmbeddingGenerator), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => ServiceProviderKeyedServiceExtensions.GetRequiredKeyedService<IEmbeddingGenerator<TInput, TEmbedding>>(services, serviceKey)), lifetime)); return builder; } } [Experimental("MEAI001")] public static class ImageGeneratorBuilderServiceCollectionExtensions { public static ImageGeneratorBuilder AddImageGenerator(this IServiceCollection serviceCollection, IImageGenerator innerGenerator, ServiceLifetime lifetime = ServiceLifetime.Singleton) { IImageGenerator innerGenerator2 = innerGenerator; return serviceCollection.AddImageGenerator((Func<IServiceProvider, IImageGenerator>)((IServiceProvider _) => innerGenerator2), lifetime); } public static ImageGeneratorBuilder AddImageGenerator(this IServiceCollection serviceCollection, Func<IServiceProvider, IImageGenerator> innerGeneratorFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) { Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull(innerGeneratorFactory, "innerGeneratorFactory"); ImageGeneratorBuilder imageGeneratorBuilder = new ImageGeneratorBuilder(innerGeneratorFactory); serviceCollection.Add(new ServiceDescriptor(typeof(IImageGenerator), imageGeneratorBuilder.Build, lifetime)); return imageGeneratorBuilder; } public static ImageGeneratorBuilder AddKeyedImageGenerator(this IServiceCollection serviceCollection, object? serviceKey, IImageGenerator innerGenerator, ServiceLifetime lifetime = ServiceLifetime.Singleton) { IImageGenerator innerGenerator2 = innerGenerator; return serviceCollection.AddKeyedImageGenerator(serviceKey, (Func<IServiceProvider, IImageGenerator>)((IServiceProvider _) => innerGenerator2), lifetime); } public static ImageGeneratorBuilder AddKeyedImageGenerator(this IServiceCollection serviceCollection, object? serviceKey, Func<IServiceProvider, IImageGenerator> innerGeneratorFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) { Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull(innerGeneratorFactory, "innerGeneratorFactory"); ImageGeneratorBuilder builder = new ImageGeneratorBuilder(innerGeneratorFactory); serviceCollection.Add(new ServiceDescriptor(typeof(IImageGenerator), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => builder.Build(services)), lifetime)); return builder; } } [Experimental("MEAI001")] public static class SpeechToTextClientBuilderServiceCollectionExtensions { public static SpeechToTextClientBuilder AddSpeechToTextClient(this IServiceCollection serviceCollection, ISpeechToTextClient innerClient, ServiceLifetime lifetime = ServiceLifetime.Singleton) { ISpeechToTextClient innerClient2 = innerClient; return serviceCollection.AddSpeechToTextClient((Func<IServiceProvider, ISpeechToTextClient>)((IServiceProvider _) => innerClient2), lifetime); } public static SpeechToTextClientBuilder AddSpeechToTextClient(this IServiceCollection serviceCollection, Func<IServiceProvider, ISpeechToTextClient> innerClientFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) { Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull(innerClientFactory, "innerClientFactory"); SpeechToTextClientBuilder speechToTextClientBuilder = new SpeechToTextClientBuilder(innerClientFactory); serviceCollection.Add(new ServiceDescriptor(typeof(ISpeechToTextClient), speechToTextClientBuilder.Build, lifetime)); return speechToTextClientBuilder; } public static SpeechToTextClientBuilder AddKeyedSpeechToTextClient(this IServiceCollection serviceCollection, object? serviceKey, ISpeechToTextClient innerClient, ServiceLifetime lifetime = ServiceLifetime.Singleton) { ISpeechToTextClient innerClient2 = innerClient; return serviceCollection.AddKeyedSpeechToTextClient(serviceKey, (Func<IServiceProvider, ISpeechToTextClient>)((IServiceProvider _) => innerClient2), lifetime); } public static SpeechToTextClientBuilder AddKeyedSpeechToTextClient(this IServiceCollection serviceCollection, object? serviceKey, Func<IServiceProvider, ISpeechToTextClient> innerClientFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) { Throw.IfNull(serviceCollection, "serviceCollection"); Throw.IfNull(innerClientFactory, "innerClientFactory"); SpeechToTextClientBuilder builder = new SpeechToTextClientBuilder(innerClientFactory); serviceCollection.Add(new ServiceDescriptor(typeof(ISpeechToTextClient), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => builder.Build(services)), lifetime)); return builder; } } } namespace Microsoft.Extensions.AI { internal sealed class AnonymousDelegatingChatClient : DelegatingChatClient { private readonly Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, Task<ChatResponse>>? _getResponseFunc; private readonly Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, IAsyncEnumerable<ChatResponseUpdate>>? _getStreamingResponseFunc; private readonly Func<IEnumerable<ChatMessage>, ChatOptions?, Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, Task>, CancellationToken, Task>? _sharedFunc; public AnonymousDelegatingChatClient(IChatClient innerClient, Func<IEnumerable<ChatMessage>, ChatOptions?, Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, Task>, CancellationToken, Task> sharedFunc) : base(innerClient) { Throw.IfNull(sharedFunc, "sharedFunc"); _sharedFunc = sharedFunc; } public AnonymousDelegatingChatClient(IChatClient innerClient, Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, Task<ChatResponse>>? getResponseFunc, Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, IAsyncEnumerable<ChatResponseUpdate>>? getStreamingResponseFunc) : base(innerClient) { ThrowIfBothDelegatesNull(getResponseFunc, getStreamingResponseFunc); _getResponseFunc = getResponseFunc; _getStreamingResponseFunc = getStreamingResponseFunc; } public override Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(messages, "messages"); if (_sharedFunc != null) { return GetResponseViaSharedAsync(messages, options, cancellationToken); } if (_getResponseFunc != null) { return _getResponseFunc(messages, options, ((DelegatingChatClient)this).InnerClient, cancellationToken); } return ChatResponseExtensions.ToChatResponseAsync(_getStreamingResponseFunc(messages, options, ((DelegatingChatClient)this).InnerClient, cancellationToken), cancellationToken); async Task<ChatResponse> GetResponseViaSharedAsync(IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken) { ChatResponse response = null; await _sharedFunc(messages, options, async delegate(IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken) { response = await ((DelegatingChatClient)this).InnerClient.GetResponseAsync(messages, options, cancellationToken); }, cancellationToken); if (response == null) { Throw.InvalidOperationException("The wrapper completed successfully without producing a ChatResponse."); } return response; } } public override IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { IEnumerable<ChatMessage> messages2 = messages; ChatOptions options2 = options; Throw.IfNull(messages2, "messages"); Channel<ChatResponseUpdate> updates; if (_sharedFunc != null) { updates = Channel.CreateBounded<ChatResponseUpdate>(1); ProcessAsync(); return ReadAllAsync((Channel<ChatResponseUpdate, ChatResponseUpdate>)updates, cancellationToken); } if (_getStreamingResponseFunc != null) { return _getStreamingResponseFunc(messages2, options2, ((DelegatingChatClient)this).InnerClient, cancellationToken); } return GetStreamingResponseAsyncViaGetResponseAsync(_getResponseFunc(messages2, options2, ((DelegatingChatClient)this).InnerClient, cancellationToken)); static async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsyncViaGetResponseAsync(Task<ChatResponse> task) { ChatResponseUpdate[] array = (await task).ToChatResponseUpdates(); for (int i = 0; i < array.Length; i++) { yield return array[i]; } } async Task ProcessAsync() { Exception error = null; try { await _sharedFunc(messages2, options2, async delegate(IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken) { await foreach (ChatResponseUpdate item2 in ((DelegatingChatClient)this).InnerClient.GetStreamingResponseAsync(messages, options, cancellationToken)) { await updates.Writer.WriteAsync(item2, cancellationToken); } }, cancellationToken); } catch (Exception ex) { error = ex; throw; } finally { updates.Writer.TryComplete(error); } } static async IAsyncEnumerable<ChatResponseUpdate> ReadAllAsync(ChannelReader<ChatResponseUpdate> channel, [EnumeratorCancellation] CancellationToken cancellationToken) { while (await channel.WaitToReadAsync(cancellationToken)) { ChatResponseUpdate item; while (channel.TryRead(out item)) { yield return item; } } } } internal static void ThrowIfBothDelegatesNull(object? getResponseFunc, object? getStreamingResponseFunc) { if (getResponseFunc == null && getStreamingResponseFunc == null) { Throw.ArgumentNullException("getResponseFunc", "At least one of the getResponseFunc or getStreamingResponseFunc delegates must be non-null."); } } } public abstract class CachingChatClient : DelegatingChatClient { private static readonly object _boxedTrue = true; private static readonly object _boxedFalse = false; public bool CoalesceStreamingUpdates { get; set; } = true; protected CachingChatClient(IChatClient innerClient) : base(innerClient) { } public override Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(messages, "messages"); if (!EnableCaching(messages, options)) { return ((DelegatingChatClient)this).GetResponseAsync(messages, options, cancellationToken); } return GetCachedResponseAsync(messages, options, cancellationToken); } private async Task<ChatResponse> GetCachedResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { string cacheKey = GetCacheKey(messages, options, new ReadOnlySpan<object>(new object[1] { _boxedFalse })); ChatResponse result = await ReadCacheAsync(cacheKey, cancellationToken); if (result == null) { result = await <>n__0(messages, options, cancellationToken); await WriteCacheAsync(cacheKey, result, cancellationToken); } return result; } public override IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(messages, "messages"); if (!EnableCaching(messages, options)) { return ((DelegatingChatClient)this).GetStreamingResponseAsync(messages, options, cancellationToken); } return GetCachedStreamingResponseAsync(messages, options, cancellationToken); } private async IAsyncEnumerable<ChatResponseUpdate> GetCachedStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { string cacheKey2; List<ChatResponseUpdate> capturedItems2; if (CoalesceStreamingUpdates) { cacheKey2 = GetCacheKey(messages, options, new ReadOnlySpan<object>(new object[1] { _boxedTrue })); ChatResponse val = await ReadCacheAsync(cacheKey2, cancellationToken); if (val != null) { ChatResponseUpdate[] array = val.ToChatResponseUpdates(); for (int i = 0; i < array.Length; i++) { yield return array[i]; } yield break; } capturedItems2 = new List<ChatResponseUpdate>(); await foreach (ChatResponseUpdate item in <>n__1(messages, options, cancellationToken)) { capturedItems2.Add(item); yield return item; } await WriteCacheAsync(cacheKey2, ChatResponseExtensions.ToChatResponse((IEnumerable<ChatResponseUpdate>)capturedItems2), cancellationToken); yield break; } cacheKey2 = GetCacheKey(messages, options, new ReadOnlySpan<object>(new object[1] { _boxedTrue })); IReadOnlyList<ChatResponseUpdate> readOnlyList = await ReadCacheStreamingAsync(cacheKey2, cancellationToken); if (readOnlyList != null) { string conversationId = null; foreach (ChatResponseUpdate item2 in readOnlyList) { if (conversationId == null) { conversationId = item2.ConversationId; } yield return item2; } yield break; } capturedItems2 = new List<ChatResponseUpdate>(); await foreach (ChatResponseUpdate item3 in <>n__1(messages, options, cancellationToken)) { capturedItems2.Add(item3); yield return item3; } await WriteCacheStreamingAsync(cacheKey2, capturedItems2, cancellationToken); } protected abstract string GetCacheKey(IEnumerable<ChatMessage> messages, ChatOptions? options, [ParamCollection] scoped ReadOnlySpan<object?> additionalValues); protected abstract Task<ChatResponse?> ReadCacheAsync(string key, CancellationToken cancellationToken); protected abstract Task<IReadOnlyList<ChatResponseUpdate>?> ReadCacheStreamingAsync(string key, CancellationToken cancellationToken); protected abstract Task WriteCacheAsync(string key, ChatResponse value, CancellationToken cancellationToken); protected abstract Task WriteCacheStreamingAsync(string key, IReadOnlyList<ChatResponseUpdate> value, CancellationToken cancellationToken); protected virtual bool EnableCaching(IEnumerable<ChatMessage> messages, ChatOptions? options) { return ((options != null) ? options.ConversationId : null) == null; } [CompilerGenerated] [DebuggerHidden] private Task<ChatResponse> <>n__0(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return ((DelegatingChatClient)this).GetResponseAsync(messages, options, cancellationToken); } [CompilerGenerated] [DebuggerHidden] private IAsyncEnumerable<ChatResponseUpdate> <>n__1(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return ((DelegatingChatClient)this).GetStreamingResponseAsync(messages, options, cancellationToken); } } public sealed class ChatClientBuilder { private readonly Func<IServiceProvider, IChatClient> _innerClientFactory; private List<Func<IChatClient, IServiceProvider, IChatClient>>? _clientFactories; public ChatClientBuilder(IChatClient innerClient) { IChatClient innerClient2 = innerClient; base..ctor(); Throw.IfNull<IChatClient>(innerClient2, "innerClient"); _innerClientFactory = (IServiceProvider _) => innerClient2; } public ChatClientBuilder(Func<IServiceProvider, IChatClient> innerClientFactory) { _innerClientFactory = Throw.IfNull(innerClientFactory, "innerClientFactory"); } public IChatClient Build(IServiceProvider? services = null) { if (services == null) { services = EmptyServiceProvider.Instance; } IChatClient val = _innerClientFactory(services); if (_clientFactories != null) { for (int num = _clientFactories.Count - 1; num >= 0; num--) { val = _clientFactories[num](val, services); if (val == null) { Throw.InvalidOperationException(string.Format("The {0} entry at index {1} returned null. ", "ChatClientBuilder", num) + "Ensure that the callbacks passed to Use return non-null IChatClient instances."); } } } return val; } public ChatClientBuilder Use(Func<IChatClient, IChatClient> clientFactory) { Func<IChatClient, IChatClient> clientFactory2 = clientFactory; Throw.IfNull(clientFactory2, "clientFactory"); return Use((IChatClient innerClient, IServiceProvider _) => clientFactory2(innerClient)); } public ChatClientBuilder Use(Func<IChatClient, IServiceProvider, IChatClient> clientFactory) { Throw.IfNull(clientFactory, "clientFactory"); (_clientFactories ?? (_clientFactories = new List<Func<IChatClient, IServiceProvider, IChatClient>>())).Add(clientFactory); return this; } public ChatClientBuilder Use(Func<IEnumerable<ChatMessage>, ChatOptions?, Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, Task>, CancellationToken, Task> sharedFunc) { Func<IEnumerable<ChatMessage>, ChatOptions?, Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, Task>, CancellationToken, Task> sharedFunc2 = sharedFunc; Throw.IfNull(sharedFunc2, "sharedFunc"); return Use((IChatClient innerClient, IServiceProvider _) => (IChatClient)(object)new AnonymousDelegatingChatClient(innerClient, sharedFunc2)); } public ChatClientBuilder Use(Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, Task<ChatResponse>>? getResponseFunc, Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, IAsyncEnumerable<ChatResponseUpdate>>? getStreamingResponseFunc) { Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, Task<ChatResponse>> getResponseFunc2 = getResponseFunc; Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, IAsyncEnumerable<ChatResponseUpdate>> getStreamingResponseFunc2 = getStreamingResponseFunc; AnonymousDelegatingChatClient.ThrowIfBothDelegatesNull(getResponseFunc2, getStreamingResponseFunc2); return Use((IChatClient innerClient, IServiceProvider _) => (IChatClient)(object)new AnonymousDelegatingChatClient(innerClient, getResponseFunc2, getStreamingResponseFunc2)); } } public static class ChatClientBuilderChatClientExtensions { public static ChatClientBuilder AsBuilder(this IChatClient innerClient) { Throw.IfNull<IChatClient>(innerClient, "innerClient"); return new ChatClientBuilder(innerClient); } } public static class ChatClientStructuredOutputExtensions { public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, IEnumerable<ChatMessage> messages, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken)) { return chatClient.GetResponseAsync<T>(messages, AIJsonUtilities.DefaultOptions, options, useJsonSchemaResponseFormat, cancellationToken); } public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, string chatMessage, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken)) { //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_0015: Expected O, but got Unknown return chatClient.GetResponseAsync<T>(new ChatMessage(ChatRole.User, chatMessage), options, useJsonSchemaResponseFormat, cancellationToken); } public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, ChatMessage chatMessage, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken)) { return chatClient.GetResponseAsync<T>((IEnumerable<ChatMessage>)new <>z__ReadOnlySingleElementList<ChatMessage>(chatMessage), options, useJsonSchemaResponseFormat, cancellationToken); } public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, string chatMessage, JsonSerializerOptions serializerOptions, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken)) { //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_0017: Expected O, but got Unknown return chatClient.GetResponseAsync<T>(new ChatMessage(ChatRole.User, chatMessage), serializerOptions, options, useJsonSchemaResponseFormat, cancellationToken); } public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, ChatMessage chatMessage, JsonSerializerOptions serializerOptions, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken)) { return chatClient.GetResponseAsync<T>((IEnumerable<ChatMessage>)new <>z__ReadOnlySingleElementList<ChatMessage>(chatMessage), serializerOptions, options, useJsonSchemaResponseFormat, cancellationToken); } public static async Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, IEnumerable<ChatMessage> messages, JsonSerializerOptions serializerOptions, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull<IChatClient>(chatClient, "chatClient"); Throw.IfNull(messages, "messages"); Throw.IfNull(serializerOptions, "serializerOptions"); serializerOptions.MakeReadOnly(); ChatResponseFormatJson val = ChatResponseFormat.ForJsonSchema<T>(serializerOptions, (string)null, (string)null); JsonElement value = val.Schema.Value; bool isWrappedInObject = false; if (!SchemaRepresentsObject(value)) { isWrappedInObject = true; JsonObject jsonObject = new JsonObject(); jsonObject.Add("$schema", "https://json-schema.org/draft/2020-12/schema"); jsonObject.Add("type", "object"); jsonObject.Add("properties", new JsonObject { { "data", JsonElementToJsonNode(value) } }); jsonObject.Add("additionalProperties", (JsonNode)false); jsonObject.Add("required", new JsonArray("data")); value = JsonSerializer.SerializeToElement((object)jsonObject, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonObject))); val = ChatResponseFormat.ForJsonSchema(value, val.SchemaName, val.SchemaDescription); } options = (ChatOptions?)((options != null) ? ((object)options.Clone()) : ((object)new ChatOptions())); if (useJsonSchemaResponseFormat.GetValueOrDefault(true)) { options.ResponseFormat = (ChatResponseFormat)(object)val; } else { options.ResponseFormat = (ChatResponseFormat)(object)ChatResponseFormat.Json; ChatMessage item = new ChatMessage(ChatRole.User, $"Respond with a JSON value conforming to the following schema:\r\n```\r\n{val.Schema}\r\n```"); List<ChatMessage> list = new List<ChatMessage>(); list.AddRange(messages); list.Add(item); messages = new <>z__ReadOnlyList<ChatMessage>(list); } return new ChatResponse<T>(await chatClient.GetResponseAsync(messages, options, cancellationToken), serializerOptions) { IsWrappedInObject = isWrappedInObject }; static JsonNode? JsonElementToJsonNode(JsonElement element) { return element.ValueKind switch { JsonValueKind.Null => null, JsonValueKind.Array => JsonArray.Create(element), JsonValueKind.Object => JsonObject.Create(element), _ => JsonValue.Create(element), }; } static bool SchemaRepresentsObject(JsonElement schemaElement) { if (schemaElement.ValueKind == JsonValueKind.Object) { foreach (JsonProperty item2 in schemaElement.EnumerateObject()) { if (item2.NameEquals("type"u8)) { return item2.Value.ValueKind == JsonValueKind.String && item2.Value.ValueEquals("object"u8); } } } return false; } } } public class ChatResponse<T> : ChatResponse { private enum FailureReason { ResultDidNotContainJson, DeserializationProducedNull, ResultDidNotContainDataProperty } private static readonly JsonReaderOptions _allowMultipleValuesJsonReaderOptions = default(JsonReaderOptions); private readonly JsonSerializerOptions _serializerOptions; private T? _deserializedResult; private bool _hasDeserializedResult; public T Result { get { FailureReason? failureReason; T resultCore = GetResultCore(out failureReason); return failureReason switch { FailureReason.ResultDidNotContainJson => throw new InvalidOperationException("The response did not contain JSON to be deserialized."), FailureReason.DeserializationProducedNull => throw new InvalidOperationException("The deserialized response is null."), FailureReason.ResultDidNotContainDataProperty => throw new InvalidOperationException("The response did not contain the expected 'data' property."), _ => resultCore, }; } } internal bool IsWrappedInObject { get; set; } public ChatResponse(ChatResponse response, JsonSerializerOptions serializerOptions) : base(Throw.IfNull<ChatResponse>(response, "response").Messages) { _serializerOptions = Throw.IfNull(serializerOptions, "serializerOptions"); ((ChatResponse)this).AdditionalProperties = response.AdditionalProperties; ((ChatResponse)this).ConversationId = response.ConversationId; ((ChatResponse)this).CreatedAt = response.CreatedAt; ((ChatResponse)this).FinishReason = response.FinishReason; ((ChatResponse)this).ModelId = response.ModelId; ((ChatResponse)this).RawRepresentation = response.RawRepresentation; ((ChatResponse)this).ResponseId = response.ResponseId; ((ChatResponse)this).Usage = response.Usage; } public bool TryGetResult([NotNullWhen(true)] out T? result) { try { result = GetResultCore(out var failureReason); return !failureReason.HasValue; } catch { result = default(T); return false; } } private static T? DeserializeFirstTopLevelObject(string json, JsonTypeInfo<T> typeInfo) { int byteCount = Encoding.UTF8.GetByteCount(json); byte[] array = ArrayPool<byte>.Shared.Rent(byteCount); try { int bytes = Encoding.UTF8.GetBytes(json, 0, json.Length, array, 0); ReadOnlySpan<byte> jsonData = new ReadOnlySpan<byte>(array, 0, bytes); Utf8JsonReader reader = new Utf8JsonReader(jsonData, _allowMultipleValuesJsonReaderOptions); return JsonSerializer.Deserialize(ref reader, typeInfo); } finally { ArrayPool<byte>.Shared.Return(array); } } private T? GetResultCore(out FailureReason? failureReason) { if (_hasDeserializedResult) { failureReason = null; return _deserializedResult; } string text = ((((ChatResponse)this).Messages.Count > 0) ? ((ChatResponse)this).Messages[((ChatResponse)this).Messages.Count - 1].Text : string.Empty); if (string.IsNullOrEmpty(text)) { failureReason = FailureReason.ResultDidNotContainJson; return default(T); } T val = default(T); if (IsWrappedInObject) { if (!JsonDocument.Parse(text).RootElement.TryGetProperty("data", out var value)) { failureReason = FailureReason.ResultDidNotContainDataProperty; return default(T); } text = value.GetRawText(); } val = DeserializeFirstTopLevelObject(text, (JsonTypeInfo<T>)_serializerOptions.GetTypeInfo(typeof(T))); if (val == null) { failureReason = FailureReason.DeserializationProducedNull; return default(T); } _deserializedResult = val; _hasDeserializedResult = true; failureReason = null; return val; } } public sealed class ConfigureOptionsChatClient : DelegatingChatClient { private readonly Action<ChatOptions> _configureOptions; public ConfigureOptionsChatClient(IChatClient innerClient, Action<ChatOptions> configure) : base(innerClient) { _configureOptions = Throw.IfNull(configure, "configure"); } public override async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return await <>n__0(messages, Configure(options), cancellationToken); } public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { await foreach (ChatResponseUpdate item in <>n__1(messages, Configure(options), cancellationToken)) { yield return item; } } private ChatOptions Configure(ChatOptions? options) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) options = (ChatOptions?)(((object)((options != null) ? options.Clone() : null)) ?? ((object)new ChatOptions())); _configureOptions(options); return options; } [CompilerGenerated] [DebuggerHidden] private Task<ChatResponse> <>n__0(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return ((DelegatingChatClient)this).GetResponseAsync(messages, options, cancellationToken); } [CompilerGenerated] [DebuggerHidden] private IAsyncEnumerable<ChatResponseUpdate> <>n__1(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return ((DelegatingChatClient)this).GetStreamingResponseAsync(messages, options, cancellationToken); } } public static class ConfigureOptionsChatClientBuilderExtensions { public static ChatClientBuilder ConfigureOptions(this ChatClientBuilder builder, Action<ChatOptions> configure) { Action<ChatOptions> configure2 = configure; Throw.IfNull(builder, "builder"); Throw.IfNull(configure2, "configure"); return builder.Use((IChatClient innerClient) => (IChatClient)(object)new ConfigureOptionsChatClient(innerClient, configure2)); } } public class DistributedCachingChatClient : CachingChatClient { private static readonly object _cacheVersion = 2; private readonly IDistributedCache _storage; private object[]? _cacheKeyAdditionalValues; private JsonSerializerOptions _jsonSerializerOptions = AIJsonUtilities.DefaultOptions; public JsonSerializerOptions JsonSerializerOptions { get { return _jsonSerializerOptions; } set { _jsonSerializerOptions = Throw.IfNull(value, "value"); } } public IReadOnlyList<object>? CacheKeyAdditionalValues { get { return _cacheKeyAdditionalValues; } set { _cacheKeyAdditionalValues = value?.ToArray(); } } public DistributedCachingChatClient(IChatClient innerClient, IDistributedCache storage) : base(innerClient) { _storage = Throw.IfNull(storage, "storage"); } protected override async Task<ChatResponse?> ReadCacheAsync(string key, CancellationToken cancellationToken) { Throw.IfNull(key, "key"); _jsonSerializerOptions.MakeReadOnly(); byte[] array = await _storage.GetAsync(key, cancellationToken); if (array != null) { return (ChatResponse)JsonSerializer.Deserialize((ReadOnlySpan<byte>)array, _jsonSerializerOptions.GetTypeInfo(typeof(ChatResponse))); } return null; } protected override async Task<IReadOnlyList<ChatResponseUpdate>?> ReadCacheStreamingAsync(string key, CancellationToken cancellationToken) { Throw.IfNull(key, "key"); _jsonSerializerOptions.MakeReadOnly(); byte[] array = await _storage.GetAsync(key, cancellationToken); if (array != null) { return (IReadOnlyList<ChatResponseUpdate>)JsonSerializer.Deserialize((ReadOnlySpan<byte>)array, _jsonSerializerOptions.GetTypeInfo(typeof(IReadOnlyList<ChatResponseUpdate>))); } return null; } protected override async Task WriteCacheAsync(string key, ChatResponse value, CancellationToken cancellationToken) { Throw.IfNull(key, "key"); Throw.IfNull<ChatResponse>(value, "value"); _jsonSerializerOptions.MakeReadOnly(); byte[] value2 = JsonSerializer.SerializeToUtf8Bytes((object)value, _jsonSerializerOptions.GetTypeInfo(typeof(ChatResponse))); await _storage.SetAsync(key, value2, cancellationToken); } protected override async Task WriteCacheStreamingAsync(string key, IReadOnlyList<ChatResponseUpdate> value, CancellationToken cancellationToken) { Throw.IfNull(key, "key"); Throw.IfNull(value, "value"); _jsonSerializerOptions.MakeReadOnly(); byte[] value2 = JsonSerializer.SerializeToUtf8Bytes((object)value, _jsonSerializerOptions.GetTypeInfo(typeof(IReadOnlyList<ChatResponseUpdate>))); await _storage.SetAsync(key, value2, cancellationToken); } protected override string GetCacheKey(IEnumerable<ChatMessage> messages, ChatOptions? options, [ParamCollection] scoped ReadOnlySpan<object?> additionalValues) { object[] array = _cacheKeyAdditionalValues ?? Array.Empty<object>(); int num = 3 + additionalValues.Length + array.Length; object[] array2 = ArrayPool<object>.Shared.Rent(num); try { array2[0] = _cacheVersion; array2[1] = messages; array2[2] = options; additionalValues.CopyTo(array2.AsSpan(3)); array.CopyTo(array2, 3 + additionalValues.Length); return AIJsonUtilities.HashDataToString((ReadOnlySpan<object>)array2.AsSpan(0, num), _jsonSerializerOptions); } finally { Array.Clear(array2, 0, num); ArrayPool<object>.Shared.Return(array2); } } } public static class DistributedCachingChatClientBuilderExtensions { public static ChatClientBuilder UseDistributedCache(this ChatClientBuilder builder, IDistributedCache? storage = null, Action<DistributedCachingChatClient>? configure = null) { IDistributedCache storage2 = storage; Action<DistributedCachingChatClient> configure2 = configure; Throw.IfNull(builder, "builder"); return builder.Use(delegate(IChatClient innerClient, IServiceProvider services) { if (storage2 == null) { storage2 = services.GetRequiredService<IDistributedCache>(); } DistributedCachingChatClient distributedCachingChatClient = new DistributedCachingChatClient(innerClient, storage2); configure2?.Invoke(distributedCachingChatClient); return (IChatClient)(object)distributedCachingChatClient; }); } } public class FunctionInvocationContext { private static readonly AIFunction _nopFunction = AIFunctionFactory.Create((Delegate)(Action)delegate { }, "FunctionInvocationContext", (string)null, (JsonSerializerOptions)null); private IList<ChatMessage> _messages = Array.Empty<ChatMessage>(); private AIFunction _function = _nopFunction; private FunctionCallContent? _callContent; private AIFunctionArguments? _arguments; public AIFunction Function { get { return _function; } set { _function = Throw.IfNull<AIFunction>(value, "value"); } } public AIFunctionArguments Arguments { get { //IL_000b: 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: Expected O, but got Unknown //IL_0017: Expected O, but got Unknown AIFunctionArguments obj = _arguments; if (obj == null) { AIFunctionArguments val = new AIFunctionArguments(); AIFunctionArguments val2 = val; _arguments = val; obj = val2; } return obj; } set { _arguments = Throw.IfNull<AIFunctionArguments>(value, "value"); } } public FunctionCallContent CallContent { get { //IL_001f: 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) //IL_0026: Expected O, but got Unknown //IL_002b: Expected O, but got Unknown FunctionCallContent obj = _callContent; if (obj == null) { FunctionCallContent val = new FunctionCallContent(string.Empty, ((AITool)_nopFunction).Name, (IDictionary<string, object>)EmptyReadOnlyDictionary<string, object>.Instance); FunctionCallContent val2 = val; _callContent = val; obj = val2; } return obj; } set { _callContent = Throw.IfNull<FunctionCallContent>(value, "value"); } } public IList<ChatMessage> Messages { get { return _messages; } set { _messages = Throw.IfNull(value, "value"); } } public ChatOptions? Options { get; set; } public int Iteration { get; set; } public int FunctionCallIndex { get; set; } public int FunctionCount { get; set; } public bool Terminate { get; set; } public bool IsStreaming { get; set; } } public class FunctionInvokingChatClient : DelegatingChatClient { public sealed class FunctionInvocationResult { public FunctionInvocationStatus Status { get; } public FunctionCallContent CallContent { get; } public object? Result { get; } public Exception? Exception { get; } public bool Terminate { get; } internal FunctionInvocationResult(bool terminate, FunctionInvocationStatus status, FunctionCallContent callContent, object? result, Exception? exception) { Terminate = terminate; Status = status; CallContent = callContent; Result = result; Exception = exception; } } public enum FunctionInvocationStatus { RanToCompletion, NotFound, Exception } private struct ApprovalResultWithRequestMessage { public FunctionApprovalResponseContent Response { get; set; } public ChatMessage? RequestMessage { get; set; } } private static readonly AsyncLocal<FunctionInvocationContext?> _currentContext = new AsyncLocal<FunctionInvocationContext>(); private readonly ILogger _logger; private readonly ActivitySource? _activitySource; private int _maximumIterationsPerRequest = 40; private int _maximumConsecutiveErrorsPerRequest = 3; [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __LogInvokingCallback = LoggerMessage.Define<string>(LogLevel.Debug, new EventId(807273242, "LogInvoking"), "Invoking {MethodName}.", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, string, Exception?> __LogInvokingSensitiveCallback = LoggerMessage.Define<string, string>(LogLevel.Trace, new EventId(1953841678, "LogInvokingSensitive"), "Invoking {MethodName}({Arguments}).", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, TimeSpan, Exception?> __LogInvocationCompletedCallback = LoggerMessage.Define<string, TimeSpan>(LogLevel.Debug, new EventId(1098781176, "LogInvocationCompleted"), "{MethodName} invocation completed. Duration: {Duration}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, TimeSpan, string, Exception?> __LogInvocationCompletedSensitiveCallback = LoggerMessage.Define<string, TimeSpan, string>(LogLevel.Trace, new EventId(700532736, "LogInvocationCompletedSensitive"), "{MethodName} invocation completed. Duration: {Duration}. Result: {Result}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __LogInvocationCanceledCallback = LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1891493904, "LogInvocationCanceled"), "{MethodName} invocation canceled.", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __LogInvocationFailedCallback = LoggerMessage.Define<string>(LogLevel.Error, new EventId(1784604714, "LogInvocationFailed"), "{MethodName} invocation failed.", new LogDefineOptions { SkipEnabledCheck = true }); protected IServiceProvider? FunctionInvocationServices { get; } public static FunctionInvocationContext? CurrentContext { get { return _currentContext.Value; } protected set { _currentContext.Value = value; } } public bool IncludeDetailedErrors { get; set; } public bool AllowConcurrentInvocation { get; set; } public int MaximumIterationsPerRequest { get { return _maximumIterationsPerRequest; } set { if (value < 1) { Throw.ArgumentOutOfRangeException("value"); } _maximumIterationsPerRequest = value; } } public int MaximumConsecutiveErrorsPerRequest { get { return _maximumConsecutiveErrorsPerRequest; } set { _maximumConsecutiveErrorsPerRequest = Throw.IfLessThan(value, 0, "value"); } } public IList<AITool>? AdditionalTools { get; set; } public bool TerminateOnUnknownCalls { get; set; } public Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>>? FunctionInvoker { get; set; } public FunctionInvokingChatClient(IChatClient innerClient, ILoggerFactory? loggerFactory = null, IServiceProvider? functionInvocationServices = null) : base(innerClient) { ILogger logger = loggerFactory?.CreateLogger<FunctionInvokingChatClient>(); _logger = logger ?? NullLogger.Instance; _activitySource = ChatClientExtensions.GetService<ActivitySource>(innerClient, (object)null); FunctionInvocationServices = functionInvocationServices; } public override async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(messages, "messages"); using Activity activity = _activitySource?.StartActivity("FunctionInvokingChatClient.GetResponseAsync"); List<ChatMessage> originalMessages = messages.ToList(); messages = originalMessages; List<ChatMessage> augmentedHistory = null; List<ChatMessage> responseMessages = null; UsageDetails totalUsage = null; List<FunctionCallContent> functionCallContents = null; bool lastIterationHadConversationId = false; int consecutiveErrorCount = 0; IList<AITool>[] obj = new IList<AITool>[2] { AdditionalTools, null }; ChatOptions? obj2 = options; obj[1] = ((obj2 != null) ? obj2.Tools : null); Dictionary<string, AITool> toolMap; bool anyToolsRequireApproval; (toolMap, anyToolsRequireApproval) = CreateToolsMap(new ReadOnlySpan<IList<AITool>>(obj)); if (HasAnyApprovalContent(originalMessages)) { ChatOptions? obj3 = options; List<ApprovalResultWithRequestMessage> notInvokedApprovals; (responseMessages, notInvokedApprovals) = ProcessFunctionApprovalResponses(originalMessages, !string.IsNullOrWhiteSpace((obj3 != null) ? obj3.ConversationId : null), null, null); IList<ChatMessage> list; bool flag; (list, flag, consecutiveErrorCount) = await InvokeApprovedFunctionApprovalResponsesAsync(notInvokedApprovals, toolMap, originalMessages, options, consecutiveErrorCount, isStreaming: false, cancellationToken); if (list != null) { List<ChatMessage> list2 = responseMessages; if (list2 == null) { List<ChatMessage> list3; responseMessages = (list3 = new List<ChatMessage>()); list2 = list3; } list2.AddRange(list); } if (flag) { return new ChatResponse((IList<ChatMessage>)responseMessages); } } int iteration = 0; ChatResponse response; while (true) { functionCallContents?.Clear(); response = await <>n__0(messages, options, cancellationToken); if (response == null) { Throw.InvalidOperationException("The inner IChatClient returned a null ChatResponse."); } if (anyToolsRequireApproval) { response.Messages = ReplaceFunctionCallsWithApprovalRequests(response.Messages, toolMap); } bool flag2 = iteration < MaximumIterationsPerRequest && CopyFunctionCalls(response.Messages, ref functionCallContents); if (!flag2 && iteration == 0) { if (responseMessages != null && responseMessages.Count > 0) { responseMessages.AddRange(response.Messages); response.Messages = responseMessages; } return response; } List<ChatMessage> list4 = responseMessages; if (list4 == null) { List<ChatMessage> list3; responseMessages = (list3 = new List<ChatMessage>()); list4 = list3; } list4.AddRange(response.Messages); if (response.Usage != null) { if (totalUsage != null) { totalUsage.Add(response.Usage); } else { totalUsage = response.Usage; } } if (!flag2 || ShouldTerminateLoopBasedOnHandleableFunctions(functionCallContents, toolMap)) { break; } FixupHistories(originalMessages, ref messages, ref augmentedHistory, response, responseMessages, ref lastIterationHadConversationId); (bool, int, IList<ChatMessage>) tuple4 = await ProcessFunctionCallsAsync(augmentedHistory, options, toolMap, functionCallContents, iteration, consecutiveErrorCount, isStreaming: false, cancellationToken); responseMessages.AddRange(tuple4.Item3); consecutiveErrorCount = tuple4.Item2; if (tuple4.Item1) { break; } UpdateOptionsForNextIteration(ref options, response.ConversationId); iteration++; } response.Messages = responseMessages; response.Usage = totalUsage; AddUsageTags(activity, totalUsage); return response; } public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(messages, "messages"); using Activity activity = _activitySource?.StartActivity("FunctionInvokingChatClient.GetStreamingResponseAsync"); UsageDetails totalUsage = ((activity == null || !activity.IsAllDataRequested) ? ((UsageDetails)null) : new UsageDetails()); List<ChatMessage> originalMessages = messages.ToList(); messages = originalMessages; AITool[] approvalRequiredFunctions = null; List<ChatMessage> augmentedHistory = null; List<FunctionCallContent> functionCallContents = null; List<ChatMessage> responseMessages = null; bool lastIterationHadConversationId = false; List<ChatResponseUpdate> updates = new List<ChatResponseUpdate>(); int consecutiveErrorCount = 0; IList<AITool>[] obj = new IList<AITool>[2] { AdditionalTools, null }; ChatOptions? obj2 = options; obj[1] = ((obj2 != null) ? obj2.Tools : null); (Dictionary<string, AITool>, bool) tuple = CreateToolsMap(new ReadOnlySpan<IList<AITool>>(obj)); Dictionary<string, AITool> toolMap = tuple.Item1; bool anyToolsRequireApproval = tuple.Item2; string toolMessageId = Guid.NewGuid().ToString("N"); if (HasAnyApprovalContent(originalMessages)) { string functionCallContentFallbackMessageId = Guid.NewGuid().ToString("N"); ChatOptions? obj3 = options; var (list, notInvokedApprovals) = ProcessFunctionApprovalResponses(originalMessages, !string.IsNullOrWhiteSpace((obj3 != null) ? obj3.ConversationId : null), toolMessageId, functionCallContentFallbackMessageId); if (list != null) { foreach (ChatMessage item in list) { ChatOptions? obj4 = options; yield return ConvertToolResultMessageToUpdate(item, (obj4 != null) ? obj4.ConversationId : null, item.MessageId); Activity.Current = activity; } } IList<ChatMessage> list2; bool shouldTerminate2; (list2, shouldTerminate2, consecutiveErrorCount) = await InvokeApprovedFunctionApprovalResponsesAsync(notInvokedApprovals, toolMap, originalMessages, options, consecutiveErrorCount, isStreaming: true, cancellationToken); if (list2 != null) { foreach (ChatMessage item2 in list2) { item2.MessageId = toolMessageId; ChatOptions? obj5 = options; yield return ConvertToolResultMessageToUpdate(item2, (obj5 != null) ? obj5.ConversationId : null, item2.MessageId); Activity.Current = activity; } if (shouldTerminate2) { yield break; } } } int iteration = 0; while (true) { updates.Clear(); functionCallContents?.Clear(); bool shouldTerminate2 = false; int lastApprovalCheckedFCCIndex = 0; int lastYieldedUpdateIndex = 0; await foreach (ChatResponseUpdate item3 in <>n__1(messages, options, cancellationToken)) { if (item3 == null) { Throw.InvalidOperationException("The inner IChatClient streamed a null ChatResponseUpdate."); } updates.Add(item3); CopyFunctionCalls(item3.Contents, ref functionCallContents); if (totalUsage != null) { IList<AIContent> contents = item3.Contents; int count = contents.Count; for (int i = 0; i < count; i++) { AIContent obj6 = contents[i]; UsageContent val = (UsageContent)(object)((obj6 is UsageContent) ? obj6 : null); if (val != null) { totalUsage.Add(val.Details); } } } if (anyToolsRequireApproval && approvalRequiredFunctions == null && functionCallContents != null && functionCallContents.Count > 0) { ChatOptions? obj7 = options; IEnumerable<AITool> enumerable = ((obj7 != null) ? obj7.Tools : null); IEnumerable<AITool> first = enumerable ?? Enumerable.Empty<AITool>(); enumerable = AdditionalTools; approvalRequiredFunctions = (from t in first.Concat(enumerable ?? Enumerable.Empty<AITool>()) where t.GetService<ApprovalRequiredAIFunction>((object)null) != null select t).ToArray(); } if (approvalRequiredFunctions == null || approvalRequiredFunctions.Length <= 0) { lastYieldedUpdateIndex++; yield return item3; Activity.Current = activity; continue; } (shouldTerminate2, lastApprovalCheckedFCCIndex) = CheckForApprovalRequiringFCC(functionCallContents, approvalRequiredFunctions, shouldTerminate2, lastApprovalCheckedFCCIndex); if (!shouldTerminate2) { continue; } for (; lastYieldedUpdateIndex < updates.Count; lastYieldedUpdateIndex++) { ChatResponseUpdate val2 = updates[lastYieldedUpdateIndex]; if (TryReplaceFunctionCallsWithApprovalRequests(val2.Contents, out List<AIContent> updatedContent)) { val2.Contents = updatedContent; } yield return val2; Activity.Current = activity; } } if (iteration >= MaximumIterationsPerRequest || shouldTerminate2 || ShouldTerminateLoopBasedOnHandleableFunctions(functionCallContents, toolMap)) { break; } ChatResponse response = ChatResponseExtensions.ToChatResponse((IEnumerable<ChatResponseUpdate>)updates); List<ChatMessage> list3 = responseMessages; if (list3 == null) { List<ChatMessage> list4; responseMessages = (list4 = new List<ChatMessage>()); list3 = list4; } list3.AddRange(response.Messages); FixupHistories(originalMessages, ref messages, ref augmentedHistory, response, responseMessages, ref lastIterationHadConversationId); (bool ShouldTerminate, int NewConsecutiveErrorCount, IList<ChatMessage> MessagesAdded) modeAndMessages = await ProcessFunctionCallsAsync(augmentedHistory, options, toolMap, functionCallContents, iteration, consecutiveErrorCount, isStreaming: true, cancellationToken); responseMessages.AddRange(modeAndMessages.MessagesAdded); consecutiveErrorCount = modeAndMessages.NewConsecutiveErrorCount; foreach (ChatMessage item4 in modeAndMessages.MessagesAdded) { yield return ConvertToolResultMessageToUpdate(item4, response.ConversationId, toolMessageId); Activity.Current = activity; } if (modeAndMessages.ShouldTerminate) { break; } UpdateOptionsForNextIteration(ref options, response.ConversationId); iteration++; } AddUsageTags(activity, totalUsage); } private static ChatResponseUpdate ConvertToolResultMessageToUpdate(ChatMessage message, string? conversationId, string? messageId) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005a: 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_006c: Expected O, but got Unknown return new ChatResponseUpdate { AdditionalProperties = message.AdditionalProperties, AuthorName = message.AuthorName, ConversationId = conversationId, CreatedAt = DateTimeOffset.UtcNow, Contents = message.Contents, RawRepresentation = message.RawRepresentation, ResponseId = messageId, MessageId = messageId, Role = message.Role }; } private static void AddUsageTags(Activity? activity, UsageDetails? usage) { if (usage != null && activity != null && activity.IsAllDataRequested) { long? inputTokenCount = usage.InputTokenCount; if (inputTokenCount.HasValue) { long valueOrDefault = inputTokenCount.GetValueOrDefault(); activity.AddTag("gen_ai.usage.input_tokens", (int)valueOrDefault); } inputTokenCount = usage.OutputTokenCount; if (inputTokenCount.HasValue) { long valueOrDefault2 = inputTokenCount.GetValueOrDefault(); activity.AddTag("gen_ai.usage.output_tokens", (int)valueOrDefault2); } } } private static void FixupHistories(IEnumerable<ChatMessage> originalMessages, ref IEnumerable<ChatMessage> messages, [NotNull] ref List<ChatMessage>? augmentedHistory, ChatResponse response, List<ChatMessage> allTurnsResponseMessages, ref bool lastIterationHadConversationId) { if (response.ConversationId != null) { if (augmentedHistory != null) { augmentedHistory.Clear(); } else { augmentedHistory = new List<ChatMessage>(); } lastIterationHadConversationId = true; } else if (lastIterationHadConversationId) { if (augmentedHistory == null) { augmentedHistory = new List<ChatMessage>(); } augmentedHistory.Clear(); augmentedHistory.AddRange(originalMessages); augmentedHistory.AddRange(allTurnsResponseMessages); lastIterationHadConversationId = false; } else { if (augmentedHistory == null) { augmentedHistory = originalMessages.ToList(); } ChatResponseExtensions.AddMessages((IList<ChatMessage>)augmentedHistory, response); lastIterationHadConversationId = false; } messages = augmentedHistory; } private static (Dictionary<string, AITool>? ToolMap, bool AnyRequireApproval) CreateToolsMap([ParamCollection] scoped ReadOnlySpan<IList<AITool>?> toolLists) { Dictionary<string, AITool> dictionary = null; bool flag = false; ReadOnlySpan<IList<AITool>> readOnlySpan = toolLists; for (int i = 0; i < readOnlySpan.Length; i++) { IList<AITool> list = readOnlySpan[i]; int? num = list?.Count; if (!num.HasValue) { continue; } int valueOrDefault = num.GetValueOrDefault(); if (valueOrDefault > 0) { if (dictionary == null) { dictionary = new Dictionary<string, AITool>(StringComparer.Ordinal); } for (int j = 0; j < valueOrDefault; j++) { AITool val = list[j]; flag |= val.GetService<ApprovalRequiredAIFunction>((object)null) != null; dictionary[val.Name] = val; } } } return (dictionary, flag); } private static bool HasAnyApprovalContent(List<ChatMessage> messages) { return messages.Any((ChatMessage m) => m.Contents.Any((AIContent c) => (c is FunctionApprovalRequestContent || c is FunctionApprovalResponseContent) ? true : false)); } private static bool CopyFunctionCalls(IList<ChatMessage> messages, [NotNullWhen(true)] ref List<FunctionCallContent>? functionCalls) { bool flag = false; int count = messages.Count; for (int i = 0; i < count; i++) { flag |= CopyFunctionCalls(messages[i].Contents, ref functionCalls); } return flag; } private static bool CopyFunctionCalls(IList<AIContent> content, [NotNullWhen(true)] ref List<FunctionCallContent>? functionCalls) { bool result = false; int count = content.Count; for (int i = 0; i < count; i++) { AIContent obj = content[i]; FunctionCallContent val = (FunctionCallContent)(object)((obj is FunctionCallContent) ? obj : null); if (val != null) { (functionCalls ?? (functionCalls = new List<FunctionCallContent>())).Add(val); result = true; } } return result; } private static void UpdateOptionsForNextIteration(ref ChatOptions? options, string? conversationId) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown if (options == null) { if (conversationId != null) { options = new ChatOptions { ConversationId = conversationId }; } } else if (options.ToolMode is RequiredChatToolMode) { options = options.Clone(); options.ToolMode = null; options.ConversationId = conversationId; } else if (options.ConversationId != conversationId) { options = options.Clone(); options.ConversationId = conversationId; } } private bool ShouldTerminateLoopBasedOnHandleableFunctions(List<FunctionCallContent>? functionCalls, Dictionary<string, AITool>? toolMap) { if (functionCalls == null || functionCalls.Count <= 0) { return true; } if (toolMap == null || toolMap.Count <= 0) { return TerminateOnUnknownCalls; } foreach (FunctionCallContent functionCall in functionCalls) { if (toolMap.TryGetValue(functionCall.Name, out AITool value)) { if (!(value is AIFunction)) { return true; } } else if (TerminateOnUnknownCalls) { return true; } } return false; } private async Task<(bool ShouldTerminate, int NewConsecutiveErrorCount, IList<ChatMessage> MessagesAdded)> ProcessFunctionCallsAsync(List<ChatMessage> messages, ChatOptions? options, Dictionary<string, AITool>? toolMap, List<FunctionCallContent> functionCallContents, int iteration, int consecutiveErrorCount, bool isStreaming, CancellationToken cancellationToken) { List<ChatMessage> messages2 = messages; ChatOptions options2 = options; Dictionary<string, AITool> toolMap2 = toolMap; List<FunctionCallContent> functionCallContents2 = functionCallContents; bool shouldTerminate = false; bool captureCurrentIterationExceptions = consecutiveErrorCount < MaximumConsecutiveErrorsPerRequest; if (functionCallContents2.Count == 1) { FunctionInvocationResult functionInvocationResult = await ProcessFunctionCallAsync(messages2, options2, toolMap2, functionCallContents2, iteration, 0, captureCurrentIterationExceptions, isStreaming, cancellationToken); IList<ChatMessage> list = CreateResponseMessages(new ReadOnlySpan<FunctionInvocationResult>(new FunctionInvocationResult[1] { functionInvocationResult })); ThrowIfNoFunctionResultsAdded(list); UpdateConsecutiveErrorCountOrThrow(list, ref consecutiveErrorCount); messages2.AddRange(list); return (functionInvocationResult.Terminate, consecutiveErrorCount, list); } List<FunctionInvocationResult> results = new List<FunctionInvocationResult>(); if (AllowConcurrentInvocation) { List<FunctionInvocationResult> list2 = results; list2.AddRange(await Task.WhenAll(from callIndex in Enumerable.Range(0, functionCallContents2.Count) select ProcessFunctionCallAsync(messages2, options2, toolMap2, functionCallContents2, iteration, callIndex, captureExceptions: true, isStreaming, cancellationToken))); shouldTerminate = results.Any((FunctionInvocationResult r) => r.Terminate); } else { for (int callIndex2 = 0; callIndex2 < functionCallContents2.Count; callIndex2++) { FunctionInvocationResult functionInvocationResult2 = await ProcessFunctionCallAsync(messages2, options2, toolMap2, functionCallContents2, iteration, callIndex2, captureCurrentIterationExceptions, isStreaming, cancellationToken); results.Add(functionInvocationResult2); if (functionInvocationResult2.Terminate) { shouldTerminate = true; break; } } } IList<ChatMessage> list3 = CreateResponseMessages(results.ToArray()); ThrowIfNoFunctionResultsAdded(list3); UpdateConsecutiveErrorCountOrThrow(list3, ref consecutiveErrorCount); messages2.AddRange(list3); return (shouldTerminate, consecutiveErrorCount, list3); } private void UpdateConsecutiveErrorCountOrThrow(IList<ChatMessage> added, ref int consecutiveErrorCount) { if (added.Any((ChatMessage m) => m.Contents.Any(delegate(AIContent c) { FunctionResultContent val = (FunctionResultContent)(object)((c is FunctionResultContent) ? c : null); return val != null && val.Exception != null; }))) { consecutiveErrorCount++; if (consecutiveErrorCount > MaximumConsecutiveErrorsPerRequest) { Exception[] array = (from frc in added.SelectMany((ChatMessage m) => m.Contents.OfType<FunctionResultContent>()) select frc.Exception into e where e != null select e).ToArray(); if (array.Length == 1) { ExceptionDispatchInfo.Capture(array[0]).Throw(); } throw new AggregateException(array); } } else { consecutiveErrorCount = 0; } } private void ThrowIfNoFunctionResultsAdded(IList<ChatMessage>? messages) { if (messages == null || messages.Count <= 0) { Throw.InvalidOperationException(((object)this).GetType().Name + ".CreateResponseMessages returned null or an empty collection of messages."); } } private async Task<FunctionInvocationResult> ProcessFunctionCallAsync(List<ChatMessage> messages, ChatOptions? options, Dictionary<string, AITool>? toolMap, List<FunctionCallContent> callContents, int iteration, int functionCallIndex, bool captureExceptions, bool isStreaming, CancellationToken cancellationToken) { FunctionCallContent callContent = callContents[functionCallIndex]; if (toolMap != null && toolMap.TryGetValue(callContent.Name, out AITool value)) { AIFunction val = (AIFunction)(object)((value is AIFunction) ? value : null); if (val != null) { FunctionInvocationContext context = new FunctionInvocationContext { Function = val, Arguments = new AIFunctionArguments(callContent.Arguments) { Services = FunctionInvocationServices }, Messages = messages, Options = options, CallContent = callContent, Iteration = iteration, FunctionCallIndex = functionCallIndex, FunctionCount = callContents.Count, IsStreaming = isStreaming }; object result; try { result = await InstrumentedInvokeFunctionAsync(context, cancellationToken); } catch (Exception exception) when (!cancellationToken.IsCancellationRequested) { if (!captureExceptions) { throw; } return new FunctionInvocationResult(terminate: false, FunctionInvocationStatus.Exception, callContent, null, exception); } return new FunctionInvocationResult(context.Terminate, FunctionInvocationStatus.RanToCompletion, callContent, result, null); } } return new FunctionInvocationResult(terminate: false, FunctionInvocationStatus.NotFound, callContent, null, null); } protected virtual IList<ChatMessage> CreateResponseMessages(ReadOnlySpan<FunctionInvocationResult> results) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown List<AIContent> list = new List<AIContent>(results.Length); for (int i = 0; i < results.Length; i++) { list.Add((AIContent)(object)CreateFunctionResultContent(results[i])); } return new List<ChatMessage>(1) { new ChatMessage(ChatRole.Tool, (IList<AIContent>)list) }; FunctionResultContent CreateFunctionResultContent(FunctionInvocationResult result) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown Throw.IfNull(result, "result"); object obj; if (result.Status == FunctionInvocationStatus.RanToCompletion) { obj = result.Result ?? "Success: Function completed."; } else { string text = result.Status switch { FunctionInvocationStatus.NotFound => "Error: Requested function \"" + result.CallContent.Name + "\" not found.", FunctionInvocationStatus.Exception => "Error: Function failed.", _ => "Error: Unknown error.", }; if (IncludeDetailedErrors && result.Exception != null) { text = text + " Exception: " + result.Exception.Message; } obj = text; } return new FunctionResultContent(result.CallContent.CallId, obj) { Exception = result.Exception }; } } private async Task<object?> InstrumentedInvokeFunctionAsync(FunctionInvocationContext context, CancellationToken cancellationToken) { Throw.IfNull(context, "context"); using Activity activity = _activitySource?.StartActivity("execute_tool " + ((AITool)context.Function).Name, ActivityKind.Internal, default(ActivityContext), new <>z__ReadOnlyArray<KeyValuePair<string, object>>(new KeyValuePair<string, object>[5] { new KeyValuePair<string, object>("gen_ai.operation.name", "execute_tool"), new KeyValuePair<string, object>("gen_ai.tool.type", "function"), new KeyValuePair<string, object>("gen_ai.tool.call.id", context.CallContent.CallId), new KeyValuePair<string, object>("gen_ai.tool.name", ((AITool)context.Function).Name), new KeyValuePair<string, object>("gen_ai.tool.description", ((AITool)context.Function).Description) })); long startingTimestamp = Stopwatch.GetTimestamp(); bool enableSensitiveData = activity != null && activity.IsAllDataRequested && (ChatClientExtensions.GetService<OpenTelemetryChatClient>(((DelegatingChatClient)this).InnerClient, (object)null)?.EnableSensitiveData ?? false); bool traceLoggingEnabled = _logger.IsEnabled(LogLevel.Trace); bool flag = false; if (enableSensitiveData || traceLoggingEnabled) { string text = TelemetryHelpers.AsJson<AIFunctionArguments>(context.Arguments, context.Function.JsonSerializerOptions); if (enableSensitiveData) { activity?.SetTag("gen_ai.tool.call.arguments", text); } if (traceLoggingEnabled) { LogInvokingSensitive(((AITool)context.Function).Name, text); flag = true; } } if (!flag && _logger.IsEnabled(LogLevel.Debug)) { LogInvoking(((AITool)context.Function).Name); } object result = null; try { CurrentContext = context; result = await InvokeFunctionAsync(context, cancellationToken); } catch (Exception ex) { activity?.SetTag("error.type", ex.GetType().FullName).SetStatus(ActivityStatusCode.Error, ex.Message); if (ex is OperationCanceledException) { LogInvocationCanceled(((AITool)context.Function).Name); } else { LogInvocationFailed(((AITool)context.Function).Name, ex); } throw; } finally { bool flag2 = false; if (enableSensitiveData || traceLoggingEnabled) { string text2 = TelemetryHelpers.AsJson(result, context.Function.JsonSerializerOptions); if (enableSensitiveData) { activity?.SetTag("gen_ai.tool.call.result", text2); } if (traceLoggingEnabled) { LogInvocationCompletedSensitive(((AITool)context.Function).Name, GetElapsedTime(startingTimestamp), text2); flag2 = true; } } if (!flag2 && _logger.IsEnabled(LogLevel.Debug)) { LogInvocationCompleted(((AITool)context.Function).Name, GetElapsedTime(startingTimestamp)); } } return result; } protected virtual ValueTask<object?> InvokeFunctionAsync(FunctionInvocationContext context, CancellationToken cancellationToken) { Throw.IfNull(context, "context"); return FunctionInvoker?.Invoke(context, cancellationToken) ?? context.Function.InvokeAsync(context.Arguments, cancellationToken); } private static (List<ChatMessage>? preDownstreamCallHistory, List<ApprovalResultWithRequestMessage>? approvals) ProcessFunctionApprovalResponses(List<ChatMessage> originalMessages, bool hasConversationId, string? toolMessageId, string? functionCallContentFallbackMessageId) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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) (List<ApprovalResultWithRequestMessage>, List<ApprovalResultWithRequestMessage>) tuple = ExtractAndRemoveApprovalRequestsAndResponses(originalMessages); List<ApprovalResultWithRequestMessage> list = new List<ApprovalResultWithRequestMessage>(); IEnumerable<ApprovalResultWithRequestMessage> item = tuple.Item2; list.AddRange(item ?? Enumerable.Empty<ApprovalResultWithRequestMessage>()); (item, _) = tuple; list.AddRange(item ?? Enumerable.Empty<ApprovalResultWithRequestMessage>()); ICollection<ChatMessage> collection = ConvertToFunctionCallContentMessages(list, functionCallContentFallbackMessageId); List<AIContent> list2 = GenerateRejectedFunctionResults(tuple.Item2); ChatMessage val = ((list2 == null) ? ((ChatMessage)null) : new ChatMessage(ChatRole.Tool, (IList<AIContent>)list2) { MessageId = toolMessageId }); List<ChatMessage> list3 = null; if (collection != null) { list3 = collection.ToList(); if (!hasConversationId) { originalMessages.AddRange(list3); } } if (val != null) { (list3 ?? (list3 = new List<ChatMessage>())).Add(val); originalMessages.Add(val); } return (list3, tuple.Item1); } private static (List<ApprovalResultWithRequestMessage>? approvals, List<ApprovalResultWithRequestMessage>? rejections) ExtractAndRemoveApprovalRequestsAndResponses(List<ChatMessage> messages) { Dictionary<string, ChatMessage> dictionary = null; List<FunctionApprovalResponseContent> list = null; HashSet<string> hashSet = null; HashSet<string> hashSet2 = null; bool flag = false; for (int i = 0; i < messages.Count; i++) { ChatMessage val = messages[i]; List<AIContent> list2 = null; for (int j = 0; j < val.Contents.Count; j++) { AIContent val2 = val.Contents[j]; FunctionApprovalRequestContent val3 = (FunctionApprovalRequestContent)(object)((val2 is FunctionApprovalRequestContent) ? val2 : null); if (val3 == null) { FunctionApprovalResponseContent val4 = (FunctionApprovalResponseContent)(object)((val2 is FunctionApprovalResponseContent) ? val2 : null); if (val4 == null) { FunctionResultContent val5 = (FunctionResultContent)(object)((val2 is FunctionResultContent) ? val2 : null); if (val5 != null) { (hashSet2 ?? (hashSet2 = new HashSet<string>())).Add(val5.CallId); } (list2 ?? (list2 = new List<AIContent>())).Add(val2); } else { hashSet?.Remove(val4.FunctionCall.CallId); (list ?? (list = new List<FunctionApprovalResponseContent>())).Add(val4); } } else { (hashSet ?? (hashSet = new HashSet<string>())).Add(val3.FunctionCall.CallId); (dictionary ?? (dictionary = new Dictionary<string, ChatMessage>())).Add(((UserInputRequestContent)val3).Id, val); } } if (list2?.Count != val.Contents.Count) { if (list2 != null && list2.Count > 0) { ChatMessage val6 = val.Clone(); val6.Contents = list2; messages[i] = val6; } else { flag = true; messages[i] = null; } } } if (flag) { messages.RemoveAll((ChatMessage m) => m == null); } if (hashSet != null && hashSet.Count > 0) { Throw.InvalidOperationException("FunctionApprovalRequestContent found with FunctionCall.CallId(s) '" + string.Join(", ", hashSet) + "' that have no matching FunctionApprovalResponseContent."); } List<ApprovalResultWithRequestMessage> item = null; List<ApprovalResultWithRequestMessage> item2 = null; if (list != null && list.Count > 0) { foreach (FunctionApprovalResponseContent item3 in list) { if ((!(hashSet2?.Contains(item3.FunctionCall.CallId))) ?? true) { ref List<ApprovalResultWithRequestMessage> reference = ref item3.Approved ? ref item : ref item2; ChatMessage value = null; dictionary?.TryGetValue(item3.FunctionCall.CallId, out value); (reference ?? (reference = new List<ApprovalResultWithRequestMessage>())).Add(new ApprovalResultWithRequestMessage { Response = item3, RequestMessage = value }); } } } return (item, item2); } private static List<AIContent>? GenerateRejectedFunctionResults(List<ApprovalResultWithRequestMessage>? rejections) { if (rejections == null || rejections.Count <= 0) { return null; } return rejections.ConvertAll((ApprovalResultWithRequestMessage m) => (AIContent)new FunctionResultContent(m.Response.FunctionCall.CallId, (object)"Error: Tool call invocation was rejected by user.")); } private static ICollection<ChatMessage>? ConvertToFunctionCallContentMessages(List<ApprovalResultWithRequestMessage>? resultWithRequestMessages, string? fallbackMessageId) { if (resultWithRequestMessages != null) { ChatMessage value = null; Dictionary<string, ChatMessage> dictionary = null; foreach (ApprovalResultWithRequestMessage resultWithRequestMessage in resultWithRequestMessages) { if (dictionary == null && value != null && (resultWithRequestMessage.RequestMessage != null || !(value.MessageId == fallbackMessageId)) && resultWithRequestMessage.RequestMessage != null && value.MessageId != resultWithRequestMessage.RequestMessage.MessageId) { dictionary = new Dictionary<string, ChatMessage>(); dictionary[value.MessageId ?? string.Empty] = value; } if (dictionary != null) { Dictionary<string, ChatMessage> dictionary2 = dictionary; ChatMessage? requestMessage = resultWithRequestMessage.RequestMessage; dictionary2.TryGetValue(((requestMessage != null) ? requestMessage.MessageId : null) ?? string.Empty, out value); } if (value == null) { value = ConvertToFunctionCallContentMessage(resultWithRequestMessage, fallbackMessageId); } else { value.Contents.Add((AIContent)(object)resultWithRequestMessage.Response.FunctionCall); } if (dictionary != null) { dictionary[value.MessageId ?? string.Empty] = value; } } ICollection<ChatMessage> collection = dictionary?.Values; if (collection != null) { return collection; } if (value != null) { return new List<ChatMessage>(1) { value }; } } return null; } private static ChatMessage ConvertToFunctionCallContentMessage(ApprovalResultWithRequestMessage resultWithRequestMessage, string? fallbackMessageId) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) ChatMessage? requestMessage = resultWithRequestMessage.RequestMessage; ChatMessage val = (ChatMessage)(((object)((requestMessage != null) ? requestMessage.Clone() : null)) ?? ((object)new ChatMessage { Role = ChatRole.Assistant })); val.Contents = new List<AIContent>(1) { (AIContent)(object)resultWithRequestMessage.Response.FunctionCall }; ChatMessage val2 = val; if (val2.MessageId == null) { string text2 = (val2.MessageId = fallbackMessageId); } return val; } private static (bool hasApprovalRequiringFcc, int lastApprovalCheckedFCCIndex) CheckForApprovalRequiringFCC(List<FunctionCallContent>? functionCallContents, AITool[] approvalRequiredFunctions, bool hasApprovalRequiringFcc, int lastApprovalCheckedFCCIndex) { if (hasApprovalRequiringFcc) { return (true, functionCallContents.Count); } if (functionCallContents != null) { while (lastApprovalCheckedFCCIndex < functionCallContents.Count) { FunctionCallContent val = functionCallContents[lastApprovalCheckedFCCIndex]; foreach (AITool val2 in approvalRequiredFunctions) { if (val2.Name == val.Name) { hasApprovalRequiringFcc = true; break; } } lastApprovalCheckedFCCIndex++; } } return (hasApprovalRequiringFcc, lastApprovalCheckedFCCIndex); } private static bool TryReplaceFunctionCallsWithApprovalRequests(IList<AIContent> content, out List<AIContent>? updatedContent) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown updatedContent = null; if (content != null && content.Count > 0) { for (int i = 0; i < content.Count; i++) { AIContent obj = content[i]; FunctionCallContent val = (FunctionCallContent)(object)((obj is FunctionCallContent) ? obj : null); if (val != null) { if (updatedContent == null) { updatedContent = content.ToList(); } updatedContent[i] = (AIContent)new FunctionApprovalRequestContent(val.CallId, val); } } } return updatedContent != null; } private static IList<ChatMessage> ReplaceFunctionCallsWithApprovalRequests(IList<ChatMessage> messages, Dictionary<string, AITool> toolMap) { //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Expected O, but got Unknown //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Expected O, but got Unknown IList<ChatMessage> list = messages; bool flag = false; List<(int, int)> list2 = null; for (int i = 0; i < messages.Count; i++) { IList<AIContent> contents = messages[i].Contents; for (int j = 0; j < contents.Count; j++) { AIContent obj = contents[j]; FunctionCallContent val = (FunctionCallContent)(object)((obj is FunctionCallContent) ? obj : null); if (val == null) { continue; } (list2 ?? (list2 = new List<(int, int)>())).Add((i, j)); if (flag) { continue; } foreach (KeyValuePair<string, AITool> item3 in toolMap) { ApprovalRequiredAIFunction service = item3.Value.GetService<ApprovalRequiredAIFunction>((object)null); if (service != null && ((AITool)service).Name == val.Name) { flag = true; break; } } } } if (flag) { List<ChatMessage> list3 = new List<ChatMessage>(messages.Count); list3.AddRange(messages); list = list3; int num = -1; foreach (var item4 in list2) { int item = item4.Item1; int item2 = item4.Item2; ChatMessage val2 = ((num != item) ? list[item].Clone() : list[item]); IList<AIContent> contents2 = val2.Contents; List<AIContent> list4 = new List<AIContent>(contents2.Count); list4.AddRange(contents2); val2.Contents = list4; FunctionCallContent val3 = (FunctionCallContent)val2.Contents[item2]; val2.Contents[item2] = (AIContent)new FunctionApprovalRequestContent(val3.CallId, val3); list[item] = val2; num = item; } } return list; } private static TimeSpan GetElapsedTime(long startingTimestamp) { return new TimeSpan((long)((double)(Stopwatch.GetTimestamp() - startingTimestamp) * (10000000.0 / (double)Stopwatch.Frequency))); } private async Task<(IList<ChatMessage>? FunctionResultContentMessages, bool ShouldTerminate, int ConsecutiveErrorCount)> InvokeApprovedFunctionApprovalResponsesAsync(List<ApprovalResultWithRequestMessage>? notInvokedApprovals, Dictionary<string, AITool>? toolMap, List<ChatMessage> originalMessages, ChatOptions? options, int consecutiveErrorCount, bool isStreaming, CancellationToken cancellationToken) { if (notInvokedApprovals != null && notInvokedApprovals.Count > 0) { (bool, int, IList<ChatMessage>) tuple = await ProcessFunctionCallsAsync(originalMessages, options, toolMap, notInvokedApprovals.Select((ApprovalResultWithRequestMessage x) => x.Response.FunctionCall).ToList(), 0, consecutiveErrorCount, isStreaming, cancellationToken); consecutiveErrorCount = tuple.Item2; return (tuple.Item3, tuple.Item1, consecutiveErrorCount); } return (null, false, consecutiveErrorCount); } [LoggerMessage(LogLevel.Debug, "Invoking {MethodName}.", SkipEnabledCheck = true)] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private void LogInvoking(string methodName) { __LogInvokingCallback(_logger, methodName, null); } [LoggerMessage(LogLevel.Trace, "Invoking {MethodName}({Arguments}).", SkipEnabledCheck = true)] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private void LogInvokingSensitive(string methodName, string arguments) { __LogInvokingSensitiveCallback(_logger, methodName, arguments, null); } [LoggerMessage(LogLevel.Debug, "{MethodName} invocation completed. Duration: {Duration}", SkipEnabledCheck = true)] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private void LogInvocationCompleted(string methodName, TimeSpan duration) { __LogInvocationCompletedCallback(_logger, methodName, duration, null); } [LoggerMessage(LogLevel.Trace, "{MethodName} invocation completed. Duration: {Duration}. Result: {Result}", SkipEnabledCheck = true)] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private void LogInvocationCompletedSensitive(string methodName, TimeSpan duration, string result) { __LogInvocationCompletedSensitiveCallback(_logger, methodName, duration, result, null); } [LoggerMessage(LogLevel.Debug, "{MethodName} invocation canceled.")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private void LogInvocationCanceled(string methodName) { if (_logger.IsEnabled(LogLevel.Debug)) { __LogInvocationCanceledCallback(_logger, methodName, null); } } [LoggerMessage(LogLevel.Error, "{MethodName} invocation failed.")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private void LogInvocationFailed(string methodName, Exception error) { if (_logger.IsEnabled(LogLevel.Error)) { __LogInvocationFailedCallback(_logger, methodName, error); } } [CompilerGenerated] [DebuggerHidden] private Task<ChatResponse> <>n__0(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return ((DelegatingChatClient)this).GetResponseAsync(messages, options, cancellationToken); } [CompilerGenerated] [DebuggerHidden] private IAsyncEnumerable<ChatResponseUpdate> <>n__1(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return ((DelegatingChatClient)this).GetStreamingResponseAsync(messages, options, cancellationToken); } } public static class FunctionInvokingChatClientBuilderExtensions { public static ChatClientBuilder UseFunctionInvocation(this ChatClientBuilder builder, ILoggerFactory? loggerFactory = null, Action<FunctionInvokingChatClient>? configure = null) { ILoggerFactory loggerFactory2 = loggerFactory; Action<FunctionInvokingChatClient> configure2 = configure; Throw.IfNull(builder, "builder"); return builder.Use(delegate(IChatClient innerClient, IServiceProvider services) { if (loggerFactory2 == null) { loggerFactory2 = services.GetService<ILoggerFactory>(); } FunctionInvokingChatClient functionInvokingChatClient = new FunctionInvokingChatClient(innerClient, loggerFactory2, services); configure2?.Invoke(functionInvokingChatClient); return (IChatClient)(object)functionInvokingChatClient; }); } } public class LoggingChatClient : DelegatingChatClient { private readonly ILogger _logger; private JsonSerializerOptions _jsonSerializerOptions; [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __LogInvokedCallback = LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1723383095, "LogInvoked"), "{MethodName} invoked.", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, string, string, string, Exception?> __LogInvokedSensitiveCallback = LoggerMessage.Define<string, string, string, string>(LogLevel.Trace, new EventId(805843669, "LogInvokedSensitive"), "{MethodName} invoked: {Messages}. Options: {ChatOptions}. Metadata: {ChatClientMetadata}.", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __LogCompletedCallback = LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1553703230, "LogCompleted"), "{MethodName} completed.", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, string, Exception?> __LogCompletedSensitiveCallback = LoggerMessage.Define<string, string>(LogLevel.Trace, new EventId(384896670, "LogCompletedSensitive"), "{MethodName} completed: {ChatResponse}.", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __LogStreamingUpdateSensitiveCallback = LoggerMessage.Define<string>(LogLevel.Trace, new EventId(1513570378, "LogStreamingUpdateSensitive"), "GetStreamingResponseAsync received update: {ChatResponseUpdate}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __LogInvocationCanceledCallback = LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1891493904, "LogInvocationCanceled"), "{MethodName} canceled.", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __LogInvocationFailedCallback = LoggerMessage.Define<string>(LogLevel.Error, new EventId(1784604714, "LogInvocationFailed"), "{MethodName} failed.", new LogDefineOptions { SkipEnabledCheck = true }); public JsonSerializerOptions JsonSerializerOptions { get { return _jsonSerializerOptions; } set { _jsonSerializerOptions = Throw.IfNull(value, "value"); } } public LoggingChatClient(IChatClient innerClient, ILogger logger) : base(innerClient) { _logger = Throw.IfNull(logger, "logger"); _jsonSerializerOptions = AIJsonUtilities.DefaultOptions; } public override async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { if (_logger.IsEnabled(LogLevel.Debug)) { if (_logger.IsEnabled(LogLevel.Trace)) { LogInvokedSensitive("GetResponseAsync", AsJson(messages), AsJson<ChatOptions>(options), AsJson<ChatClientMetadata>(ChatClientExtensions.GetService<ChatClientMetadata>((IChatClient)(object)this, (object)null))); } else { LogInvoked("GetResponseAsync"); } } try { ChatResponse val = await <>n__0(messages, options, cancellationToken); if (_logger.IsEnabled(LogLevel.Debug)) { if (_logger.IsEnabled(LogLevel.Trace)) { LogCompletedSensitive("GetResponseAsync", AsJson<ChatResponse>(val)); } else { LogCompleted("GetResponseAsync"); } } return val; } catch (OperationCanceledException) { LogInvocationCanceled("GetResponseAsync"); throw; } catch (Exception error) { LogInvocationFailed("GetResponseAsync", error); throw; } } public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { if (_logger.IsEnabled(LogLevel.Debug)) { if (_logger.IsEnabled(LogLevel.Trace)) { LogInvokedSensitive("GetStreamingResponseAsync", AsJson(messages), AsJson<ChatOptions>(options), AsJson<ChatClientMetadata>(ChatClientExtensions.GetService<ChatClientMetadata>((IChatClient)(object)this, (object)null))); } else { LogInvoked("GetStreamingResponseAsync"); } } IAsyncEnumerator<ChatResponseUpdate> e; try { e = <>n__1(messages, options, cancellationToken).GetAsyncEnumerator(cancellationToken); } catch (OperationCanceledException) { LogInvocationCanceled("GetStreamingResponseAsync"); throw; } catch (Exception error) { LogInvocationFailed("GetStreamingResponseAsync", error); throw; } try { while (true) { ChatResponseUpdate current; try { if (!(await e.MoveNextAsync())) { break; } current = e.Current; goto IL_01a7; } catch (OperationCanceledException) { LogInvocationCanceled("GetStreamingResponseAsync"); throw; } catch (Exception error2) { LogInvocationFailed("GetStreamingResponseAsync", error2); throw; } IL_01a7: if (_logger.IsEnabled(LogLevel.Trace)) { LogStreamingUpdateSensitive(AsJson<ChatResponseUpdate>(current)); } yield return current; } LogCompleted("GetStreamingResponseAsync"); } finally { await e.DisposeAsync(); } } private string AsJson<T>(T value) { return TelemetryHelpers.AsJson(value, _jsonSerializerOptions); } [LoggerMessage(LogLevel.Debug, "{MethodName} invoked.")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private void LogInvoked(string methodName) { if (_logger.IsEnabled(LogLevel.Debug)) { __LogInvokedCallback(_logger, methodName, null); } } [LoggerMessage(LogLevel.Trace, "{MethodName} invoked: {Messages}. Options: {ChatOptions}. Metadata: {ChatClientMetadata}.")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private void LogInvokedSensitive(string methodName, string messages, string chatOptions, string
deps/Microsoft.Extensions.AI.OpenAI.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.ClientModel; using System.ClientModel.Primitives; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.AI; using Microsoft.Shared.Diagnostics; using OpenAI.Assistants; using OpenAI.Audio; using OpenAI.Chat; using OpenAI.Embeddings; using OpenAI.Images; using OpenAI.Realtime; using OpenAI.Responses; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Implementation of generative AI abstractions for OpenAI-compatible endpoints.")] [assembly: AssemblyFileVersion("9.900.125.47406")] [assembly: AssemblyInformationalVersion("9.9.1-preview.1.25474.6+54f611c53feaaecb28108edd16725b7577c8a9aa")] [assembly: AssemblyProduct("Microsoft.Extensions.AI.OpenAI")] [assembly: AssemblyTitle("Microsoft.Extensions.AI.OpenAI")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/extensions")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("9.9.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] 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 OpenAI.Responses { public static class MicrosoftExtensionsAIResponsesExtensions { public static FunctionTool AsOpenAIResponseTool(this AIFunctionDeclaration function) { return OpenAIResponsesChatClient.ToResponseTool(Throw.IfNull<AIFunctionDeclaration>(function, "function")); } public static ResponseTextFormat? AsOpenAIResponseTextFormat(this ChatResponseFormat? format, ChatOptions? options = null) { return OpenAIResponsesChatClient.ToOpenAIResponseTextFormat(format, options); } public static IEnumerable<ResponseItem> AsOpenAIResponseItems(this IEnumerable<ChatMessage> messages, ChatOptions? options = null) { return OpenAIResponsesChatClient.ToOpenAIResponseItems(Throw.IfNull(messages, "messages"), options); } public static IEnumerable<ChatMessage> AsChatMessages(this IEnumerable<ResponseItem> items) { return OpenAIResponsesChatClient.ToChatMessages(Throw.IfNull(items, "items")); } public static ChatResponse AsChatResponse(this OpenAIResponse response, ResponseCreationOptions? options = null) { return OpenAIResponsesChatClient.FromOpenAIResponse(Throw.IfNull<OpenAIResponse>(response, "response"), options); } public static IAsyncEnumerable<ChatResponseUpdate> AsChatResponseUpdatesAsync(this IAsyncEnumerable<StreamingResponseUpdate> responseUpdates, ResponseCreationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return OpenAIResponsesChatClient.FromOpenAIStreamingResponseUpdatesAsync(Throw.IfNull(responseUpdates, "responseUpdates"), options, cancellationToken); } public static OpenAIResponse AsOpenAIResponse(this ChatResponse response, ChatOptions? options = null) { Throw.IfNull<ChatResponse>(response, "response"); object rawRepresentation = response.RawRepresentation; OpenAIResponse val = (OpenAIResponse)((rawRepresentation is OpenAIResponse) ? rawRepresentation : null); if (val != null) { return val; } string responseId = response.ResponseId; DateTimeOffset valueOrDefault = response.CreatedAt.GetValueOrDefault(); ResponseStatus? val2 = (ResponseStatus)1; int? obj = ((options != null) ? options.MaxOutputTokens : null); IEnumerable<ResponseItem> enumerable = OpenAIResponsesChatClient.ToOpenAIResponseItems(response.Messages, options); bool valueOrDefault2 = ((options != null) ? options.AllowMultipleToolCalls : null).GetValueOrDefault(); string text = response.ModelId ?? ((options != null) ? options.ModelId : null); float? num = ((options != null) ? options.Temperature : null); float? num2 = ((options != null) ? options.TopP : null); string text2 = ((options != null) ? options.ConversationId : null); string text3 = ((options != null) ? options.Instructions : null); return OpenAIResponsesModelFactory.OpenAIResponse(responseId, valueOrDefault, val2, (ResponseError)null, (ResponseTokenUsage)null, (string)null, (ResponseReasoningOptions)null, obj, (ResponseTextOptions)null, (ResponseTruncationMode?)null, (ResponseIncompleteStatusDetails)null, enumerable, valueOrDefault2, (ResponseToolChoice)null, text, (IDictionary<string, string>)null, num, num2, (ResponseServiceTier?)null, text2, (bool?)null, text3, (IEnumerable<ResponseTool>)null); } public static void Add(this IList<AITool> tools, ResponseTool tool) { Throw.IfNull(tools, "tools"); tools.Add(tool.AsAITool()); } public static AITool AsAITool(this ResponseTool tool) { Throw.IfNull<ResponseTool>(tool, "tool"); return (AITool)(object)new OpenAIResponsesChatClient.ResponseToolAITool(tool); } } } namespace OpenAI.Realtime { public static class MicrosoftExtensionsAIRealtimeExtensions { public static ConversationFunctionTool AsOpenAIConversationFunctionTool(this AIFunctionDeclaration function) { return OpenAIRealtimeConversationClient.ToOpenAIConversationFunctionTool(Throw.IfNull<AIFunctionDeclaration>(function, "function")); } } } namespace OpenAI.Chat { public static class MicrosoftExtensionsAIChatExtensions { public static ChatTool AsOpenAIChatTool(this AIFunctionDeclaration function) { return OpenAIChatClient.ToOpenAIChatTool(Throw.IfNull<AIFunctionDeclaration>(function, "function")); } public static ChatResponseFormat? AsOpenAIChatResponseFormat(this ChatResponseFormat? format, ChatOptions? options = null) { return OpenAIChatClient.ToOpenAIChatResponseFormat(format, options); } public static IEnumerable<ChatMessage> AsOpenAIChatMessages(this IEnumerable<ChatMessage> messages, ChatOptions? options = null) { return OpenAIChatClient.ToOpenAIChatMessages(Throw.IfNull(messages, "messages"), options); } public static ChatCompletion AsOpenAIChatCompletion(this ChatResponse response) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Expected O, but got Unknown Throw.IfNull<ChatResponse>(response, "response"); object rawRepresentation = response.RawRepresentation; ChatCompletion val = (ChatCompletion)((rawRepresentation is ChatCompletion) ? rawRepresentation : null); if (val != null) { return val; } ChatMessage val2 = response.Messages.LastOrDefault(); ChatMessageRole val3 = ToChatMessageRole((val2 != null) ? new ChatRole?(val2.Role) : null); ChatFinishReason val4 = ToChatFinishReason(response.FinishReason); UsageDetails usage = response.Usage; int valueOrDefault = ((int?)((usage != null) ? usage.OutputTokenCount : null)).GetValueOrDefault(); UsageDetails usage2 = response.Usage; int valueOrDefault2 = ((int?)((usage2 != null) ? usage2.InputTokenCount : null)).GetValueOrDefault(); UsageDetails usage3 = response.Usage; ChatTokenUsage val5 = OpenAIChatModelFactory.ChatTokenUsage(valueOrDefault, valueOrDefault2, ((int?)((usage3 != null) ? usage3.TotalTokenCount : null)).GetValueOrDefault(), (ChatOutputTokenUsageDetails)null, (ChatInputTokenUsageDetails)null); IEnumerable<ChatToolCall> enumerable = ((val2 != null) ? (from c in val2.Contents.OfType<FunctionCallContent>() select ChatToolCall.CreateFunctionToolCall(c.CallId, c.Name, new BinaryData(JsonSerializer.SerializeToUtf8Bytes((object)c.Arguments, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(IDictionary<string, object>)))))) : null); string responseId = response.ResponseId; ChatMessageContent val6 = new ChatMessageContent((IEnumerable<ChatMessageContentPart>)OpenAIChatClient.ToOpenAIChatContent(((val2 != null) ? val2.Contents : null) ?? new List<AIContent>())); DateTimeOffset valueOrDefault3 = response.CreatedAt.GetValueOrDefault(); string modelId = response.ModelId; ChatTokenUsage val7 = val5; ChatOutputAudio val8 = ((val2 != null) ? (from dc in val2.Contents.OfType<DataContent>() where dc.HasTopLevelMediaType("audio") select dc into a select OpenAIChatModelFactory.ChatOutputAudio(new BinaryData(a.Data), (string)null, (string)null, default(DateTimeOffset))).FirstOrDefault() : null); IEnumerable<ChatMessageAnnotation> enumerable2 = ConvertAnnotations((val2 != null) ? val2.Contents : null); return OpenAIChatModelFactory.ChatCompletion(responseId, val4, val6, (string)null, enumerable, val3, (ChatFunctionCall)null, (IEnumerable<ChatTokenLogProbabilityDetails>)null, (IEnumerable<ChatTokenLogProbabilityDetails>)null, valueOrDefault3, modelId, (ChatServiceTier?)null, (string)null, val7, val8, enumerable2); static IEnumerable<ChatMessageAnnotation> ConvertAnnotations(IEnumerable<AIContent>? contents) { if (contents != null) { foreach (AIContent content in contents) { if (content.Annotations != null) { foreach (AIAnnotation annotation in content.Annotations) { CitationAnnotation citation = (CitationAnnotation)(object)((annotation is CitationAnnotation) ? annotation : null); if (citation != null) { TextSpanAnnotatedRegion[] array = ((AIAnnotation)citation).AnnotatedRegions?.OfType<TextSpanAnnotatedRegion>().ToArray(); if (array != null && array.Length > 0) { TextSpanAnnotatedRegion[] array2 = array; foreach (TextSpanAnnotatedRegion val9 in array2) { yield return OpenAIChatModelFactory.ChatMessageAnnotation(val9.StartIndex.GetValueOrDefault(), val9.EndIndex.GetValueOrDefault(), citation.Url, citation.Title); } } else { yield return OpenAIChatModelFactory.ChatMessageAnnotation(0, 0, citation.Url, citation.Title); } } } } } } } } public static async IAsyncEnumerable<StreamingChatCompletionUpdate> AsOpenAIStreamingChatCompletionUpdatesAsync(this IAsyncEnumerable<ChatResponseUpdate> responseUpdates, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(responseUpdates, "responseUpdates"); await foreach (ChatResponseUpdate item in responseUpdates.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { object rawRepresentation = item.RawRepresentation; StreamingChatCompletionUpdate val = (StreamingChatCompletionUpdate)((rawRepresentation is StreamingChatCompletionUpdate) ? rawRepresentation : null); if (val != null) { yield return val; continue; } AIContent? obj = ((IEnumerable<AIContent>)item.Contents).FirstOrDefault((Func<AIContent, bool>)((AIContent c) => c is UsageContent)); UsageContent val2 = (UsageContent)(object)((obj is UsageContent) ? obj : null); ChatTokenUsage val3 = ((val2 != null) ? OpenAIChatModelFactory.ChatTokenUsage(((int?)val2.Details.OutputTokenCount).GetValueOrDefault(), ((int?)val2.Details.InputTokenCount).GetValueOrDefault(), ((int?)val2.Details.TotalTokenCount).GetValueOrDefault(), (ChatOutputTokenUsageDetails)null, (ChatInputTokenUsageDetails)null) : null); List<StreamingChatToolCallUpdate> list = item.Contents.OfType<FunctionCallContent>().Select((FunctionCallContent fcc, int index) => OpenAIChatModelFactory.StreamingChatToolCallUpdate(index, fcc.CallId, (ChatToolCallKind)0, fcc.Name, new BinaryData(JsonSerializer.SerializeToUtf8Bytes((object)fcc.Arguments, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(IDictionary<string, object>)))))).ToList(); string responseId = item.ResponseId; ChatMessageContent val4 = new ChatMessageContent((IEnumerable<ChatMessageContentPart>)OpenAIChatClient.ToOpenAIChatContent(item.Contents)); ChatMessageRole? val5 = ToChatMessageRole(item.Role); ChatFinishReason? val6 = ToChatFinishReason(item.FinishReason); DateTimeOffset valueOrDefault = item.CreatedAt.GetValueOrDefault(); string modelId = item.ModelId; ChatTokenUsage val7 = val3; yield return OpenAIChatModelFactory.StreamingChatCompletionUpdate(responseId, val4, (StreamingChatFunctionCallUpdate)null, (IEnumerable<StreamingChatToolCallUpdate>)list, val5, (string)null, (IEnumerable<ChatTokenLogProbabilityDetails>)null, (IEnumerable<ChatTokenLogProbabilityDetails>)null, val6, valueOrDefault, modelId, (ChatServiceTier?)null, (string)null, val7, (StreamingChatOutputAudioUpdate)null); } } public static IEnumerable<ChatMessage> AsChatMessages(this IEnumerable<ChatMessage> messages) { Throw.IfNull(messages, "messages"); foreach (ChatMessage message in messages) { ChatMessage val = new ChatMessage { RawRepresentation = message }; AssistantChatMessage val2 = (AssistantChatMessage)(object)((message is AssistantChatMessage) ? message : null); if (val2 == null) { UserChatMessage val3 = (UserChatMessage)(object)((message is UserChatMessage) ? message : null); if (val3 == null) { DeveloperChatMessage val4 = (DeveloperChatMessage)(object)((message is DeveloperChatMessage) ? message : null); if (val4 == null) { SystemChatMessage val5 = (SystemChatMessage)(object)((message is SystemChatMessage) ? message : null); if (val5 == null) { ToolChatMessage val6 = (ToolChatMessage)(object)((message is ToolChatMessage) ? message : null); if (val6 != null) { val.Contents.Add((AIContent)new FunctionResultContent(val6.ToolCallId, ToToolResult(((ChatMessage)val6).Content)) { RawRepresentation = val6 }); } } else { val.AuthorName = val5.ParticipantName; OpenAIChatClient.ConvertContentParts(((ChatMessage)val5).Content, val.Contents); } } else { val.AuthorName = val4.ParticipantName; OpenAIChatClient.ConvertContentParts(((ChatMessage)val4).Content, val.Contents); } } else { val.AuthorName = val3.ParticipantName; OpenAIChatClient.ConvertContentParts(((ChatMessage)val3).Content, val.Contents); } } else { val.AuthorName = val2.ParticipantName; OpenAIChatClient.ConvertContentParts(((ChatMessage)val2).Content, val.Contents); foreach (ChatToolCall toolCall in val2.ToolCalls) { FunctionCallContent val7 = OpenAIClientExtensions.ParseCallContent(toolCall.FunctionArguments, toolCall.Id, toolCall.FunctionName); ((AIContent)val7).RawRepresentation = toolCall; val.Contents.Add((AIContent)(object)val7); } } yield return val; } static object ToToolResult(ChatMessageContent content) { if (((Collection<ChatMessageContentPart>)(object)content).Count == 1) { ChatMessageContentPart val8 = ((Collection<ChatMessageContentPart>)(object)content)[0]; if (val8 != null) { string text = val8.Text; if (text != null) { return text; } } } MemoryStream memoryStream = new MemoryStream(); using Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(memoryStream, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); foreach (ChatMessageContentPart item in (Collection<ChatMessageContentPart>)(object)content) { ((IJsonModel<ChatMessageContentPart>)(object)item).Write(utf8JsonWriter, ModelReaderWriterOptions.Json); } return JsonSerializer.Deserialize((ReadOnlySpan<byte>)memoryStream.GetBuffer().AsSpan(0, (int)memoryStream.Position), AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement))); } } public static ChatResponse AsChatResponse(this ChatCompletion chatCompletion, ChatCompletionOptions? options = null) { return OpenAIChatClient.FromOpenAIChatCompletion(Throw.IfNull<ChatCompletion>(chatCompletion, "chatCompletion"), options); } public static IAsyncEnumerable<ChatResponseUpdate> AsChatResponseUpdatesAsync(this IAsyncEnumerable<StreamingChatCompletionUpdate> chatCompletionUpdates, ChatCompletionOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return OpenAIChatClient.FromOpenAIStreamingChatCompletionAsync(Throw.IfNull(chatCompletionUpdates, "chatCompletionUpdates"), options, cancellationToken); } private static ChatMessageRole ToChatMessageRole(ChatRole? role) { //IL_000e: 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_0060: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) object obj; if (!role.HasValue) { obj = null; } else { ChatRole valueOrDefault = role.GetValueOrDefault(); obj = ((ChatRole)(ref valueOrDefault)).Value; } return (ChatMessageRole)((string)obj switch { "user" => 1, "function" => 4, "tool" => 3, "developer" => 5, "system" => 0, _ => 2, }); } private static ChatFinishReason ToChatFinishReason(ChatFinishReason? finishReason) { //IL_000e: 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_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) object obj; if (!finishReason.HasValue) { obj = null; } else { ChatFinishReason valueOrDefault = finishReason.GetValueOrDefault(); obj = ((ChatFinishReason)(ref valueOrDefault)).Value; } return (ChatFinishReason)((string)obj switch { "length" => 1, "content_filter" => 2, "tool_calls" => 3, "function_call" => 4, _ => 0, }); } } } namespace OpenAI.Assistants { public static class MicrosoftExtensionsAIAssistantsExtensions { public static FunctionToolDefinition AsOpenAIAssistantsFunctionToolDefinition(this AIFunctionDeclaration function) { return OpenAIAssistantsChatClient.ToOpenAIAssistantsFunctionToolDefinition(Throw.IfNull<AIFunctionDeclaration>(function, "function")); } } } namespace Microsoft.Extensions.AI { internal sealed class OpenAIAssistantsChatClient : IChatClient, IDisposable { private readonly AssistantClient _client; private readonly ChatClientMetadata _metadata; private readonly string _assistantId; private readonly string? _defaultThreadId; private IReadOnlyList<ToolDefinition>? _assistantTools; public OpenAIAssistantsChatClient(AssistantClient assistantClient, string assistantId, string? defaultThreadId) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown _client = Throw.IfNull<AssistantClient>(assistantClient, "assistantClient"); _assistantId = Throw.IfNullOrWhitespace(assistantId, "assistantId"); _defaultThreadId = defaultThreadId; _metadata = new ChatClientMetadata("openai", assistantClient.Endpoint, (string)null); } public OpenAIAssistantsChatClient(AssistantClient assistantClient, Assistant assistant, string? defaultThreadId) : this(assistantClient, Throw.IfNull<Assistant>(assistant, "assistant").Id, defaultThreadId) { _assistantTools = assistant.Tools; } public object? GetService(Type serviceType, object? serviceKey = null) { if ((object)serviceType != null) { if (serviceKey == null) { if (!(serviceType == typeof(ChatClientMetadata))) { if (!(serviceType == typeof(AssistantClient))) { if (!serviceType.IsInstanceOfType(this)) { return null; } return this; } return _client; } return _metadata; } return null; } throw new ArgumentNullException("serviceType"); } public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return ChatResponseExtensions.ToChatResponseAsync(GetStreamingResponseAsync(messages, options, cancellationToken), cancellationToken); } public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(messages, "messages"); (RunCreationOptions, ToolResources, List<FunctionResultContent>) tuple = await CreateRunOptionsAsync(messages, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); RunCreationOptions runOptions = tuple.Item1; ToolResources toolResources = tuple.Item2; List<FunctionResultContent> toolResults = tuple.Item3; string threadId = ((options != null) ? options.ConversationId : null) ?? _defaultThreadId; if (threadId == null && toolResults != null) { Throw.ArgumentException("messages", "No thread ID was provided, but chat messages includes tool results."); } ThreadRun threadRun = null; if (threadId != null) { { ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator enumerator = ((IAsyncEnumerable<ThreadRun>)_client.GetRunsAsync(threadId, new RunCollectionOptions { Order = RunCollectionOrder.Descending, PageSizeLimit = 1 }, cancellationToken)).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); try { if (await enumerator.MoveNextAsync()) { ThreadRun current = enumerator.Current; if (current.Status != RunStatus.Completed && current.Status != RunStatus.Cancelled && current.Status != RunStatus.Failed && current.Status != RunStatus.Expired) { threadRun = current; } } } finally { IAsyncDisposable asyncDisposable = enumerator as IAsyncDisposable; if (asyncDisposable != null) { await asyncDisposable.DisposeAsync(); } } } } IAsyncEnumerable<StreamingUpdate> source; if (threadRun != null) { List<ToolOutput> toolOutputs; string text = ConvertFunctionResultsToToolOutput(toolResults, out toolOutputs); if (text != null && text == threadRun.Id) { source = (IAsyncEnumerable<StreamingUpdate>)_client.SubmitToolOutputsToRunStreamingAsync(threadRun.ThreadId, threadRun.Id, (IEnumerable<ToolOutput>)toolOutputs, cancellationToken); goto IL_05b5; } } if (threadId == null) { ThreadCreationOptions val = new ThreadCreationOptions { ToolResources = toolResources }; foreach (ThreadInitializationMessage additionalMessage in runOptions.AdditionalMessages) { val.InitialMessages.Add(additionalMessage); } runOptions.AdditionalMessages.Clear(); threadId = (await _client.CreateThreadAsync(val, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Value.Id; } else if (threadRun != null) { await _client.CancelRunAsync(threadId, threadRun.Id, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } source = (IAsyncEnumerable<StreamingUpdate>)_client.CreateRunStreamingAsync(threadId, _assistantId, runOptions, cancellationToken); goto IL_05b5; IL_05b5: string responseId = null; await foreach (StreamingUpdate item in source.ConfigureAwait(continueOnCapturedContext: false)) { ThreadUpdate val2 = (ThreadUpdate)(object)((item is ThreadUpdate) ? item : null); if (val2 == null) { RunUpdate val3 = (RunUpdate)(object)((item is RunUpdate) ? item : null); if (val3 != null) { if (threadId == null) { threadId = ((StreamingUpdate<ThreadRun>)(object)val3).Value.ThreadId; } if (responseId == null) { responseId = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Id; } ChatResponseUpdate val4 = new ChatResponseUpdate { AuthorName = _assistantId, ConversationId = threadId, CreatedAt = ((StreamingUpdate<ThreadRun>)(object)val3).Value.CreatedAt, MessageId = responseId, ModelId = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Model, RawRepresentation = val3, ResponseId = responseId, Role = ChatRole.Assistant }; RunTokenUsage usage = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Usage; if (usage != null) { val4.Contents.Add((AIContent)new UsageContent(new UsageDetails { InputTokenCount = usage.InputTokenCount, OutputTokenCount = usage.OutputTokenCount, TotalTokenCount = usage.TotalTokenCount })); } RequiredActionUpdate val5 = (RequiredActionUpdate)(object)((val3 is RequiredActionUpdate) ? val3 : null); if (val5 != null) { string toolCallId = val5.ToolCallId; if (toolCallId != null) { string functionName = val5.FunctionName; if (functionName != null) { FunctionCallContent val6 = OpenAIClientExtensions.ParseCallContent(val5.FunctionArguments, JsonSerializer.Serialize(new string[2] { ((StreamingUpdate<ThreadRun>)(object)val3).Value.Id, toolCallId }, OpenAIJsonContext.Default.StringArray), functionName); ((AIContent)val6).RawRepresentation = val3; val4.Contents.Add((AIContent)(object)val6); } } } yield return val4; continue; } MessageContentUpdate val7 = (MessageContentUpdate)(object)((item is MessageContentUpdate) ? item : null); if (val7 != null) { ChatResponseUpdate val8 = new ChatResponseUpdate((ChatRole?)((val7.Role == (MessageRole?)0) ? ChatRole.User : ChatRole.Assistant), val7.Text) { AuthorName = _assistantId, ConversationId = threadId, MessageId = responseId, RawRepresentation = val7, ResponseId = responseId }; TextAnnotationUpdate textAnnotation = val7.TextAnnotation; if (textAnnotation != null) { string text2 = null; string toolName = null; if (!string.IsNullOrWhiteSpace(textAnnotation.InputFileId)) { text2 = textAnnotation.InputFileId; toolName = "file_search"; } else if (!string.IsNullOrWhiteSpace(textAnnotation.OutputFileId)) { text2 = textAnnotation.OutputFileId; toolName = "code_interpreter"; } if (text2 != null) { if (val8.Contents.Count == 0) { val8.Contents.Add((AIContent)new TextContent(string.Empty)); } TextContent val9 = (TextContent)val8.Contents[0]; (((AIContent)val9).Annotations ?? (((AIContent)val9).Annotations = new List<AIAnnotation>())).Add((AIAnnotation)new CitationAnnotation { RawRepresentation = textAnnotation, AnnotatedRegions = new List<AnnotatedRegion>(1) { (AnnotatedRegion)new TextSpanAnnotatedRegion { StartIndex = textAnnotation.StartIndex, EndIndex = textAnnotation.EndIndex } }, FileId = text2, ToolName = toolName }); } } yield return val8; continue; } } else if (threadId == null) { threadId = ((StreamingUpdate<AssistantThread>)(object)val2).Value.Id; } yield return new ChatResponseUpdate { AuthorName = _assistantId, ConversationId = threadId, MessageId = responseId, RawRepresentation = item, ResponseId = responseId, Role = ChatRole.Assistant }; } } void IDisposable.Dispose() { } internal static FunctionToolDefinition ToOpenAIAssistantsFunctionToolDefinition(AIFunctionDeclaration aiFunction, ChatOptions? options = null) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown bool? flag = OpenAIClientExtensions.HasStrict(((AITool)aiFunction).AdditionalProperties) ?? OpenAIClientExtensions.HasStrict((IReadOnlyDictionary<string, object?>?)((options != null) ? options.AdditionalProperties : null)); return new FunctionToolDefinition(((AITool)aiFunction).Name) { Description = ((AITool)aiFunction).Description, Parameters = OpenAIClientExtensions.ToOpenAIFunctionParameters(aiFunction, flag), StrictParameterSchemaEnabled = flag }; } private async ValueTask<(RunCreationOptions RunOptions, ToolResources? Resources, List<FunctionResultContent>? ToolResults)> CreateRunOptionsAsync(IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken) { object obj = ((options == null) ? null : options.RawRepresentationFactory?.Invoke((IChatClient)(object)this)); RunCreationOptions runOptions = (RunCreationOptions)(((obj is RunCreationOptions) ? obj : null) ?? ((object)new RunCreationOptions())); ToolResources resources = null; if (options != null) { RunCreationOptions val = runOptions; if (!val.MaxOutputTokenCount.HasValue) { val.MaxOutputTokenCount = options.MaxOutputTokens; } val = runOptions; if (val.ModelOverride == null) { val.ModelOverride = options.ModelId; } val = runOptions; if (!val.NucleusSamplingFactor.HasValue) { val.NucleusSamplingFactor = options.TopP; } val = runOptions; if (!val.Temperature.HasValue) { val.Temperature = options.Temperature; } val = runOptions; if (!val.AllowParallelToolCalls.HasValue) { val.AllowParallelToolCalls = options.AllowMultipleToolCalls; } IList<AITool> tools = options.Tools; if (tools != null && tools.Count > 0) { if (runOptions.ToolsOverride.Count == 0) { if (_assistantTools == null) { _assistantTools = (await _client.GetAssistantAsync(_assistantId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Value.Tools; } foreach (ToolDefinition assistantTool in _assistantTools) { runOptions.ToolsOverride.Add(assistantTool); } } foreach (AITool item2 in tools) { AIFunctionDeclaration val2 = (AIFunctionDeclaration)(object)((item2 is AIFunctionDeclaration) ? item2 : null); if (val2 == null) { HostedCodeInterpreterTool val3 = (HostedCodeInterpreterTool)(object)((item2 is HostedCodeInterpreterTool) ? item2 : null); if (val3 == null) { HostedFileSearchTool val4 = (HostedFileSearchTool)(object)((item2 is HostedFileSearchTool) ? item2 : null); if (val4 == null) { continue; } runOptions.ToolsOverride.Add((ToolDefinition)(object)ToolDefinition.CreateFileSearch(val4.MaximumResultCount)); IList<AIContent> inputs = val4.Inputs; if (inputs == null || inputs.Count <= 0) { continue; } foreach (AIContent item3 in inputs) { HostedVectorStoreContent val5 = (HostedVectorStoreContent)(object)((item3 is HostedVectorStoreContent) ? item3 : null); if (val5 != null) { ToolResources obj2 = resources; if (obj2 == null) { ToolResources val6 = new ToolResources(); ToolResources val7 = val6; resources = val6; obj2 = val7; } ToolResources val8 = obj2; if (val8.FileSearch == null) { val8.FileSearch = new FileSearchToolResources(); } resources.FileSearch.VectorStoreIds.Add(val5.VectorStoreId); } } continue; } CodeInterpreterToolDefinition item = ToolDefinition.CreateCodeInterpreter(); runOptions.ToolsOverride.Add((ToolDefinition)(object)item); int? num = val3.Inputs?.Count; if (!num.HasValue || num.GetValueOrDefault() <= 0) { continue; } ThreadInitializationMessage val9 = null; foreach (AIContent input in val3.Inputs) { HostedFileContent val10 = (HostedFileContent)(object)((input is HostedFileContent) ? input : null); if (val10 != null) { if (val9 == null) { val9 = new ThreadInitializationMessage((MessageRole)0, (IEnumerable<MessageContent>)new <>z__ReadOnlySingleElementList<MessageContent>(MessageContent.FromText("attachments"))); } ((MessageCreationOptions)val9).Attachments.Add(new MessageCreationAttachment(val10.FileId, (IEnumerable<ToolDefinition>)new <>z__ReadOnlySingleElementList<ToolDefinition>((ToolDefinition)(object)item))); } } if (val9 != null) { runOptions.AdditionalMessages.Add(val9); } } else { runOptions.ToolsOverride.Add((ToolDefinition)(object)ToOpenAIAssistantsFunctionToolDefinition(val2, options)); } } } if (runOptions.ToolConstraint == null) { ChatToolMode toolMode = options.ToolMode; if (!(toolMode is NoneChatToolMode)) { if (!(toolMode is AutoChatToolMode)) { RequiredChatToolMode val11 = (RequiredChatToolMode)(object)((toolMode is RequiredChatToolMode) ? toolMode : null); if (val11 != null) { string requiredFunctionName = val11.RequiredFunctionName; if (requiredFunctionName != null) { runOptions.ToolConstraint = new ToolConstraint((ToolDefinition)(object)ToolDefinition.CreateFunction(requiredFunctionName, (string)null, (BinaryData)null, (bool?)null)); } else { runOptions.ToolConstraint = ToolConstraint.Required; } } } else { runOptions.ToolConstraint = ToolConstraint.Auto; } } else { runOptions.ToolConstraint = ToolConstraint.None; } } if (runOptions.ResponseFormat == null) { ChatResponseFormat responseFormat = options.ResponseFormat; if (!(responseFormat is ChatResponseFormatText)) { ChatResponseFormatJson val12 = (ChatResponseFormatJson)(object)((responseFormat is ChatResponseFormatJson) ? responseFormat : null); if (val12 != null) { JsonElement? orCreateTransformedSchema = OpenAIClientExtensions.StrictSchemaTransformCache.GetOrCreateTransformedSchema(val12); if (orCreateTransformedSchema.HasValue) { JsonElement valueOrDefault = orCreateTransformedSchema.GetValueOrDefault(); runOptions.ResponseFormat = AssistantResponseFormat.CreateJsonSchemaFormat(val12.SchemaName, BinaryData.FromBytes(JsonSerializer.SerializeToUtf8Bytes(valueOrDefault, OpenAIJsonContext.Default.JsonElement)), val12.SchemaDescription, OpenAIClientExtensions.HasStrict((IReadOnlyDictionary<string, object?>?)options.AdditionalProperties)); } else { runOptions.ResponseFormat = AssistantResponseFormat.CreateJsonObjectFormat(); } } } else { runOptions.ResponseFormat = AssistantResponseFormat.CreateTextFormat(); } } } StringBuilder instructions = null; AppendSystemInstructions(runOptions.AdditionalInstructions); AppendSystemInstructions((options != null) ? options.Instructions : null); List<FunctionResultContent> list = null; foreach (ChatMessage message in messages) { List<MessageContent> list2 = new List<MessageContent>(); if (message.Role == ChatRole.System || message.Role == OpenAIClientExtensions.ChatRoleDeveloper) { foreach (TextContent item4 in message.Contents.OfType<TextContent>()) { AppendSystemInstructions(item4.Text); } continue; } foreach (AIContent content in message.Contents) { AIContent val13 = content; if (val13 == null) { continue; } object rawRepresentation = content.RawRepresentation; MessageContent val14 = (MessageContent)((rawRepresentation is MessageContent) ? rawRepresentation : null); if (val14 == null) { TextContent val15 = (TextContent)(object)((val13 is TextContent) ? val13 : null); if (val15 == null) { UriContent val16 = (UriContent)(object)((val13 is UriContent) ? val13 : null); if (val16 == null) { FunctionResultContent val17 = (FunctionResultContent)(object)((val13 is FunctionResultContent) ? val13 : null); if (val17 != null) { (list ?? (list = new List<FunctionResultContent>())).Add(val17); } } else if (val16.HasTopLevelMediaType("image")) { list2.Add(MessageContent.FromImageUri(val16.Uri, (MessageImageDetail?)null)); } } else { list2.Add(MessageContent.FromText(val15.Text)); } } else { list2.Add(val14); } } if (list2.Count > 0) { runOptions.AdditionalMessages.Add(new ThreadInitializationMessage((MessageRole)((message.Role == ChatRole.Assistant) ? 1 : 0), (IEnumerable<MessageContent>)list2)); } } runOptions.AdditionalInstructions = instructions?.ToString(); return (runOptions, resources, list); void AppendSystemInstructions(string? toAppend) { if (!string.IsNullOrEmpty(toAppend)) { if (instructions == null) { instructions = new StringBuilder(toAppend); } else { instructions.AppendLine().AppendLine(toAppend); } } } } private static string? ConvertFunctionResultsToToolOutput(List<FunctionResultContent>? toolResults, out List<ToolOutput>? toolOutputs) { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown string text = null; toolOutputs = null; if (toolResults != null && toolResults.Count > 0) { foreach (FunctionResultContent toolResult in toolResults) { string[] array; try { array = JsonSerializer.Deserialize(toolResult.CallId, OpenAIJsonContext.Default.StringArray); } catch { continue; } if (array != null && array.Length == 2 && !string.IsNullOrWhiteSpace(array[0]) && !string.IsNullOrWhiteSpace(array[1]) && (text == null || !(text != array[0]))) { text = array[0]; (toolOutputs ?? (toolOutputs = new List<ToolOutput>())).Add(new ToolOutput(array[1], toolResult.Result?.ToString() ?? string.Empty)); } } } return text; } } internal sealed class OpenAIChatClient : IChatClient, IDisposable { private sealed class FunctionCallInfo { public string? CallId; public string? Name; public StringBuilder? Arguments; } private static readonly Func<ChatClient, IEnumerable<ChatMessage>, ChatCompletionOptions, RequestOptions, Task<ClientResult<ChatCompletion>>>? _completeChatAsync = (Func<ChatClient, IEnumerable<ChatMessage>, ChatCompletionOptions, RequestOptions, Task<ClientResult<ChatCompletion>>>)(typeof(ChatClient).GetMethod("CompleteChatAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { typeof(IEnumerable<ChatMessage>), typeof(ChatCompletionOptions), typeof(RequestOptions) }, null)?.CreateDelegate(typeof(Func<ChatClient, IEnumerable<ChatMessage>, ChatCompletionOptions, RequestOptions, Task<ClientResult<ChatCompletion>>>))); private static readonly Func<ChatClient, IEnumerable<ChatMessage>, ChatCompletionOptions, RequestOptions, AsyncCollectionResult<StreamingChatCompletionUpdate>>? _completeChatStreamingAsync = (Func<ChatClient, IEnumerable<ChatMessage>, ChatCompletionOptions, RequestOptions, AsyncCollectionResult<StreamingChatCompletionUpdate>>)(typeof(ChatClient).GetMethod("CompleteChatStreamingAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { typeof(IEnumerable<ChatMessage>), typeof(ChatCompletionOptions), typeof(RequestOptions) }, null)?.CreateDelegate(typeof(Func<ChatClient, IEnumerable<ChatMessage>, ChatCompletionOptions, RequestOptions, AsyncCollectionResult<StreamingChatCompletionUpdate>>))); private readonly ChatClientMetadata _metadata; private readonly ChatClient _chatClient; private const string InvalidAuthorNamePattern = "[^a-zA-Z0-9_]+"; private static readonly Regex _invalidAuthorNameRegex = new Regex("[^a-zA-Z0-9_]+", RegexOptions.Compiled); public OpenAIChatClient(ChatClient chatClient) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown _chatClient = Throw.IfNull<ChatClient>(chatClient, "chatClient"); _metadata = new ChatClientMetadata("openai", chatClient.Endpoint, _chatClient.Model); } object? IChatClient.GetService(Type serviceType, object? serviceKey) { Throw.IfNull(serviceType, "serviceType"); if (serviceKey == null) { if (!(serviceType == typeof(ChatClientMetadata))) { if (!(serviceType == typeof(ChatClient))) { if (!serviceType.IsInstanceOfType(this)) { return null; } return this; } return _chatClient; } return _metadata; } return null; } public async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(messages, "messages"); IEnumerable<ChatMessage> enumerable = ToOpenAIChatMessages(messages, options); ChatCompletionOptions openAIOptions = ToOpenAIOptions(options); Task<ClientResult<ChatCompletion>> task = ((_completeChatAsync != null) ? _completeChatAsync(_chatClient, enumerable, openAIOptions, cancellationToken.ToRequestOptions(streaming: false)) : _chatClient.CompleteChatAsync(enumerable, openAIOptions, cancellationToken)); return FromOpenAIChatCompletion((await task.ConfigureAwait(continueOnCapturedContext: false)).Value, openAIOptions); } public IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull(messages, "messages"); IEnumerable<ChatMessage> enumerable = ToOpenAIChatMessages(messages, options); ChatCompletionOptions val = ToOpenAIOptions(options); AsyncCollectionResult<StreamingChatCompletionUpdate> updates = ((_completeChatStreamingAsync != null) ? _completeChatStreamingAsync(_chatClient, enumerable, val, cancellationToken.ToRequestOptions(streaming: true)) : _chatClient.CompleteChatStreamingAsync(enumerable, val, cancellationToken)); return FromOpenAIStreamingChatCompletionAsync((IAsyncEnumerable<StreamingChatCompletionUpdate>)updates, val, cancellationToken); } void IDisposable.Dispose() { } internal static ChatTool ToOpenAIChatTool(AIFunctionDeclaration aiFunction, ChatOptions? options = null) { bool? flag = OpenAIClientExtensions.HasStrict(((AITool)aiFunction).AdditionalProperties) ?? OpenAIClientExtensions.HasStrict((IReadOnlyDictionary<string, object?>?)((options != null) ? options.AdditionalProperties : null)); return ChatTool.CreateFunctionTool(((AITool)aiFunction).Name, ((AITool)aiFunction).Description, OpenAIClientExtensions.ToOpenAIFunctionParameters(aiFunction, flag), flag); } internal static IEnumerable<ChatMessage> ToOpenAIChatMessages(IEnumerable<ChatMessage> inputs, ChatOptions? chatOptions) { string text = ((chatOptions != null) ? chatOptions.Instructions : null); if (text != null && !string.IsNullOrWhiteSpace(text)) { yield return (ChatMessage)new SystemChatMessage(text); } foreach (ChatMessage input in inputs) { object rawRepresentation = input.RawRepresentation; ChatMessage val = (ChatMessage)((rawRepresentation is ChatMessage) ? rawRepresentation : null); if (val != null) { yield return val; } else if (input.Role == ChatRole.System || input.Role == ChatRole.User || input.Role == OpenAIClientExtensions.ChatRoleDeveloper) { List<ChatMessageContentPart> list = ToOpenAIChatContent(input.Contents); string participantName = SanitizeAuthorName(input.AuthorName); yield return (ChatMessage)((input.Role == ChatRole.System) ? new SystemChatMessage((IEnumerable<ChatMessageContentPart>)list) { ParticipantName = participantName } : ((input.Role == OpenAIClientExtensions.ChatRoleDeveloper) ? new DeveloperChatMessage((IEnumerable<ChatMessageContentPart>)list) { ParticipantName = participantName } : new UserChatMessage((IEnumerable<ChatMessageContentPart>)list) { ParticipantName = participantName })); } else if (input.Role == ChatRole.Tool) { foreach (AIContent content in input.Contents) { FunctionResultContent val2 = (FunctionResultContent)(object)((content is FunctionResultContent) ? content : null); if (val2 == null) { continue; } string text2 = val2.Result as string; if (text2 == null && val2.Result != null) { try { text2 = JsonSerializer.Serialize(val2.Result, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(object))); } catch (NotSupportedException) { } } yield return (ChatMessage)new ToolChatMessage(val2.CallId, text2 ?? string.Empty); } } else { if (!(input.Role == ChatRole.Assistant)) { continue; } List<ChatMessageContentPart> list2 = null; List<ChatToolCall> list3 = null; string refusal = null; foreach (AIContent content2 in input.Contents) { AIContent val3 = content2; ErrorContent val4 = (ErrorContent)(object)((val3 is ErrorContent) ? val3 : null); if (val4 == null) { FunctionCallContent val5 = (FunctionCallContent)(object)((val3 is FunctionCallContent) ? val3 : null); if (val5 != null) { (list3 ?? (list3 = new List<ChatToolCall>())).Add(ChatToolCall.CreateFunctionToolCall(val5.CallId, val5.Name, new BinaryData(JsonSerializer.SerializeToUtf8Bytes((object)val5.Arguments, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(IDictionary<string, object>)))))); continue; } } else if (val4.ErrorCode == "Refusal") { refusal = val4.Message; continue; } ChatMessageContentPart val6 = ToChatMessageContentPart(content2); if (val6 != null) { (list2 ?? (list2 = new List<ChatMessageContentPart>())).Add(val6); } } AssistantChatMessage val7; if (list2 != null) { val7 = new AssistantChatMessage((IEnumerable<ChatMessageContentPart>)list2); if (list3 != null) { foreach (ChatToolCall item in list3) { val7.ToolCalls.Add(item); } } } else { val7 = ((list3 != null) ? new AssistantChatMessage((IEnumerable<ChatToolCall>)list3) : new AssistantChatMessage((ChatMessageContentPart[])(object)new ChatMessageContentPart[1] { ChatMessageContentPart.CreateTextPart(string.Empty) })); } val7.ParticipantName = SanitizeAuthorName(input.AuthorName); val7.Refusal = refusal; yield return (ChatMessage)(object)val7; } } } internal static List<ChatMessageContentPart> ToOpenAIChatContent(IEnumerable<AIContent> contents) { List<ChatMessageContentPart> list = new List<ChatMessageContentPart>(); foreach (AIContent content in contents) { object rawRepresentation = content.RawRepresentation; ChatMessageContentPart val = (ChatMessageContentPart)((rawRepresentation is ChatMessageContentPart) ? rawRepresentation : null); if (val != null) { list.Add(val); continue; } ChatMessageContentPart val2 = ToChatMessageContentPart(content); if (val2 != null) { list.Add(val2); } } if (list.Count == 0) { list.Add(ChatMessageContentPart.CreateTextPart(string.Empty)); } return list; } private static ChatMessageContentPart? ToChatMessageContentPart(AIContent content) { //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) if (content != null) { object rawRepresentation = content.RawRepresentation; ChatMessageContentPart val = (ChatMessageContentPart)((rawRepresentation is ChatMessageContentPart) ? rawRepresentation : null); if (val != null) { return val; } TextContent val2 = (TextContent)(object)((content is TextContent) ? content : null); if (val2 != null) { return ChatMessageContentPart.CreateTextPart(val2.Text); } UriContent val3 = (UriContent)(object)((content is UriContent) ? content : null); if (val3 == null) { DataContent val4 = (DataContent)(object)((content is DataContent) ? content : null); if (val4 == null) { HostedFileContent val5 = (HostedFileContent)(object)((content is HostedFileContent) ? content : null); if (val5 != null) { return ChatMessageContentPart.CreateFilePart(val5.FileId); } } else { if (val4.HasTopLevelMediaType("image")) { return ChatMessageContentPart.CreateImagePart(BinaryData.FromBytes(val4.Data), val4.MediaType, GetImageDetail(content)); } DataContent val6 = val4; if (val6.HasTopLevelMediaType("audio")) { BinaryData val7 = BinaryData.FromBytes(val6.Data); if (val6.MediaType.Equals("audio/mpeg", StringComparison.OrdinalIgnoreCase)) { return ChatMessageContentPart.CreateInputAudioPart(val7, ChatInputAudioFormat.Mp3); } if (val6.MediaType.Equals("audio/wav", StringComparison.OrdinalIgnoreCase)) { return ChatMessageContentPart.CreateInputAudioPart(val7, ChatInputAudioFormat.Wav); } } else { DataContent val8 = val4; if (val8.MediaType.StartsWith("application/pdf", StringComparison.OrdinalIgnoreCase)) { return ChatMessageContentPart.CreateFilePart(BinaryData.FromBytes(val8.Data), val8.MediaType, val8.Name ?? $"{Guid.NewGuid():N}.pdf"); } } } } else if (val3.HasTopLevelMediaType("image")) { return ChatMessageContentPart.CreateImagePart(val3.Uri, GetImageDetail(content)); } } return null; } private static ChatImageDetailLevel? GetImageDetail(AIContent content) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) object obj = default(object); if (((AdditionalPropertiesDictionary<object>)(object)content.AdditionalProperties)?.TryGetValue("detail", ref obj) ?? false) { return (ChatImageDetailLevel)((obj is string text) ? new ChatImageDetailLevel(text) : ((!(obj is ChatImageDetailLevel val)) ? ChatImageDetailLevel.op_Implicit((string)null) : val)); } return null; } internal static async IAsyncEnumerable<ChatResponseUpdate> FromOpenAIStreamingChatCompletionAsync(IAsyncEnumerable<StreamingChatCompletionUpdate> updates, ChatCompletionOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken) { Dictionary<int, FunctionCallInfo> functionCallInfos = null; ChatRole? streamedRole = null; ChatFinishReason? finishReason = null; StringBuilder refusal = null; string responseId = null; DateTimeOffset? createdAt = null; string modelId = null; await foreach (StreamingChatCompletionUpdate item2 in updates.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { ChatRole? val = streamedRole; if (!val.HasValue) { ChatMessageRole? role = item2.Role; ChatRole? obj; if (role.HasValue) { ChatMessageRole valueOrDefault = role.GetValueOrDefault(); obj = FromOpenAIChatRole(valueOrDefault); } else { obj = null; } streamedRole = obj; } ChatFinishReason? val2 = finishReason; if (!val2.HasValue) { ChatFinishReason? finishReason2 = item2.FinishReason; ChatFinishReason? obj2; if (finishReason2.HasValue) { ChatFinishReason valueOrDefault2 = finishReason2.GetValueOrDefault(); obj2 = FromOpenAIFinishReason(valueOrDefault2); } else { obj2 = null; } finishReason = obj2; } if (responseId == null) { responseId = item2.CompletionId; } createdAt.GetValueOrDefault(); if (!createdAt.HasValue) { DateTimeOffset createdAt2 = item2.CreatedAt; createdAt = createdAt2; } if (modelId == null) { modelId = item2.Model; } ChatResponseUpdate val3 = new ChatResponseUpdate { ResponseId = item2.CompletionId, MessageId = item2.CompletionId, CreatedAt = item2.CreatedAt, FinishReason = finishReason, ModelId = modelId, RawRepresentation = item2, Role = streamedRole }; ChatMessageContent contentUpdate = item2.ContentUpdate; if (contentUpdate != null && ((Collection<ChatMessageContentPart>)(object)contentUpdate).Count > 0) { ConvertContentParts(item2.ContentUpdate, val3.Contents); } StreamingChatOutputAudioUpdate outputAudioUpdate = item2.OutputAudioUpdate; if (outputAudioUpdate != null) { val3.Contents.Add((AIContent)new DataContent(outputAudioUpdate.AudioBytesUpdate.ToMemory(), GetOutputAudioMimeType(options)) { RawRepresentation = outputAudioUpdate }); } if (item2.RefusalUpdate != null) { StringBuilder stringBuilder = refusal; if (stringBuilder == null) { StringBuilder stringBuilder2; refusal = (stringBuilder2 = new StringBuilder()); stringBuilder = stringBuilder2; } stringBuilder.Append(item2.RefusalUpdate); } IReadOnlyList<StreamingChatToolCallUpdate> toolCallUpdates = item2.ToolCallUpdates; if (toolCallUpdates != null && toolCallUpdates.Count > 0) { foreach (StreamingChatToolCallUpdate item3 in toolCallUpdates) { if (functionCallInfos == null) { functionCallInfos = new Dictionary<int, FunctionCallInfo>(); } if (!functionCallInfos.TryGetValue(item3.Index, out FunctionCallInfo value)) { value = (functionCallInfos[item3.Index] = new FunctionCallInfo()); } FunctionCallInfo functionCallInfo2 = value; if (functionCallInfo2.CallId == null) { functionCallInfo2.CallId = item3.ToolCallId; } functionCallInfo2 = value; if (functionCallInfo2.Name == null) { functionCallInfo2.Name = item3.FunctionName; } BinaryData functionArgumentsUpdate = item3.FunctionArgumentsUpdate; if (functionArgumentsUpdate != null && !functionArgumentsUpdate.ToMemory().IsEmpty) { functionCallInfo2 = value; (functionCallInfo2.Arguments ?? (functionCallInfo2.Arguments = new StringBuilder())).Append(((object)functionArgumentsUpdate).ToString()); } } } ChatTokenUsage usage = item2.Usage; if (usage != null) { val3.Contents.Add((AIContent)new UsageContent(FromOpenAIUsage(usage)) { RawRepresentation = usage }); } yield return val3; } if (functionCallInfos == null) { yield break; } ChatResponseUpdate val4 = new ChatResponseUpdate { ResponseId = responseId, MessageId = responseId, CreatedAt = createdAt, FinishReason = finishReason, ModelId = modelId, Role = streamedRole }; foreach (KeyValuePair<int, FunctionCallInfo> item4 in functionCallInfos) { FunctionCallInfo value2 = item4.Value; if (!string.IsNullOrWhiteSpace(value2.Name)) { FunctionCallContent item = OpenAIClientExtensions.ParseCallContent(value2.Arguments?.ToString() ?? string.Empty, value2.CallId, value2.Name); val4.Contents.Add((AIContent)(object)item); } } if (refusal != null) { val4.Contents.Add((AIContent)new ErrorContent(refusal.ToString()) { ErrorCode = "Refusal" }); } yield return val4; } private static string GetOutputAudioMimeType(ChatCompletionOptions? options) { //IL_0013: 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) object obj; if (options == null) { obj = null; } else { ChatAudioOptions audioOptions = options.AudioOptions; if (audioOptions == null) { obj = null; } else { ChatOutputAudioFormat outputAudioFormat = audioOptions.OutputAudioFormat; obj = ((object)(ChatOutputAudioFormat)(ref outputAudioFormat)).ToString()?.ToLowerInvariant(); } } return (string)obj switch { "opus" => "audio/opus", "aac" => "audio/aac", "flac" => "audio/flac", "wav" => "audio/wav", "pcm" => "audio/pcm", _ => "audio/mpeg", }; } internal static ChatResponse FromOpenAIChatCompletion(ChatCompletion openAICompletion, ChatCompletionOptions? chatCompletionOptions) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Expected O, but got Unknown //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Expected O, but got Unknown //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Expected O, but got Unknown //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01de: 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_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Expected O, but got Unknown //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Expected O, but got Unknown Throw.IfNull<ChatCompletion>(openAICompletion, "openAICompletion"); ChatMessage val = new ChatMessage { CreatedAt = openAICompletion.CreatedAt, MessageId = openAICompletion.Id, RawRepresentation = openAICompletion, Role = FromOpenAIChatRole(openAICompletion.Role) }; foreach (ChatMessageContentPart item in (Collection<ChatMessageContentPart>)(object)openAICompletion.Content) { AIContent val2 = ToAIContent(item); if (val2 != null) { val.Contents.Add(val2); } } ChatOutputAudio outputAudio = openAICompletion.OutputAudio; if (outputAudio != null) { val.Contents.Add((AIContent)new DataContent(outputAudio.AudioBytes.ToMemory(), GetOutputAudioMimeType(chatCompletionOptions)) { RawRepresentation = outputAudio }); } foreach (ChatToolCall toolCall in openAICompletion.ToolCalls) { if (!string.IsNullOrWhiteSpace(toolCall.FunctionName)) { FunctionCallContent val3 = OpenAIClientExtensions.ParseCallContent(toolCall.FunctionArguments, toolCall.Id, toolCall.FunctionName); ((AIContent)val3).RawRepresentation = toolCall; val.Contents.Add((AIContent)(object)val3); } } string refusal = openAICompletion.Refusal; if (refusal != null) { val.Contents.Add((AIContent)new ErrorContent(refusal) { ErrorCode = "Refusal" }); } IReadOnlyList<ChatMessageAnnotation> annotations = openAICompletion.Annotations; if (annotations != null && annotations.Count > 0) { TextContent val4 = val.Contents.OfType<TextContent>().FirstOrDefault(); if (val4 == null) { val4 = new TextContent((string)null); val.Contents.Add((AIContent)(object)val4); } foreach (ChatMessageAnnotation annotation in openAICompletion.Annotations) { TextContent val5 = val4; (((AIContent)val5).Annotations ?? (((AIContent)val5).Annotations = new List<AIAnnotation>())).Add((AIAnnotation)new CitationAnnotation { RawRepresentation = annotation, AnnotatedRegions = new List<AnnotatedRegion>(1) { (AnnotatedRegion)new TextSpanAnnotatedRegion { StartIndex = annotation.StartIndex, EndIndex = annotation.EndIndex } }, Title = annotation.WebResourceTitle, Url = annotation.WebResourceUri }); } } ChatResponse val6 = new ChatResponse(val) { CreatedAt = openAICompletion.CreatedAt, FinishReason = FromOpenAIFinishReason(openAICompletion.FinishReason), ModelId = openAICompletion.Model, RawRepresentation = openAICompletion, ResponseId = openAICompletion.Id }; ChatTokenUsage usage = openAICompletion.Usage; if (usage != null) { val6.Usage = FromOpenAIUsage(usage); } return val6; } private ChatCompletionOptions ToOpenAIOptions(ChatOptions? options) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown if (options == null) { return new ChatCompletionOptions(); } object obj = options.RawRepresentationFactory?.Invoke((IChatClient)(object)this); ChatCompletionOptions val = (ChatCompletionOptions)((obj is ChatCompletionOptions) ? obj : null); if (val == null) { val = new ChatCompletionOptions(); } ChatCompletionOptions val2 = val; if (!val2.FrequencyPenalty.HasValue) { float? num = (val2.FrequencyPenalty = options.FrequencyPenalty); } val2 = val; if (!val2.MaxOutputTokenCount.HasValue) { int? num2 = (val2.MaxOutputTokenCount = options.MaxOutputTokens); } val2 = val; if (!val2.TopP.HasValue) { float? num = (val2.TopP = options.TopP); } val2 = val; if (!val2.PresencePenalty.HasValue) { float? num = (val2.PresencePenalty = options.PresencePenalty); } val2 = val; if (!val2.Temperature.HasValue) { float? num = (val2.Temperature = options.Temperature); } val2 = val; if (!val2.Seed.HasValue) { long? num3 = (val2.Seed = options.Seed); } IList<string> stopSequences = options.StopSequences; if (stopSequences != null && stopSequences.Count > 0) { foreach (string item in stopSequences) { val.StopSequences.Add(item); } } IList<AITool> tools = options.Tools; if (tools != null && tools.Count > 0) { foreach (AITool item2 in tools) { AIFunctionDeclaration val3 = (AIFunctionDeclaration)(object)((item2 is AIFunctionDeclaration) ? item2 : null); if (val3 != null) { val.Tools.Add(ToOpenAIChatTool(val3, options)); } } if (val.Tools.Count > 0) { val2 = val; if (!val2.AllowParallelToolCalls.HasValue) { bool? flag = (val2.AllowParallelToolCalls = options.AllowMultipleToolCalls); } } if (val.ToolChoice == null && val.Tools.Count > 0) { ChatToolMode toolMode = options.ToolMode; if (!(toolMode is NoneChatToolMode)) { if (!(toolMode is AutoChatToolMode) && toolMode != null) { RequiredChatToolMode val4 = (RequiredChatToolMode)(object)((toolMode is RequiredChatToolMode) ? toolMode : null); if (val4 != null) { val.ToolChoice = ((val4.RequiredFunctionName == null) ? ChatToolChoice.CreateRequiredChoice() : ChatToolChoice.CreateFunctionChoice(val4.RequiredFunctionName)); } } else { val.ToolChoice = ChatToolChoice.CreateAutoChoice(); } } else { val.ToolChoice = ChatToolChoice.CreateNoneChoice(); } } } val2 = val; if (val2.ResponseFormat == null) { ChatResponseFormat val6 = (val2.ResponseFormat = ToOpenAIChatResponseFormat(options.ResponseFormat, options)); } return val; } internal static ChatResponseFormat? ToOpenAIChatResponseFormat(ChatResponseFormat? format, ChatOptions? options) { if (!(format is ChatResponseFormatText)) { ChatResponseFormatJson val = (ChatResponseFormatJson)(object)((format is ChatResponseFormatJson) ? format : null); if (val != null) { JsonElement? orCreateTransformedSchema = OpenAIClientExtensions.StrictSchemaTransformCache.GetOrCreateTransformedSchema(val); if (orCreateTransformedSchema.HasValue) { JsonElement valueOrDefault = orCreateTransformedSchema.GetValueOrDefault(); return ChatResponseFormat.CreateJsonSchemaFormat(val.SchemaName ?? "json_schema", BinaryData.FromBytes(JsonSerializer.SerializeToUtf8Bytes(valueOrDefault, OpenAIJsonContext.Default.JsonElement)), val.SchemaDescription, OpenAIClientExtensions.HasStrict((IReadOnlyDictionary<string, object?>?)((options != null) ? options.AdditionalProperties : null))); } return ChatResponseFormat.CreateJsonObjectFormat(); } return null; } return ChatResponseFormat.CreateTextFormat(); } private static UsageDetails FromOpenAIUsage(ChatTokenUsage tokenUsage) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown UsageDetails val = new UsageDetails { InputTokenCount = tokenUsage.InputTokenCount, OutputTokenCount = tokenUsage.OutputTokenCount, TotalTokenCount = tokenUsage.TotalTokenCount, AdditionalCounts = new AdditionalPropertiesDictionary<long>() }; AdditionalPropertiesDictionary<long> additionalCounts = val.AdditionalCounts; ChatInputTokenUsageDetails inputTokenDetails = tokenUsage.InputTokenDetails; if (inputTokenDetails != null) { additionalCounts.Add("InputTokenDetails.AudioTokenCount", (long)inputTokenDetails.AudioTokenCount); additionalCounts.Add("InputTokenDetails.CachedTokenCount", (long)inputTokenDetails.CachedTokenCount); } ChatOutputTokenUsageDetails outputTokenDetails = tokenUsage.OutputTokenDetails; if (outputTokenDetails != null) { additionalCounts.Add("OutputTokenDetails.ReasoningTokenCount", (long)outputTokenDetails.ReasoningTokenCount); additionalCounts.Add("OutputTokenDetails.AudioTokenCount", (long)outputTokenDetails.AudioTokenCount); additionalCounts.Add("OutputTokenDetails.AcceptedPredictionTokenCount", (long)outputTokenDetails.AcceptedPredictionTokenCount); additionalCounts.Add("OutputTokenDetails.RejectedPredictionTokenCount", (long)outputTokenDetails.RejectedPredictionTokenCount); } return val; } private static ChatRole FromOpenAIChatRole(ChatMessageRole role) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown //IL_0020: 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_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_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) return (ChatRole)((int)role switch { 0 => ChatRole.System, 1 => ChatRole.User, 2 => ChatRole.Assistant, 3 => ChatRole.Tool, 5 => OpenAIClientExtensions.ChatRoleDeveloper, _ => new ChatRole(((object)(ChatMessageRole)(ref role)).ToString()), }); } internal static void ConvertContentParts(ChatMessageContent content, IList<AIContent> results) { foreach (ChatMessageContentPart item in (Collection<ChatMessageContentPart>)(object)content) { AIContent val = ToAIContent(item); if (val != null) { results.Add(val); } } } private static AIContent? ToAIContent(ChatMessageContentPart contentPart) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected I4, but got Unknown //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Expected O, but got Unknown //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Expected O, but got Unknown //IL_0143: Expected O, but got Unknown //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown //IL_00c5: Expected O, but got Unknown AIContent val = null; ChatMessageContentPartKind kind = contentPart.Kind; switch ((int)kind) { case 0: val = (AIContent)new TextContent(contentPart.Text); break; case 2: { val = (AIContent)(((object)contentPart.ImageUri == null) ? ((object)((contentPart.ImageBytes == null) ? ((DataContent)null) : new DataContent(contentPart.ImageBytes.ToMemory(), contentPart.ImageBytesMediaType))) : ((object)new UriContent(contentPart.ImageUri, "image/*"))); if (val == null) { break; } ChatImageDetailLevel? imageDetailLevel = contentPart.ImageDetailLevel; object obj; if (!imageDetailLevel.HasValue) { obj = null; } else { ChatImageDetailLevel valueOrDefault = imageDetailLevel.GetValueOrDefault(); obj = ((object)(ChatImageDetailLevel)(ref valueOrDefault)).ToString(); } string text = (string)obj; if (text != null) { AIContent val2 = val; AdditionalPropertiesDictionary obj2 = val2.AdditionalProperties; if (obj2 == null) { AIContent obj3 = val2; AdditionalPropertiesDictionary val3 = new AdditionalPropertiesDictionary(); AdditionalPropertiesDictionary val4 = val3; obj3.AdditionalProperties = val3; obj2 = val4; } ((AdditionalPropertiesDictionary<object>)(object)obj2)["ImageDetailLevel"] = text; } break; } case 4: val = (AIContent)((contentPart.FileId == null) ? ((object)((contentPart.FileBytes == null) ? ((DataContent)null) : new DataContent(contentPart.FileBytes.ToMemory(), contentPart.FileBytesMediaType) { Name = contentPart.Filename })) : ((object)new HostedFileContent(contentPart.FileId))); break; } if (val != null) { string refusal = contentPart.Refusal; if (refusal != null) { AIContent val2 = val; AdditionalPropertiesDictionary obj4 = val2.AdditionalProperties; if (obj4 == null) { AIContent obj5 = val2; AdditionalPropertiesDictionary val5 = new AdditionalPropertiesDictionary(); AdditionalPropertiesDictionary val4 = val5; obj5.AdditionalProperties = val5; obj4 = val4; } ((AdditionalPropertiesDictionary<object>)(object)obj4)["Refusal"] = refusal; } val.RawRepresentation = contentPart; } return val; } private static ChatFinishReason? FromOpenAIFinishReason(ChatFinishReason? finishReason) { //IL_000e: 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_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected I4, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) object obj; if (!finishReason.HasValue) { obj = null; } else { ChatFinishReason valueOrDefault = finishReason.GetValueOrDefault(); obj = ((object)(ChatFinishReason)(ref valueOrDefault)).ToString(); } string text = (string)obj; ChatFinishReason? result; if (text == null) { result = null; } else { ChatFinishReason value; switch (finishReason) { case 0L: value = ChatFinishReason.Stop; break; case 1L: value = ChatFinishReason.Length; break; case 2L: value = ChatFinishReason.ContentFilter; break; case 3L: case 4L: value = ChatFinishReason.ToolCalls; break; default: value = new ChatFinishReason(text); break; } result = value; } return result; } private static string? SanitizeAuthorName(string? name) { if (name != null) { name = InvalidAuthorNameRegex().Replace(name, string.Empty); if (name.Length == 0) { name = null; } else if (name.Length > 64) { name = name.Substring(0, 64); } } return name; } private static Regex InvalidAuthorNameRegex() { return _invalidAuthorNameRegex; } } public static class OpenAIClientExtensions { internal sealed class ToolJson { [JsonPropertyName("type")] public string Type { get; set; } = "object"; [JsonPropertyName("required")] public HashSet<string> Required { get; set; } = new HashSet<string>(); [JsonPropertyName("properties")] public Dictionary<string, JsonElement> Properties { get; set; } = new Dictionary<string, JsonElement>(); [JsonPropertyName("additionalProperties")] public bool AdditionalProperties { get; set; } } private const string StrictKey = "strictJsonSchema"; internal static Uri DefaultOpenAIEndpoint { get; } = new Uri("https://api.openai.com/v1"); internal static ChatRole ChatRoleDeveloper { get; } = new ChatRole("developer"); internal static AIJsonSchemaTransformCache StrictSchemaTransformCache { get; } public static IChatClient AsIChatClient(this ChatClient chatClient) { return (IChatClient)(object)new OpenAIChatClient(chatClient); } public static IChatClient AsIChatClient(this OpenAIResponseClient responseClient) { return (IChatClient)(object)new OpenAIResponsesChatClient(responseClient); } public static IChatClient AsIChatClient(this AssistantClient assistantClient, string assistantId, string? threadId = null) { return (IChatClient)(object)new OpenAIAssistantsChatClient(assistantClient, assistantId, threadId); } public static IChatClient AsIChatClient(this AssistantClient assistantClient, Assistant assistant, string? threadId = null) { return (IChatClient)(object)new OpenAIAssistantsChatClient(assistantClient, assistant, threadId); } [Experimental("MEAI001")] public static ISpeechToTextClient AsISpeechToTextClient(this AudioClient audioClient) { return (ISpeechToTextClient)(object)new OpenAISpeechToTextClient(audioClient); } [Experimental("MEAI001")] public static IImageGenerator AsIImageGenerator(this ImageClient imageClient) { return (IImageGenerator)(object)new OpenAIImageGenerator(imageClient); } public static IEmbeddingGenerator<string, Embedding<float>> AsIEmbeddingGenerator(this EmbeddingClient embeddingClient, int? defaultModelDimensions = null) { return (IEmbeddingGenerator<string, Embedding<float>>)(object)new OpenAIEmbeddingGenerator(embeddingClient, defaultModelDimensions); } internal static bool? HasStrict(IReadOnlyDictionary<string, object?>? additionalProperties) { object value = default(object); bool? flag = additionalProperties?.TryGetValue("strictJsonSchema", out value); if (!flag.HasValue || !flag.GetValueOrDefault() || !(value is bool)) { return null; } return (bool)value; } internal static BinaryData ToOpenAIFunctionParameters(AIFunctionDeclaration aiFunction, bool? strict) { JsonElement element = ((strict ?? false) ? StrictSchemaTransformCache.GetOrCreateTransformedSchema(aiFunction) : aiFunction.JsonSchema); ToolJson value = element.Deserialize(OpenAIJsonContext.Default.ToolJson); return BinaryData.FromBytes(JsonSerializer.SerializeToUtf8Bytes(value, OpenAIJsonContext.Default.ToolJson)); } internal static FunctionCallContent ParseCallContent(string json, string callId, string name) { return FunctionCallContent.CreateFromParsedArguments<string>(json, callId, name, (Func<string, IDictionary<string, object>>)((string json) => JsonSerializer.Deserialize(json, OpenAIJsonContext.Default.IDictionaryStringObject))); } internal static FunctionCallContent ParseCallContent(BinaryData utf8json, string callId, string name) { return FunctionCallContent.CreateFromParsedArguments<BinaryData>(utf8json, callId, name, (Func<BinaryData, IDictionary<string, object>>)((BinaryData utf8json) => JsonSerializer.Deserialize(BinaryData.op_Implicit(utf8json), OpenAIJsonContext.Default.IDictionaryStringObject))); } static OpenAIClientExtensions() { //IL_0014: 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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown AIJsonSchemaTransformOptions val = new AIJsonSchemaTransformOptions(); val.set_DisallowAdditionalProperties(true); val.set_ConvertBooleanSchemas(true); val.set_MoveDefaultKeywordToDescription(true); val.set_RequireAllProperties(true); val.set_TransformSchemaNode((Func<AIJsonSchemaTransformContext, JsonNode, JsonNode>)delegate(AIJsonSchemaTransformContext ctx, JsonNode node) { if (node is JsonObject jsonObject) { StringBuilder sb2 = null; object obj = global::<PrivateImplementationDetails>.2925465225EAEF840FBB80BBFCC6BD7AA78E9F08F79374EF7EE8AFD1A25C192B_B11; if (obj == null) { obj = new string[22] { "contentEncoding", "contentMediaType", "not", "minLength", "maxLength", "pattern", "format", "minimum", "maximum", "multipleOf", "patternProperties", "minItems", "maxItems", "unevaluatedProperties", "propertyNames", "minProperties", "maxProperties", "unevaluatedItems", "contains", "minContains", "maxContains", "uniqueItems" }; global::<PrivateImplementationDetails>.2925465225EAEF840FBB80BBFCC6BD7AA78E9F08F79374EF7EE8AFD1A25C192B_B11 = (string[])obj; } ReadOnlySpan<string> readOnlySpan = new ReadOnlySpan<string>((string[]?)obj); ReadOnlySpan<string> readOnlySpan2 = readOnlySpan; for (int i = 0; i < readOnlySpan2.Length; i++) { string text = readOnlySpan2[i]; JsonNode jsonNode = jsonObject[text]; if (jsonNode != null) { jsonObject.Remove(text); AppendLine(ref sb2, text, jsonNode); } static void AppendLine(ref StringBuilder? sb, string propName, JsonNode propNode) { if (sb == null) { sb = new StringBuilder(); } if (sb.Length > 0) { sb.AppendLine(); } sb.Append(propName).Append(": ").Append(propNode); } } if (sb2 != null) { JsonNode jsonNode2 = jsonObject["description"]; jsonObject["description"] = ((jsonNode2 != null && jsonNode2.GetValueKind() == JsonValueKind.String) ? $"{jsonNode2.GetValue<string>()}{Environment.NewLine}{sb2}" : sb2.ToString()); } return node; } return node; }); StrictSchemaTransformCache = new AIJsonSchemaTransformCache(val); } } internal sealed class OpenAIEmbeddingGenerator : IEmbeddingGenerator<string, Embedding<float>>, IEmbeddingGenerator, IDisposable { private static readonly Func<EmbeddingClient, IEnumerable<string>, EmbeddingGenerationOptions, RequestOptions, Task<ClientResult<OpenAIEmbeddingCollection>>>? _generateEmbeddingsAsync = (Func<EmbeddingClient, IEnumerable<string>, EmbeddingGenerationOptions, RequestOptions, Task<ClientResult<OpenAIEmbeddingCollection>>>)(typeof(EmbeddingClient).GetMethod("GenerateEmbeddingsAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { typeof(IEnumerable<string>), typeof(EmbeddingGenerationOptions), typeof(RequestOptions) }, null)?.CreateDelegate(typeof(Func<EmbeddingClient, IEnumerable<string>, EmbeddingGenerationOptions, RequestOptions, Task<ClientResult<OpenAIEmbeddingCollection>>>))); private readonly EmbeddingGeneratorMetadata _metadata; private readonly EmbeddingClient _embeddingClient; private readonly int? _dimensions; public OpenAIEmbeddingGenerator(EmbeddingClient embeddingClient, int? defaultModelDimensions = null) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown _embeddingClient = Throw.IfNull<EmbeddingClient>(embeddingClient, "embeddingClient"); _dimensions = defaultModelDimensions; if (defaultModelDimensions < 1) { Throw.ArgumentOutOfRangeException("defaultModelDimensions", "Value must be greater than 0."); } _metadata = new EmbeddingGeneratorMetadata("openai", embeddingClient.Endpoint, _embeddingClient.Model, defaultModelDimensions); } public async Task<GeneratedEmbeddings<Embedding<float>>> GenerateAsync(IEnumerable<string> values, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { EmbeddingGenerationOptions val = ToOpenAIOptions(options); Task<ClientResult<OpenAIEmbeddingCollection>> task = ((_generateEmbeddingsAsync != null) ? _generateEmbeddingsAsync(_embeddingClient, values, val, cancellationToken.ToRequestOptions(streaming: false)) : _embeddingClient.GenerateEmbeddingsAsync(values, val, cancellationToken)); OpenAIEmbeddingCollection embeddings = (await task.ConfigureAwait(continueOnCapturedContext: false)).Value; return new GeneratedEmbeddings<Embedding<float>>(((IEnumerable<OpenAIEmbedding>)embeddings).Select(delegate(OpenAIEmbedding e) { Embedding<float> obj = new Embedding<float>(e.ToFloats()); ((Embedding)obj).CreatedAt = DateTimeOffset.UtcNow; ((Embedding)obj).ModelId = embeddings.Model; return obj; })) { Usage = new UsageDetails { InputTokenCount = embeddings.Usage.InputTokenCount, TotalTokenCount = embeddings.Usage.TotalTokenCount } }; } void IDisposable.Dispose() { } object? IEmbeddingGenerator.GetService(Type serviceType, object? serviceKey) { Throw.IfNull(serviceType, "serviceType"); if (serviceKey == null) { if (!(serviceType == typeof(EmbeddingGeneratorMetadata))) { if (!(serviceType == typeof(EmbeddingClient))) { if (!serviceType.IsInstanceOfType(this)) { return null; } return this; } return _embeddingClient; } return _metadata; } return null; } private EmbeddingGenerationOptions ToOpenAIOptions(EmbeddingGenerationOptions? options) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown object obj = ((options == null) ? null : options.RawRepresentationFactory?.Invoke((IEmbeddingGenerator)(object)this)); EmbeddingGenerationOptions val = (EmbeddingGenerationOptions)((obj is EmbeddingGenerationOptions) ? obj : null); if (val == null) { val = new EmbeddingGenerationOptions(); } EmbeddingGenerationOptions val2 = val; if (!val2.Dimensions.HasValue) { int? num2 = (val2.Dimensions = ((options != null) ? options.Dimensions : null) ?? _dimensions); } return val; } } internal sealed class OpenAIImageGenerator : IImageGenerator, IDisposable { private static readonly Dictionary<string, string> _mimeTypeToExtension = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { ["image/png"] = ".png", ["image/jpeg"] = ".jpg", ["image/webp"] = ".webp", ["image/gif"] = ".gif", ["image/bmp"] = ".bmp", ["image/tiff"] = ".tiff" }; private readonly ImageGeneratorMetadata _metadata; private readonly ImageClient _imageClient; public OpenAIImageGenerator(ImageClient imageClient) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown _imageClient = Throw.IfNull<ImageClient>(imageClient, "imageClient"); _metadata = new ImageGeneratorMetadata("openai", imageClient.Endpoint, _imageClient.Model); } public async Task<ImageGenerationResponse> GenerateAsync(ImageGenerationRequest request, ImageGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { Throw.IfNull<ImageGenerationRequest>(request, "request"); string prompt = request.Prompt; Throw.IfNull(prompt, "prompt"); if (request.OriginalImages != null && request.OriginalImages.Any()) { ImageEditOptions val = ToOpenAIImageEditOptions(options); string text = null; Stream stream = null; AIContent val2 = request.OriginalImages.FirstOrDefault(); DataContent val3 = (DataContent)(object)((val2 is DataContent) ? val2 : null); if (val3 != null) { stream = (MemoryMarshal.TryGetArray(val3.Data, out var segment) ? new MemoryStream(segment.Array, segment.Offset, segment.Count) : new MemoryStream(val3.Data.ToArray())); text = val3.Name; if (text == null) { text = ((val3.MediaType == null || !_mimeTypeToExtension.TryGetValue(val3.MediaType, out string value)) ? "image.png" : ("image" + value)); } } GeneratedImageCollection generatedImages = ClientResult<GeneratedImageCollection>.op_Implicit(await _imageClient.GenerateImageEditsAsync(stream, text, prompt, ((options != null) ? options.Count : null).GetValueOrDefault(1), val, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); return ToImageGenerationResponse(generatedImages); } ImageGenerationOptions val4 = ToOpenAIImageGenerationOptions(options); GeneratedImageCollection generatedImages2 = ClientResult<GeneratedImageCollection>.op_Implicit(await _imageClient.GenerateImagesAsync(prompt, ((options != null) ? options.Count : null).GetValueOrDefault(1), val4, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)); return ToImageGenerationResponse(generatedImages2); } public object? GetService(Type serviceType, object? serviceKey = null) { if ((object)serviceType != null) { if (serviceKey == null) { if (!(serviceType == typeof(ImageGeneratorMetadata))) { if (!(serviceType == typeof(ImageClient))) { if (!serviceType.IsInstanceOfType(this)) { return null; } return this; } return _imageClient; } return _metadata; } return null; } throw new ArgumentNullException("serviceType"); } void IDisposable.Dispose() { } private static GeneratedImageSize? ToOpenAIImageSize(Size? requestedSize) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (requestedSize.HasValue) { return new GeneratedImageSize(requestedSize.Value.Width, requestedSize.Value.Height); } return null; } private static ImageGenerationResponse ToImageGenerationResponse(GeneratedImageCollection generatedImages) { //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Expected O, but got Unknown //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Expected O, but got Unknown //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Expected O, but got Unknown string text = "image/png"; if (typeof(GeneratedImageCollection).GetProperty("SerializedAdditionalRawData", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(generatedImages) is IDictionary<string, BinaryData> dictionary && dictionary.TryGetValue("output_format", out var value)) { JsonTypeInfo<string> jsonTypeInfo = (JsonTypeInfo<string>)AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(string)); string text2 = JsonSerializer.Deserialize(BinaryData.op_Implicit(value), jsonTypeInfo); text = "image/" + text2; } List<AIContent> list = new List<AIContent>(); foreach (GeneratedImage item in (ReadOnlyCollection<GeneratedImage>)(object)generatedImages) { if (item.ImageBytes != null) { list.Add((AIContent)new DataContent(item.ImageBytes.ToMemory(), text)); continue; } if ((object)item.ImageUri != null) { list.Add((AIContent)new UriContent(item.ImageUri, text)); continue; } throw new InvalidOperationException("Generated image does not contain a valid URI or byte array."); } UsageDetails val = null; ImageTokenUsage usage = generatedImages.Usage; if (usage != null) { val = new UsageDetails { InputTokenCount = usage.InputTokenCount, OutputTokenCount = usage.OutputTokenCount, TotalTokenCount = usage.TotalTokenCount }; ImageInputTokenUsageDetails inputTokenDetails = usage.InputTokenDetails; if (inputTokenDetails != null) { UsageDetails val2 = val; if (val2.AdditionalCounts == null) { AdditionalPropertiesDictionary<long> val4 = (val2.AdditionalCounts = new AdditionalPropertiesDictionary<long>()); } val.AdditionalCounts.Add("InputTokenDetails.ImageTokenCount", (long)inputTokenDetails.ImageTokenCount); val.AdditionalCounts.Add("InputTokenDetails.TextTokenCount", (long)inputTokenDetails.TextTokenCount); } } return new ImageGenerationResponse((IList<AIContent>)list) { RawRepresentation = generatedImages, Usage = val }; } private ImageGenerationOptions ToOpenAIImageGenerationOptions(ImageGenerationOptions? options) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Invalid comparison between Unknown and I4 //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) object obj = ((options == null) ? null : options.RawRepresentationFactory?.Invoke((IImageGenerator)(object)this)); ImageGenerationOptions val = (ImageGenerationOptions)(((obj is ImageGenerationOptions) ? obj : null) ?? ((object)new ImageGenerationOptions())); if (!val.OutputFileFormat.HasValue) { if (options != null && (options.MediaType?.Equals("image/png", StringComparison.OrdinalIgnoreCase)).GetValueOrDefault()) { val.OutputFileFormat = GeneratedImageFileFormat.Png; } else if (options != null && (options.MediaType?.Equals("image/jpeg", StringComparison.OrdinalIgnoreCase)).GetValueOrDefault()) { val.OutputFileFormat = GeneratedImageFileFormat.Jpeg; } else if (options != null && (options.MediaType?.Equals("image/webp", StringComparison.OrdinalIgnoreCase)).GetValueOrDefault()) { val.OutputFileFormat = GeneratedImageFileFormat.Webp; } } ImageGenerationOptions val2 = val; GeneratedImageFormat? responseFormat = val2.ResponseFormat; GeneratedImageFormat? val3; if (responseFormat.HasValue) { val3 = responseFormat; goto IL_0190; } ImageGenerationOptions val4 = val2; ImageGenerationResponseFormat? val5 = ((options != null) ? options.ResponseFormat : null); if (!val5.HasValue) { goto IL_0174; } ImageGenerationResponseFormat valueOrDefault = val5.GetValueOrDefault(); GeneratedImageFormat? val6; if ((int)valueOrDefault != 0) { if ((int)valueOrDefault != 1) { goto IL_0174;
deps/Microsoft.Extensions.Caching.Abstractions.dll
Decompiled a day agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Caching.Abstractions")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Caching abstractions for in-memory cache and distributed cache.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Caching.Distributed.IDistributedCache\r\nMicrosoft.Extensions.Caching.Memory.IMemoryCache")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Caching.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("8.0.0.0")] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 ThrowHelper { internal static void ThrowIfNull(object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { Throw(paramName); } } private static void Throw(string paramName) { throw new ArgumentNullException(paramName); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string IfNullOrWhitespace(string argument, [CallerArgumentExpression("argument")] string paramName = "") { if (argument == null) { throw new ArgumentNullException(paramName); } if (string.IsNullOrWhiteSpace(argument)) { if (argument == null) { throw new ArgumentNullException(paramName); } throw new ArgumentException(paramName, "Argument is whitespace"); } return argument; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } } namespace Microsoft.Extensions.Internal { public interface ISystemClock { DateTimeOffset UtcNow { get; } } public class SystemClock : ISystemClock { public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; } } namespace Microsoft.Extensions.Caching.Distributed { public static class DistributedCacheEntryExtensions { public static DistributedCacheEntryOptions SetAbsoluteExpiration(this DistributedCacheEntryOptions options, TimeSpan relative) { options.AbsoluteExpirationRelativeToNow = relative; return options; } public static DistributedCacheEntryOptions SetAbsoluteExpiration(this DistributedCacheEntryOptions options, DateTimeOffset absolute) { options.AbsoluteExpiration = absolute; return options; } public static DistributedCacheEntryOptions SetSlidingExpiration(this DistributedCacheEntryOptions options, TimeSpan offset) { options.SlidingExpiration = offset; return options; } } public class DistributedCacheEntryOptions { private DateTimeOffset? _absoluteExpiration; private TimeSpan? _absoluteExpirationRelativeToNow; private TimeSpan? _slidingExpiration; public DateTimeOffset? AbsoluteExpiration { get { return _absoluteExpiration; } set { _absoluteExpiration = value; } } public TimeSpan? AbsoluteExpirationRelativeToNow { get { return _absoluteExpirationRelativeToNow; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("AbsoluteExpirationRelativeToNow", value, "The relative expiration value must be positive."); } _absoluteExpirationRelativeToNow = value; } } public TimeSpan? SlidingExpiration { get { return _slidingExpiration; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("SlidingExpiration", value, "The sliding expiration value must be positive."); } _slidingExpiration = value; } } } public static class DistributedCacheExtensions { public static void Set(this IDistributedCache cache, string key, byte[] value) { System.ThrowHelper.ThrowIfNull(key, "key"); System.ThrowHelper.ThrowIfNull(value, "value"); cache.Set(key, value, new DistributedCacheEntryOptions()); } public static Task SetAsync(this IDistributedCache cache, string key, byte[] value, CancellationToken token = default(CancellationToken)) { System.ThrowHelper.ThrowIfNull(key, "key"); System.ThrowHelper.ThrowIfNull(value, "value"); return cache.SetAsync(key, value, new DistributedCacheEntryOptions(), token); } public static void SetString(this IDistributedCache cache, string key, string value) { cache.SetString(key, value, new DistributedCacheEntryOptions()); } public static void SetString(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options) { System.ThrowHelper.ThrowIfNull(key, "key"); System.ThrowHelper.ThrowIfNull(value, "value"); cache.Set(key, Encoding.UTF8.GetBytes(value), options); } public static Task SetStringAsync(this IDistributedCache cache, string key, string value, CancellationToken token = default(CancellationToken)) { return cache.SetStringAsync(key, value, new DistributedCacheEntryOptions(), token); } public static Task SetStringAsync(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) { System.ThrowHelper.ThrowIfNull(key, "key"); System.ThrowHelper.ThrowIfNull(value, "value"); return cache.SetAsync(key, Encoding.UTF8.GetBytes(value), options, token); } public static string? GetString(this IDistributedCache cache, string key) { byte[] array = cache.Get(key); if (array == null) { return null; } return Encoding.UTF8.GetString(array, 0, array.Length); } public static async Task<string?> GetStringAsync(this IDistributedCache cache, string key, CancellationToken token = default(CancellationToken)) { byte[] array = await cache.GetAsync(key, token).ConfigureAwait(continueOnCapturedContext: false); if (array == null) { return null; } return Encoding.UTF8.GetString(array, 0, array.Length); } } public interface IDistributedCache { byte[]? Get(string key); Task<byte[]?> GetAsync(string key, CancellationToken token = default(CancellationToken)); void Set(string key, byte[] value, DistributedCacheEntryOptions options); Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)); void Refresh(string key); Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)); void Remove(string key); Task RemoveAsync(string key, CancellationToken token = default(CancellationToken)); } } namespace Microsoft.Extensions.Caching.Memory { public static class CacheEntryExtensions { public static ICacheEntry SetPriority(this ICacheEntry entry, CacheItemPriority priority) { entry.Priority = priority; return entry; } public static ICacheEntry AddExpirationToken(this ICacheEntry entry, IChangeToken expirationToken) { System.ThrowHelper.ThrowIfNull(expirationToken, "expirationToken"); entry.ExpirationTokens.Add(expirationToken); return entry; } public static ICacheEntry SetAbsoluteExpiration(this ICacheEntry entry, TimeSpan relative) { entry.AbsoluteExpirationRelativeToNow = relative; return entry; } public static ICacheEntry SetAbsoluteExpiration(this ICacheEntry entry, DateTimeOffset absolute) { entry.AbsoluteExpiration = absolute; return entry; } public static ICacheEntry SetSlidingExpiration(this ICacheEntry entry, TimeSpan offset) { entry.SlidingExpiration = offset; return entry; } public static ICacheEntry RegisterPostEvictionCallback(this ICacheEntry entry, PostEvictionDelegate callback) { System.ThrowHelper.ThrowIfNull(callback, "callback"); return entry.RegisterPostEvictionCallbackNoValidation(callback, null); } public static ICacheEntry RegisterPostEvictionCallback(this ICacheEntry entry, PostEvictionDelegate callback, object? state) { System.ThrowHelper.ThrowIfNull(callback, "callback"); return entry.RegisterPostEvictionCallbackNoValidation(callback, state); } private static ICacheEntry RegisterPostEvictionCallbackNoValidation(this ICacheEntry entry, PostEvictionDelegate callback, object state) { entry.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration { EvictionCallback = callback, State = state }); return entry; } public static ICacheEntry SetValue(this ICacheEntry entry, object? value) { entry.Value = value; return entry; } public static ICacheEntry SetSize(this ICacheEntry entry, long size) { if (size < 0) { throw new ArgumentOutOfRangeException("size", size, "size must be non-negative."); } entry.Size = size; return entry; } public static ICacheEntry SetOptions(this ICacheEntry entry, MemoryCacheEntryOptions options) { System.ThrowHelper.ThrowIfNull(options, "options"); entry.AbsoluteExpiration = options.AbsoluteExpiration; entry.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow; entry.SlidingExpiration = options.SlidingExpiration; entry.Priority = options.Priority; entry.Size = options.Size; foreach (IChangeToken expirationToken in options.ExpirationTokens) { entry.AddExpirationToken(expirationToken); } for (int i = 0; i < options.PostEvictionCallbacks.Count; i++) { PostEvictionCallbackRegistration postEvictionCallbackRegistration = options.PostEvictionCallbacks[i]; if (postEvictionCallbackRegistration.EvictionCallback == null) { ThrowNullCallback(i, "options"); } entry.RegisterPostEvictionCallbackNoValidation(postEvictionCallbackRegistration.EvictionCallback, postEvictionCallbackRegistration.State); } return entry; } [DoesNotReturn] private static void ThrowNullCallback(int index, string paramName) { string message = $"MemoryCacheEntryOptions.PostEvictionCallbacks contains a PostEvictionCallbackRegistration with a null EvictionCallback at index {index}."; throw new ArgumentException(message, paramName); } } public enum CacheItemPriority { Low, Normal, High, NeverRemove } public enum EvictionReason { None, Removed, Replaced, Expired, TokenExpired, Capacity } public interface ICacheEntry : IDisposable { object Key { get; } object? Value { get; set; } DateTimeOffset? AbsoluteExpiration { get; set; } TimeSpan? AbsoluteExpirationRelativeToNow { get; set; } TimeSpan? SlidingExpiration { get; set; } IList<IChangeToken> ExpirationTokens { get; } IList<PostEvictionCallbackRegistration> PostEvictionCallbacks { get; } CacheItemPriority Priority { get; set; } long? Size { get; set; } } public interface IMemoryCache : IDisposable { bool TryGetValue(object key, out object? value); ICacheEntry CreateEntry(object key); void Remove(object key); } public static class MemoryCacheEntryExtensions { public static MemoryCacheEntryOptions SetPriority(this MemoryCacheEntryOptions options, CacheItemPriority priority) { options.Priority = priority; return options; } public static MemoryCacheEntryOptions SetSize(this MemoryCacheEntryOptions options, long size) { if (size < 0) { throw new ArgumentOutOfRangeException("size", size, "size must be non-negative."); } options.Size = size; return options; } public static MemoryCacheEntryOptions AddExpirationToken(this MemoryCacheEntryOptions options, IChangeToken expirationToken) { System.ThrowHelper.ThrowIfNull(expirationToken, "expirationToken"); options.ExpirationTokens.Add(expirationToken); return options; } public static MemoryCacheEntryOptions SetAbsoluteExpiration(this MemoryCacheEntryOptions options, TimeSpan relative) { options.AbsoluteExpirationRelativeToNow = relative; return options; } public static MemoryCacheEntryOptions SetAbsoluteExpiration(this MemoryCacheEntryOptions options, DateTimeOffset absolute) { options.AbsoluteExpiration = absolute; return options; } public static MemoryCacheEntryOptions SetSlidingExpiration(this MemoryCacheEntryOptions options, TimeSpan offset) { options.SlidingExpiration = offset; return options; } public static MemoryCacheEntryOptions RegisterPostEvictionCallback(this MemoryCacheEntryOptions options, PostEvictionDelegate callback) { System.ThrowHelper.ThrowIfNull(callback, "callback"); return options.RegisterPostEvictionCallback(callback, null); } public static MemoryCacheEntryOptions RegisterPostEvictionCallback(this MemoryCacheEntryOptions options, PostEvictionDelegate callback, object? state) { System.ThrowHelper.ThrowIfNull(callback, "callback"); options.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration { EvictionCallback = callback, State = state }); return options; } } public class MemoryCacheEntryOptions { private DateTimeOffset? _absoluteExpiration; private TimeSpan? _absoluteExpirationRelativeToNow; private TimeSpan? _slidingExpiration; private long? _size; public DateTimeOffset? AbsoluteExpiration { get { return _absoluteExpiration; } set { _absoluteExpiration = value; } } public TimeSpan? AbsoluteExpirationRelativeToNow { get { return _absoluteExpirationRelativeToNow; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("AbsoluteExpirationRelativeToNow", value, "The relative expiration value must be positive."); } _absoluteExpirationRelativeToNow = value; } } public TimeSpan? SlidingExpiration { get { return _slidingExpiration; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("SlidingExpiration", value, "The sliding expiration value must be positive."); } _slidingExpiration = value; } } public IList<IChangeToken> ExpirationTokens { get; } = new List<IChangeToken>(); public IList<PostEvictionCallbackRegistration> PostEvictionCallbacks { get; } = new List<PostEvictionCallbackRegistration>(); public CacheItemPriority Priority { get; set; } = CacheItemPriority.Normal; public long? Size { get { return _size; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", value, "value must be non-negative."); } _size = value; } } } public static class CacheExtensions { public static object? Get(this IMemoryCache cache, object key) { cache.TryGetValue(key, out object value); return value; } public static TItem? Get<TItem>(this IMemoryCache cache, object key) { return (TItem)(cache.Get(key) ?? ((object)default(TItem))); } public static bool TryGetValue<TItem>(this IMemoryCache cache, object key, out TItem? value) { if (cache.TryGetValue(key, out object value2)) { if (value2 == null) { value = default(TItem); return true; } if (value2 is TItem val) { value = val; return true; } } value = default(TItem); return false; } public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value) { using ICacheEntry cacheEntry = cache.CreateEntry(key); cacheEntry.Value = value; return value; } public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, DateTimeOffset absoluteExpiration) { using ICacheEntry cacheEntry = cache.CreateEntry(key); cacheEntry.AbsoluteExpiration = absoluteExpiration; cacheEntry.Value = value; return value; } public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, TimeSpan absoluteExpirationRelativeToNow) { using ICacheEntry cacheEntry = cache.CreateEntry(key); cacheEntry.AbsoluteExpirationRelativeToNow = absoluteExpirationRelativeToNow; cacheEntry.Value = value; return value; } public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, IChangeToken expirationToken) { using ICacheEntry cacheEntry = cache.CreateEntry(key); cacheEntry.AddExpirationToken(expirationToken); cacheEntry.Value = value; return value; } public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions? options) { using ICacheEntry cacheEntry = cache.CreateEntry(key); if (options != null) { cacheEntry.SetOptions(options); } cacheEntry.Value = value; return value; } public static TItem? GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory) { if (!cache.TryGetValue(key, out object value)) { using ICacheEntry cacheEntry = cache.CreateEntry(key); value = (cacheEntry.Value = factory(cacheEntry)); } return (TItem)value; } public static async Task<TItem?> GetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory) { if (!cache.TryGetValue(key, out object value)) { using ICacheEntry entry = cache.CreateEntry(key); value = (entry.Value = await factory(entry).ConfigureAwait(continueOnCapturedContext: false)); } return (TItem)value; } } public class MemoryCacheStatistics { public long CurrentEntryCount { get; init; } public long? CurrentEstimatedSize { get; init; } public long TotalMisses { get; init; } public long TotalHits { get; init; } } public class PostEvictionCallbackRegistration { public PostEvictionDelegate? EvictionCallback { get; set; } public object? State { get; set; } } public delegate void PostEvictionDelegate(object key, object? value, EvictionReason reason, object? state); }
deps/Microsoft.Extensions.DependencyInjection.Abstractions.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.DependencyInjection.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Abstractions for dependency injection.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.DependencyInjection.IServiceCollection")] [assembly: AssemblyFileVersion("8.0.1024.46610")] [assembly: AssemblyInformationalVersion("8.0.10+81cabf2857a01351e5ab578947c7403a5b128ad1")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("8.0.0.0")] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 FxResources.Microsoft.Extensions.DependencyInjection.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } private static void Throw(string paramName) { throw new ArgumentNullException(paramName); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "") { if (argument == null) { throw new ArgumentNullException(paramName); } if (string.IsNullOrWhiteSpace(argument)) { if (argument == null) { throw new ArgumentNullException(paramName); } throw new ArgumentException(paramName, "Argument is whitespace"); } return argument; } } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string AmbiguousConstructorMatch => GetResourceString("AmbiguousConstructorMatch"); internal static string CannotResolveService => GetResourceString("CannotResolveService"); internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch"); internal static string NoServiceRegistered => GetResourceString("NoServiceRegistered"); internal static string ServiceCollectionReadOnly => GetResourceString("ServiceCollectionReadOnly"); internal static string TryAddIndistinguishableTypeToEnumerable => GetResourceString("TryAddIndistinguishableTypeToEnumerable"); internal static string MultipleCtorsMarkedWithAttribute => GetResourceString("MultipleCtorsMarkedWithAttribute"); internal static string MarkedCtorMissingArgumentTypes => GetResourceString("MarkedCtorMissingArgumentTypes"); internal static string CannotCreateAbstractClasses => GetResourceString("CannotCreateAbstractClasses"); internal static string MultipleCtorsFoundWithBestLength => GetResourceString("MultipleCtorsFoundWithBestLength"); internal static string UnableToResolveService => GetResourceString("UnableToResolveService"); internal static string CtorNotLocated => GetResourceString("CtorNotLocated"); internal static string MultipleCtorsFound => GetResourceString("MultipleCtorsFound"); internal static string KeyedServicesNotSupported => GetResourceString("KeyedServicesNotSupported"); internal static string NonKeyedDescriptorMisuse => GetResourceString("NonKeyedDescriptorMisuse"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } 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.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; } } [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.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } } namespace Microsoft.Extensions.Internal { internal static class ParameterDefaultValue { public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue) { bool tryToGetDefaultValue; bool flag = CheckHasDefaultValue(parameter, out tryToGetDefaultValue); defaultValue = null; if (flag) { if (tryToGetDefaultValue) { defaultValue = parameter.DefaultValue; } bool flag2 = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>); if (defaultValue == null && parameter.ParameterType.IsValueType && !flag2) { defaultValue = CreateValueType(parameter.ParameterType); } if (defaultValue != null && flag2) { Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType != null && underlyingType.IsEnum) { defaultValue = Enum.ToObject(underlyingType, defaultValue); } } } return flag; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")] static object? CreateValueType(Type t) { return RuntimeHelpers.GetUninitializedObject(t); } } public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue) { tryToGetDefaultValue = true; try { return parameter.HasDefaultValue; } catch (FormatException) when (parameter.ParameterType == typeof(DateTime)) { tryToGetDefaultValue = false; return true; } } } } namespace Microsoft.Extensions.DependencyInjection { public static class ActivatorUtilities { private readonly struct FactoryParameterContext { public Type ParameterType { get; } public bool HasDefaultValue { get; } public object DefaultValue { get; } public int ArgumentIndex { get; } public object ServiceKey { get; } public FactoryParameterContext(Type parameterType, bool hasDefaultValue, object defaultValue, int argumentIndex, object serviceKey) { ParameterType = parameterType; HasDefaultValue = hasDefaultValue; DefaultValue = defaultValue; ArgumentIndex = argumentIndex; ServiceKey = serviceKey; } } private sealed class ConstructorInfoEx { public readonly ConstructorInfo Info; public readonly ParameterInfo[] Parameters; public readonly bool IsPreferred; private readonly object[] _parameterKeys; public ConstructorInfoEx(ConstructorInfo constructor) { Info = constructor; Parameters = constructor.GetParameters(); IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false); for (int i = 0; i < Parameters.Length; i++) { FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false); if (fromKeyedServicesAttribute != null) { if (_parameterKeys == null) { _parameterKeys = new object[Parameters.Length]; } _parameterKeys[i] = fromKeyedServicesAttribute.Key; } } } public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex) { ParameterInfo parameterInfo = Parameters[parameterIndex]; object[] parameterKeys = _parameterKeys; object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null); if (obj != null) { if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService) { return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, obj); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } return serviceProviderIsService.IsService(parameterInfo.ParameterType); } public object GetService(IServiceProvider serviceProvider, int parameterIndex) { ParameterInfo parameterInfo = Parameters[parameterIndex]; object[] parameterKeys = _parameterKeys; object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null); if (obj != null) { if (serviceProvider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, obj); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } return serviceProvider.GetService(parameterInfo.ParameterType); } } private readonly struct ConstructorMatcher { private readonly ConstructorInfoEx _constructor; private readonly object[] _parameterValues; public ConstructorMatcher(ConstructorInfoEx constructor) { _constructor = constructor; _parameterValues = new object[constructor.Parameters.Length]; } public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService) { for (int i = 0; i < givenParameters.Length; i++) { Type c = givenParameters[i]?.GetType(); bool flag = false; for (int j = 0; j < _constructor.Parameters.Length; j++) { if (_parameterValues[j] == null && _constructor.Parameters[j].ParameterType.IsAssignableFrom(c)) { flag = true; _parameterValues[j] = givenParameters[i]; break; } } if (!flag) { return -1; } } for (int k = 0; k < _constructor.Parameters.Length; k++) { if (_parameterValues[k] == null && !_constructor.IsService(serviceProviderIsService, k)) { if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[k], out object defaultValue)) { return -1; } _parameterValues[k] = defaultValue; } } return _constructor.Parameters.Length; } public object CreateInstance(IServiceProvider provider) { for (int i = 0; i < _constructor.Parameters.Length; i++) { if (_parameterValues[i] != null) { continue; } object service = _constructor.GetService(provider, i); if (service == null) { if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object defaultValue)) { throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, _constructor.Parameters[i].ParameterType, _constructor.Info.DeclaringType)); } _parameterValues[i] = defaultValue; } else { _parameterValues[i] = service; } } return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, null, _parameterValues, null); } public void MapParameters(int?[] parameterMap, object[] givenParameters) { for (int i = 0; i < _constructor.Parameters.Length; i++) { if (parameterMap[i].HasValue) { _parameterValues[i] = givenParameters[parameterMap[i].Value]; } } } } private static readonly MethodInfo GetServiceInfo = GetMethodInfo<Func<IServiceProvider, Type, Type, bool, object, object>>((IServiceProvider sp, Type t, Type r, bool c, object k) => GetService(sp, t, r, c, k)); public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters) { if (provider == null) { throw new ArgumentNullException("provider"); } if (instanceType.IsAbstract) { throw new InvalidOperationException(System.SR.CannotCreateAbstractClasses); } ConstructorInfoEx[] array = CreateConstructorInfoExs(instanceType); IServiceProviderIsService service = provider.GetService<IServiceProviderIsService>(); ConstructorInfoEx constructorInfoEx; if (service != null) { int num = -1; bool flag = false; ConstructorMatcher constructorMatcher = default(ConstructorMatcher); bool flag2 = false; for (int i = 0; i < array.Length; i++) { constructorInfoEx = array[i]; ConstructorMatcher constructorMatcher2 = new ConstructorMatcher(constructorInfoEx); bool isPreferred = constructorInfoEx.IsPreferred; int num2 = constructorMatcher2.Match(parameters, service); if (isPreferred) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (num2 == -1) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } } if (isPreferred || num < num2) { num = num2; constructorMatcher = constructorMatcher2; flag2 = false; } else if (num == num2) { flag2 = true; } flag = flag || isPreferred; } if (num != -1) { if (flag2) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFoundWithBestLength, instanceType, num)); } return constructorMatcher.CreateInstance(provider); } } Type[] array2; if (parameters.Length == 0) { array2 = Type.EmptyTypes; } else { array2 = new Type[parameters.Length]; for (int j = 0; j < array2.Length; j++) { array2[j] = parameters[j]?.GetType(); } } FindApplicableConstructor(instanceType, array2, out var matchingConstructor, out var matchingParameterMap); constructorInfoEx = null; ConstructorInfoEx[] array3 = array; foreach (ConstructorInfoEx constructorInfoEx2 in array3) { if ((object)constructorInfoEx2.Info == matchingConstructor) { constructorInfoEx = constructorInfoEx2; break; } } ConstructorMatcher constructorMatcher3 = new ConstructorMatcher(constructorInfoEx); constructorMatcher3.MapParameters(matchingParameterMap, parameters); return constructorMatcher3.CreateInstance(provider); } private static ConstructorInfoEx[] CreateConstructorInfoExs([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { ConstructorInfo[] constructors = type.GetConstructors(); ConstructorInfoEx[] array = new ConstructorInfoEx[constructors.Length]; for (int i = 0; i < constructors.Length; i++) { array[i] = new ConstructorInfoEx(constructors[i]); } return array; } public static ObjectFactory CreateFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes) { if (!RuntimeFeature.IsDynamicCodeCompiled) { return CreateFactoryReflection(instanceType, argumentTypes); } CreateFactoryInternal(instanceType, argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody); Expression<Func<IServiceProvider, object[], object>> expression = Expression.Lambda<Func<IServiceProvider, object[], object>>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }); Func<IServiceProvider, object[], object> @object = expression.Compile(); return @object.Invoke; } public static ObjectFactory<T> CreateFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(Type[] argumentTypes) { if (!RuntimeFeature.IsDynamicCodeCompiled) { ObjectFactory factory = CreateFactoryReflection(typeof(T), argumentTypes); return (IServiceProvider serviceProvider, object[] arguments) => (T)factory(serviceProvider, arguments); } CreateFactoryInternal(typeof(T), argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody); Expression<Func<IServiceProvider, object[], T>> expression = Expression.Lambda<Func<IServiceProvider, object[], T>>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }); Func<IServiceProvider, object[], T> @object = expression.Compile(); return @object.Invoke; } private static void CreateFactoryInternal([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ParameterExpression provider, out ParameterExpression argumentArray, out Expression factoryExpressionBody) { FindApplicableConstructor(instanceType, argumentTypes, out var matchingConstructor, out var matchingParameterMap); provider = Expression.Parameter(typeof(IServiceProvider), "provider"); argumentArray = Expression.Parameter(typeof(object[]), "argumentArray"); factoryExpressionBody = BuildFactoryExpression(matchingConstructor, matchingParameterMap, provider, argumentArray); } public static T CreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider, params object[] parameters) { return (T)CreateInstance(provider, typeof(T), parameters); } public static T GetServiceOrCreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider) { return (T)GetServiceOrCreateInstance(provider, typeof(T)); } public static object GetServiceOrCreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { return provider.GetService(type) ?? CreateInstance(provider, type); } private static MethodInfo GetMethodInfo<T>(Expression<T> expr) { MethodCallExpression methodCallExpression = (MethodCallExpression)expr.Body; return methodCallExpression.Method; } private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool hasDefaultValue, object key) { object obj = ((key == null) ? sp.GetService(type) : GetKeyedService(sp, type, key)); if (obj == null && !hasDefaultValue) { ThrowHelperUnableToResolveService(type, requiredBy); } return obj; } [DoesNotReturn] private static void ThrowHelperUnableToResolveService(Type type, Type requiredBy) { throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, type, requiredBy)); } private static BlockExpression BuildFactoryExpression(ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray) { ParameterInfo[] parameters = constructor.GetParameters(); Expression[] array = new Expression[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameterInfo = parameters[i]; Type parameterType = parameterInfo.ParameterType; object defaultValue; bool flag = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue); if (parameterMap[i].HasValue) { array[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i])); } else { FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false); Expression[] arguments = new Expression[5] { serviceProvider, Expression.Constant(parameterType, typeof(Type)), Expression.Constant(constructor.DeclaringType, typeof(Type)), Expression.Constant(flag), Expression.Constant(fromKeyedServicesAttribute?.Key) }; array[i] = Expression.Call(GetServiceInfo, arguments); } if (flag) { ConstantExpression right = Expression.Constant(defaultValue); array[i] = Expression.Coalesce(array[i], right); } array[i] = Expression.Convert(array[i], parameterType); } return Expression.Block(Expression.IfThen(Expression.Equal(serviceProvider, Expression.Constant(null)), Expression.Throw(Expression.Constant(new ArgumentNullException("serviceProvider")))), Expression.New(constructor, array)); } [DoesNotReturn] private static void ThrowHelperArgumentNullExceptionServiceProvider() { throw new ArgumentNullException("serviceProvider"); } private static ObjectFactory CreateFactoryReflection([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes) { FindApplicableConstructor(instanceType, argumentTypes, out var constructor, out var parameterMap); Type declaringType = constructor.DeclaringType; ParameterInfo[] constructorParameters = constructor.GetParameters(); if (constructorParameters.Length == 0) { return (IServiceProvider serviceProvider, object[] arguments) => constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, null, null); } FactoryParameterContext[] parameters = GetFactoryParameterContext(); return (IServiceProvider serviceProvider, object[] arguments) => ReflectionFactoryCanonical(constructor, parameters, declaringType, serviceProvider, arguments); FactoryParameterContext[] GetFactoryParameterContext() { FactoryParameterContext[] array = new FactoryParameterContext[constructorParameters.Length]; for (int i = 0; i < constructorParameters.Length; i++) { ParameterInfo parameterInfo = constructorParameters[i]; FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false); object defaultValue; bool hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue); array[i] = new FactoryParameterContext(parameterInfo.ParameterType, hasDefaultValue, defaultValue, parameterMap[i] ?? (-1), fromKeyedServicesAttribute?.Key); } return array; } } private static void FindApplicableConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap) { if (!TryFindPreferredConstructor(instanceType, argumentTypes, out var matchingConstructor2, out var parameterMap) && !TryFindMatchingConstructor(instanceType, argumentTypes, out matchingConstructor2, out parameterMap)) { throw new InvalidOperationException(System.SR.Format(System.SR.CtorNotLocated, instanceType)); } matchingConstructor = matchingConstructor2; matchingParameterMap = parameterMap; } private static bool TryFindMatchingConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap) { matchingConstructor = null; parameterMap = null; ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo constructorInfo in constructors) { if (TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2)) { if (matchingConstructor != null) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFound, instanceType)); } matchingConstructor = constructorInfo; parameterMap = parameterMap2; } } if (matchingConstructor != null) { return true; } return false; } private static bool TryFindPreferredConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap) { bool flag = false; matchingConstructor = null; parameterMap = null; ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo constructorInfo in constructors) { if (constructorInfo.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false)) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (!TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2)) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } matchingConstructor = constructorInfo; parameterMap = parameterMap2; flag = true; } } if (matchingConstructor != null) { return true; } return false; } private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap) { parameterMap = new int?[constructorParameters.Length]; for (int i = 0; i < argumentTypes.Length; i++) { bool flag = false; Type c = argumentTypes[i]; for (int j = 0; j < constructorParameters.Length; j++) { if (!parameterMap[j].HasValue && constructorParameters[j].ParameterType.IsAssignableFrom(c)) { flag = true; parameterMap[j] = i; break; } } if (!flag) { return false; } } return true; } private static void ThrowMultipleCtorsMarkedWithAttributeException() { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsMarkedWithAttribute, "ActivatorUtilitiesConstructorAttribute")); } private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments() { throw new InvalidOperationException(System.SR.Format(System.SR.MarkedCtorMissingArgumentTypes, "ActivatorUtilitiesConstructorAttribute")); } private static object ReflectionFactoryCanonical(ConstructorInfo constructor, FactoryParameterContext[] parameters, Type declaringType, IServiceProvider serviceProvider, object[] arguments) { if (serviceProvider == null) { ThrowHelperArgumentNullExceptionServiceProvider(); } object[] array = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ref FactoryParameterContext reference = ref parameters[i]; array[i] = ((reference.ArgumentIndex != -1) ? arguments[reference.ArgumentIndex] : GetService(serviceProvider, reference.ParameterType, declaringType, reference.HasDefaultValue, reference.ServiceKey)) ?? reference.DefaultValue; } return constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, array, null); } private static object GetKeyedService(IServiceProvider provider, Type type, object serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetKeyedService(type, serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } } [AttributeUsage(AttributeTargets.All)] public class ActivatorUtilitiesConstructorAttribute : Attribute { } [DebuggerDisplay("{ServiceProvider,nq}")] public readonly struct AsyncServiceScope : IServiceScope, IDisposable, IAsyncDisposable { private readonly IServiceScope _serviceScope; public IServiceProvider ServiceProvider => _serviceScope.ServiceProvider; public AsyncServiceScope(IServiceScope serviceScope) { System.ThrowHelper.ThrowIfNull(serviceScope, "serviceScope"); _serviceScope = serviceScope; } public void Dispose() { _serviceScope.Dispose(); } public ValueTask DisposeAsync() { if (_serviceScope is IAsyncDisposable asyncDisposable) { return asyncDisposable.DisposeAsync(); } _serviceScope.Dispose(); return default(ValueTask); } } [AttributeUsage(AttributeTargets.Parameter)] public class FromKeyedServicesAttribute : Attribute { public object Key { get; } public FromKeyedServicesAttribute(object key) { Key = key; } } public interface IKeyedServiceProvider : IServiceProvider { object? GetKeyedService(Type serviceType, object? serviceKey); object GetRequiredKeyedService(Type serviceType, object? serviceKey); } public static class KeyedService { private sealed class AnyKeyObj { public override string ToString() { return "*"; } } public static object AnyKey { get; } = new AnyKeyObj(); } public interface IServiceCollection : IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable { } public interface IServiceProviderFactory<TContainerBuilder> where TContainerBuilder : notnull { TContainerBuilder CreateBuilder(IServiceCollection services); IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder); } public interface IServiceProviderIsKeyedService : IServiceProviderIsService { bool IsKeyedService(Type serviceType, object? serviceKey); } public interface IServiceProviderIsService { bool IsService(Type serviceType); } public interface IServiceScope : IDisposable { IServiceProvider ServiceProvider { get; } } public interface IServiceScopeFactory { IServiceScope CreateScope(); } public interface ISupportRequiredService { object GetRequiredService(Type serviceType); } public delegate object ObjectFactory(IServiceProvider serviceProvider, object?[]? arguments); public delegate T ObjectFactory<T>(IServiceProvider serviceProvider, object?[]? arguments); [DebuggerDisplay("{DebuggerToString(),nq}")] [DebuggerTypeProxy(typeof(ServiceCollectionDebugView))] public class ServiceCollection : IServiceCollection, IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable { private sealed class ServiceCollectionDebugView { private readonly ServiceCollection _services; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public ServiceDescriptor[] Items { get { ServiceDescriptor[] array = new ServiceDescriptor[_services.Count]; _services.CopyTo(array, 0); return array; } } public ServiceCollectionDebugView(ServiceCollection services) { _services = services; } } private readonly List<ServiceDescriptor> _descriptors = new List<ServiceDescriptor>(); private bool _isReadOnly; public int Count => _descriptors.Count; public bool IsReadOnly => _isReadOnly; public ServiceDescriptor this[int index] { get { return _descriptors[index]; } set { CheckReadOnly(); _descriptors[index] = value; } } public void Clear() { CheckReadOnly(); _descriptors.Clear(); } public bool Contains(ServiceDescriptor item) { return _descriptors.Contains(item); } public void CopyTo(ServiceDescriptor[] array, int arrayIndex) { _descriptors.CopyTo(array, arrayIndex); } public bool Remove(ServiceDescriptor item) { CheckReadOnly(); return _descriptors.Remove(item); } public IEnumerator<ServiceDescriptor> GetEnumerator() { return _descriptors.GetEnumerator(); } void ICollection<ServiceDescriptor>.Add(ServiceDescriptor item) { CheckReadOnly(); _descriptors.Add(item); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int IndexOf(ServiceDescriptor item) { return _descriptors.IndexOf(item); } public void Insert(int index, ServiceDescriptor item) { CheckReadOnly(); _descriptors.Insert(index, item); } public void RemoveAt(int index) { CheckReadOnly(); _descriptors.RemoveAt(index); } public void MakeReadOnly() { _isReadOnly = true; } private void CheckReadOnly() { if (_isReadOnly) { ThrowReadOnlyException(); } } private static void ThrowReadOnlyException() { throw new InvalidOperationException(System.SR.ServiceCollectionReadOnly); } private string DebuggerToString() { string text = $"Count = {_descriptors.Count}"; if (_isReadOnly) { text += ", IsReadOnly = true"; } return text; } } public static class ServiceCollectionServiceExtensions { public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); } public static IServiceCollection AddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddTransient(serviceType, serviceType); } public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService)); } public static IServiceCollection AddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddScoped(serviceType, serviceType); } public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService)); } public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddSingleton(serviceType, serviceType); } public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService)); } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, object implementationInstance) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationInstance); services.Add(item); return services; } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return services.AddSingleton(typeof(TService), implementationInstance); } private static IServiceCollection Add(IServiceCollection collection, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationType, lifetime); collection.Add(item); return collection; } private static IServiceCollection Add(IServiceCollection collection, Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationFactory, lifetime); collection.Add(item); return collection; } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Transient); } public static IServiceCollection AddKeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedTransient(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedTransient(typeof(TService), serviceKey); } public static IServiceCollection AddKeyedTransient<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedTransient<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static IServiceCollection AddKeyedScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedScoped(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedScoped(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedScoped(typeof(TService), serviceKey); } public static IServiceCollection AddKeyedScoped<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedScoped<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static IServiceCollection AddKeyedSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedSingleton(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TService)); } public static IServiceCollection AddKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, object implementationInstance) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationInstance); services.Add(item); return services; } public static IServiceCollection AddKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationInstance); } private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime); collection.Add(item); return collection; } private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, Func<IServiceProvider, object, object> implementationFactory, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime); collection.Add(item); return collection; } } [DebuggerDisplay("{DebuggerToString(),nq}")] public class ServiceDescriptor { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] private Type _implementationType; private object _implementationInstance; private object _implementationFactory; public ServiceLifetime Lifetime { get; } public object? ServiceKey { get; } public Type ServiceType { get; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public Type? ImplementationType { get { if (!IsKeyedService) { return _implementationType; } return null; } } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public Type? KeyedImplementationType { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return _implementationType; } } public object? ImplementationInstance { get { if (!IsKeyedService) { return _implementationInstance; } return null; } } public object? KeyedImplementationInstance { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return _implementationInstance; } } public Func<IServiceProvider, object>? ImplementationFactory { get { if (!IsKeyedService) { return (Func<IServiceProvider, object>)_implementationFactory; } return null; } } public Func<IServiceProvider, object?, object>? KeyedImplementationFactory { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return (Func<IServiceProvider, object, object>)_implementationFactory; } } public bool IsKeyedService => ServiceKey != null; public ServiceDescriptor(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) : this(serviceType, null, implementationType, lifetime) { } public ServiceDescriptor(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) : this(serviceType, serviceKey, lifetime) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); _implementationType = implementationType; } public ServiceDescriptor(Type serviceType, object instance) : this(serviceType, null, instance) { } public ServiceDescriptor(Type serviceType, object? serviceKey, object instance) : this(serviceType, serviceKey, ServiceLifetime.Singleton) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(instance, "instance"); _implementationInstance = instance; } public ServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime) : this(serviceType, (object)null, lifetime) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(factory, "factory"); _implementationFactory = factory; } public ServiceDescriptor(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> factory, ServiceLifetime lifetime) { Func<IServiceProvider, object, object> factory2 = factory; this..ctor(serviceType, serviceKey, lifetime); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(factory2, "factory"); if (serviceKey == null) { Func<IServiceProvider, object> implementationFactory = (IServiceProvider sp) => factory2(sp, null); _implementationFactory = implementationFactory; } else { _implementationFactory = factory2; } } private ServiceDescriptor(Type serviceType, object serviceKey, ServiceLifetime lifetime) { Lifetime = lifetime; ServiceType = serviceType; ServiceKey = serviceKey; } public override string ToString() { string text = string.Format("{0}: {1} {2}: {3} ", "ServiceType", ServiceType, "Lifetime", Lifetime); if (IsKeyedService) { text += string.Format("{0}: {1} ", "ServiceKey", ServiceKey); if (KeyedImplementationType != null) { return text + string.Format("{0}: {1}", "KeyedImplementationType", KeyedImplementationType); } if (KeyedImplementationFactory != null) { return text + string.Format("{0}: {1}", "KeyedImplementationFactory", KeyedImplementationFactory.Method); } return text + string.Format("{0}: {1}", "KeyedImplementationInstance", KeyedImplementationInstance); } if (ImplementationType != null) { return text + string.Format("{0}: {1}", "ImplementationType", ImplementationType); } if (ImplementationFactory != null) { return text + string.Format("{0}: {1}", "ImplementationFactory", ImplementationFactory.Method); } return text + string.Format("{0}: {1}", "ImplementationInstance", ImplementationInstance); } internal Type GetImplementationType() { if (ServiceKey == null) { if (ImplementationType != null) { return ImplementationType; } if (ImplementationInstance != null) { return ImplementationInstance.GetType(); } if (ImplementationFactory != null) { Type[] genericTypeArguments = ImplementationFactory.GetType().GenericTypeArguments; return genericTypeArguments[1]; } } else { if (KeyedImplementationType != null) { return KeyedImplementationType; } if (KeyedImplementationInstance != null) { return KeyedImplementationInstance.GetType(); } if (KeyedImplementationFactory != null) { Type[] genericTypeArguments2 = KeyedImplementationFactory.GetType().GenericTypeArguments; return genericTypeArguments2[2]; } } return null; } public static ServiceDescriptor Transient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Scoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { return Describe(service, implementationType, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Singleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return Singleton(typeof(TService), implementationInstance); } public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return KeyedSingleton(typeof(TService), serviceKey, implementationInstance); } public static ServiceDescriptor Singleton(Type serviceType, object implementationInstance) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, implementationInstance); } public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, object implementationInstance) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, serviceKey, implementationInstance); } private static ServiceDescriptor DescribeKeyed<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object serviceKey, ServiceLifetime lifetime) where TService : class where TImplementation : class, TService { return DescribeKeyed(typeof(TService), serviceKey, typeof(TImplementation), lifetime); } public static ServiceDescriptor Describe(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationType, lifetime); } public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime); } public static ServiceDescriptor Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationFactory, lifetime); } public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime); } private string DebuggerToString() { string text = $"Lifetime = {Lifetime}, ServiceType = \"{ServiceType.FullName}\""; if (IsKeyedService) { text += $", ServiceKey = \"{ServiceKey}\""; if (KeyedImplementationType != null) { return text + ", KeyedImplementationType = \"" + KeyedImplementationType.FullName + "\""; } if (KeyedImplementationFactory != null) { return text + $", KeyedImplementationFactory = {KeyedImplementationFactory.Method}"; } return text + $", KeyedImplementationInstance = {KeyedImplementationInstance}"; } if (ImplementationType != null) { return text + ", ImplementationType = \"" + ImplementationType.FullName + "\""; } if (ImplementationFactory != null) { return text + $", ImplementationFactory = {ImplementationFactory.Method}"; } return text + $", ImplementationInstance = {ImplementationInstance}"; } private static void ThrowNonKeyedDescriptor() { throw new InvalidOperationException(System.SR.NonKeyedDescriptorMisuse); } } [AttributeUsage(AttributeTargets.Parameter)] public class ServiceKeyAttribute : Attribute { } public enum ServiceLifetime { Singleton, Scoped, Transient } public static class ServiceProviderKeyedServiceExtensions { public static T? GetKeyedService<T>(this IServiceProvider provider, object? serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return (T)keyedServiceProvider.GetKeyedService(typeof(T), serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static object GetRequiredKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetRequiredKeyedService(serviceType, serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static T GetRequiredKeyedService<T>(this IServiceProvider provider, object? serviceKey) where T : notnull { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey); } public static IEnumerable<T> GetKeyedServices<T>(this IServiceProvider provider, object? serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return provider.GetRequiredKeyedService<IEnumerable<T>>(serviceKey); } [RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")] public static IEnumerable<object?> GetKeyedServices(this IServiceProvider provider, Type serviceType, object? serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable<object>)provider.GetRequiredKeyedService(serviceType2, serviceKey); } } public static class ServiceProviderServiceExtensions { public static T? GetService<T>(this IServiceProvider provider) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetService(typeof(T)); } public static object GetRequiredService(this IServiceProvider provider, Type serviceType) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); if (provider is ISupportRequiredService supportRequiredService) { return supportRequiredService.GetRequiredService(serviceType); } object service = provider.GetService(serviceType); if (service == null) { throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType)); } return service; } public static T GetRequiredService<T>(this IServiceProvider provider) where T : notnull { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredService(typeof(T)); } public static IEnumerable<T> GetServices<T>(this IServiceProvider provider) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return provider.GetRequiredService<IEnumerable<T>>(); } [RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")] public static IEnumerable<object?> GetServices(this IServiceProvider provider, Type serviceType) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable<object>)provider.GetRequiredService(serviceType2); } public static IServiceScope CreateScope(this IServiceProvider provider) { return provider.GetRequiredService<IServiceScopeFactory>().CreateScope(); } public static AsyncServiceScope CreateAsyncScope(this IServiceProvider provider) { return new AsyncServiceScope(provider.CreateScope()); } public static AsyncServiceScope CreateAsyncScope(this IServiceScopeFactory serviceScopeFactory) { return new AsyncServiceScope(serviceScopeFactory.CreateScope()); } } } namespace Microsoft.Extensions.DependencyInjection.Extensions { public static class ServiceCollectionDescriptorExtensions { public static IServiceCollection Add(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); collection.Add(descriptor); return collection; } public static IServiceCollection Add(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.Add(descriptor); } return collection; } public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); int count = collection.Count; for (int i = 0; i < count; i++) { if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey)) { return; } } collection.Add(descriptor); } public static void TryAdd(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.TryAdd(descriptor); } } public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, service); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TService)); } public static void TryAddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TImplementation)); } public static void TryAddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Transient(implementationFactory)); } public static void TryAddScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, service); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TService)); } public static void TryAddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TImplementation)); } public static void TryAddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Scoped(implementationFactory)); } public static void TryAddSingleton(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, service); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TService)); } public static void TryAddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TImplementation)); } public static void TryAddSingleton<TService>(this IServiceCollection collection, TService instance) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(instance, "instance"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(typeof(TService), instance); collection.TryAdd(descriptor); } public static void TryAddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Singleton(implementationFactory)); } public static void TryAddEnumerable(this IServiceCollection services, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); Type implementationType = descriptor.GetImplementationType(); if (implementationType == typeof(object) || implementationType == descriptor.ServiceType) { throw new ArgumentException(System.SR.Format(System.SR.TryAddIndistinguishableTypeToEnumerable, implementationType, descriptor.ServiceType), "descriptor"); } int count = services.Count; for (int i = 0; i < count; i++) { ServiceDescriptor serviceDescriptor = services[i]; if (serviceDescriptor.ServiceType == descriptor.ServiceType && serviceDescriptor.GetImplementationType() == implementationType && object.Equals(serviceDescriptor.ServiceKey, descriptor.ServiceKey)) { return; } } services.Add(descriptor); } public static void TryAddEnumerable(this IServiceCollection services, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { services.TryAddEnumerable(descriptor); } } public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); int count = collection.Count; for (int i = 0; i < count; i++) { if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey)) { collection.RemoveAt(i); break; } } collection.Add(descriptor); return collection; } public static IServiceCollection RemoveAll<T>(this IServiceCollection collection) { return collection.RemoveAll(typeof(T)); } public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); for (int num = collection.Count - 1; num >= 0; num--) { ServiceDescriptor serviceDescriptor = collection[num]; if (serviceDescriptor.ServiceType == serviceType && serviceDescriptor.ServiceKey == null) { collection.RemoveAt(num); } } return collection; } public static void TryAddKeyedTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, service); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient(this IServiceCollection collection, Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationType); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient(this IServiceCollection collection, Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddKeyedTransient(typeof(TService), serviceKey, typeof(TService)); } public static void TryAddKeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection, object? serviceKey) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation)); } public static void TryAddKeyedTransient<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.KeyedTransient(serviceKey, implementationFactory)); } public static void TryAddKeyedScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, service); collection.TryAdd(descriptor); } public static void TryAddKeyedScoped(this IServiceCollection collection, Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, implementationType); collection.TryAdd(descriptor); } public static void TryAddKeyedScoped(this IServiceCollection collection, Type service, object? serviceKey, Func<IServiceProvider, objec
deps/Microsoft.Extensions.Logging.Abstractions.dll
Decompiled a day agousing System; using System.Buffers; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using FxResources.Microsoft.Extensions.Logging.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Logging abstractions for Microsoft.Extensions.Logging.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Logging.ILogger\r\nMicrosoft.Extensions.Logging.ILoggerFactory\r\nMicrosoft.Extensions.Logging.ILogger<TCategoryName>\r\nMicrosoft.Extensions.Logging.LogLevel\r\nMicrosoft.Extensions.Logging.Logger<T>\r\nMicrosoft.Extensions.Logging.LoggerMessage\r\nMicrosoft.Extensions.Logging.Abstractions.NullLogger")] [assembly: AssemblyFileVersion("8.0.1325.6609")] [assembly: AssemblyInformationalVersion("8.0.13+eba546b0f0d448e0176a2222548fd7a2fbf464c0")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] 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] internal sealed class IsByRefLikeAttribute : 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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 FxResources.Microsoft.Extensions.Logging.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull(object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } private static void Throw(string paramName) { throw new ArgumentNullException(paramName); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string IfNullOrWhitespace(string? argument, [CallerArgumentExpression("argument")] string paramName = "") { if (argument == null) { throw new ArgumentNullException(paramName); } if (string.IsNullOrWhiteSpace(argument)) { if (argument == null) { throw new ArgumentNullException(paramName); } throw new ArgumentException(paramName, "Argument is whitespace"); } return argument; } } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string UnexpectedNumberOfNamedParameters => GetResourceString("UnexpectedNumberOfNamedParameters"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } } namespace System.Text { internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span<char> RawChars => _chars; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if ((uint)capacity > (uint)_chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string? s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; Span<char> chars = _chars; if ((uint)pos < (uint)chars.Length) { chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string? s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.AsSpan().CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } Span<char> span = _chars.Slice(_pos, length); for (int i = 0; i < span.Length; i++) { span[i] = *(value++); } _pos += length; } public void Append(ReadOnlySpan<char> value) { int pos = _pos; if (pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<char> AppendSpan(int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } _pos = pos + length; return _chars.Slice(pos, length); } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowAndAppend(char c) { Grow(1); Append(c); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalCapacityBeyondPos) { int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u)); char[] array = ArrayPool<char>.Shared.Rent(minimumLength); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(System.Text.ValueStringBuilder); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } } } namespace Microsoft.Extensions.Internal { internal static class TypeNameHelper { private readonly struct DisplayNameOptions { public bool FullName { get; } public bool IncludeGenericParameters { get; } public bool IncludeGenericParameterNames { get; } public char NestedTypeDelimiter { get; } public DisplayNameOptions(bool fullName, bool includeGenericParameterNames, bool includeGenericParameters, char nestedTypeDelimiter) { FullName = fullName; IncludeGenericParameters = includeGenericParameters; IncludeGenericParameterNames = includeGenericParameterNames; NestedTypeDelimiter = nestedTypeDelimiter; } } private const char DefaultNestedTypeDelimiter = '+'; private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string> { { typeof(void), "void" }, { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(char), "char" }, { typeof(decimal), "decimal" }, { typeof(double), "double" }, { typeof(float), "float" }, { typeof(int), "int" }, { typeof(long), "long" }, { typeof(object), "object" }, { typeof(sbyte), "sbyte" }, { typeof(short), "short" }, { typeof(string), "string" }, { typeof(uint), "uint" }, { typeof(ulong), "ulong" }, { typeof(ushort), "ushort" } }; [return: NotNullIfNotNull("item")] public static string? GetTypeDisplayName(object? item, bool fullName = true) { if (item != null) { return GetTypeDisplayName(item.GetType(), fullName); } return null; } public static string GetTypeDisplayName(Type type, bool fullName = true, bool includeGenericParameterNames = false, bool includeGenericParameters = true, char nestedTypeDelimiter = '+') { StringBuilder builder = null; DisplayNameOptions options = new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter); string text = ProcessType(ref builder, type, in options); return text ?? builder?.ToString() ?? string.Empty; } private static string ProcessType(ref StringBuilder builder, Type type, in DisplayNameOptions options) { string value; if (type.IsGenericType) { Type[] genericArguments = type.GetGenericArguments(); if (builder == null) { builder = new StringBuilder(); } ProcessGenericType(builder, type, genericArguments, genericArguments.Length, in options); } else if (type.IsArray) { if (builder == null) { builder = new StringBuilder(); } ProcessArrayType(builder, type, in options); } else if (_builtInTypeNames.TryGetValue(type, out value)) { if (builder == null) { return value; } builder.Append(value); } else if (type.IsGenericParameter) { if (options.IncludeGenericParameterNames) { if (builder == null) { return type.Name; } builder.Append(type.Name); } } else { string text = (options.FullName ? type.FullName : type.Name); if (builder == null) { if (options.NestedTypeDelimiter != '+') { return text.Replace('+', options.NestedTypeDelimiter); } return text; } builder.Append(text); if (options.NestedTypeDelimiter != '+') { builder.Replace('+', options.NestedTypeDelimiter, builder.Length - text.Length, text.Length); } } return null; } private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options) { Type type2 = type; while (type2.IsArray) { type2 = type2.GetElementType(); } ProcessType(ref builder, type2, in options); while (type.IsArray) { builder.Append('['); builder.Append(',', type.GetArrayRank() - 1); builder.Append(']'); type = type.GetElementType(); } } private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, in DisplayNameOptions options) { int num = 0; if (type.IsNested) { num = type.DeclaringType.GetGenericArguments().Length; } if (options.FullName) { if (type.IsNested) { ProcessGenericType(builder, type.DeclaringType, genericArguments, num, in options); builder.Append(options.NestedTypeDelimiter); } else if (!string.IsNullOrEmpty(type.Namespace)) { builder.Append(type.Namespace); builder.Append('.'); } } int num2 = type.Name.IndexOf('`'); if (num2 <= 0) { builder.Append(type.Name); return; } builder.Append(type.Name, 0, num2); if (!options.IncludeGenericParameters) { return; } builder.Append('<'); for (int i = num; i < length; i++) { ProcessType(ref builder, genericArguments[i], in options); if (i + 1 != length) { builder.Append(','); if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter) { builder.Append(' '); } } } builder.Append('>'); } } } namespace Microsoft.Extensions.Logging { public readonly struct EventId : IEquatable<EventId> { public int Id { get; } public string? Name { get; } public static implicit operator EventId(int i) { return new EventId(i); } public static bool operator ==(EventId left, EventId right) { return left.Equals(right); } public static bool operator !=(EventId left, EventId right) { return !left.Equals(right); } public EventId(int id, string? name = null) { Id = id; Name = name; } public override string ToString() { return Name ?? Id.ToString(); } public bool Equals(EventId other) { return Id == other.Id; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) { return false; } if (obj is EventId other) { return Equals(other); } return false; } public override int GetHashCode() { return Id; } } internal readonly struct FormattedLogValues : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>> { internal const int MaxCachedFormatters = 1024; private const string NullFormat = "[null]"; private static int s_count; private static readonly ConcurrentDictionary<string, LogValuesFormatter> s_formatters = new ConcurrentDictionary<string, LogValuesFormatter>(); private readonly LogValuesFormatter _formatter; private readonly object[] _values; private readonly string _originalMessage; internal LogValuesFormatter? Formatter => _formatter; public KeyValuePair<string, object?> this[int index] { get { if (index < 0 || index >= Count) { throw new IndexOutOfRangeException("index"); } if (index == Count - 1) { return new KeyValuePair<string, object>("{OriginalFormat}", _originalMessage); } return _formatter.GetValue(_values, index); } } public int Count { get { if (_formatter == null) { return 1; } return _formatter.ValueNames.Count + 1; } } public FormattedLogValues(string? format, params object?[]? values) { if (values != null && values.Length != 0 && format != null) { if (s_count >= 1024) { if (!s_formatters.TryGetValue(format, out _formatter)) { _formatter = new LogValuesFormatter(format); } } else { _formatter = s_formatters.GetOrAdd(format, delegate(string f) { Interlocked.Increment(ref s_count); return new LogValuesFormatter(f); }); } } else { _formatter = null; } _originalMessage = format ?? "[null]"; _values = values; } public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { if (_formatter == null) { return _originalMessage; } return _formatter.Format(_values); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public interface IExternalScopeProvider { void ForEachScope<TState>(Action<object?, TState> callback, TState state); IDisposable Push(object? state); } public interface ILogger { void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter); bool IsEnabled(LogLevel logLevel); IDisposable? BeginScope<TState>(TState state) where TState : notnull; } public interface ILoggerFactory : IDisposable { ILogger CreateLogger(string categoryName); void AddProvider(ILoggerProvider provider); } public interface ILoggerProvider : IDisposable { ILogger CreateLogger(string categoryName); } public interface ILogger<out TCategoryName> : ILogger { } public interface ILoggingBuilder { IServiceCollection Services { get; } } public interface ISupportExternalScope { void SetScopeProvider(IExternalScopeProvider scopeProvider); } public class LogDefineOptions { public bool SkipEnabledCheck { get; set; } } public static class LoggerExtensions { private static readonly Func<FormattedLogValues, Exception, string> _messageFormatter = MessageFormatter; public static void LogDebug(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Debug, eventId, exception, message, args); } public static void LogDebug(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Debug, eventId, message, args); } public static void LogDebug(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Debug, exception, message, args); } public static void LogDebug(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Debug, message, args); } public static void LogTrace(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Trace, eventId, exception, message, args); } public static void LogTrace(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Trace, eventId, message, args); } public static void LogTrace(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Trace, exception, message, args); } public static void LogTrace(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Trace, message, args); } public static void LogInformation(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Information, eventId, exception, message, args); } public static void LogInformation(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Information, eventId, message, args); } public static void LogInformation(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Information, exception, message, args); } public static void LogInformation(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Information, message, args); } public static void LogWarning(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Warning, eventId, exception, message, args); } public static void LogWarning(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Warning, eventId, message, args); } public static void LogWarning(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Warning, exception, message, args); } public static void LogWarning(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Warning, message, args); } public static void LogError(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Error, eventId, exception, message, args); } public static void LogError(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Error, eventId, message, args); } public static void LogError(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Error, exception, message, args); } public static void LogError(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Error, message, args); } public static void LogCritical(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Critical, eventId, exception, message, args); } public static void LogCritical(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Critical, eventId, message, args); } public static void LogCritical(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Critical, exception, message, args); } public static void LogCritical(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Critical, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, string? message, params object?[] args) { logger.Log(logLevel, 0, null, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string? message, params object?[] args) { logger.Log(logLevel, eventId, null, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, Exception? exception, string? message, params object?[] args) { logger.Log(logLevel, 0, exception, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, string? message, params object?[] args) { System.ThrowHelper.ThrowIfNull(logger, "logger"); logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); } public static IDisposable? BeginScope(this ILogger logger, string messageFormat, params object?[] args) { System.ThrowHelper.ThrowIfNull(logger, "logger"); return logger.BeginScope(new FormattedLogValues(messageFormat, args)); } private static string MessageFormatter(FormattedLogValues state, Exception error) { return state.ToString(); } } public class LoggerExternalScopeProvider : IExternalScopeProvider { private sealed class Scope : IDisposable { private readonly LoggerExternalScopeProvider _provider; private bool _isDisposed; public Scope Parent { get; } public object State { get; } internal Scope(LoggerExternalScopeProvider provider, object state, Scope parent) { _provider = provider; State = state; Parent = parent; } public override string ToString() { return State?.ToString(); } public void Dispose() { if (!_isDisposed) { _provider._currentScope.Value = Parent; _isDisposed = true; } } } private readonly AsyncLocal<Scope> _currentScope = new AsyncLocal<Scope>(); public void ForEachScope<TState>(Action<object?, TState> callback, TState state) { Action<object, TState> callback2 = callback; TState state2 = state; Report(_currentScope.Value); void Report(Scope? current) { if (current != null) { Report(current.Parent); callback2(current.State, state2); } } } public IDisposable Push(object? state) { Scope value = _currentScope.Value; Scope scope = new Scope(this, state, value); _currentScope.Value = scope; return scope; } } public static class LoggerFactoryExtensions { public static ILogger<T> CreateLogger<T>(this ILoggerFactory factory) { System.ThrowHelper.ThrowIfNull(factory, "factory"); return new Logger<T>(factory); } public static ILogger CreateLogger(this ILoggerFactory factory, Type type) { System.ThrowHelper.ThrowIfNull(factory, "factory"); System.ThrowHelper.ThrowIfNull(type, "type"); return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.')); } } public static class LoggerMessage { private readonly struct LogValues : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues, Exception, string> Callback = (LogValues state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; public KeyValuePair<string, object> this[int index] { get { if (index == 0) { return new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat); } throw new IndexOutOfRangeException("index"); } } public int Count => 1; public LogValues(LogValuesFormatter formatter) { _formatter = formatter; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { yield return this[0]; } public override string ToString() { return _formatter.Format(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0>, Exception, string> Callback = (LogValues<T0> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public int Count => 2; public LogValues(LogValuesFormatter formatter, T0 value0) { _formatter = formatter; _value0 = value0; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { return _formatter.Format(_value0); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1>, Exception, string> Callback = (LogValues<T0, T1> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public int Count => 3; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1) { _formatter = formatter; _value0 = value0; _value1 = value1; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { return _formatter.Format(_value0, _value1); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2>, Exception, string> Callback = (LogValues<T0, T1, T2> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; public int Count => 4; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; } public override string ToString() { return _formatter.Format(_value0, _value1, _value2); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3>, Exception, string> Callback = (LogValues<T0, T1, T2, T3> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; public int Count => 5; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; } private object[] ToArray() { return new object[4] { _value0, _value1, _value2, _value3 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3, T4> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3, T4>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; private readonly T4 _value4; public int Count => 6; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 5 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; _value4 = value4; } private object[] ToArray() { return new object[5] { _value0, _value1, _value2, _value3, _value4 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3, T4, T5> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3, T4, T5>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4, T5> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; private readonly T4 _value4; private readonly T5 _value5; public int Count => 7; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 5 => new KeyValuePair<string, object>(_formatter.ValueNames[5], _value5), 6 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; _value4 = value4; _value5 = value5; } private object[] ToArray() { return new object[6] { _value0, _value1, _value2, _value3, _value4, _value5 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static Func<ILogger, IDisposable?> DefineScope(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0); LogValues logValues = new LogValues(formatter); return (ILogger logger) => logger.BeginScope(logValues); } public static Func<ILogger, T1, IDisposable?> DefineScope<T1>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1); return (ILogger logger, T1 arg1) => logger.BeginScope(new LogValues<T1>(formatter, arg1)); } public static Func<ILogger, T1, T2, IDisposable?> DefineScope<T1, T2>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2); return (ILogger logger, T1 arg1, T2 arg2) => logger.BeginScope(new LogValues<T1, T2>(formatter, arg1, arg2)); } public static Func<ILogger, T1, T2, T3, IDisposable?> DefineScope<T1, T2, T3>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3) => logger.BeginScope(new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3)); } public static Func<ILogger, T1, T2, T3, T4, IDisposable?> DefineScope<T1, T2, T3, T4>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4) => logger.BeginScope(new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4)); } public static Func<ILogger, T1, T2, T3, T4, T5, IDisposable?> DefineScope<T1, T2, T3, T4, T5>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5)); } public static Func<ILogger, T1, T2, T3, T4, T5, T6, IDisposable?> DefineScope<T1, T2, T3, T4, T5, T6>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6)); } public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString) { return Define(logLevel, eventId, formatString, null); } public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, exception); } }; void Log(ILogger logger, Exception exception) { logger.Log(logLevel, eventId, new LogValues(formatter), exception, LogValues.Callback); } } public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, exception); } }; void Log(ILogger logger, T1 arg1, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1>(formatter, arg1), exception, LogValues<T1>.Callback); } } public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2>(formatter, arg1, arg2), exception, LogValues<T1, T2>.Callback); } } public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3), exception, LogValues<T1, T2, T3>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4), exception, LogValues<T1, T2, T3, T4>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4, T5>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, arg5, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5), exception, LogValues<T1, T2, T3, T4, T5>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4, T5, T6>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, arg5, arg6, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6), exception, LogValues<T1, T2, T3, T4, T5, T6>.Callback); } } private static LogValuesFormatter CreateLogValuesFormatter(string formatString, int expectedNamedParameterCount) { LogValuesFormatter logValuesFormatter = new LogValuesFormatter(formatString); int count = logValuesFormatter.ValueNames.Count; if (count != expectedNamedParameterCount) { throw new ArgumentException(System.SR.Format(System.SR.UnexpectedNumberOfNamedParameters, formatString, expectedNamedParameterCount, count)); } return logValuesFormatter; } } [AttributeUsage(AttributeTargets.Method)] public sealed class LoggerMessageAttribute : Attribute { public int EventId { get; set; } = -1; public string? EventName { get; set; } public LogLevel Level { get; set; } = LogLevel.None; public string Message { get; set; } = ""; public bool SkipEnabledCheck { get; set; } public LoggerMessageAttribute() { } public LoggerMessageAttribute(int eventId, LogLevel level, string message) { EventId = eventId; Level = level; Message = message; } public LoggerMessageAttribute(LogLevel level, string message) { Level = level; Message = message; } public LoggerMessageAttribute(LogLevel level) { Level = level; } public LoggerMessageAttribute(string message) { Message = message; } } [DebuggerDisplay("{DebuggerToString(),nq}")] public class Logger<T> : ILogger<T>, ILogger { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private readonly ILogger _logger; public Logger(ILoggerFactory factory) { System.ThrowHelper.ThrowIfNull(factory, "factory"); _logger = factory.CreateLogger(GetCategoryName()); } IDisposable ILogger.BeginScope<TState>(TState state) { return _logger.BeginScope(state); } bool ILogger.IsEnabled(LogLevel logLevel) { return _logger.IsEnabled(logLevel); } void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { _logger.Log(logLevel, eventId, state, exception, formatter); } private static string GetCategoryName() { return TypeNameHelper.GetTypeDisplayName(typeof(T), fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.'); } internal string DebuggerToString() { return DebuggerDisplayFormatting.DebuggerToString(GetCategoryName(), this); } } public enum LogLevel { Trace, Debug, Information, Warning, Error, Critical, None } internal sealed class LogValuesFormatter { private const string NullValue = "(null)"; private static readonly char[] FormatDelimiters = new char[2] { ',', ':' }; private readonly List<string> _valueNames = new List<string>(); private readonly string _format; public string OriginalFormat { get; private set; } public List<string> ValueNames => _valueNames; public LogValuesFormatter(string format) { System.ThrowHelper.ThrowIfNull(format, "format"); OriginalFormat = format; Span<char> initialBuffer = stackalloc char[256]; System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer); int num = 0; int length = format.Length; while (num < length) { int num2 = FindBraceIndex(format, '{', num, length); if (num == 0 && num2 == length) { _format = format; return; } int num3 = FindBraceIndex(format, '}', num2, length); if (num3 == length) { valueStringBuilder.Append(format.AsSpan(num, length - num)); num = length; continue; } int num4 = FindIndexOfAny(format, FormatDelimiters, num2, num3); valueStringBuilder.Append(format.AsSpan(num, num2 - num + 1)); valueStringBuilder.Append(_valueNames.Count.ToString()); _valueNames.Add(format.Substring(num2 + 1, num4 - num2 - 1)); valueStringBuilder.Append(format.AsSpan(num4, num3 - num4 + 1)); num = num3 + 1; } _format = valueStringBuilder.ToString(); } private static int FindBraceIndex(string format, char brace, int startIndex, int endIndex) { int result = endIndex; int i = startIndex; int num = 0; for (; i < endIndex; i++) { if (num > 0 && format[i] != brace) { if (num % 2 != 0) { break; } num = 0; result = endIndex; } else { if (format[i] != brace) { continue; } if (brace == '}') { if (num == 0) { result = i; } } else { result = i; } num++; } } return result; } private static int FindIndexOfAny(string format, char[] chars, int startIndex, int endIndex) { int num = format.IndexOfAny(chars, startIndex, endIndex - startIndex); if (num != -1) { return num; } return endIndex; } public string Format(object?[]? values) { object[] array = values; if (values != null) { for (int i = 0; i < values.Length; i++) { object obj = FormatArgument(values[i]); if (obj != values[i]) { array = new object[values.Length]; Array.Copy(values, array, i); array[i++] = obj; for (; i < values.Length; i++) { array[i] = FormatArgument(values[i]); } break; } } } return string.Format(CultureInfo.InvariantCulture, _format, array ?? Array.Empty<object>()); } internal string FormatWithOverwrite(object?[]? values) { if (values != null) { for (int i = 0; i < values.Length; i++) { values[i] = FormatArgument(values[i]); } } return string.Format(CultureInfo.InvariantCulture, _format, values ?? Array.Empty<object>()); } internal string Format() { return _format; } internal string Format(object? arg0) { return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0)); } internal string Format(object? arg0, object? arg1) { return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1)); } internal string Format(object? arg0, object? arg1, object? arg2) { return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1), FormatArgument(arg2)); } public KeyValuePair<string, object?> GetValue(object?[] values, int index) { if (index < 0 || index > _valueNames.Count) { throw new IndexOutOfRangeException("index"); } if (_valueNames.Count > index) { return new KeyValuePair<string, object>(_valueNames[index], values[index]); } return new KeyValuePair<string, object>("{OriginalFormat}", OriginalFormat); } public IEnumerable<KeyValuePair<string, object?>> GetValues(object[] values) { KeyValuePair<string, object>[] array = new KeyValuePair<string, object>[values.Length + 1]; for (int i = 0; i != _valueNames.Count; i++) { array[i] = new KeyValuePair<string, object>(_valueNames[i], values[i]); } array[^1] = new KeyValuePair<string, object>("{OriginalFormat}", OriginalFormat); return array; } private static object FormatArgument(object value) { if (!TryFormatArgumentIfNullOrEnumerable(value, out var stringValue)) { return value; } return stringValue; } private static bool TryFormatArgumentIfNullOrEnumerable<T>(T value, [NotNullWhen(true)] out object stringValue) { if (value == null) { stringValue = "(null)"; return true; } if (!(value is string) && (object)value is IEnumerable enumerable) { Span<char> initialBuffer = stackalloc char[256]; System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer); bool flag = true; foreach (object item in enumerable) { if (!flag) { valueStringBuilder.Append(", "); } valueStringBuilder.Append((item != null) ? item.ToString() : "(null)"); flag = false; } stringValue = valueStringBuilder.ToString(); return true; } stringValue = null; return false; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { public static IExternalScopeProvider Instance { get; } = new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : IDisposable { public static NullScope Instance { get; } = new NullScope(); private NullScope() { } public void Dispose() { } } internal static class DebuggerDisplayFormatting { internal static string DebuggerToString(string name, ILogger logger) { LogLevel? logLevel = CalculateEnabledLogLevel(logger); string text = "Name = \"" + name + "\""; if (logLevel.HasValue) { return text + $", MinLevel = {logLevel}"; } return text + ", Enabled = false"; } internal static LogLevel? CalculateEnabledLogLevel(ILogger logger) { Span<LogLevel> span = stackalloc LogLevel[6] { LogLevel.Critical, LogLevel.Error, LogLevel.Warning, LogLevel.Information, LogLevel.Debug, LogLevel.Trace }; ReadOnlySpan<LogLevel> readOnlySpan = span; LogLevel? result = null; ReadOnlySpan<LogLevel> readOnlySpan2 = readOnlySpan; for (int i = 0; i < readOnlySpan2.Length; i++) { LogLevel logLevel = readOnlySpan2[i]; if (!logger.IsEnabled(logLevel)) { break; } result = logLevel; } return result; } } } namespace Microsoft.Extensions.Logging.Abstractions { public readonly struct LogEntry<TState> { public LogLevel LogLevel { get; } public string Category { get; } public EventId EventId { get; } public TState State { get; } public Exception? Exception { get; } public Func<TState, Exception?, string> Formatter { get; } public LogEntry(LogLevel logLevel, string category, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { LogLevel = logLevel; Category = category; EventId = eventId; State = state; Exception = exception; Formatter = formatter; } } public class NullLogger : ILogger { public static NullLogger Instance { get; } = new NullLogger(); private NullLogger() { } public IDisposable BeginScope<TState>(TState state) where TState : notnull { return NullScope.Instance; } public bool IsEnabled(LogLevel logLevel) { return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { } } public class NullLoggerFactory : ILoggerFactory, IDisposable { public static readonly NullLoggerFactory Instance = new NullLoggerFactory(); public ILogger CreateLogger(string name) { return NullLogger.Instance; } public void AddProvider(ILoggerProvider provider) { } public void Dispose() { } } public class NullLoggerProvider : ILoggerProvider, IDisposable { public static NullLoggerProvider Instance { get; } = new NullLoggerProvider(); private NullLoggerProvider() { } public ILogger CreateLogger(string categoryName) { return NullLogger.Instance; } public void Dispose() { } } public class NullLogger<T> : ILogger<T>, ILogger { public static readonly NullLogger<T> Instance = new NullLogger<T>(); public IDisposable BeginScope<TState>(TState state) where TState : notnull { return NullScope.Instance; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { } public bool IsEnabled(LogLevel logLevel) { return false; } } }
deps/Microsoft.Extensions.Primitives.dll
Decompiled a day agousing System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using FxResources.Microsoft.Extensions.Primitives; using Microsoft.CodeAnalysis; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Primitives")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Primitives shared by framework extensions. Commonly used types include:\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Primitives.IChangeToken\r\nMicrosoft.Extensions.Primitives.StringValues\r\nMicrosoft.Extensions.Primitives.StringSegment")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Primitives")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] 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] internal sealed class IsByRefLikeAttribute : 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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 FxResources.Microsoft.Extensions.Primitives { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string Argument_InvalidOffsetLength => GetResourceString("Argument_InvalidOffsetLength"); internal static string Argument_InvalidOffsetLengthStringSegment => GetResourceString("Argument_InvalidOffsetLengthStringSegment"); internal static string Capacity_CannotChangeAfterWriteStarted => GetResourceString("Capacity_CannotChangeAfterWriteStarted"); internal static string Capacity_NotEnough => GetResourceString("Capacity_NotEnough"); internal static string Capacity_NotUsedEntirely => GetResourceString("Capacity_NotUsedEntirely"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Text { internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span<char> RawChars => _chars; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if ((uint)capacity > (uint)_chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; Span<char> chars = _chars; if ((uint)pos < (uint)chars.Length) { chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.AsSpan().CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } Span<char> span = _chars.Slice(_pos, length); for (int i = 0; i < span.Length; i++) { span[i] = *(value++); } _pos += length; } public void Append(ReadOnlySpan<char> value) { int pos = _pos; if (pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<char> AppendSpan(int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } _pos = pos + length; return _chars.Slice(pos, length); } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowAndAppend(char c) { Grow(1); Append(c); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalCapacityBeyondPos) { int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u)); char[] array = ArrayPool<char>.Shared.Rent(minimumLength); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(System.Text.ValueStringBuilder); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } } } namespace System.Numerics.Hashing { internal static class HashHelpers { public static int Combine(int h1, int h2) { uint num = (uint)(h1 << 5) | ((uint)h1 >> 27); return ((int)num + h1) ^ h2; } } } namespace Microsoft.Extensions.FileProviders { internal sealed class EmptyDisposable : IDisposable { public static EmptyDisposable Instance { get; } = new EmptyDisposable(); private EmptyDisposable() { } public void Dispose() { } } } namespace Microsoft.Extensions.Internal { internal static class ChangeCallbackRegistrar { internal static IDisposable UnsafeRegisterChangeCallback<T>(Action<object> callback, object state, CancellationToken token, Action<T> onFailure, T onFailureState) { bool flag = false; if (!ExecutionContext.IsFlowSuppressed()) { ExecutionContext.SuppressFlow(); flag = true; } try { return token.Register(callback, state); } catch (ObjectDisposedException) { onFailure(onFailureState); } finally { if (flag) { ExecutionContext.RestoreFlow(); } } return EmptyDisposable.Instance; } } } namespace Microsoft.Extensions.Primitives { [DebuggerDisplay("HasChanged = {HasChanged}")] public class CancellationChangeToken : IChangeToken { public bool ActiveChangeCallbacks { get; private set; } = true; public bool HasChanged => Token.IsCancellationRequested; private CancellationToken Token { get; } public CancellationChangeToken(CancellationToken cancellationToken) { Token = cancellationToken; } public IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { return ChangeCallbackRegistrar.UnsafeRegisterChangeCallback(callback, state, Token, delegate(CancellationChangeToken s) { s.ActiveChangeCallbacks = false; }, this); } } public static class ChangeToken { private sealed class ChangeTokenRegistration<TState> : IDisposable { private sealed class NoopDisposable : IDisposable { public void Dispose() { } } private readonly Func<IChangeToken> _changeTokenProducer; private readonly Action<TState> _changeTokenConsumer; private readonly TState _state; private IDisposable _disposable; private static readonly NoopDisposable _disposedSentinel = new NoopDisposable(); public ChangeTokenRegistration(Func<IChangeToken> changeTokenProducer, Action<TState> changeTokenConsumer, TState state) { _changeTokenProducer = changeTokenProducer; _changeTokenConsumer = changeTokenConsumer; _state = state; IChangeToken token = changeTokenProducer(); RegisterChangeTokenCallback(token); } private void OnChangeTokenFired() { IChangeToken token = _changeTokenProducer(); try { _changeTokenConsumer(_state); } finally { RegisterChangeTokenCallback(token); } } private void RegisterChangeTokenCallback(IChangeToken token) { if (token != null) { IDisposable disposable = token.RegisterChangeCallback(delegate(object s) { ((ChangeTokenRegistration<TState>)s).OnChangeTokenFired(); }, this); if (token.HasChanged && token.ActiveChangeCallbacks) { disposable?.Dispose(); } else { SetDisposable(disposable); } } } private void SetDisposable(IDisposable disposable) { IDisposable disposable2 = Volatile.Read(ref _disposable); if (disposable2 == _disposedSentinel) { disposable.Dispose(); return; } IDisposable disposable3 = Interlocked.CompareExchange(ref _disposable, disposable, disposable2); if (disposable3 == _disposedSentinel) { disposable.Dispose(); } else if (disposable3 != disposable2) { throw new InvalidOperationException("Somebody else set the _disposable field"); } } public void Dispose() { Interlocked.Exchange(ref _disposable, _disposedSentinel)?.Dispose(); } } public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Action changeTokenConsumer) { if (changeTokenProducer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer); } if (changeTokenConsumer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer); } return new ChangeTokenRegistration<Action>(changeTokenProducer, delegate(Action callback) { callback(); }, changeTokenConsumer); } public static IDisposable OnChange<TState>(Func<IChangeToken?> changeTokenProducer, Action<TState> changeTokenConsumer, TState state) { if (changeTokenProducer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer); } if (changeTokenConsumer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer); } return new ChangeTokenRegistration<TState>(changeTokenProducer, changeTokenConsumer, state); } } [DebuggerDisplay("HasChanged = {HasChanged}")] public class CompositeChangeToken : IChangeToken { private static readonly Action<object> _onChangeDelegate = OnChange; private readonly object _callbackLock = new object(); private CancellationTokenSource _cancellationTokenSource; private List<IDisposable> _disposables; [MemberNotNullWhen(true, "_cancellationTokenSource")] [MemberNotNullWhen(true, "_disposables")] private bool RegisteredCallbackProxy { [MemberNotNullWhen(true, "_cancellationTokenSource")] [MemberNotNullWhen(true, "_disposables")] get; [MemberNotNullWhen(true, "_cancellationTokenSource")] [MemberNotNullWhen(true, "_disposables")] set; } public IReadOnlyList<IChangeToken> ChangeTokens { get; } public bool HasChanged { get { if (_cancellationTokenSource != null && _cancellationTokenSource.Token.IsCancellationRequested) { return true; } for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].HasChanged) { OnChange(this); return true; } } return false; } } public bool ActiveChangeCallbacks { get; } public CompositeChangeToken(IReadOnlyList<IChangeToken> changeTokens) { if (changeTokens == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokens); } ChangeTokens = changeTokens; for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { ActiveChangeCallbacks = true; break; } } } public IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { EnsureCallbacksInitialized(); return _cancellationTokenSource.Token.Register(callback, state); } [MemberNotNull("_cancellationTokenSource")] [MemberNotNull("_disposables")] private void EnsureCallbacksInitialized() { if (RegisteredCallbackProxy) { return; } lock (_callbackLock) { if (RegisteredCallbackProxy) { return; } _cancellationTokenSource = new CancellationTokenSource(); _disposables = new List<IDisposable>(); for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { IDisposable disposable = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this); if (_cancellationTokenSource.IsCancellationRequested) { disposable.Dispose(); break; } _disposables.Add(disposable); } } RegisteredCallbackProxy = true; } } private static void OnChange(object state) { CompositeChangeToken compositeChangeToken = (CompositeChangeToken)state; if (compositeChangeToken._cancellationTokenSource == null) { return; } lock (compositeChangeToken._callbackLock) { if (compositeChangeToken._cancellationTokenSource.IsCancellationRequested) { return; } try { compositeChangeToken._cancellationTokenSource.Cancel(); } catch { } } List<IDisposable> disposables = compositeChangeToken._disposables; for (int i = 0; i < disposables.Count; i++) { disposables[i].Dispose(); } } } public static class Extensions { public static StringBuilder Append(this StringBuilder builder, StringSegment segment) { return builder.Append(segment.Buffer, segment.Offset, segment.Length); } } public interface IChangeToken { bool HasChanged { get; } bool ActiveChangeCallbacks { get; } IDisposable RegisterChangeCallback(Action<object?> callback, object? state); } [DebuggerDisplay("Value = {_value}")] [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This type is retained only for compatibility. The recommended alternative is string.Create<TState> (int length, TState state, System.Buffers.SpanAction<char,TState> action).", true)] public struct InplaceStringBuilder { private int _offset; private int _capacity; private string _value; public int Capacity { get { return _capacity; } set { if (value < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } if (_offset > 0) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_CannotChangeAfterWriteStarted); } _capacity = value; } } public InplaceStringBuilder(int capacity) { this = default(InplaceStringBuilder); if (capacity < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); } _capacity = capacity; } public void Append(string? value) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } Append(value, 0, value.Length); } public void Append(StringSegment segment) { Append(segment.Buffer, segment.Offset, segment.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void Append(string? value, int offset, int count) { EnsureValueIsInitialized(); if (value == null || offset < 0 || value.Length - offset < count || Capacity - _offset < count) { ThrowValidationError(value, offset, count); } fixed (char* ptr = _value) { fixed (char* ptr2 = value) { Unsafe.CopyBlockUnaligned(ptr + _offset, ptr2 + offset, (uint)(count * 2)); _offset += count; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void Append(char c) { EnsureValueIsInitialized(); if (_offset >= Capacity) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotEnough, 1, Capacity - _offset); } fixed (char* ptr = _value) { ptr[_offset++] = c; } } public override string? ToString() { if (Capacity != _offset) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotUsedEntirely, Capacity, _offset); } return _value; } private void EnsureValueIsInitialized() { if (_value == null) { _value = new string('\0', _capacity); } } private void ThrowValidationError(string value, int offset, int count) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (offset < 0 || value.Length - offset < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset); } if (Capacity - _offset < count) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotEnough, value.Length, Capacity - _offset); } } } [DebuggerDisplay("{Value}")] public readonly struct StringSegment : IEquatable<StringSegment>, IEquatable<string?> { public static readonly StringSegment Empty = string.Empty; public string? Buffer { get; } public int Offset { get; } public int Length { get; } public string? Value { get { if (!HasValue) { return null; } return Buffer.Substring(Offset, Length); } } [MemberNotNullWhen(true, "Buffer")] [MemberNotNullWhen(true, "Value")] public bool HasValue { [MemberNotNullWhen(true, "Buffer")] [MemberNotNullWhen(true, "Value")] get { return Buffer != null; } } public char this[int index] { get { if ((uint)index >= (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return Buffer[Offset + index]; } } public StringSegment(string? buffer) { Buffer = buffer; Offset = 0; Length = buffer?.Length ?? 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public StringSegment(string buffer, int offset, int length) { if (buffer == null || (uint)offset > (uint)buffer.Length || (uint)length > (uint)(buffer.Length - offset)) { ThrowInvalidArguments(buffer, offset, length); } Buffer = buffer; Offset = offset; Length = length; } public ReadOnlySpan<char> AsSpan() { return Buffer.AsSpan(Offset, Length); } public ReadOnlySpan<char> AsSpan(int start) { if (!HasValue || start < 0) { ThrowInvalidArguments(start, Length - start, ExceptionArgument.start); } return Buffer.AsSpan(Offset + start, Length - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { if (!HasValue || start < 0 || length < 0 || (uint)(start + length) > (uint)Length) { ThrowInvalidArguments(start, length, ExceptionArgument.start); } return Buffer.AsSpan(Offset + start, length); } public ReadOnlyMemory<char> AsMemory() { return Buffer.AsMemory(Offset, Length); } public static int Compare(StringSegment a, StringSegment b, StringComparison comparisonType) { if (a.HasValue && b.HasValue) { return a.AsSpan().CompareTo(b.AsSpan(), comparisonType); } CheckStringComparison(comparisonType); if (a.HasValue) { return 1; } if (!b.HasValue) { return 0; } return -1; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is StringSegment other) { return Equals(other); } return false; } public bool Equals(StringSegment other) { return Equals(other, StringComparison.Ordinal); } public bool Equals(StringSegment other, StringComparison comparisonType) { if (HasValue && other.HasValue) { return MemoryExtensions.Equals(AsSpan(), other.AsSpan(), comparisonType); } CheckStringComparison(comparisonType); if (!HasValue) { return !other.HasValue; } return false; } public static bool Equals(StringSegment a, StringSegment b, StringComparison comparisonType) { return a.Equals(b, comparisonType); } public bool Equals(string? text) { return Equals(text, StringComparison.Ordinal); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(string? text, StringComparison comparisonType) { if (!HasValue || text == null) { CheckStringComparison(comparisonType); return text == Buffer; } return MemoryExtensions.Equals(AsSpan(), text.AsSpan(), comparisonType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return Value?.GetHashCode() ?? 0; } public static bool operator ==(StringSegment left, StringSegment right) { return left.Equals(right); } public static bool operator !=(StringSegment left, StringSegment right) { return !left.Equals(right); } public static implicit operator StringSegment(string? value) { return new StringSegment(value); } public static implicit operator ReadOnlySpan<char>(StringSegment segment) { return segment.AsSpan(); } public static implicit operator ReadOnlyMemory<char>(StringSegment segment) { return segment.AsMemory(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool StartsWith(string text, StringComparison comparisonType) { if (text == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } if (!HasValue) { CheckStringComparison(comparisonType); return false; } return AsSpan().StartsWith(text.AsSpan(), comparisonType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool EndsWith(string text, StringComparison comparisonType) { if (text == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } if (!HasValue) { CheckStringComparison(comparisonType); return false; } return AsSpan().EndsWith(text.AsSpan(), comparisonType); } public string Substring(int offset) { return Substring(offset, Length - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string Substring(int offset, int length) { if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length) { ThrowInvalidArguments(offset, length, ExceptionArgument.offset); } return Buffer.Substring(Offset + offset, length); } public StringSegment Subsegment(int offset) { return Subsegment(offset, Length - offset); } public StringSegment Subsegment(int offset, int length) { if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length) { ThrowInvalidArguments(offset, length, ExceptionArgument.offset); } return new StringSegment(Buffer, Offset + offset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int IndexOf(char c, int start, int count) { int num = -1; if (HasValue) { if ((uint)start > (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if ((uint)count > (uint)(Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } num = AsSpan(start, count).IndexOf(c); if (num >= 0) { num += start; } } return num; } public int IndexOf(char c, int start) { return IndexOf(c, start, Length - start); } public int IndexOf(char c) { return IndexOf(c, 0, Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int IndexOfAny(char[] anyOf, int startIndex, int count) { int num = -1; if (HasValue) { if ((uint)startIndex > (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if ((uint)count > (uint)(Length - startIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } num = Buffer.IndexOfAny(anyOf, Offset + startIndex, count); if (num != -1) { num -= Offset; } } return num; } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, Length - startIndex); } public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, Length); } public int LastIndexOf(char value) { return AsSpan().LastIndexOf(value); } public StringSegment Trim() { return TrimStart().TrimEnd(); } public StringSegment TrimStart() { ReadOnlySpan<char> readOnlySpan = AsSpan(); int i; for (i = 0; i < readOnlySpan.Length && char.IsWhiteSpace(readOnlySpan[i]); i++) { } return Subsegment(i); } public StringSegment TrimEnd() { ReadOnlySpan<char> readOnlySpan = AsSpan(); int num = readOnlySpan.Length - 1; while (num >= 0 && char.IsWhiteSpace(readOnlySpan[num])) { num--; } return Subsegment(0, num + 1); } public StringTokenizer Split(char[] chars) { return new StringTokenizer(this, chars); } public static bool IsNullOrEmpty(StringSegment value) { bool result = false; if (!value.HasValue || value.Length == 0) { result = true; } return result; } public override string ToString() { return Value ?? string.Empty; } private static void CheckStringComparison(StringComparison comparisonType) { if ((uint)comparisonType > 5u) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.comparisonType); } } [DoesNotReturn] private static void ThrowInvalidArguments(string buffer, int offset, int length) { throw GetInvalidArgumentsException(); Exception GetInvalidArgumentsException() { if (buffer == null) { return ThrowHelper.GetArgumentNullException(ExceptionArgument.buffer); } if (offset < 0) { return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.offset); } if (length < 0) { return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length); } return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLength); } } [DoesNotReturn] private void ThrowInvalidArguments(int offset, int length, ExceptionArgument offsetOrStart) { throw GetInvalidArgumentsException(HasValue); Exception GetInvalidArgumentsException(bool hasValue) { if (!hasValue) { return ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart); } if (offset < 0) { return ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart); } if (length < 0) { return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length); } return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLengthStringSegment); } } } public class StringSegmentComparer : IComparer<StringSegment>, IEqualityComparer<StringSegment> { public static StringSegmentComparer Ordinal { get; } = new StringSegmentComparer(StringComparison.Ordinal, StringComparer.Ordinal); public static StringSegmentComparer OrdinalIgnoreCase { get; } = new StringSegmentComparer(StringComparison.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); private StringComparison Comparison { get; } private StringComparer Comparer { get; } private StringSegmentComparer(StringComparison comparison, StringComparer comparer) { Comparison = comparison; Comparer = comparer; } public int Compare(StringSegment x, StringSegment y) { return StringSegment.Compare(x, y, Comparison); } public bool Equals(StringSegment x, StringSegment y) { return StringSegment.Equals(x, y, Comparison); } public int GetHashCode(StringSegment obj) { if (!obj.HasValue) { return 0; } return Comparer.GetHashCode(obj.Value); } } public readonly struct StringTokenizer : IEnumerable<StringSegment>, IEnumerable { public struct Enumerator : IEnumerator<StringSegment>, IEnumerator, IDisposable { private readonly StringSegment _value; private readonly char[] _separators; private int _index; public StringSegment Current { get; private set; } object IEnumerator.Current => Current; internal Enumerator(in StringSegment value, char[] separators) { _value = value; _separators = separators; Current = default(StringSegment); _index = 0; } public Enumerator(ref StringTokenizer tokenizer) { _value = tokenizer._value; _separators = tokenizer._separators; Current = default(StringSegment); _index = 0; } public void Dispose() { } public bool MoveNext() { if (!_value.HasValue || _index > _value.Length) { Current = default(StringSegment); return false; } int num = _value.IndexOfAny(_separators, _index); if (num == -1) { num = _value.Length; } Current = _value.Subsegment(_index, num - _index); _index = num + 1; return true; } public void Reset() { Current = default(StringSegment); _index = 0; } } private readonly StringSegment _value; private readonly char[] _separators; public StringTokenizer(string value, char[] separators) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (separators == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators); } _value = value; _separators = separators; } public StringTokenizer(StringSegment value, char[] separators) { if (!value.HasValue) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (separators == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators); } _value = value; _separators = separators; } public Enumerator GetEnumerator() { return new Enumerator(in _value, _separators); } IEnumerator<StringSegment> IEnumerable<StringSegment>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [DebuggerDisplay("{ToString()}")] [DebuggerTypeProxy(typeof(StringValuesDebugView))] public readonly struct StringValues : IList<string?>, ICollection<string?>, IEnumerable<string?>, IEnumerable, IReadOnlyList<string?>, IReadOnlyCollection<string?>, IEquatable<StringValues>, IEquatable<string?>, IEquatable<string?[]?> { public struct Enumerator : IEnumerator<string?>, IEnumerator, IDisposable { private readonly string[] _values; private int _index; private string _current; public string? Current => _current; object? IEnumerator.Current => _current; internal Enumerator(object value) { if (value is string current) { _values = null; _current = current; } else { _current = null; _values = Unsafe.As<string[]>(value); } _index = 0; } public Enumerator(ref StringValues values) : this(values._values) { } public bool MoveNext() { int index = _index; if (index < 0) { return false; } string[] values = _values; if (values != null) { if ((uint)index < (uint)values.Length) { _index = index + 1; _current = values[index]; return true; } _index = -1; return false; } _index = -1; return _current != null; } void IEnumerator.Reset() { throw new NotSupportedException(); } public void Dispose() { } } private sealed class StringValuesDebugView { [CompilerGenerated] private StringValues <values>P; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public string[] Items => <values>P.ToArray(); public StringValuesDebugView(StringValues values) { <values>P = values; base..ctor(); } } public static readonly StringValues Empty = new StringValues(Array.Empty<string>()); private readonly object _values; public int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object values = _values; if (values == null) { return 0; } if (values is string) { return 1; } return Unsafe.As<string[]>(values).Length; } } bool ICollection<string>.IsReadOnly => true; string? IList<string>.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } public string? this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object values = _values; if (values is string result) { if (index == 0) { return result; } } else if (values != null) { return Unsafe.As<string[]>(values)[index]; } return OutOfBounds(); } } public StringValues(string? value) { _values = value; } public StringValues(string?[]? values) { _values = values; } public static implicit operator StringValues(string? value) { return new StringValues(value); } public static implicit operator StringValues(string?[]? values) { return new StringValues(values); } public static implicit operator string?(StringValues values) { return values.GetStringValue(); } public static implicit operator string?[]?(StringValues value) { return value.GetArrayValue(); } [MethodImpl(MethodImplOptions.NoInlining)] private static string OutOfBounds() { return Array.Empty<string>()[0]; } public override string ToString() { return GetStringValue() ?? string.Empty; } private string GetStringValue() { object values2 = _values; if (values2 is string result) { return result; } return GetStringValueFromArray(values2); static string GetJoinedStringValueFromArray(string[] values) { int num = 0; foreach (string text in values) { if (text != null && text.Length > 0) { if (num > 0) { num++; } num += text.Length; } } System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(num); bool flag = false; foreach (string text2 in values) { if (text2 != null && text2.Length > 0) { if (flag) { valueStringBuilder.Append(','); } valueStringBuilder.Append(text2); flag = true; } } return valueStringBuilder.ToString(); } static string GetStringValueFromArray(object value) { if (value == null) { return null; } string[] array = Unsafe.As<string[]>(value); return array.Length switch { 0 => null, 1 => array[0], _ => GetJoinedStringValueFromArray(array), }; } } public string?[] ToArray() { return GetArrayValue() ?? Array.Empty<string>(); } private string[] GetArrayValue() { object values = _values; if (values is string[] result) { return result; } if (values != null) { return new string[1] { Unsafe.As<string>(values) }; } return null; } int IList<string>.IndexOf(string item) { return IndexOf(item); } private int IndexOf(string item) { object values = _values; if (values is string[] array) { for (int i = 0; i < array.Length; i++) { if (string.Equals(array[i], item, StringComparison.Ordinal)) { return i; } } return -1; } if (values != null) { if (!string.Equals(Unsafe.As<string>(values), item, StringComparison.Ordinal)) { return -1; } return 0; } return -1; } bool ICollection<string>.Contains(string item) { return IndexOf(item) >= 0; } void ICollection<string>.CopyTo(string[] array, int arrayIndex) { CopyTo(array, arrayIndex); } private void CopyTo(string[] array, int arrayIndex) { object values = _values; if (values is string[] array2) { Array.Copy(array2, 0, array, arrayIndex, array2.Length); } else if (values != null) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex"); } if (array.Length - arrayIndex < 1) { throw new ArgumentException("'array' is not long enough to copy all the items in the collection. Check 'arrayIndex' and 'array' length."); } array[arrayIndex] = Unsafe.As<string>(values); } } void ICollection<string>.Add(string item) { throw new NotSupportedException(); } void IList<string>.Insert(int index, string item) { throw new NotSupportedException(); } bool ICollection<string>.Remove(string item) { throw new NotSupportedException(); } void IList<string>.RemoveAt(int index) { throw new NotSupportedException(); } void ICollection<string>.Clear() { throw new NotSupportedException(); } public Enumerator GetEnumerator() { return new Enumerator(_values); } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public static bool IsNullOrEmpty(StringValues value) { object values = value._values; if (values == null) { return true; } if (values is string[] array) { return array.Length switch { 0 => true, 1 => string.IsNullOrEmpty(array[0]), _ => false, }; } return string.IsNullOrEmpty(Unsafe.As<string>(values)); } public static StringValues Concat(StringValues values1, StringValues values2) { int count = values1.Count; int count2 = values2.Count; if (count == 0) { return values2; } if (count2 == 0) { return values1; } string[] array = new string[count + count2]; values1.CopyTo(array, 0); values2.CopyTo(array, count); return new StringValues(array); } public static StringValues Concat(in StringValues values, string? value) { if (value == null) { return values; } int count = values.Count; if (count == 0) { return new StringValues(value); } string[] array = new string[count + 1]; values.CopyTo(array, 0); array[count] = value; return new StringValues(array); } public static StringValues Concat(string? value, in StringValues values) { if (value == null) { return values; } int count = values.Count; if (count == 0) { return new StringValues(value); } string[] array = new string[count + 1]; array[0] = value; values.CopyTo(array, 1); return new StringValues(array); } public static bool Equals(StringValues left, StringValues right) { int count = left.Count; if (count != right.Count) { return false; } for (int i = 0; i < count; i++) { if (left[i] != right[i]) { return false; } } return true; } public static bool operator ==(StringValues left, StringValues right) { return Equals(left, right); } public static bool operator !=(StringValues left, StringValues right) { return !Equals(left, right); } public bool Equals(StringValues other) { return Equals(this, other); } public static bool Equals(string? left, StringValues right) { return Equals(new StringValues(left), right); } public static bool Equals(StringValues left, string? right) { return Equals(left, new StringValues(right)); } public bool Equals(string? other) { return Equals(this, new StringValues(other)); } public static bool Equals(string?[]? left, StringValues right) { return Equals(new StringValues(left), right); } public static bool Equals(StringValues left, string?[]? right) { return Equals(left, new StringValues(right)); } public bool Equals(string?[]? other) { return Equals(this, new StringValues(other)); } public static bool operator ==(StringValues left, string? right) { return Equals(left, new StringValues(right)); } public static bool operator !=(StringValues left, string? right) { return !Equals(left, new StringValues(right)); } public static bool operator ==(string? left, StringValues right) { return Equals(new StringValues(left), right); } public static bool operator !=(string? left, StringValues right) { return !Equals(new StringValues(left), right); } public static bool operator ==(StringValues left, string?[]? right) { return Equals(left, new StringValues(right)); } public static bool operator !=(StringValues left, string?[]? right) { return !Equals(left, new StringValues(right)); } public static bool operator ==(string?[]? left, StringValues right) { return Equals(new StringValues(left), right); } public static bool operator !=(string?[]? left, StringValues right) { return !Equals(new StringValues(left), right); } public static bool operator ==(StringValues left, object? right) { return left.Equals(right); } public static bool operator !=(StringValues left, object? right) { return !left.Equals(right); } public static bool operator ==(object? left, StringValues right) { return right.Equals(left); } public static bool operator !=(object? left, StringValues right) { return !right.Equals(left); } public override bool Equals(object? obj) { if (obj == null) { return Equals(this, Empty); } if (obj is string right) { return Equals(this, right); } if (obj is string[] right2) { return Equals(this, right2); } if (obj is StringValues right3) { return Equals(this, right3); } return false; } public override int GetHashCode() { object values = _values; if (values is string[] array) { if (Count == 1) { return Unsafe.As<string>(this[0])?.GetHashCode() ?? Count.GetHashCode(); } int num = 0; for (int i = 0; i < array.Length; i++) { num = HashHelpers.Combine(num, array[i]?.GetHashCode() ?? 0); } return num; } return Unsafe.As<string>(values)?.GetHashCode() ?? Count.GetHashCode(); } } internal static class ThrowHelper { [DoesNotReturn] internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw new ArgumentNullException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentException(ExceptionResource resource) { throw new ArgumentException(GetResourceText(resource)); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource) { throw new InvalidOperationException(GetResourceText(resource)); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource, params object[] args) { string message = string.Format(GetResourceText(resource), args); throw new InvalidOperationException(message); } internal static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument) { return new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceText(resource)); } private static string GetResourceText(ExceptionResource resource) { return resource switch { ExceptionResource.Argument_InvalidOffsetLength => System.SR.Argument_InvalidOffsetLength, ExceptionResource.Argument_InvalidOffsetLengthStringSegment => System.SR.Argument_InvalidOffsetLengthStringSegment, ExceptionResource.Capacity_CannotChangeAfterWriteStarted => System.SR.Capacity_CannotChangeAfterWriteStarted, ExceptionResource.Capacity_NotEnough => System.SR.Capacity_NotEnough, ExceptionResource.Capacity_NotUsedEntirely => System.SR.Capacity_NotUsedEntirely, _ => "", }; } private static string GetArgumentName(ExceptionArgument argument) { return argument.ToString(); } } internal enum ExceptionArgument { buffer, offset, length, text, start, count, index, value, capacity, separators, comparisonType, changeTokens, changeTokenProducer, changeTokenConsumer, array } internal enum ExceptionResource { Argument_InvalidOffsetLength, Argument_InvalidOffsetLengthStringSegment, Capacity_CannotChangeAfterWriteStarted, Capacity_NotEnough, Capacity_NotUsedEntirely } }
deps/Microsoft.Win32.Registry.dll
Decompiled a day agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.AccessControl; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Microsoft.Win32.Registry")] [assembly: AssemblyDescription("Microsoft.Win32.Registry")] [assembly: AssemblyDefaultAlias("Microsoft.Win32.Registry")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyInformationalVersion("4.0.0.0")] [assembly: AssemblyFileVersion("4.0.0.0")] [assembly: AssemblyVersion("4.1.0.0")] [assembly: TypeForwardedTo(typeof(Registry))] [assembly: TypeForwardedTo(typeof(RegistryHive))] [assembly: TypeForwardedTo(typeof(RegistryKey))] [assembly: TypeForwardedTo(typeof(RegistryKeyPermissionCheck))] [assembly: TypeForwardedTo(typeof(RegistryOptions))] [assembly: TypeForwardedTo(typeof(RegistryValueKind))] [assembly: TypeForwardedTo(typeof(RegistryValueOptions))] [assembly: TypeForwardedTo(typeof(RegistryView))] [assembly: TypeForwardedTo(typeof(SafeRegistryHandle))] [assembly: TypeForwardedTo(typeof(RegistryAccessRule))] [assembly: TypeForwardedTo(typeof(RegistryAuditRule))] [assembly: TypeForwardedTo(typeof(RegistryRights))] [assembly: TypeForwardedTo(typeof(RegistrySecurity))]
deps/Mono.Posix.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Mono.Unix; using Mono.Unix.Native; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Mono.Posix.dll")] [assembly: AssemblyDescription("Unix Integration Classes")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyDelaySign(true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal sealed class Locale { private Locale() { } public static string GetText(string msg) { return msg; } public static string GetText(string fmt, params object[] args) { return string.Format(fmt, args); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Delegate)] internal class MapAttribute : Attribute { private string nativeType; private string suppressFlags; public string NativeType => nativeType; public string SuppressFlags { get { return suppressFlags; } set { suppressFlags = value; } } public MapAttribute() { } public MapAttribute(string nativeType) { this.nativeType = nativeType; } } namespace Mono.Unix { [Serializable] public class AbstractUnixEndPoint : EndPoint { private string path; public string Path { get { return path; } set { path = value; } } public override AddressFamily AddressFamily => AddressFamily.Unix; public AbstractUnixEndPoint(string path) { if (path == null) { throw new ArgumentNullException("path"); } if (path == "") { throw new ArgumentException("Cannot be empty.", "path"); } this.path = path; } public override EndPoint Create(SocketAddress socketAddress) { byte[] array = new byte[socketAddress.Size - 2 - 1]; for (int i = 0; i < array.Length; i++) { array[i] = socketAddress[3 + i]; } return new AbstractUnixEndPoint(Encoding.Default.GetString(array)); } public override SocketAddress Serialize() { byte[] bytes = Encoding.Default.GetBytes(path); SocketAddress socketAddress = new SocketAddress(AddressFamily, 3 + bytes.Length); socketAddress[2] = 0; for (int i = 0; i < bytes.Length; i++) { socketAddress[i + 2 + 1] = bytes[i]; } return socketAddress; } public override string ToString() { return path; } public override int GetHashCode() { return path.GetHashCode(); } public override bool Equals(object o) { if (!(o is AbstractUnixEndPoint abstractUnixEndPoint)) { return false; } return abstractUnixEndPoint.path == path; } } public class Catalog { private Catalog() { } [DllImport("intl", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr bindtextdomain(IntPtr domainname, IntPtr dirname); [DllImport("intl", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr bind_textdomain_codeset(IntPtr domainname, IntPtr codeset); [DllImport("intl", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr textdomain(IntPtr domainname); public static void Init(string package, string localedir) { MarshalStrings(package, out var p, localedir, out var p2, "UTF-8", out var p3); try { if (bindtextdomain(p, p2) == IntPtr.Zero) { throw new UnixIOException(Errno.ENOMEM); } if (bind_textdomain_codeset(p, p3) == IntPtr.Zero) { throw new UnixIOException(Errno.ENOMEM); } if (textdomain(p) == IntPtr.Zero) { throw new UnixIOException(Errno.ENOMEM); } } finally { UnixMarshal.FreeHeap(p); UnixMarshal.FreeHeap(p2); UnixMarshal.FreeHeap(p3); } } private static void MarshalStrings(string s1, out IntPtr p1, string s2, out IntPtr p2, string s3, out IntPtr p3) { p1 = (p2 = (p3 = IntPtr.Zero)); bool flag = true; try { p1 = UnixMarshal.StringToHeap(s1); p2 = UnixMarshal.StringToHeap(s2); if (s3 != null) { p3 = UnixMarshal.StringToHeap(s3); } flag = false; } finally { if (flag) { UnixMarshal.FreeHeap(p1); UnixMarshal.FreeHeap(p2); UnixMarshal.FreeHeap(p3); } } } [DllImport("intl", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr gettext(IntPtr instring); public static string GetString(string s) { IntPtr intPtr = UnixMarshal.StringToHeap(s); try { IntPtr intPtr2 = gettext(intPtr); if (intPtr2 != intPtr) { return UnixMarshal.PtrToStringUnix(intPtr2); } return s; } finally { UnixMarshal.FreeHeap(intPtr); } } [DllImport("intl", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr ngettext(IntPtr singular, IntPtr plural, int n); public static string GetPluralString(string s, string p, int n) { MarshalStrings(s, out var p2, p, out var p3, null, out var _); try { IntPtr intPtr = ngettext(p2, p3, n); if (intPtr == p2) { return s; } if (intPtr == p3) { return p; } return UnixMarshal.PtrToStringUnix(intPtr); } finally { UnixMarshal.FreeHeap(p2); UnixMarshal.FreeHeap(p3); } } } public enum FileAccessPattern { Normal = 0, Sequential = 2, Random = 1, NoReuse = 5, PreLoad = 3, FlushCache = 4 } [Flags] public enum FileAccessPermissions { UserReadWriteExecute = 0x1C0, UserRead = 0x100, UserWrite = 0x80, UserExecute = 0x40, GroupReadWriteExecute = 0x38, GroupRead = 0x20, GroupWrite = 0x10, GroupExecute = 8, OtherReadWriteExecute = 7, OtherRead = 4, OtherWrite = 2, OtherExecute = 1, DefaultPermissions = 0x1B6, AllPermissions = 0x1FF } public sealed class FileHandleOperations { private FileHandleOperations() { } public static void AdviseFileAccessPattern(int fd, FileAccessPattern pattern, long offset, long len) { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.posix_fadvise(fd, offset, len, (PosixFadviseAdvice)pattern)); } public static void AdviseFileAccessPattern(int fd, FileAccessPattern pattern) { AdviseFileAccessPattern(fd, pattern, 0L, 0L); } public static void AdviseFileAccessPattern(FileStream file, FileAccessPattern pattern, long offset, long len) { if (file == null) { throw new ArgumentNullException("file"); } UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.posix_fadvise(file.Handle.ToInt32(), offset, len, (PosixFadviseAdvice)pattern)); } public static void AdviseFileAccessPattern(FileStream file, FileAccessPattern pattern) { AdviseFileAccessPattern(file, pattern, 0L, 0L); } public static void AdviseFileAccessPattern(UnixStream stream, FileAccessPattern pattern, long offset, long len) { if (stream == null) { throw new ArgumentNullException("stream"); } UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.posix_fadvise(stream.Handle, offset, len, (PosixFadviseAdvice)pattern)); } public static void AdviseFileAccessPattern(UnixStream stream, FileAccessPattern pattern) { AdviseFileAccessPattern(stream, pattern, 0L, 0L); } } [Flags] public enum FileSpecialAttributes { SetUserId = 0x800, SetGroupId = 0x400, Sticky = 0x200 } public enum FileTypes { Directory = 16384, CharacterDevice = 8192, BlockDevice = 24576, RegularFile = 32768, Fifo = 4096, SymbolicLink = 40960, Socket = 49152 } internal struct PeerCredData { public int pid; public int uid; public int gid; } public class PeerCred { private const int so_peercred = 10001; private PeerCredData data; public int ProcessID => data.pid; public int UserID => data.uid; public int GroupID => data.gid; public PeerCred(Socket sock) { if (sock.AddressFamily != AddressFamily.Unix) { throw new ArgumentException("Only Unix sockets are supported", "sock"); } data = (PeerCredData)sock.GetSocketOption(SocketOptionLevel.Socket, (SocketOptionName)10001); } } public class StdioFileStream : Stream { public static readonly IntPtr InvalidFileStream = IntPtr.Zero; public static readonly IntPtr StandardInput = Stdlib.stdin; public static readonly IntPtr StandardOutput = Stdlib.stdout; public static readonly IntPtr StandardError = Stdlib.stderr; private bool canSeek; private bool canRead; private bool canWrite; private bool owner = true; private IntPtr file = InvalidFileStream; public IntPtr Handle { get { AssertNotDisposed(); GC.KeepAlive(this); return file; } } public override bool CanRead => canRead; public override bool CanSeek => canSeek; public override bool CanWrite => canWrite; public override long Length { get { AssertNotDisposed(); if (!CanSeek) { throw new NotSupportedException("File Stream doesn't support seeking"); } long num = Stdlib.ftell(file); if (num == -1) { throw new NotSupportedException("Unable to obtain current file position"); } UnixMarshal.ThrowExceptionForLastErrorIf(Stdlib.fseek(file, 0L, SeekFlags.SEEK_END)); long num2 = Stdlib.ftell(file); if (num2 == -1) { UnixMarshal.ThrowExceptionForLastError(); } UnixMarshal.ThrowExceptionForLastErrorIf(Stdlib.fseek(file, num, SeekFlags.SEEK_SET)); GC.KeepAlive(this); return num2; } } public override long Position { get { AssertNotDisposed(); if (!CanSeek) { throw new NotSupportedException("The stream does not support seeking"); } long num = Stdlib.ftell(file); if (num == -1) { UnixMarshal.ThrowExceptionForLastError(); } GC.KeepAlive(this); return num; } set { AssertNotDisposed(); Seek(value, SeekOrigin.Begin); } } public StdioFileStream(IntPtr fileStream) : this(fileStream, ownsHandle: true) { } public StdioFileStream(IntPtr fileStream, bool ownsHandle) { InitStream(fileStream, ownsHandle); } public StdioFileStream(IntPtr fileStream, FileAccess access) : this(fileStream, access, ownsHandle: true) { } public StdioFileStream(IntPtr fileStream, FileAccess access, bool ownsHandle) { InitStream(fileStream, ownsHandle); InitCanReadWrite(access); } public StdioFileStream(string path) { if (path == null) { throw new ArgumentNullException("path"); } InitStream(Fopen(path, "rb"), ownsHandle: true); } public StdioFileStream(string path, string mode) { if (path == null) { throw new ArgumentNullException("path"); } InitStream(Fopen(path, mode), ownsHandle: true); } public StdioFileStream(string path, FileMode mode) { if (path == null) { throw new ArgumentNullException("path"); } InitStream(Fopen(path, ToFopenMode(path, mode)), ownsHandle: true); } public StdioFileStream(string path, FileAccess access) { if (path == null) { throw new ArgumentNullException("path"); } InitStream(Fopen(path, ToFopenMode(path, access)), ownsHandle: true); InitCanReadWrite(access); } public StdioFileStream(string path, FileMode mode, FileAccess access) { if (path == null) { throw new ArgumentNullException("path"); } InitStream(Fopen(path, ToFopenMode(path, mode, access)), ownsHandle: true); InitCanReadWrite(access); } private static IntPtr Fopen(string path, string mode) { if (path.Length == 0) { throw new ArgumentException("path"); } if (mode == null) { throw new ArgumentNullException("mode"); } IntPtr intPtr = Stdlib.fopen(path, mode); if (intPtr == IntPtr.Zero) { throw new DirectoryNotFoundException("path", UnixMarshal.CreateExceptionForLastError()); } return intPtr; } private void InitStream(IntPtr fileStream, bool ownsHandle) { if (InvalidFileStream == fileStream) { throw new ArgumentException(Locale.GetText("Invalid file stream"), "fileStream"); } file = fileStream; owner = ownsHandle; try { if ((long)Stdlib.fseek(file, 0L, SeekFlags.SEEK_CUR) != -1) { canSeek = true; } Stdlib.fread(IntPtr.Zero, 0uL, 0uL, file); if (Stdlib.ferror(file) == 0) { canRead = true; } Stdlib.fwrite(IntPtr.Zero, 0uL, 0uL, file); if (Stdlib.ferror(file) == 0) { canWrite = true; } Stdlib.clearerr(file); } catch (Exception) { throw new ArgumentException(Locale.GetText("Invalid file stream"), "fileStream"); } GC.KeepAlive(this); } private void InitCanReadWrite(FileAccess access) { canRead = canRead && (access == FileAccess.Read || access == FileAccess.ReadWrite); canWrite = canWrite && (access == FileAccess.Write || access == FileAccess.ReadWrite); } private static string ToFopenMode(string file, FileMode mode) { string result = NativeConvert.ToFopenMode(mode); AssertFileMode(file, mode); return result; } private static string ToFopenMode(string file, FileAccess access) { return NativeConvert.ToFopenMode(access); } private static string ToFopenMode(string file, FileMode mode, FileAccess access) { string result = NativeConvert.ToFopenMode(mode, access); bool flag = AssertFileMode(file, mode); if (mode == FileMode.OpenOrCreate && access == FileAccess.Read && !flag) { result = "w+b"; } return result; } private static bool AssertFileMode(string file, FileMode mode) { bool flag = FileExists(file); if (mode == FileMode.CreateNew && flag) { throw new IOException("File exists and FileMode.CreateNew specified"); } if ((mode == FileMode.Open || mode == FileMode.Truncate) && !flag) { throw new FileNotFoundException("File doesn't exist and FileMode.Open specified", file); } return flag; } private static bool FileExists(string file) { IntPtr intPtr = Stdlib.fopen(file, "r"); bool result = intPtr != IntPtr.Zero; if (intPtr != IntPtr.Zero) { Stdlib.fclose(intPtr); } return result; } private void AssertNotDisposed() { if (file == InvalidFileStream) { throw new ObjectDisposedException("Invalid File Stream"); } GC.KeepAlive(this); } public void SaveFilePosition(FilePosition pos) { AssertNotDisposed(); UnixMarshal.ThrowExceptionForLastErrorIf(Stdlib.fgetpos(file, pos)); GC.KeepAlive(this); } public void RestoreFilePosition(FilePosition pos) { AssertNotDisposed(); if (pos == null) { throw new ArgumentNullException("value"); } UnixMarshal.ThrowExceptionForLastErrorIf(Stdlib.fsetpos(file, pos)); GC.KeepAlive(this); } public override void Flush() { AssertNotDisposed(); if (Stdlib.fflush(file) != 0) { UnixMarshal.ThrowExceptionForLastError(); } GC.KeepAlive(this); } public unsafe override int Read([In][Out] byte[] buffer, int offset, int count) { AssertNotDisposed(); AssertValidBuffer(buffer, offset, count); if (!CanRead) { throw new NotSupportedException("Stream does not support reading"); } ulong num; fixed (byte* ptr = &buffer[offset]) { num = Stdlib.fread(ptr, 1uL, (ulong)count, file); } if (num != (ulong)count && Stdlib.ferror(file) != 0) { throw new IOException(); } GC.KeepAlive(this); return (int)num; } private void AssertValidBuffer(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "< 0"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "< 0"); } if (offset > buffer.Length) { throw new ArgumentException("destination offset is beyond array size"); } if (offset > buffer.Length - count) { throw new ArgumentException("would overrun buffer"); } } public void Rewind() { AssertNotDisposed(); Stdlib.rewind(file); GC.KeepAlive(this); } public override long Seek(long offset, SeekOrigin origin) { AssertNotDisposed(); if (!CanSeek) { throw new NotSupportedException("The File Stream does not support seeking"); } SeekFlags seekFlags = SeekFlags.SEEK_CUR; if (Stdlib.fseek(origin: origin switch { SeekOrigin.Begin => SeekFlags.SEEK_SET, SeekOrigin.Current => SeekFlags.SEEK_CUR, SeekOrigin.End => SeekFlags.SEEK_END, _ => throw new ArgumentException("origin"), }, stream: file, offset: offset) != 0) { throw new IOException("Unable to seek", UnixMarshal.CreateExceptionForLastError()); } long num = Stdlib.ftell(file); if (num == -1) { throw new IOException("Unable to get current file position", UnixMarshal.CreateExceptionForLastError()); } GC.KeepAlive(this); return num; } public override void SetLength(long value) { throw new NotSupportedException("ANSI C doesn't provide a way to truncate a file"); } public unsafe override void Write(byte[] buffer, int offset, int count) { AssertNotDisposed(); AssertValidBuffer(buffer, offset, count); if (!CanWrite) { throw new NotSupportedException("File Stream does not support writing"); } ulong num; fixed (byte* ptr = &buffer[offset]) { num = Stdlib.fwrite(ptr, 1uL, (ulong)count, file); } if (num != (ulong)count) { UnixMarshal.ThrowExceptionForLastError(); } GC.KeepAlive(this); } ~StdioFileStream() { Close(); } public override void Close() { if (file == InvalidFileStream) { return; } if (owner) { if (Stdlib.fclose(file) != 0) { UnixMarshal.ThrowExceptionForLastError(); } } else { Flush(); } file = InvalidFileStream; canRead = false; canSeek = false; canWrite = false; GC.SuppressFinalize(this); GC.KeepAlive(this); } } public class UnixClient : MarshalByRefObject, IDisposable { private NetworkStream stream; private Socket client; private bool disposed; public Socket Client { get { return client; } set { client = value; stream = null; } } public PeerCred PeerCredential { get { CheckDisposed(); return new PeerCred(client); } } public LingerOption LingerState { get { CheckDisposed(); return (LingerOption)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger); } set { CheckDisposed(); client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value); } } public int ReceiveBufferSize { get { CheckDisposed(); return (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); } set { CheckDisposed(); client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); } } public int ReceiveTimeout { get { CheckDisposed(); return (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); } set { CheckDisposed(); client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); } } public int SendBufferSize { get { CheckDisposed(); return (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); } set { CheckDisposed(); client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); } } public int SendTimeout { get { CheckDisposed(); return (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); } set { CheckDisposed(); client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); } } public UnixClient() { if (client != null) { client.Close(); client = null; } client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP); } public UnixClient(string path) : this() { if (path == null) { throw new ArgumentNullException("ep"); } Connect(path); } public UnixClient(UnixEndPoint ep) : this() { if (ep == null) { throw new ArgumentNullException("ep"); } Connect(ep); } internal UnixClient(Socket sock) { Client = sock; } public void Close() { CheckDisposed(); Dispose(); } public void Connect(UnixEndPoint remoteEndPoint) { CheckDisposed(); client.Connect(remoteEndPoint); stream = new NetworkStream(client, ownsSocket: true); } public void Connect(string path) { CheckDisposed(); Connect(new UnixEndPoint(path)); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { NetworkStream networkStream = stream; stream = null; if (networkStream != null) { networkStream.Close(); networkStream = null; } else if (client != null) { client.Close(); } client = null; } disposed = true; } public NetworkStream GetStream() { CheckDisposed(); if (stream == null) { stream = new NetworkStream(client, ownsSocket: true); } return stream; } private void CheckDisposed() { if (disposed) { throw new ObjectDisposedException(GetType().FullName); } } ~UnixClient() { Dispose(disposing: false); } } public sealed class UnixDirectoryInfo : UnixFileSystemInfo { public override string Name { get { string fileName = UnixPath.GetFileName(base.FullPath); if (fileName == null || fileName.Length == 0) { return base.FullPath; } return fileName; } } public UnixDirectoryInfo Parent { get { if (base.FullPath == "/") { return this; } string directoryName = UnixPath.GetDirectoryName(base.FullPath); if (directoryName == "") { throw new InvalidOperationException("Do not know parent directory for path `" + base.FullPath + "'"); } return new UnixDirectoryInfo(directoryName); } } public UnixDirectoryInfo Root { get { string pathRoot = UnixPath.GetPathRoot(base.FullPath); if (pathRoot == null) { return null; } return new UnixDirectoryInfo(pathRoot); } } public UnixDirectoryInfo(string path) : base(path) { } internal UnixDirectoryInfo(string path, Stat stat) : base(path, stat) { } [CLSCompliant(false)] public void Create(FilePermissions mode) { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.mkdir(base.FullPath, mode)); Refresh(); } public void Create(FileAccessPermissions mode) { Create((FilePermissions)mode); } public void Create() { FilePermissions mode = FilePermissions.ACCESSPERMS; Create(mode); } public override void Delete() { Delete(recursive: false); } public void Delete(bool recursive) { if (recursive) { UnixFileSystemInfo[] fileSystemEntries = GetFileSystemEntries(); foreach (UnixFileSystemInfo unixFileSystemInfo in fileSystemEntries) { if (unixFileSystemInfo is UnixDirectoryInfo unixDirectoryInfo) { unixDirectoryInfo.Delete(recursive: true); } else { unixFileSystemInfo.Delete(); } } } UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.rmdir(base.FullPath)); Refresh(); } public Dirent[] GetEntries() { IntPtr intPtr = Syscall.opendir(base.FullPath); if (intPtr == IntPtr.Zero) { UnixMarshal.ThrowExceptionForLastError(); } bool flag = false; try { Dirent[] entries = GetEntries(intPtr); flag = true; return entries; } finally { int retval = Syscall.closedir(intPtr); if (flag) { UnixMarshal.ThrowExceptionForLastErrorIf(retval); } } } private static Dirent[] GetEntries(IntPtr dirp) { ArrayList arrayList = new ArrayList(); int num; IntPtr result; do { Dirent dirent = new Dirent(); num = Syscall.readdir_r(dirp, dirent, out result); if (num == 0 && result != IntPtr.Zero && dirent.d_name != "." && dirent.d_name != "..") { arrayList.Add(dirent); } } while (num == 0 && result != IntPtr.Zero); if (num != 0) { UnixMarshal.ThrowExceptionForLastErrorIf(num); } return (Dirent[])arrayList.ToArray(typeof(Dirent)); } public Dirent[] GetEntries(Regex regex) { IntPtr intPtr = Syscall.opendir(base.FullPath); if (intPtr == IntPtr.Zero) { UnixMarshal.ThrowExceptionForLastError(); } try { return GetEntries(intPtr, regex); } finally { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.closedir(intPtr)); } } private static Dirent[] GetEntries(IntPtr dirp, Regex regex) { ArrayList arrayList = new ArrayList(); int num; IntPtr result; do { Dirent dirent = new Dirent(); num = Syscall.readdir_r(dirp, dirent, out result); if (num == 0 && result != IntPtr.Zero && regex.Match(dirent.d_name).Success && dirent.d_name != "." && dirent.d_name != "..") { arrayList.Add(dirent); } } while (num == 0 && result != IntPtr.Zero); if (num != 0) { UnixMarshal.ThrowExceptionForLastError(); } return (Dirent[])arrayList.ToArray(typeof(Dirent)); } public Dirent[] GetEntries(string regex) { Regex regex2 = new Regex(regex); return GetEntries(regex2); } public UnixFileSystemInfo[] GetFileSystemEntries() { Dirent[] entries = GetEntries(); return GetFileSystemEntries(entries); } private UnixFileSystemInfo[] GetFileSystemEntries(Dirent[] dentries) { UnixFileSystemInfo[] array = new UnixFileSystemInfo[dentries.Length]; for (int i = 0; i != array.Length; i++) { array[i] = UnixFileSystemInfo.GetFileSystemEntry(UnixPath.Combine(base.FullPath, dentries[i].d_name)); } return array; } public UnixFileSystemInfo[] GetFileSystemEntries(Regex regex) { Dirent[] entries = GetEntries(regex); return GetFileSystemEntries(entries); } public UnixFileSystemInfo[] GetFileSystemEntries(string regex) { Regex regex2 = new Regex(regex); return GetFileSystemEntries(regex2); } public static string GetCurrentDirectory() { StringBuilder stringBuilder = new StringBuilder(16); IntPtr zero = IntPtr.Zero; do { stringBuilder.Capacity *= 2; zero = Syscall.getcwd(stringBuilder, (ulong)stringBuilder.Capacity); } while (zero == IntPtr.Zero && Stdlib.GetLastError() == Errno.ERANGE); if (zero == IntPtr.Zero) { UnixMarshal.ThrowExceptionForLastError(); } return stringBuilder.ToString(); } public static void SetCurrentDirectory(string path) { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.chdir(path)); } } public enum UnixDriveType { Unknown, NoRootDirectory, Removable, Fixed, Network, CDRom, Ram } public sealed class UnixDriveInfo { private Statvfs stat; private string fstype; private string mount_point; private string block_device; public long AvailableFreeSpace { get { Refresh(); return Convert.ToInt64(stat.f_bavail * stat.f_frsize); } } public string DriveFormat => fstype; public UnixDriveType DriveType => UnixDriveType.Unknown; public bool IsReady { get { bool flag = Refresh(throwException: false); if (mount_point == "/" || !flag) { return flag; } if (Syscall.statvfs(RootDirectory.Parent.FullName, out var buf) != 0) { return false; } return buf.f_fsid != stat.f_fsid; } } public string Name => mount_point; public UnixDirectoryInfo RootDirectory => new UnixDirectoryInfo(mount_point); public long TotalFreeSpace { get { Refresh(); return (long)(stat.f_bfree * stat.f_frsize); } } public long TotalSize { get { Refresh(); return (long)(stat.f_frsize * stat.f_blocks); } } public string VolumeLabel => block_device; public long MaximumFilenameLength { get { Refresh(); return Convert.ToInt64(stat.f_namemax); } } public UnixDriveInfo(string mountPoint) { if (mountPoint == null) { throw new ArgumentNullException("mountPoint"); } Fstab fstab = Syscall.getfsfile(mountPoint); if (fstab != null) { FromFstab(fstab); return; } mount_point = mountPoint; block_device = ""; fstype = "Unknown"; } private void FromFstab(Fstab fstab) { fstype = fstab.fs_vfstype; mount_point = fstab.fs_file; block_device = fstab.fs_spec; } public static UnixDriveInfo GetForSpecialFile(string specialFile) { if (specialFile == null) { throw new ArgumentNullException("specialFile"); } Fstab fstab = Syscall.getfsspec(specialFile); if (fstab == null) { throw new ArgumentException("specialFile isn't valid: " + specialFile); } return new UnixDriveInfo(fstab); } private UnixDriveInfo(Fstab fstab) { FromFstab(fstab); } public static UnixDriveInfo[] GetDrives() { ArrayList arrayList = new ArrayList(); lock (Syscall.fstab_lock) { if (Syscall.setfsent() != 1) { throw new IOException("Error calling setfsent(3)", new UnixIOException()); } try { Fstab fstab; while ((fstab = Syscall.getfsent()) != null) { if (fstab.fs_file != null && fstab.fs_file.StartsWith("/")) { arrayList.Add(new UnixDriveInfo(fstab)); } } } finally { Syscall.endfsent(); } } return (UnixDriveInfo[])arrayList.ToArray(typeof(UnixDriveInfo)); } public override string ToString() { return VolumeLabel; } private void Refresh() { Refresh(throwException: true); } private bool Refresh(bool throwException) { int num = Syscall.statvfs(mount_point, out stat); if (num == -1 && throwException) { Errno lastError = Stdlib.GetLastError(); throw new InvalidOperationException(UnixMarshal.GetErrorDescription(lastError), new UnixIOException(lastError)); } if (num == -1) { return false; } return true; } } [Serializable] public class UnixEncoding : Encoding { [Serializable] private class UnixDecoder : Decoder { private uint leftOverBits; private uint leftOverCount; public UnixDecoder() { leftOverBits = 0u; leftOverCount = 0u; } public override int GetCharCount(byte[] bytes, int index, int count) { return InternalGetCharCount(bytes, index, count, leftOverBits, leftOverCount, throwOnInvalid: true, flush: false); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return InternalGetChars(bytes, byteIndex, byteCount, chars, charIndex, ref leftOverBits, ref leftOverCount, throwOnInvalid: true, flush: false); } } [Serializable] private class UnixEncoder : Encoder { private uint leftOver; public UnixEncoder() { leftOver = 0u; } public override int GetByteCount(char[] chars, int index, int count, bool flush) { return InternalGetByteCount(chars, index, count, leftOver, flush); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteCount, bool flush) { return InternalGetBytes(chars, charIndex, charCount, bytes, byteCount, ref leftOver, flush); } } public static readonly Encoding Instance = new UnixEncoding(); public static readonly char EscapeByte = '\0'; private static int InternalGetByteCount(char[] chars, int index, int count, uint leftOver, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || index > chars.Length) { throw new ArgumentOutOfRangeException("index", _("ArgRange_Array")); } if (count < 0 || count > chars.Length - index) { throw new ArgumentOutOfRangeException("count", _("ArgRange_Array")); } int num = 0; uint num2 = leftOver; while (count > 0) { char c = chars[index]; if (num2 == 0) { if (c == EscapeByte && count > 1) { num++; index++; count--; } else if (c < '\u0080') { num++; } else if (c < 'ࠀ') { num += 2; } else if (c >= '\ud800' && c <= '\udbff') { num2 = c; } else { num += 3; } } else { if (c < '\udc00' || c > '\udfff') { num += 3; num2 = 0u; continue; } num += 4; num2 = 0u; } index++; count--; } if (flush && num2 != 0) { num += 3; } return num; } public override int GetByteCount(char[] chars, int index, int count) { return InternalGetByteCount(chars, index, count, 0u, flush: true); } public override int GetByteCount(string s) { if (s == null) { throw new ArgumentNullException("s"); } int num = 0; int num2 = s.Length; int num3 = 0; while (num2 > 0) { char c = s[num++]; if (c == EscapeByte && num2 > 1) { num3++; num++; num2--; } else if (c < '\u0080') { num3++; } else if (c < 'ࠀ') { num3 += 2; } else if (c >= '\ud800' && c <= '\udbff' && num2 > 1) { uint num4 = s[num]; if (num4 >= 56320 && num4 <= 57343) { num3 += 4; num++; num2--; } else { num3 += 3; } } else { num3 += 3; } num2--; } return num3; } private static int InternalGetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, ref uint leftOver, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", _("ArgRange_Array")); } if (charCount < 0 || charCount > chars.Length - charIndex) { throw new ArgumentOutOfRangeException("charCount", _("ArgRange_Array")); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", _("ArgRange_Array")); } int num = bytes.Length; uint num2 = leftOver; int num3 = byteIndex; while (charCount > 0) { char c = chars[charIndex++]; charCount--; uint num4; if (num2 == 0) { if (c >= '\ud800' && c <= '\udbff') { num2 = c; continue; } if (c == EscapeByte) { if (num3 >= num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } if (--charCount >= 0) { bytes[num3++] = (byte)chars[charIndex++]; } continue; } num4 = c; } else if (c >= '\udc00' && c <= '\udfff') { num4 = (uint)((int)(num2 - 55296 << 10) + (c - 56320) + 65536); num2 = 0u; } else { num4 = num2; num2 = 0u; charIndex--; charCount++; } if (num4 < 128) { if (num3 >= num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num3++] = (byte)num4; continue; } if (num4 < 2048) { if (num3 + 2 > num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num3++] = (byte)(0xC0u | (num4 >> 6)); bytes[num3++] = (byte)(0x80u | (num4 & 0x3Fu)); continue; } if (num4 < 65536) { if (num3 + 3 > num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num3++] = (byte)(0xE0u | (num4 >> 12)); bytes[num3++] = (byte)(0x80u | ((num4 >> 6) & 0x3Fu)); bytes[num3++] = (byte)(0x80u | (num4 & 0x3Fu)); continue; } if (num3 + 4 > num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num3++] = (byte)(0xF0u | (num4 >> 18)); bytes[num3++] = (byte)(0x80u | ((num4 >> 12) & 0x3Fu)); bytes[num3++] = (byte)(0x80u | ((num4 >> 6) & 0x3Fu)); bytes[num3++] = (byte)(0x80u | (num4 & 0x3Fu)); } if (flush && num2 != 0) { if (num3 + 3 > num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num3++] = (byte)(0xE0u | (num2 >> 12)); bytes[num3++] = (byte)(0x80u | ((num2 >> 6) & 0x3Fu)); bytes[num3++] = (byte)(0x80u | (num2 & 0x3Fu)); num2 = 0u; } leftOver = num2; return num3 - byteIndex; } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { uint leftOver = 0u; return InternalGetBytes(chars, charIndex, charCount, bytes, byteIndex, ref leftOver, flush: true); } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null) { throw new ArgumentNullException("s"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charIndex > s.Length) { throw new ArgumentOutOfRangeException("charIndex", _("ArgRange_StringIndex")); } if (charCount < 0 || charCount > s.Length - charIndex) { throw new ArgumentOutOfRangeException("charCount", _("ArgRange_StringRange")); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", _("ArgRange_Array")); } fixed (char* ptr = s) { fixed (byte* ptr2 = bytes) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, bytes.Length - byteIndex); } } } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { if ((bytes == null && byteCount != 0) || (chars == null && charCount != 0)) { throw new ArgumentNullException((bytes == null && byteCount != 0) ? "bytes" : "chars"); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount"); } int num = 0; int num2 = 0; while (charCount > 0) { char c = chars[num2++]; uint num3; if (c >= '\ud800' && c <= '\udbff' && charCount > 1) { num3 = chars[num2]; if (num3 >= 56320 && num3 <= 57343) { num3 = (uint)((int)(num3 - 56320) + (c - 55296 << 10) + 65536); num2++; charCount--; } else { num3 = c; } } else { if (c == EscapeByte && charCount > 1) { if (num >= byteCount) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } charCount -= 2; if (charCount >= 0) { bytes[num++] = (byte)chars[num2++]; } continue; } num3 = c; } charCount--; if (num3 < 128) { if (num >= byteCount) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num++] = (byte)num3; continue; } if (num3 < 2048) { if (num + 2 > byteCount) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num++] = (byte)(0xC0u | (num3 >> 6)); bytes[num++] = (byte)(0x80u | (num3 & 0x3Fu)); continue; } if (num3 < 65536) { if (num + 3 > byteCount) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num++] = (byte)(0xE0u | (num3 >> 12)); bytes[num++] = (byte)(0x80u | ((num3 >> 6) & 0x3Fu)); bytes[num++] = (byte)(0x80u | (num3 & 0x3Fu)); continue; } if (num + 4 > byteCount) { throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes"); } bytes[num++] = (byte)(0xF0u | (num3 >> 18)); bytes[num++] = (byte)(0x80u | ((num3 >> 12) & 0x3Fu)); bytes[num++] = (byte)(0x80u | ((num3 >> 6) & 0x3Fu)); bytes[num++] = (byte)(0x80u | (num3 & 0x3Fu)); } return num; } private static int InternalGetCharCount(byte[] bytes, int index, int count, uint leftOverBits, uint leftOverCount, bool throwOnInvalid, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (index < 0 || index > bytes.Length) { throw new ArgumentOutOfRangeException("index", _("ArgRange_Array")); } if (count < 0 || count > bytes.Length - index) { throw new ArgumentOutOfRangeException("count", _("ArgRange_Array")); } int num = 0; int num2 = 0; uint num3 = leftOverBits; uint num4 = leftOverCount & 0xFu; uint num5 = (leftOverCount >> 4) & 0xFu; while (count > 0) { uint num6 = bytes[index++]; num++; count--; if (num5 == 0) { if (num6 < 128) { num2++; num = 0; } else if ((num6 & 0xE0) == 192) { num3 = num6 & 0x1Fu; num4 = 1u; num5 = 2u; } else if ((num6 & 0xF0) == 224) { num3 = num6 & 0xFu; num4 = 1u; num5 = 3u; } else if ((num6 & 0xF8) == 240) { num3 = num6 & 7u; num4 = 1u; num5 = 4u; } else if ((num6 & 0xFC) == 248) { num3 = num6 & 3u; num4 = 1u; num5 = 5u; } else if ((num6 & 0xFE) == 252) { num3 = num6 & 3u; num4 = 1u; num5 = 6u; } else { num2 += num * 2; num = 0; } } else if ((num6 & 0xC0) == 128) { num3 = (num3 << 6) | (num6 & 0x3Fu); if (++num4 < num5) { continue; } if (num3 < 65536) { bool flag = false; switch (num5) { case 2u: flag = num3 <= 127; break; case 3u: flag = num3 <= 2047; break; case 4u: flag = num3 <= 65535; break; case 5u: flag = num3 <= 2097151; break; case 6u: flag = num3 <= 67108863; break; } num2 = ((!flag) ? (num2 + 1) : (num2 + num * 2)); } else if (num3 < 1114112) { num2 += 2; } else if (throwOnInvalid) { num2 += num * 2; } num5 = 0u; num = 0; } else { if (num6 < 128) { index--; count++; num--; } num2 += num * 2; num5 = 0u; num = 0; } } if (flush && num5 != 0 && throwOnInvalid) { num2 += num * 2; } return num2; } public override int GetCharCount(byte[] bytes, int index, int count) { return InternalGetCharCount(bytes, index, count, 0u, 0u, throwOnInvalid: true, flush: true); } private static int InternalGetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, ref uint leftOverBits, ref uint leftOverCount, bool throwOnInvalid, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", _("ArgRange_Array")); } if (byteCount < 0 || byteCount > bytes.Length - byteIndex) { throw new ArgumentOutOfRangeException("byteCount", _("ArgRange_Array")); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", _("ArgRange_Array")); } if (charIndex == chars.Length) { return 0; } byte[] array = new byte[6]; int next_raw = 0; int num = chars.Length; int posn = charIndex; uint num2 = leftOverBits; uint num3 = leftOverCount & 0xFu; uint num4 = (leftOverCount >> 4) & 0xFu; while (byteCount > 0) { uint num5 = bytes[byteIndex++]; array[next_raw++] = (byte)num5; byteCount--; if (num4 == 0) { if (num5 < 128) { if (posn >= num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "chars"); } next_raw = 0; chars[posn++] = (char)num5; } else if ((num5 & 0xE0) == 192) { num2 = num5 & 0x1Fu; num3 = 1u; num4 = 2u; } else if ((num5 & 0xF0) == 224) { num2 = num5 & 0xFu; num3 = 1u; num4 = 3u; } else if ((num5 & 0xF8) == 240) { num2 = num5 & 7u; num3 = 1u; num4 = 4u; } else if ((num5 & 0xFC) == 248) { num2 = num5 & 3u; num3 = 1u; num4 = 5u; } else if ((num5 & 0xFE) == 252) { num2 = num5 & 3u; num3 = 1u; num4 = 6u; } else { next_raw = 0; chars[posn++] = EscapeByte; chars[posn++] = (char)num5; } } else if ((num5 & 0xC0) == 128) { num2 = (num2 << 6) | (num5 & 0x3Fu); if (++num3 < num4) { continue; } if (num2 < 65536) { bool flag = false; switch (num4) { case 2u: flag = num2 <= 127; break; case 3u: flag = num2 <= 2047; break; case 4u: flag = num2 <= 65535; break; case 5u: flag = num2 <= 2097151; break; case 6u: flag = num2 <= 67108863; break; } if (flag) { CopyRaw(array, ref next_raw, chars, ref posn, num); } else { if (posn >= num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "chars"); } chars[posn++] = (char)num2; } } else if (num2 < 1114112) { if (posn + 2 > num) { throw new ArgumentException(_("Arg_InsufficientSpace"), "chars"); } num2 -= 65536; chars[posn++] = (char)((num2 >> 10) + 55296); chars[posn++] = (char)((num2 & 0x3FF) + 56320); } else if (throwOnInvalid) { CopyRaw(array, ref next_raw, chars, ref posn, num); } num4 = 0u; next_raw = 0; } else { if (num5 < 128) { byteIndex--; byteCount++; next_raw--; } CopyRaw(array, ref next_raw, chars, ref posn, num); num4 = 0u; next_raw = 0; } } if (flush && num4 != 0 && throwOnInvalid) { CopyRaw(array, ref next_raw, chars, ref posn, num); } leftOverBits = num2; leftOverCount = num3 | (num4 << 4); return posn - charIndex; } private static void CopyRaw(byte[] raw, ref int next_raw, char[] chars, ref int posn, int length) { if (posn + next_raw * 2 > length) { throw new ArgumentException(_("Arg_InsufficientSpace"), "chars"); } for (int i = 0; i < next_raw; i++) { chars[posn++] = EscapeByte; chars[posn++] = (char)raw[i]; } next_raw = 0; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint leftOverBits = 0u; uint leftOverCount = 0u; return InternalGetChars(bytes, byteIndex, byteCount, chars, charIndex, ref leftOverBits, ref leftOverCount, throwOnInvalid: true, flush: true); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", _("ArgRange_NonNegative")); } return charCount * 4; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", _("ArgRange_NonNegative")); } return byteCount; } public override Decoder GetDecoder() { return new UnixDecoder(); } public override Encoder GetEncoder() { return new UnixEncoder(); } public override byte[] GetPreamble() { return new byte[0]; } public override bool Equals(object value) { if (value is UnixEncoding) { return true; } return false; } public override int GetHashCode() { return base.GetHashCode(); } public override byte[] GetBytes(string s) { if (s == null) { throw new ArgumentNullException("s"); } byte[] array = new byte[GetByteCount(s)]; GetBytes(s, 0, s.Length, array, 0); return array; } private static string _(string arg) { return arg; } } [Serializable] public class UnixEndPoint : EndPoint { private string filename; public string Filename { get { return filename; } set { filename = value; } } public override AddressFamily AddressFamily => AddressFamily.Unix; public UnixEndPoint(string filename) { if (filename == null) { throw new ArgumentNullException("filename"); } if (filename == "") { throw new ArgumentException("Cannot be empty.", "filename"); } this.filename = filename; } public override EndPoint Create(SocketAddress socketAddress) { int num = socketAddress.Size - 2; byte[] array = new byte[num]; for (int i = 0; i < array.Length; i++) { array[i] = socketAddress[i + 2]; if (array[i] == 0) { num = i; break; } } if (num == 0) { return new UnixEndPoint("dummy") { filename = "" }; } return new UnixEndPoint(Encoding.Default.GetString(array, 0, num)); } public override SocketAddress Serialize() { byte[] bytes = Encoding.Default.GetBytes(filename); SocketAddress socketAddress = new SocketAddress(AddressFamily, 2 + bytes.Length + 1); for (int i = 0; i < bytes.Length; i++) { socketAddress[2 + i] = bytes[i]; } socketAddress[2 + bytes.Length] = 0; return socketAddress; } public override string ToString() { return filename; } public override int GetHashCode() { return filename.GetHashCode(); } public override bool Equals(object o) { if (!(o is UnixEndPoint unixEndPoint)) { return false; } return unixEndPoint.filename == filename; } } public sealed class UnixEnvironment { public static string CurrentDirectory { get { return UnixDirectoryInfo.GetCurrentDirectory(); } set { UnixDirectoryInfo.SetCurrentDirectory(value); } } public static string MachineName { get { if (Syscall.uname(out var buf) != 0) { throw UnixMarshal.CreateExceptionForLastError(); } return buf.nodename; } set { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.sethostname(value)); } } public static string UserName => UnixUserInfo.GetRealUser().UserName; public static UnixGroupInfo RealGroup => new UnixGroupInfo(RealGroupId); public static long RealGroupId => Syscall.getgid(); public static UnixUserInfo RealUser => new UnixUserInfo(RealUserId); public static long RealUserId => Syscall.getuid(); public static UnixGroupInfo EffectiveGroup { get { return new UnixGroupInfo(EffectiveGroupId); } set { EffectiveGroupId = value.GroupId; } } public static long EffectiveGroupId { get { return Syscall.getegid(); } set { Syscall.setegid(Convert.ToUInt32(value)); } } public static UnixUserInfo EffectiveUser { get { return new UnixUserInfo(EffectiveUserId); } set { EffectiveUserId = value.UserId; } } public static long EffectiveUserId { get { return Syscall.geteuid(); } set { Syscall.seteuid(Convert.ToUInt32(value)); } } public static string Login => UnixUserInfo.GetRealUser().UserName; private UnixEnvironment() { } [CLSCompliant(false)] public static long GetConfigurationValue(SysconfName name) { long num = Syscall.sysconf(name); if (num == -1 && Stdlib.GetLastError() != 0) { UnixMarshal.ThrowExceptionForLastError(); } return num; } [CLSCompliant(false)] public static string GetConfigurationString(ConfstrName name) { ulong num = Syscall.confstr(name, null, 0uL); if (num == ulong.MaxValue) { UnixMarshal.ThrowExceptionForLastError(); } if (num == 0L) { return ""; } StringBuilder stringBuilder = new StringBuilder((int)num + 1); num = Syscall.confstr(name, stringBuilder, num); if (num == ulong.MaxValue) { UnixMarshal.ThrowExceptionForLastError(); } return stringBuilder.ToString(); } public static void SetNiceValue(int inc) { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.nice(inc)); } public static int CreateSession() { int num = Syscall.setsid(); UnixMarshal.ThrowExceptionForLastErrorIf(num); return num; } public static void SetProcessGroup() { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.setpgrp()); } public static int GetProcessGroup() { return Syscall.getpgrp(); } public static UnixGroupInfo[] GetSupplementaryGroups() { uint[] array = _GetSupplementaryGroupIds(); UnixGroupInfo[] array2 = new UnixGroupInfo[array.Length]; for (int i = 0; i < array2.Length; i++) { array2[i] = new UnixGroupInfo(array[i]); } return array2; } private static uint[] _GetSupplementaryGroupIds() { int num = Syscall.getgroups(0, new uint[0]); if (num == -1) { UnixMarshal.ThrowExceptionForLastError(); } uint[] array = new uint[num]; UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.getgroups(array)); return array; } public static void SetSupplementaryGroups(UnixGroupInfo[] groups) { uint[] array = new uint[groups.Length]; for (int i = 0; i < array.Length; i++) { array[i] = Convert.ToUInt32(groups[i].GroupId); } UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.setgroups(array)); } public static long[] GetSupplementaryGroupIds() { uint[] array = _GetSupplementaryGroupIds(); long[] array2 = new long[array.Length]; for (int i = 0; i < array2.Length; i++) { array2[i] = array[i]; } return array2; } public static void SetSupplementaryGroupIds(long[] list) { uint[] array = new uint[list.Length]; for (int i = 0; i < array.Length; i++) { array[i] = Convert.ToUInt32(list[i]); } UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.setgroups(array)); } public static int GetParentProcessId() { return Syscall.getppid(); } public static UnixProcess GetParentProcess() { return new UnixProcess(GetParentProcessId()); } public static string[] GetUserShells() { ArrayList arrayList = new ArrayList(); lock (Syscall.usershell_lock) { try { if (Syscall.setusershell() != 0) { UnixMarshal.ThrowExceptionForLastError(); } string value; while ((value = Syscall.getusershell()) != null) { arrayList.Add(value); } } finally { Syscall.endusershell(); } } return (string[])arrayList.ToArray(typeof(string)); } } public sealed class UnixFileInfo : UnixFileSystemInfo { public override string Name => UnixPath.GetFileName(base.FullPath); public string DirectoryName => UnixPath.GetDirectoryName(base.FullPath); public UnixDirectoryInfo Directory => new UnixDirectoryInfo(DirectoryName); public UnixFileInfo(string path) : base(path) { } internal UnixFileInfo(string path, Stat stat) : base(path, stat) { } public override void Delete() { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.unlink(base.FullPath)); Refresh(); } public UnixStream Create() { FilePermissions mode = FilePermissions.S_IRUSR | FilePermissions.S_IWUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH; return Create(mode); } [CLSCompliant(false)] public UnixStream Create(FilePermissions mode) { int num = Syscall.creat(base.FullPath, mode); if (num < 0) { UnixMarshal.ThrowExceptionForLastError(); } Refresh(); return new UnixStream(num); } public UnixStream Create(FileAccessPermissions mode) { return Create((FilePermissions)mode); } [CLSCompliant(false)] public UnixStream Open(OpenFlags flags) { if ((flags & OpenFlags.O_CREAT) != 0) { throw new ArgumentException("Cannot specify OpenFlags.O_CREAT without providing FilePermissions. Use the Open(OpenFlags, FilePermissions) method instead"); } int num = Syscall.open(base.FullPath, flags); if (num < 0) { UnixMarshal.ThrowExceptionForLastError(); } return new UnixStream(num); } [CLSCompliant(false)] public UnixStream Open(OpenFlags flags, FilePermissions mode) { int num = Syscall.open(base.FullPath, flags, mode); if (num < 0) { UnixMarshal.ThrowExceptionForLastError(); } return new UnixStream(num); } public UnixStream Open(FileMode mode) { OpenFlags flags = NativeConvert.ToOpenFlags(mode, FileAccess.ReadWrite); return Open(flags); } public UnixStream Open(FileMode mode, FileAccess access) { OpenFlags flags = NativeConvert.ToOpenFlags(mode, access); return Open(flags); } [CLSCompliant(false)] public UnixStream Open(FileMode mode, FileAccess access, FilePermissions perms) { OpenFlags flags = NativeConvert.ToOpenFlags(mode, access); int num = Syscall.open(base.FullPath, flags, perms); if (num < 0) { UnixMarshal.ThrowExceptionForLastError(); } return new UnixStream(num); } public UnixStream OpenRead() { return Open(FileMode.Open, FileAccess.Read); } public UnixStream OpenWrite() { return Open(FileMode.OpenOrCreate, FileAccess.Write); } } public abstract class UnixFileSystemInfo { private Stat stat; private string fullPath; private string originalPath; private bool valid; internal const FileSpecialAttributes AllSpecialAttributes = FileSpecialAttributes.SetUserId | FileSpecialAttributes.SetGroupId | FileSpecialAttributes.Sticky; internal const FileTypes AllFileTypes = (FileTypes)61440; protected string FullPath { get { return fullPath; } set { if (fullPath != value) { UnixPath.CheckPath(value); valid = false; fullPath = value; } } } protected string OriginalPath { get { return originalPath; } set { originalPath = value; } } public virtual string FullName => FullPath; public abstract string Name { get; } public bool Exists { get { Refresh(force: true); return valid; } } public long Device { get { AssertValid(); return Convert.ToInt64(stat.st_dev); } } public long Inode { get { AssertValid(); return Convert.ToInt64(stat.st_ino); } } [CLSCompliant(false)] public FilePermissions Protection { get { AssertValid(); return stat.st_mode; } set { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.chmod(FullPath, value)); } } public FileTypes FileType { get { AssertValid(); return (FileTypes)(stat.st_mode & FilePermissions.S_IFMT); } } public FileAccessPermissions FileAccessPermissions { get { AssertValid(); return (FileAccessPermissions)(stat.st_mode & FilePermissions.ACCESSPERMS); } set { AssertValid(); int st_mode = (int)stat.st_mode; st_mode &= -512; st_mode |= (int)value; Protection = (FilePermissions)st_mode; } } public FileSpecialAttributes FileSpecialAttributes { get { AssertValid(); return (FileSpecialAttributes)(stat.st_mode & (FilePermissions.S_ISUID | FilePermissions.S_ISGID | FilePermissions.S_ISVTX)); } set { AssertValid(); int st_mode = (int)stat.st_mode; st_mode &= -3585; st_mode |= (int)value; Protection = (FilePermissions)st_mode; } } public long LinkCount { get { AssertValid(); return Convert.ToInt64(stat.st_nlink); } } public UnixUserInfo OwnerUser { get { AssertValid(); return new UnixUserInfo(stat.st_uid); } } public long OwnerUserId { get { AssertValid(); return stat.st_uid; } } public UnixGroupInfo OwnerGroup { get { AssertValid(); return new UnixGroupInfo(stat.st_gid); } } public long OwnerGroupId { get { AssertValid(); return stat.st_gid; } } public long DeviceType { get { AssertValid(); return Convert.ToInt64(stat.st_rdev); } } public long Length { get { AssertValid(); return stat.st_size; } } public long BlockSize { get { AssertValid(); return stat.st_blksize; } } public long BlocksAllocated { get { AssertValid(); return stat.st_blocks; } } public DateTime LastAccessTime { get { AssertValid(); return NativeConvert.ToDateTime(stat.st_atime, stat.st_atime_nsec); } } public DateTime LastAccessTimeUtc => LastAccessTime.ToUniversalTime(); public DateTime LastWriteTime { get { AssertValid(); return NativeConvert.ToDateTime(stat.st_mtime, stat.st_mtime_nsec); } } public DateTime LastWriteTimeUtc => LastWriteTime.ToUniversalTime(); public DateTime LastStatusChangeTime { get { AssertValid(); return NativeConvert.ToDateTime(stat.st_ctime, stat.st_ctime_nsec); } } public DateTime LastStatusChangeTimeUtc => LastStatusChangeTime.ToUniversalTime(); public bool IsDirectory { get { AssertValid(); return IsFileType(stat.st_mode, FilePermissions.S_IFDIR); } } public bool IsCharacterDevice { get { AssertValid(); return IsFileType(stat.st_mode, FilePermissions.S_IFCHR); } } public bool IsBlockDevice { get { AssertValid(); return IsFileType(stat.st_mode, FilePermissions.S_IFBLK); } } public bool IsRegularFile { get { AssertValid(); return IsFileType(stat.st_mode, FilePermissions.S_IFREG); } } public bool IsFifo { get { AssertValid(); return IsFileType(stat.st_mode, FilePermissions.S_IFIFO); } } public bool IsSymbolicLink { get { AssertValid(); return IsFileType(stat.st_mode, FilePermissions.S_IFLNK); } } public bool IsSocket { get { AssertValid(); return IsFileType(stat.st_mode, FilePermissions.S_IFSOCK); } } public bool IsSetUser { get { AssertValid(); return IsSet(stat.st_mode, FilePermissions.S_ISUID); } } public bool IsSetGroup { get { AssertValid(); return IsSet(stat.st_mode, FilePermissions.S_ISGID); } } public bool IsSticky { get { AssertValid(); return IsSet(stat.st_mode, FilePermissions.S_ISVTX); } } protected UnixFileSystemInfo(string path) { UnixPath.CheckPath(path); originalPath = path; fullPath = UnixPath.GetFullPath(path); Refresh(force: true); } internal UnixFileSystemInfo(string path, Stat stat) { originalPath = path; fullPath = UnixPath.GetFullPath(path); this.stat = stat; valid = true; } private void AssertValid() { Refresh(force: false); if (!valid) { throw new InvalidOperationException("Path doesn't exist!"); } } internal static bool IsFileType(FilePermissions mode, FilePermissions type) { return (mode & FilePermissions.S_IFMT) == type; } internal static bool IsSet(FilePermissions mode, FilePermissions type) { return (mode & type) == type; } [CLSCompliant(false)] public bool CanAccess(AccessModes mode) { return Syscall.access(FullPath, mode) == 0; } public UnixFileSystemInfo CreateLink(string path) { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.link(FullName, path)); return GetFileSystemEntry(path); } public UnixSymbolicLinkInfo CreateSymbolicLink(string path) { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.symlink(FullName, path)); return new UnixSymbolicLinkInfo(path); } public abstract void Delete(); [CLSCompliant(false)] public long GetConfigurationValue(PathconfName name) { long num = Syscall.pathconf(FullPath, name); if (num == -1 && Stdlib.GetLastError() != 0) { UnixMarshal.ThrowExceptionForLastError(); } return num; } public void Refresh() { Refresh(force: true); } internal void Refresh(bool force) { if (!valid || force) { valid = GetFileStatus(FullPath, out stat); } } protected virtual bool GetFileStatus(string path, out Stat stat) { return Syscall.stat(path, out stat) == 0; } public void SetLength(long length) { int num; do { num = Syscall.truncate(FullPath, length); } while (UnixMarshal.ShouldRetrySyscall(num)); UnixMarshal.ThrowExceptionForLastErrorIf(num); } public virtual void SetOwner(long owner, long group) { int owner2 = Convert.ToInt32(owner); int group2 = Convert.ToInt32(group); UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.chown(FullPath, owner2, group2)); } public void SetOwner(string owner) { Passwd passwd = Syscall.getpwnam(owner); if (passwd == null) { throw new ArgumentException(Locale.GetText("invalid username"), "owner"); } uint pw_uid = passwd.pw_uid; uint pw_gid = passwd.pw_gid; SetOwner(pw_uid, pw_gid); } public void SetOwner(string owner, string group) { long owner2 = -1L; if (owner != null) { owner2 = new UnixUserInfo(owner).UserId; } long group2 = -1L; if (group != null) { group2 = new UnixGroupInfo(group).GroupId; } SetOwner(owner2, group2); } public void SetOwner(UnixUserInfo owner) { long group; long owner2 = (group = -1L); if (owner != null) { owner2 = owner.UserId; group = owner.GroupId; } SetOwner(owner2, group); } public void SetOwner(UnixUserInfo owner, UnixGroupInfo group) { long group2; long owner2 = (group2 = -1L); if (owner != null) { owner2 = owner.UserId; } if (group != null) { group2 = owner.GroupId; } SetOwner(owner2, group2); } public override string ToString() { return FullPath; } public Stat ToStat() { AssertValid(); return stat; } public static UnixFileSystemInfo GetFileSystemEntry(string path) { if (TryGetFileSystemEntry(path, out var entry)) { return entry; } UnixMarshal.ThrowExceptionForLastError(); throw new DirectoryNotFoundException("UnixMarshal.ThrowExceptionForLastError didn't throw?!"); } public static bool TryGetFileSystemEntry(string path, out UnixFileSystemInfo entry) { if (Syscall.lstat(path, out var buf) == -1) { if (Stdlib.GetLastError() == Errno.ENOENT) { entry = new UnixFileInfo(path); return true; } entry = null; return false; } if (IsFileType(buf.st_mode, FilePermissions.S_IFDIR)) { entry = new UnixDirectoryInfo(path, buf); } else if (IsFileType(buf.st_mode, FilePermissions.S_IFLNK)) { entry = new UnixSymbolicLinkInfo(path, buf); } else { entry = new UnixFileInfo(path, buf); } return true; } } public sealed class UnixGroupInfo { private Mono.Unix.Native.Group group; public string GroupName => group.gr_name; public string Password => group.gr_passwd; public long GroupId => group.gr_gid; public UnixGroupInfo(string group) { this.group = new Mono.Unix.Native.Group(); if (Syscall.getgrnam_r(group, this.group, out var grbufp) != 0 || grbufp == null) { throw new ArgumentException(Locale.GetText("invalid group name"), "group"); } } public UnixGroupInfo(long group) { this.group = new Mono.Unix.Native.Group(); if (Syscall.getgrgid_r(Convert.ToUInt32(group), this.group, out var grbufp) != 0 || grbufp == null) { throw new ArgumentException(Locale.GetText("invalid group id"), "group"); } } public UnixGroupInfo(Mono.Unix.Native.Group group) { this.group = CopyGroup(group); } private static Mono.Unix.Native.Group CopyGroup(Mono.Unix.Native.Group group) { return new Mono.Unix.Native.Group { gr_gid = group.gr_gid, gr_mem = group.gr_mem, gr_name = group.gr_name, gr_passwd = group.gr_passwd }; } public UnixUserInfo[] GetMembers() { ArrayList arrayList = new ArrayList(group.gr_mem.Length); for (int i = 0; i < group.gr_mem.Length; i++) { try { arrayList.Add(new UnixUserInfo(group.gr_mem[i])); } catch (ArgumentException) { } } return (UnixUserInfo[])arrayList.ToArray(typeof(UnixUserInfo)); } public string[] GetMemberNames() { return (string[])group.gr_mem.Clone(); } public override int GetHashCode() { return group.GetHashCode(); } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } return group.Equals(((UnixGroupInfo)obj).group); } public override string ToString() { return group.ToString(); } public Mono.Unix.Native.Group ToGroup() { return CopyGroup(group); } public static UnixGroupInfo[] GetLocalGroups() { ArrayList arrayList = new ArrayList(); lock (Syscall.grp_lock) { if (Syscall.setgrent() != 0) { UnixMarshal.ThrowExceptionForLastError(); } try { Mono.Unix.Native.Group group; while ((group = Syscall.getgrent()) != null) { arrayList.Add(new UnixGroupInfo(group)); } if (Stdlib.GetLastError() != 0) { UnixMarshal.ThrowExceptionForLastError(); } } finally { Syscall.endgrent(); } } return (UnixGroupInfo[])arrayList.ToArray(typeof(UnixGroupInfo)); } } [Serializable] public class UnixIOException : IOException { private int errno; public int NativeErrorCode => errno; public Errno ErrorCode => NativeConvert.ToErrno(errno); public UnixIOException() : this(Marshal.GetLastWin32Error()) { } public UnixIOException(int errno) : base(GetMessage(NativeConvert.ToErrno(errno))) { this.errno = errno; } public UnixIOException(int errno, Exception inner) : base(GetMessage(NativeConvert.ToErrno(errno)), inner) { this.errno = errno; } public UnixIOException(Errno errno) : base(GetMessage(errno)) { this.errno = NativeConvert.FromErrno(errno); } public UnixIOException(Errno errno, Exception inner) : base(GetMessage(errno), inner) { this.errno = NativeConvert.FromErrno(errno); } public UnixIOException(string message) : base(message) { errno = 0; } public UnixIOException(string message, Exception inner) : base(message, inner) { errno = 0; } protected UnixIOException(SerializationInfo info, StreamingContext context) : base(info, context) { } private static string GetMessage(Errno errno) { return $"{UnixMarshal.GetErrorDescription(errno)} [{errno}]."; } } public class UnixListener : MarshalByRefObject, IDisposable { private bool disposed; private bool listening; private Socket server; private EndPoint savedEP; public EndPoint LocalEndpoint => savedEP; protected Socket Server => server; private void Init(UnixEndPoint ep) { listening = false; string filename = ep.Filename; if (File.Exists(filename)) { Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP); try { socket.Connect(ep); socket.Close(); throw new InvalidOperationException("There's already a server listening on " + filename); } catch (SocketException) { } File.Delete(filename); } server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP); server.Bind(ep); savedEP = server.LocalEndPoint; } public UnixListener(string path) { if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } Init(new UnixEndPoint(path)); } public UnixListener(UnixEndPoint localEndPoint) { if (localEndPoint == null) { throw new ArgumentNullException("localendPoint"); } Init(localEndPoint); } public Socket AcceptSocket() { CheckDisposed(); if (!listening) { throw new InvalidOperationException("Socket is not listening"); } return server.Accept(); } public UnixClient AcceptUnixClient() { CheckDisposed(); if (!listening) { throw new InvalidOperationException("Socket is not listening"); } return new UnixClient(AcceptSocket()); } ~UnixListener() { Dispose(disposing: false); } public bool Pending() { CheckDisposed(); if (!listening) { throw new InvalidOperationException("Socket is not listening"); } return server.Poll(1000, SelectMode.SelectRead); } public void Start() { Start(5); } public void Start(int backlog) { CheckDisposed(); if (!listening) { server.Listen(backlog); listening = true; } } public void Stop() { CheckDisposed(); Dispose(disposing: true); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { try { File.Delete(((UnixEndPoint)savedEP).Filename); } catch { } if (server != null) { server.Close(); } server = null; } disposed = true; } private void CheckDisposed() { if (disposed) { throw new ObjectDisposedException(GetType().FullName); } } } internal class ErrorMarshal { internal delegate string ErrorTranslator(Errno errno); internal static readonly ErrorTranslator Translate; static ErrorMarshal() { try { Translate = strerror_r; Translate(Errno.ERANGE); } catch (EntryPointNotFoundException) { Translate = strerror; } } private static string strerror(Errno errno) { return Stdlib.strerror(errno); } private static string strerror_r(Errno errno) { StringBuilder stringBuilder = new StringBuilder(16); int num = 0; do { stringBuilder.Capacity *= 2; num = Syscall.strerror_r(errno, stringBuilder); } while (num == -1 && Stdlib.GetLastError() == Errno.ERANGE); if (num == -1) { int num2 = (int)errno; return "** Unknown error code: " + num2 + "**"; } return stringBuilder.ToString(); } } public sealed class UnixMarshal { private UnixMarshal() { } [CLSCompliant(false)] public static string GetErrorDescription(Errno errno) { return ErrorMarshal.Translate(errno); } public static IntPtr AllocHeap(long size) { if (size < 0) { throw new ArgumentOutOfRangeException("size", "< 0"); } return Stdlib.malloc((ulong)size); } public static IntPtr ReAllocHeap(IntPtr ptr, long size) { if (size < 0) { throw new ArgumentOutOfRangeException("size", "< 0"); } return Stdlib.realloc(ptr, (ulong)size); } public static void FreeHeap(IntPtr ptr) { Stdlib.free(ptr); } public unsafe static string PtrToStringUnix(IntPtr p) { if (p == IntPtr.Zero) { return null; } int length = checked((int)Stdlib.strlen(p)); return new string((sbyte*)(void*)p, 0, length, UnixEncoding.Instance); } public static string PtrToString(IntPtr p) { if (p == IntPtr.Zero) { return null; } return PtrToString(p, UnixEncoding.Instance); } public unsafe static string PtrToString(IntPtr p, Encoding encoding) { if (p == IntPtr.Zero) { return null; } if (encoding == null) { throw new ArgumentNullException("encoding"); } int stringByteLength = GetStringByteLength(p, encoding); string text = new string((sbyte*)(void*)p, 0, stringByteLength, encoding); stringByteLength = text.Length; while (stringByteLength > 0 && text[stringByteLength - 1] == '\0') { stringByteLength--; } if (stringByteLength == text.Length) { return text; } return text.Substring(0, stringByteLength); } private static int GetStringByteLength(IntPtr p, Encoding encoding) { Type type = encoding.GetType(); int num = -1; num = ((typeof(UTF8Encoding).IsAssignableFrom(type) || typeof(UTF7Encoding).IsAssignableFrom(type) || typeof(UnixEncoding).IsAssignableFrom(type) || typeof(ASCIIEncoding).IsAssignableFrom(type)) ? checked((int)Stdlib.strlen(p)) : (typeof(UnicodeEncoding).IsAssignableFrom(type) ? GetInt16BufferLength(p) : ((!typeof(UTF32Encoding).IsAssignableFrom(type)) ? GetRandomBufferLength(p, encoding.GetMaxByteCount(1)) : GetInt32BufferLength(p)))); if (num == -1) { throw new NotSupportedException("Unable to determine native string buffer length"); } return num; } private static int GetInt16BufferLength(IntPtr p) { int i; for (i = 0; Marshal.ReadInt16(p, i * 2) != 0; i = checked(i + 1)) { } return checked(i * 2); } private static int GetInt32BufferLength(IntPtr p) { int i; for (i = 0; Marshal.ReadInt32(p, i * 4) != 0; i = checked(i + 1)) { } return checked(i * 4); } private static int GetRandomBufferLength(IntPtr p, int nullLength) { switch (nullLength) { case 1: return checked((int)Stdlib.strlen(p)); case 2: return GetInt16BufferLength(p); case 4: return GetInt32BufferLength(p); default: { int result = 0; int num = 0; do { num = ((Marshal.ReadByte(p, result++) == 0) ? (num + 1) : 0); } while (num != nullLength); return result; } } } public static string[] PtrToStringArray(IntPtr stringArray) { return PtrToStringArray(stringArray, UnixEncoding.Instance); } public static string[] PtrToStringArray(IntPtr stringArray, Encoding encoding) { if (stringArray == IntPtr.Zero) { return new string[0]; } return PtrToStringArray(CountStrings(stringArray), stringArray, encoding); } private static int CountStrings(IntPtr stringArray) { int i; for (i = 0; Marshal.ReadIntPtr(stringArray, i * IntPtr.Size) != IntPtr.Zero; i++) { } return i; } public static string[] PtrToStringArray(int count, IntPtr stringArray) { return PtrToStringArray(count, stringArray, UnixEncoding.Instance); } public static string[] PtrToStringArray(int count, IntPtr stringArray, Encoding encoding) { if (count < 0) { throw new ArgumentOutOfRangeException("count", "< 0"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (stringArray == IntPtr.Zero) { return new string[count]; } string[] array = new string[count]; for (int i = 0; i < count; i++) { IntPtr p = Marshal.ReadIntPtr(stringArray, i * IntPtr.Size); array[i] = PtrToString(p, encoding); } return array; } public static IntPtr StringToHeap(string s) { return StringToHeap(s, UnixEncoding.Instance); } public static IntPtr StringToHeap(string s, Encoding encoding) { if (s == null) { return IntPtr.Zero; } return StringToHeap(s, 0, s.Length, encoding); } public static IntPtr StringToHeap(string s, int index, int count) { return StringToHeap(s, index, count, UnixEncoding.Instance); } public unsafe static IntPtr StringToHeap(string s, int index, int count, Encoding encoding) { if (s == null) { return IntPtr.Zero; } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", "Non - negative number required."); } if (s.Length - index < count) { throw new ArgumentOutOfRangeException("s", "Index and count must refer to a location within the string."); } int maxByteCount = encoding.GetMaxByteCount(1); int byteCount = encoding.GetByteCount(s); int num = checked(byteCount + maxByteCount); IntPtr intPtr = AllocHeap(num); if (intPtr == IntPtr.Zero) { throw new UnixIOException(Errno.ENOMEM); } fixed (char* ptr2 = s) { byte* ptr = (byte*)(void*)intPtr; int bytes; try { bytes = encoding.GetBytes(ptr2 + index, count, ptr, num); } catch { FreeHeap(intPtr); throw; } if (bytes != byteCount) { FreeHeap(intPtr); throw new NotSupportedException("encoding.GetBytes() doesn't equal encoding.GetByteCount()!"); } ptr += byteCount; for (int i = 0; i < maxByteCount; i++) { ptr[i] = 0; } } return intPtr; } public static bool ShouldRetrySyscall(int r) { if (r == -1 && Stdlib.GetLastError() == Errno.EINTR) { return true; } return false; } [CLSCompliant(false)] public static bool ShouldRetrySyscall(int r, out Errno errno) { errno = (Errno)0; if (r == -1 && (errno = Stdlib.GetLastError()) == Errno.EINTR) { return true; } return false; } internal static string EscapeFormatString(string message, char[] permitted) { if (message == null) { return ""; } StringBuilder stringBuilder = new StringBuilder(message.Length); for (int i = 0; i < message.Length; i++) { char c = message[i]; stringBuilder.Append(c); if (c == '%' && i + 1 < message.Length) { char c2 = message[i + 1]; if (c2 == '%' || IsCharPresent(permitted, c2)) { stringBuilder.Append(c2); } else { stringBuilder.Append('%').Append(c2); } i++; } else if (c == '%') { stringBuilder.Append('%'); } } return stringBuilder.ToString(); } private static bool IsCharPresent(char[] array, char c) { if (array == null) { return false; } for (int i = 0; i < array.Length; i++) { if (array[i] == c) { return true; } } return false; } internal static Exception CreateExceptionForError(Errno errno) { string errorDescription = GetErrorDescription(errno); UnixIOException ex = new UnixIOException(errno); switch (errno) { case Errno.EBADF: case Errno.EINVAL: return new ArgumentException(errorDescription, ex); case Errno.ERANGE: return new ArgumentOutOfRangeException(errorDescription); case Errno.ENOTDIR: return new DirectoryNotFoundException(errorDescription, ex); case Errno.ENOENT: return new FileNotFoundException(errorDescription, ex); case Errno.EPERM: case Errno.EOPNOTSUPP: return new InvalidOperationException(errorDescription, ex); case Errno.ENOEXEC: return new InvalidProgramException(errorDescription, ex); case Errno.EIO: case Errno.ENXIO: case Errno.ENOSPC: case Errno.ESPIPE: case Errno.EROFS: case Errno.ENOTEMPTY: return new IOException(errorDescription, ex); case Errno.EFAULT: return new NullReferenceException(errorDescription, ex); case Errno.EOVERFLOW: return new OverflowException(errorDescription, ex); case Errno.ENAMETOOLONG: return new PathTooLongException(errorDescription, ex); case Errno.EACCES: case Errno.EISDIR: return new UnauthorizedAccessException(errorDescription, ex); default: return ex; } } internal static Exception CreateExceptionForLastError() { return CreateExceptionForError(Stdlib.GetLastError()); } [CLSCompliant(false)] public static void ThrowExceptionForError(Errno errno) { throw CreateExceptionForError(errno); } public static void ThrowExceptionForLastError() { throw CreateExceptionForLastError(); } [CLSCompliant(false)] public static void ThrowExceptionForErrorIf(int retval, Errno errno) { if (retval == -1) { ThrowExceptionForError(errno); } } public static void ThrowExceptionForLastErrorIf(int retval) { if (retval == -1) { ThrowExceptionForLastError(); } } } public sealed class UnixPath { public static readonly char DirectorySeparatorChar = '/'; public static readonly char AltDirectorySeparatorChar = '/'; public static readonly char PathSeparator = ':'; public static readonly char VolumeSeparatorChar = '/'; private static readonly char[] _InvalidPathChars = new char[0]; private UnixPath() { } public static char[] GetInvalidPathChars() { return (char[])_InvalidPathChars.Clone(); } public static string Combine(string path1, params string[] paths) { if (path1 == null) { throw new ArgumentNullException("path1"); } if (paths == null) { throw new ArgumentNullException("paths"); } if (path1.IndexOfAny(_InvalidPathChars) != -1) { throw new ArgumentException("Illegal characters in path", "path1"); } int num = path1.Length; int num2 = -1; for (int i = 0; i < paths.Length; i++) { if (paths[i] == null) { throw new ArgumentNullException("paths[" + i + "]"); } if (paths[i].IndexOfAny(_InvalidPathChars) != -1) { throw new ArgumentException("Illegal characters in path", "paths[" + i + "]"); } if (IsPathRooted(paths[i])) { num = 0; num2 = i; } num += paths[i].Length + 1; } StringBuilder stringBuilder = new StringBuilder(num); if (num2 == -1) { stringBuilder.Append(path1); num2 = 0; } for (int j = num2; j < paths.Length; j++) { Combine(stringBuilder, paths[j]); } return stringBuilder.ToString(); } private static void Combine(StringBuilder path, string part) { if (path.Length > 0 && part.Length > 0) { char c = path[path.Length - 1]; if (c != DirectorySeparatorChar && c != AltDirectorySeparatorChar && c != VolumeSeparatorChar) { path.Append(DirectorySeparatorChar); } } path.Append(part); } public static string GetDirectoryName(string path) { CheckPath(path); int num = path.LastIndexOf(DirectorySeparatorChar); if (num > 0) { return path.Substring(0, num); } if (num == 0) { return "/"; } return ""; } public static string GetFileName(string path) { if (path == null || path.Length == 0) { return path; } int num = path.LastIndexOf(DirectorySeparatorChar); if (num >= 0) { return path.Substring(num + 1); } return path; } public static string GetFullPath(string path) { path = _GetFullPath(path); return GetCanonicalPath(path); } private static string _GetFullPath(string path) { if (path == null) { throw new ArgumentNullException("path"); } if (!IsPathRooted(path)) { path = UnixDirectoryInfo.GetCurrentDirectory() + DirectorySeparatorChar + path; } return path; } public static string GetCanonicalPath(string path) { GetPathComponents(path, out var components, out var lastIndex); string text = string.Join("/", components, 0, lastIndex); if (!IsPathRooted(path)) { return text; } return "/" + text; } private static void GetPathComponents(string path, out string[] components, out int lastIndex) { string[] array = path.Split(DirectorySeparatorChar); int num = 0; for (int i = 0; i < array.Length; i++) { if (!(array[i] == ".") && !(array[i] == string.Empty)) { if (array[i] == "..") { num = ((num == 0) ? (num + 1) : (num - 1)); } else { array[num++] = array[i]; } } } components = array; lastIndex = num; } public static string GetPathRoot(string path) { if (path == null) { return null; } if (!IsPathRooted(path)) { return ""; } return "/"; } public static string GetCompleteRealPath(string path) { if (path == null) { throw new ArgumentNullException("path"); } GetPathComponents(path, out var components, out var lastIndex); StringBuilder stringBuilder = new StringBuilder(); if (components.Length != 0) { string text = (IsPathRooted(path) ? "/" : ""); text += components[0]; stringBuilder.Append(GetRealPath(text)); } for (int i = 1; i < lastIndex; i++) { stringBuilder.Append("/").Append(components[i]); string realPath = GetRealPath(stringBuilder.ToString()); stringBuilder.Remove(0, stringBuilder.Length); stringBuilder.Append(realPath); } return stringBuilder.ToString(); } public static string GetRealPath(string path) { while (true) { string text = ReadSymbolicLink(path); if (text == null) { break; } if (IsPathRooted(text)) { path = text; continue; } path = GetDirectoryName(path) + DirectorySeparatorChar + text; path = GetCanonicalPath(path); } return path; } internal static string ReadSymbolicLink(string path) { string text = TryReadLink(path); if (text == null) { Errno lastError = Stdlib.GetLastError(); if (lastError != Errno.EINVAL) { UnixMarshal.ThrowExceptionForError(lastError); } } return text; } public static string TryReadLink(string path) { byte[] array = new byte[256]; checked { long num; while (true) { num = Syscall.readlink(path, array); if (num < 0) { return null; } if (num != array.Length) { break; } array = new byte[array.LongLength * 2]; } return UnixEncoding.Instance.GetString(array, 0, (int)num); } } public static string TryReadLinkAt(int dirfd, string path) { byte[] array = new byte[256]; checked { long num; while (true) { num = Syscall.readlinkat(dirfd, path, array); if (num < 0) { return null; } if (num != array.Length) { break; } array = new byte[array.LongLength * 2]; } return UnixEncoding.Instance.GetString(array, 0, (int)num); } } public static string ReadLink(string path) { string text = TryReadLink(path); if (text == null) { UnixMarshal.ThrowExceptionForLastError(); } return text; } public static string ReadLinkAt(int dirfd, string path) { string text = TryReadLinkAt(dirfd, path); if (text == null) { UnixMarshal.ThrowExceptionForLastError(); } return text; } public static bool IsPathRooted(string path) { if (path == null || path.Length == 0) { return false; } return path[0] == DirectorySeparatorChar; } internal static void CheckPath(string path) { if (path == null) { throw new ArgumentNullException(); } if (path.Length == 0) { throw new ArgumentException("Path cannot contain a zero-length string", "path"); } if (path.IndexOfAny(_InvalidPathChars) != -1) { throw new ArgumentException("Invalid characters in path.", "path"); } } } public struct UnixPipes : IEquatable<UnixPipes> { public UnixStream Reading; public UnixStream Writing; public UnixPipes(UnixStream reading, UnixStream writing) { Reading = reading; Writing = writing; } public static UnixPipes CreatePipes() { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.pipe(out var reading, out var writing)); return new UnixPipes(new UnixStream(reading), new UnixStream(writing)); } public override bool Equals(object value) { if (value == null || value.GetType() != GetType()) { return false; } UnixPipes unixPipes = (UnixPipes)value; if (Reading.Handle == unixPipes.Reading.Handle) { return Writing.Handle == unixPipes.Writing.Handle; } return false; } public bool Equals(UnixPipes value) { if (Reading.Handle == value.Reading.Handle) { return Writing.Handle == value.Writing.Handle; } return false; } public override int GetHashCode() { return Reading.Handle.GetHashCode() ^ Writing.Handle.GetHashCode(); } public static bool operator ==(UnixPipes lhs, UnixPipes rhs) { return lhs.Equals(rhs); } public static bool operator !=(UnixPipes lhs, UnixPipes rhs) { return !lhs.Equals(rhs); } } public sealed class UnixProcess { private int pid; public int Id => pid; public bool HasExited => Syscall.WIFEXITED(GetProcessStatus()); public int ExitCode { get { if (!HasExited) { throw new InvalidOperationException(Locale.GetText("Process hasn't exited")); } return Syscall.WEXITSTATUS(GetProcessStatus()); } } public bool HasSignaled => Syscall.WIFSIGNALED(GetProcessStatus()); public Signum TerminationSignal { get { if (!HasSignaled) { throw new InvalidOperationException(Locale.GetText("Process wasn't terminated by a signal")); } return Syscall.WTERMSIG(GetProcessStatus()); } } public bool HasStopped => Syscall.WIFSTOPPED(GetProcessStatus()); public Signum StopSignal { get { if (!HasStopped) { throw new InvalidOperationException(Locale.GetText("Process isn't stopped")); } return Syscall.WSTOPSIG(GetProcessStatus()); } } public int ProcessGroupId { get { return Syscall.getpgid(pid); } set { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.setpgid(pid, value)); } } public int SessionId { get { int num = Syscall.getsid(pid); UnixMarshal.ThrowExceptionForLastErrorIf(num); return num; } } internal UnixProcess(int pid) { this.pid = pid; } private int GetProcessStatus() { int status; int num = Syscall.waitpid(pid, out status, WaitOptions.WNOHANG | WaitOptions.WUNTRACED); UnixMarshal.ThrowExceptionForLastErrorIf(num); return num; } public static UnixProcess GetCurrentProcess() { return new UnixProcess(GetCurrentProcessId()); } public static int GetCurrentProcessId() { return Syscall.getpid(); } public void Kill() { Signal(Signum.SIGKILL); } [CLSCompliant(false)] public void Signal(Signum signal) { UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.kill(pid, signal)); } public void WaitForExit() { int num; do { num = Syscall.waitpid(pid, out var _, (WaitOptions)0); } while (UnixMarshal.ShouldRetrySyscall(num)); UnixMarshal.ThrowExceptionForLastErrorIf(num); } } public class UnixSignal : WaitHandle { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int Mono_Posix_RuntimeIsShuttingDown(); [Map] private struct SignalInfo { public int signum; public int count; public int read_fd; public int write_fd; public int pipecnt; public int pipelock; public int have_handler; public IntPtr handler; } private int signum; private IntPtr signal_info; private static Mono_Posix_RuntimeIsShuttingDown ShuttingDown; public Signum Signum { get { if (IsRealTimeSignal) { throw new InvalidOperationException("This signal is a RealTimeSignum"); } return NativeConvert.ToSignum(signum); } } public RealTimeSignum RealTimeSignum { get { if (!IsRealTimeSignal) { throw new InvalidOperationException("This signal is not a RealTimeSignum"); } return NativeConvert.ToRealTimeSignum(signum - GetSIGRTMIN()); } } public bool IsRealTimeSignal { get { AssertValid(); int sIGRTMIN = GetSIGRTMIN(); if (sIGRTMIN == -1) { return false; } return signum >= sIGRTMIN; } } private unsafe SignalInfo* Info { get { AssertValid(); return (SignalInfo*)(void*)signal_info; } } public bool IsSet => Count > 0; public unsafe int Count { get { return Info->count; } set { Interlocked.Exchange(ref Info->count, value); } } static UnixSignal() { ShuttingDown = RuntimeShuttingDownCallback; Stdlib.VersionCheck(); } public UnixSignal(Signum signum) { this.signum = NativeConvert.FromSignum(signum); signal_info = install(this.signum); if (signal_info == IntPtr.Zero) { throw new ArgumentException("Unable to handle signal", "signum"); } } public UnixSignal(RealTimeSignum rtsig) { signum = NativeConvert.FromRealTimeSignum(rtsig); signal_info = install(signum); Errno lastError = Stdlib.GetLastError(); if (signal_info == IntPtr.Zero) { if (lastError == Errno.EADDRINUSE) { throw new ArgumentException("Signal registered outside of Mono.Posix", "signum"); } throw new ArgumentException("Unable to handle signal", "signum"); } } [DllImport("MonoPosixHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Mono_Unix_UnixSignal_install", SetLastError = true)] private static extern IntPtr install(int signum); [DllImport("MonoPosixHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Mono_Unix_UnixSignal_uninstall")] private static extern int uninstall(IntPtr info); private static int RuntimeShuttingDownCallback() { if (!Environment.HasShutdownStarted) { return 0; } return 1; } [DllImport("MonoPosixHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Mono_Unix_UnixSignal_WaitAny")] private static extern int WaitAny(IntPtr[] infos, int count, int timeout, Mono_Posix_RuntimeIsShuttingDown shutting_down); [DllImport("MonoPosixHelper", CallingConvention = CallingConvention.Cd
deps/Mono.Security.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Configuration.Assemblies; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Security; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using Mono.Math; using Mono.Math.Prime; using Mono.Math.Prime.Generator; using Mono.Net.Security; using Mono.Security.Cryptography; using Mono.Security.X509; using Mono.Security.X509.Extensions; using Mono.Xml; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("MONO development team")] [assembly: AssemblyCopyright("(c) 2003-2004 Various Authors")] [assembly: AssemblyDescription("Mono.Security.dll")] [assembly: AssemblyProduct("MONO CLI")] [assembly: AssemblyTitle("Mono.Security.dll")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyDelaySign(true)] [assembly: InternalsVisibleTo("System, PublicKey=00000000000000000400000000000000")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class AssemblyRef { internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string EcmaPublicKey = "b77a5c561934e089"; public const string FrameworkPublicKeyFull = "00000000000000000400000000000000"; public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000"; public const string MicrosoftPublicKey = "b03f5f7f11d50a3a"; public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal sealed class Locale { private Locale() { } public static string GetText(string msg) { return msg; } public static string GetText(string fmt, params object[] args) { return string.Format(fmt, args); } } namespace Mono.Xml { [CLSCompliant(false)] public class MiniParser { public interface IReader { int Read(); } public interface IAttrList { int Length { get; } bool IsEmpty { get; } string[] Names { get; } string[] Values { get; } string GetName(int i); string GetValue(int i); string GetValue(string name); void ChangeValue(string name, string newValue); } public interface IMutableAttrList : IAttrList { void Clear(); void Add(string name, string value); void CopyFrom(IAttrList attrs); void Remove(int i); void Remove(string name); } public interface IHandler { void OnStartParsing(MiniParser parser); void OnStartElement(string name, IAttrList attrs); void OnEndElement(string name); void OnChars(string ch); void OnEndParsing(MiniParser parser); } public class HandlerAdapter : IHandler { public void OnStartParsing(MiniParser parser) { } public void OnStartElement(string name, IAttrList attrs) { } public void OnEndElement(string name) { } public void OnChars(string ch) { } public void OnEndParsing(MiniParser parser) { } } private enum CharKind : byte { LEFT_BR = 0, RIGHT_BR = 1, SLASH = 2, PI_MARK = 3, EQ = 4, AMP = 5, SQUOTE = 6, DQUOTE = 7, BANG = 8, LEFT_SQBR = 9, SPACE = 10, RIGHT_SQBR = 11, TAB = 12, CR = 13, EOL = 14, CHARS = 15, UNKNOWN = 31 } private enum ActionCode : byte { START_ELEM = 0, END_ELEM = 1, END_NAME = 2, SET_ATTR_NAME = 3, SET_ATTR_VAL = 4, SEND_CHARS = 5, START_CDATA = 6, END_CDATA = 7, ERROR = 8, STATE_CHANGE = 9, FLUSH_CHARS_STATE_CHANGE = 10, ACC_CHARS_STATE_CHANGE = 11, ACC_CDATA = 12, PROC_CHAR_REF = 13, UNKNOWN = 15 } public class AttrListImpl : IMutableAttrList, IAttrList { protected ArrayList names; protected ArrayList values; public int Length => names.Count; public bool IsEmpty => Length != 0; public string[] Names => names.ToArray(typeof(string)) as string[]; public string[] Values => values.ToArray(typeof(string)) as string[]; public AttrListImpl() : this(0) { } public AttrListImpl(int initialCapacity) { if (initialCapacity <= 0) { names = new ArrayList(); values = new ArrayList(); } else { names = new ArrayList(initialCapacity); values = new ArrayList(initialCapacity); } } public AttrListImpl(IAttrList attrs) : this(attrs?.Length ?? 0) { if (attrs != null) { CopyFrom(attrs); } } public string GetName(int i) { string result = null; if (i >= 0 && i < Length) { result = names[i] as string; } return result; } public string GetValue(int i) { string result = null; if (i >= 0 && i < Length) { result = values[i] as string; } return result; } public string GetValue(string name) { return GetValue(names.IndexOf(name)); } public void ChangeValue(string name, string newValue) { int num = names.IndexOf(name); if (num >= 0 && num < Length) { values[num] = newValue; } } public void Clear() { names.Clear(); values.Clear(); } public void Add(string name, string value) { names.Add(name); values.Add(value); } public void Remove(int i) { if (i >= 0) { names.RemoveAt(i); values.RemoveAt(i); } } public void Remove(string name) { Remove(names.IndexOf(name)); } public void CopyFrom(IAttrList attrs) { if (attrs != null && this == attrs) { Clear(); int length = attrs.Length; for (int i = 0; i < length; i++) { Add(attrs.GetName(i), attrs.GetValue(i)); } } } } public class XMLError : Exception { protected string descr; protected int line; protected int column; public int Line => line; public int Column => column; public XMLError() : this("Unknown") { } public XMLError(string descr) : this(descr, -1, -1) { } public XMLError(string descr, int line, int column) : base(descr) { this.descr = descr; this.line = line; this.column = column; } public override string ToString() { return $"{descr} @ (line = {line}, col = {column})"; } } private static readonly int INPUT_RANGE = 13; private static readonly ushort[] tbl = new ushort[262] { 2305, 43264, 63616, 10368, 6272, 14464, 18560, 22656, 26752, 34944, 39040, 47232, 30848, 2177, 10498, 6277, 14595, 18561, 22657, 26753, 35088, 39041, 43137, 47233, 30849, 64004, 4352, 43266, 64258, 2177, 10369, 14465, 18561, 22657, 26753, 34945, 39041, 47233, 30849, 14597, 2307, 10499, 6403, 18691, 22787, 26883, 35075, 39171, 43267, 47363, 30979, 63747, 64260, 8710, 4615, 41480, 2177, 14465, 18561, 22657, 26753, 34945, 39041, 47233, 30849, 6400, 2307, 10499, 14595, 18691, 22787, 26883, 35075, 39171, 43267, 47363, 30979, 63747, 6400, 2177, 10369, 14465, 18561, 22657, 26753, 34945, 39041, 43137, 47233, 30849, 63617, 2561, 23818, 11274, 7178, 15370, 19466, 27658, 35850, 39946, 43783, 48138, 31754, 64522, 64265, 8198, 4103, 43272, 2177, 14465, 18561, 22657, 26753, 34945, 39041, 47233, 30849, 64265, 17163, 43276, 2178, 10370, 6274, 14466, 22658, 26754, 34946, 39042, 47234, 30850, 2317, 23818, 11274, 7178, 15370, 19466, 27658, 35850, 39946, 44042, 48138, 31754, 64522, 26894, 30991, 43275, 2180, 10372, 6276, 14468, 18564, 22660, 34948, 39044, 47236, 63620, 17163, 43276, 2178, 10370, 6274, 14466, 22658, 26754, 34946, 39042, 47234, 30850, 63618, 9474, 35088, 2182, 6278, 14470, 18566, 22662, 26758, 39046, 43142, 47238, 30854, 63622, 25617, 23822, 2830, 11022, 6926, 15118, 19214, 35598, 39694, 43790, 47886, 31502, 64270, 29713, 23823, 2831, 11023, 6927, 15119, 19215, 27407, 35599, 39695, 43791, 47887, 64271, 38418, 6400, 1555, 9747, 13843, 17939, 22035, 26131, 34323, 42515, 46611, 30227, 62995, 8198, 4103, 43281, 64265, 2177, 14465, 18561, 22657, 26753, 34945, 39041, 47233, 30849, 46858, 3090, 11282, 7186, 15378, 19474, 23570, 27666, 35858, 39954, 44050, 31762, 64530, 3091, 11283, 7187, 15379, 19475, 23571, 27667, 35859, 39955, 44051, 48147, 31763, 64531, 65535, 65535 }; protected static string[] errors = new string[8] { "Expected element", "Invalid character in tag", "No '='", "Invalid character entity", "Invalid attr value", "Empty tag", "No end tag", "Bad entity ref" }; protected int line; protected int col; protected int[] twoCharBuff; protected bool splitCData; public MiniParser() { twoCharBuff = new int[2]; splitCData = false; Reset(); } public void Reset() { line = 0; col = 0; } protected static bool StrEquals(string str, StringBuilder sb, int sbStart, int len) { if (len != str.Length) { return false; } for (int i = 0; i < len; i++) { if (str[i] != sb[sbStart + i]) { return false; } } return true; } protected void FatalErr(string descr) { throw new XMLError(descr, line, col); } protected static int Xlat(int charCode, int state) { int num = state * INPUT_RANGE; int num2 = System.Math.Min(tbl.Length - num, INPUT_RANGE); while (--num2 >= 0) { ushort num3 = tbl[num]; if (charCode == num3 >> 12) { return num3 & 0xFFF; } num++; } return 4095; } public void Parse(IReader reader, IHandler handler) { if (reader == null) { throw new ArgumentNullException("reader"); } if (handler == null) { handler = new HandlerAdapter(); } AttrListImpl attrListImpl = new AttrListImpl(); string text = null; Stack stack = new Stack(); string text2 = null; line = 1; col = 0; int num = 0; int num2 = 0; StringBuilder stringBuilder = new StringBuilder(); bool flag = false; bool flag2 = false; bool flag3 = false; int num3 = 0; handler.OnStartParsing(this); while (true) { col++; num = reader.Read(); if (num == -1) { break; } int num4 = "<>/?=&'\"![ ]\t\r\n".IndexOf((char)num) & 0xF; switch (num4) { case 13: continue; case 12: num4 = 10; break; } if (num4 == 14) { col = 0; line++; num4 = 10; } int num5 = Xlat(num4, num2); num2 = num5 & 0xFF; if (num == 10 && (num2 == 14 || num2 == 15)) { continue; } num5 >>= 8; if (num2 >= 128) { if (num2 == 255) { FatalErr("State dispatch error."); } else { FatalErr(errors[num2 ^ 0x80]); } } switch (num5) { case 9: break; case 0: handler.OnStartElement(text2, attrListImpl); if (num != 47) { stack.Push(text2); } else { handler.OnEndElement(text2); } attrListImpl.Clear(); break; case 1: { text2 = stringBuilder.ToString(); stringBuilder = new StringBuilder(); string text6 = null; if (stack.Count == 0 || text2 != (text6 = stack.Pop() as string)) { if (text6 == null) { FatalErr("Tag stack underflow"); } else { FatalErr($"Expected end tag '{text2}' but found '{text6}'"); } } handler.OnEndElement(text2); break; } case 2: text2 = stringBuilder.ToString(); stringBuilder = new StringBuilder(); if (num != 47 && num != 62) { break; } goto case 0; case 3: text = stringBuilder.ToString(); stringBuilder = new StringBuilder(); break; case 4: if (text == null) { FatalErr("Internal error."); } attrListImpl.Add(text, stringBuilder.ToString()); stringBuilder = new StringBuilder(); text = null; break; case 5: handler.OnChars(stringBuilder.ToString()); stringBuilder = new StringBuilder(); break; case 6: { string text5 = "CDATA["; flag2 = false; flag3 = false; switch (num) { case 45: num = reader.Read(); if (num != 45) { FatalErr("Invalid comment"); } col++; flag2 = true; twoCharBuff[0] = -1; twoCharBuff[1] = -1; break; default: flag3 = true; num3 = 0; break; case 91: { for (int i = 0; i < text5.Length; i++) { if (reader.Read() != text5[i]) { col += i + 1; break; } } col += text5.Length; flag = true; break; } } break; } case 7: { int num20 = 0; num = 93; while (true) { switch (num) { case 93: goto IL_033d; default: { for (int k = 0; k < num20; k++) { stringBuilder.Append(']'); } stringBuilder.Append((char)num); num2 = 18; break; } case 62: { for (int j = 0; j < num20 - 2; j++) { stringBuilder.Append(']'); } flag = false; break; } } break; IL_033d: num = reader.Read(); num20++; } col += num20; break; } case 8: FatalErr($"Error {num2}"); break; case 10: stringBuilder = new StringBuilder(); if (num == 60) { break; } goto case 11; case 11: stringBuilder.Append((char)num); break; case 12: if (flag2) { if (num == 62 && twoCharBuff[0] == 45 && twoCharBuff[1] == 45) { flag2 = false; num2 = 0; } else { twoCharBuff[0] = twoCharBuff[1]; twoCharBuff[1] = num; } } else if (flag3) { if (num == 60 || num == 62) { num3 ^= 1; } if (num == 62 && num3 != 0) { flag3 = false; num2 = 0; } } else { if (splitCData && stringBuilder.Length > 0 && flag) { handler.OnChars(stringBuilder.ToString()); stringBuilder = new StringBuilder(); } flag = false; stringBuilder.Append((char)num); } break; case 13: { num = reader.Read(); int num6 = col + 1; if (num == 35) { int num7 = 10; int num8 = 0; int num9 = 0; num = reader.Read(); num6++; if (num == 120) { num = reader.Read(); num6++; num7 = 16; } NumberStyles style = ((num7 == 16) ? NumberStyles.HexNumber : NumberStyles.Integer); while (true) { int num10 = -1; if (char.IsNumber((char)num) || "abcdef".IndexOf(char.ToLower((char)num)) != -1) { try { num10 = int.Parse(new string((char)num, 1), style); } catch (FormatException) { num10 = -1; } } if (num10 == -1) { break; } num8 *= num7; num8 += num10; num9++; num = reader.Read(); num6++; } if (num == 59 && num9 > 0) { stringBuilder.Append((char)num8); } else { FatalErr("Bad char ref"); } } else { string text3 = "aglmopqstu"; string text4 = "&'\"><"; int num11 = 0; int num12 = 15; int num13 = 0; int length = stringBuilder.Length; while (true) { if (num11 != 15) { num11 = text3.IndexOf((char)num) & 0xF; } if (num11 == 15) { FatalErr(errors[7]); } stringBuilder.Append((char)num); int num14 = "U㾏侏ཟク\ue1f4⊙\ueeff\ueeffo"[num11]; int num15 = (num14 >> 4) & 0xF; int num16 = num14 & 0xF; int num17 = num14 >> 12; int num18 = (num14 >> 8) & 0xF; num = reader.Read(); num6++; num11 = 15; if (num15 != 15 && num == text3[num15]) { if (num17 < 14) { num12 = num17; } num13 = 12; } else if (num16 != 15 && num == text3[num16]) { if (num18 < 14) { num12 = num18; } num13 = 8; } else if (num == 59) { if (num12 != 15 && num13 != 0 && ((num14 >> num13) & 0xF) == 14) { break; } continue; } num11 = 0; } int num19 = num6 - col - 1; if (num19 > 0 && num19 < 5 && (StrEquals("amp", stringBuilder, length, num19) || StrEquals("apos", stringBuilder, length, num19) || StrEquals("quot", stringBuilder, length, num19) || StrEquals("lt", stringBuilder, length, num19) || StrEquals("gt", stringBuilder, length, num19))) { stringBuilder.Length = length; stringBuilder.Append(text4[num12]); } else { FatalErr(errors[7]); } } col = num6; break; } default: FatalErr($"Unexpected action code - {num5}."); break; } } if (num2 != 0) { FatalErr("Unexpected EOF"); } handler.OnEndParsing(this); } } [CLSCompliant(false)] public class SecurityParser : MiniParser, MiniParser.IHandler, MiniParser.IReader { private SecurityElement root; private string xmldoc; private int pos; private SecurityElement current; private Stack stack; public SecurityParser() { stack = new Stack(); } public void LoadXml(string xml) { root = null; xmldoc = xml; pos = 0; stack.Clear(); Parse(this, this); } public SecurityElement ToXml() { return root; } public int Read() { if (pos >= xmldoc.Length) { return -1; } return xmldoc[pos++]; } public void OnStartParsing(MiniParser parser) { } public void OnStartElement(string name, IAttrList attrs) { SecurityElement securityElement = new SecurityElement(name); if (root == null) { root = securityElement; current = securityElement; } else { ((SecurityElement)stack.Peek()).AddChild(securityElement); } stack.Push(securityElement); current = securityElement; int length = attrs.Length; for (int i = 0; i < length; i++) { current.AddAttribute(attrs.GetName(i), SecurityElement.Escape(attrs.GetValue(i))); } } public void OnEndElement(string name) { current = (SecurityElement)stack.Pop(); } public void OnChars(string ch) { current.Text = SecurityElement.Escape(ch); } public void OnEndParsing(MiniParser parser) { } } } namespace Mono.Security { public class ASN1 { private byte m_nTag; private byte[] m_aValue; private ArrayList elist; public int Count { get { if (elist == null) { return 0; } return elist.Count; } } public byte Tag => m_nTag; public int Length { get { if (m_aValue != null) { return m_aValue.Length; } return 0; } } public byte[] Value { get { if (m_aValue == null) { GetBytes(); } return (byte[])m_aValue.Clone(); } set { if (value != null) { m_aValue = (byte[])value.Clone(); } } } public ASN1 this[int index] { get { try { if (elist == null || index >= elist.Count) { return null; } return (ASN1)elist[index]; } catch (ArgumentOutOfRangeException) { return null; } } } public ASN1() : this(0, null) { } public ASN1(byte tag) : this(tag, null) { } public ASN1(byte tag, byte[] data) { m_nTag = tag; m_aValue = data; } public ASN1(byte[] data) { m_nTag = data[0]; int num = 0; int num2 = data[1]; if (num2 > 128) { num = num2 - 128; num2 = 0; for (int i = 0; i < num; i++) { num2 *= 256; num2 += data[i + 2]; } } else if (num2 == 128) { throw new NotSupportedException("Undefined length encoding."); } m_aValue = new byte[num2]; Buffer.BlockCopy(data, 2 + num, m_aValue, 0, num2); if ((m_nTag & 0x20) == 32) { int anPos = 0; Decode(m_aValue, ref anPos, m_aValue.Length); } } private bool CompareArray(byte[] array1, byte[] array2) { bool flag = array1.Length == array2.Length; if (flag) { for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { return false; } } } return flag; } public bool Equals(byte[] asn1) { return CompareArray(GetBytes(), asn1); } public bool CompareValue(byte[] value) { return CompareArray(m_aValue, value); } public ASN1 Add(ASN1 asn1) { if (asn1 != null) { if (elist == null) { elist = new ArrayList(); } elist.Add(asn1); } return asn1; } public virtual byte[] GetBytes() { byte[] array = null; if (Count > 0) { int num = 0; ArrayList arrayList = new ArrayList(); foreach (ASN1 item in elist) { byte[] bytes = item.GetBytes(); arrayList.Add(bytes); num += bytes.Length; } array = new byte[num]; int num2 = 0; for (int i = 0; i < elist.Count; i++) { byte[] array2 = (byte[])arrayList[i]; Buffer.BlockCopy(array2, 0, array, num2, array2.Length); num2 += array2.Length; } } else if (m_aValue != null) { array = m_aValue; } int num3 = 0; byte[] array3; if (array != null) { int num4 = array.Length; if (num4 > 127) { if (num4 <= 255) { array3 = new byte[3 + num4]; Buffer.BlockCopy(array, 0, array3, 3, num4); num3 = 129; array3[2] = (byte)num4; } else if (num4 <= 65535) { array3 = new byte[4 + num4]; Buffer.BlockCopy(array, 0, array3, 4, num4); num3 = 130; array3[2] = (byte)(num4 >> 8); array3[3] = (byte)num4; } else if (num4 <= 16777215) { array3 = new byte[5 + num4]; Buffer.BlockCopy(array, 0, array3, 5, num4); num3 = 131; array3[2] = (byte)(num4 >> 16); array3[3] = (byte)(num4 >> 8); array3[4] = (byte)num4; } else { array3 = new byte[6 + num4]; Buffer.BlockCopy(array, 0, array3, 6, num4); num3 = 132; array3[2] = (byte)(num4 >> 24); array3[3] = (byte)(num4 >> 16); array3[4] = (byte)(num4 >> 8); array3[5] = (byte)num4; } } else { array3 = new byte[2 + num4]; Buffer.BlockCopy(array, 0, array3, 2, num4); num3 = num4; } if (m_aValue == null) { m_aValue = array; } } else { array3 = new byte[2]; } array3[0] = m_nTag; array3[1] = (byte)num3; return array3; } protected void Decode(byte[] asn1, ref int anPos, int anLength) { while (anPos < anLength - 1) { DecodeTLV(asn1, ref anPos, out var tag, out var length, out var content); if (tag != 0) { ASN1 aSN = Add(new ASN1(tag, content)); if ((tag & 0x20) == 32) { int anPos2 = anPos; aSN.Decode(asn1, ref anPos2, anPos2 + length); } anPos += length; } } } protected void DecodeTLV(byte[] asn1, ref int pos, out byte tag, out int length, out byte[] content) { tag = asn1[pos++]; length = asn1[pos++]; if ((length & 0x80) == 128) { int num = length & 0x7F; length = 0; for (int i = 0; i < num; i++) { length = length * 256 + asn1[pos++]; } } content = new byte[length]; Buffer.BlockCopy(asn1, pos, content, 0, length); } public ASN1 Element(int index, byte anTag) { try { if (elist == null || index >= elist.Count) { return null; } ASN1 aSN = (ASN1)elist[index]; if (aSN.Tag == anTag) { return aSN; } return null; } catch (ArgumentOutOfRangeException) { return null; } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("Tag: {0} {1}", m_nTag.ToString("X2"), Environment.NewLine); stringBuilder.AppendFormat("Length: {0} {1}", Value.Length, Environment.NewLine); stringBuilder.Append("Value: "); stringBuilder.Append(Environment.NewLine); for (int i = 0; i < Value.Length; i++) { stringBuilder.AppendFormat("{0} ", Value[i].ToString("X2")); if ((i + 1) % 16 == 0) { stringBuilder.AppendFormat(Environment.NewLine); } } return stringBuilder.ToString(); } public void SaveToFile(string filename) { if (filename == null) { throw new ArgumentNullException("filename"); } using FileStream fileStream = File.Create(filename); byte[] bytes = GetBytes(); fileStream.Write(bytes, 0, bytes.Length); } } public static class ASN1Convert { public static ASN1 FromDateTime(DateTime dt) { if (dt.Year < 2050) { return new ASN1(23, Encoding.ASCII.GetBytes(dt.ToUniversalTime().ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z")); } return new ASN1(24, Encoding.ASCII.GetBytes(dt.ToUniversalTime().ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z")); } public static ASN1 FromInt32(int value) { byte[] bytes = BitConverterLE.GetBytes(value); Array.Reverse(bytes); int i; for (i = 0; i < bytes.Length && bytes[i] == 0; i++) { } ASN1 aSN = new ASN1(2); switch (i) { case 0: aSN.Value = bytes; break; case 4: aSN.Value = new byte[1]; break; default: { byte[] array = new byte[4 - i]; Buffer.BlockCopy(bytes, i, array, 0, array.Length); aSN.Value = array; break; } } return aSN; } public static ASN1 FromOid(string oid) { if (oid == null) { throw new ArgumentNullException("oid"); } return new ASN1(CryptoConfig.EncodeOID(oid)); } public static ASN1 FromUnsignedBigInteger(byte[] big) { if (big == null) { throw new ArgumentNullException("big"); } if (big[0] >= 128) { int num = big.Length + 1; byte[] array = new byte[num]; Buffer.BlockCopy(big, 0, array, 1, num - 1); big = array; } return new ASN1(2, big); } public static int ToInt32(ASN1 asn1) { if (asn1 == null) { throw new ArgumentNullException("asn1"); } if (asn1.Tag != 2) { throw new FormatException("Only integer can be converted"); } int num = 0; for (int i = 0; i < asn1.Value.Length; i++) { num = (num << 8) + asn1.Value[i]; } return num; } public static string ToOid(ASN1 asn1) { if (asn1 == null) { throw new ArgumentNullException("asn1"); } byte[] value = asn1.Value; StringBuilder stringBuilder = new StringBuilder(); byte b = (byte)(value[0] / 40); byte b2 = (byte)(value[0] % 40); if (b > 2) { b2 += (byte)((b - 2) * 40); b = 2; } stringBuilder.Append(b.ToString(CultureInfo.InvariantCulture)); stringBuilder.Append("."); stringBuilder.Append(b2.ToString(CultureInfo.InvariantCulture)); ulong num = 0uL; for (b = 1; b < value.Length; b++) { num = (num << 7) | (byte)(value[b] & 0x7Fu); if ((value[b] & 0x80) != 128) { stringBuilder.Append("."); stringBuilder.Append(num.ToString(CultureInfo.InvariantCulture)); num = 0uL; } } return stringBuilder.ToString(); } public static DateTime ToDateTime(ASN1 time) { if (time == null) { throw new ArgumentNullException("time"); } string text = Encoding.ASCII.GetString(time.Value); string format = null; switch (text.Length) { case 11: format = "yyMMddHHmmZ"; break; case 13: text = ((Convert.ToInt16(text.Substring(0, 2), CultureInfo.InvariantCulture) < 50) ? ("20" + text) : ("19" + text)); format = "yyyyMMddHHmmssZ"; break; case 15: format = "yyyyMMddHHmmssZ"; break; case 17: { string text2 = ((Convert.ToInt16(text.Substring(0, 2), CultureInfo.InvariantCulture) >= 50) ? "19" : "20"); char c = ((text[12] == '+') ? '-' : '+'); text = $"{text2}{text.Substring(0, 12)}{c}{text[13]}{text[14]}:{text[15]}{text[16]}"; format = "yyyyMMddHHmmsszzz"; break; } } return DateTime.ParseExact(text, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); } } internal sealed class BitConverterLE { private BitConverterLE() { } private unsafe static byte[] GetUShortBytes(byte* bytes) { if (!BitConverter.IsLittleEndian) { return new byte[2] { bytes[1], *bytes }; } return new byte[2] { *bytes, bytes[1] }; } private unsafe static byte[] GetUIntBytes(byte* bytes) { if (!BitConverter.IsLittleEndian) { return new byte[4] { bytes[3], bytes[2], bytes[1], *bytes }; } return new byte[4] { *bytes, bytes[1], bytes[2], bytes[3] }; } private unsafe static byte[] GetULongBytes(byte* bytes) { if (!BitConverter.IsLittleEndian) { return new byte[8] { bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], *bytes }; } return new byte[8] { *bytes, bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7] }; } internal static byte[] GetBytes(bool value) { return new byte[1] { (byte)(value ? 1 : 0) }; } internal unsafe static byte[] GetBytes(char value) { return GetUShortBytes((byte*)(&value)); } internal unsafe static byte[] GetBytes(short value) { return GetUShortBytes((byte*)(&value)); } internal unsafe static byte[] GetBytes(int value) { return GetUIntBytes((byte*)(&value)); } internal unsafe static byte[] GetBytes(long value) { return GetULongBytes((byte*)(&value)); } internal unsafe static byte[] GetBytes(ushort value) { return GetUShortBytes((byte*)(&value)); } internal unsafe static byte[] GetBytes(uint value) { return GetUIntBytes((byte*)(&value)); } internal unsafe static byte[] GetBytes(ulong value) { return GetULongBytes((byte*)(&value)); } internal unsafe static byte[] GetBytes(float value) { return GetUIntBytes((byte*)(&value)); } internal unsafe static byte[] GetBytes(double value) { return GetULongBytes((byte*)(&value)); } private unsafe static void UShortFromBytes(byte* dst, byte[] src, int startIndex) { if (BitConverter.IsLittleEndian) { *dst = src[startIndex]; dst[1] = src[startIndex + 1]; } else { *dst = src[startIndex + 1]; dst[1] = src[startIndex]; } } private unsafe static void UIntFromBytes(byte* dst, byte[] src, int startIndex) { if (BitConverter.IsLittleEndian) { *dst = src[startIndex]; dst[1] = src[startIndex + 1]; dst[2] = src[startIndex + 2]; dst[3] = src[startIndex + 3]; } else { *dst = src[startIndex + 3]; dst[1] = src[startIndex + 2]; dst[2] = src[startIndex + 1]; dst[3] = src[startIndex]; } } private unsafe static void ULongFromBytes(byte* dst, byte[] src, int startIndex) { if (BitConverter.IsLittleEndian) { for (int i = 0; i < 8; i++) { dst[i] = src[startIndex + i]; } } else { for (int j = 0; j < 8; j++) { dst[j] = src[startIndex + (7 - j)]; } } } internal static bool ToBoolean(byte[] value, int startIndex) { return value[startIndex] != 0; } internal unsafe static char ToChar(byte[] value, int startIndex) { char result = default(char); UShortFromBytes((byte*)(&result), value, startIndex); return result; } internal unsafe static short ToInt16(byte[] value, int startIndex) { short result = default(short); UShortFromBytes((byte*)(&result), value, startIndex); return result; } internal unsafe static int ToInt32(byte[] value, int startIndex) { int result = default(int); UIntFromBytes((byte*)(&result), value, startIndex); return result; } internal unsafe static long ToInt64(byte[] value, int startIndex) { long result = default(long); ULongFromBytes((byte*)(&result), value, startIndex); return result; } internal unsafe static ushort ToUInt16(byte[] value, int startIndex) { ushort result = default(ushort); UShortFromBytes((byte*)(&result), value, startIndex); return result; } internal unsafe static uint ToUInt32(byte[] value, int startIndex) { uint result = default(uint); UIntFromBytes((byte*)(&result), value, startIndex); return result; } internal unsafe static ulong ToUInt64(byte[] value, int startIndex) { ulong result = default(ulong); ULongFromBytes((byte*)(&result), value, startIndex); return result; } internal unsafe static float ToSingle(byte[] value, int startIndex) { float result = default(float); UIntFromBytes((byte*)(&result), value, startIndex); return result; } internal unsafe static double ToDouble(byte[] value, int startIndex) { double result = default(double); ULongFromBytes((byte*)(&result), value, startIndex); return result; } } public sealed class PKCS7 { public class Oid { public const string rsaEncryption = "1.2.840.113549.1.1.1"; public const string data = "1.2.840.113549.1.7.1"; public const string signedData = "1.2.840.113549.1.7.2"; public const string envelopedData = "1.2.840.113549.1.7.3"; public const string signedAndEnvelopedData = "1.2.840.113549.1.7.4"; public const string digestedData = "1.2.840.113549.1.7.5"; public const string encryptedData = "1.2.840.113549.1.7.6"; public const string contentType = "1.2.840.113549.1.9.3"; public const string messageDigest = "1.2.840.113549.1.9.4"; public const string signingTime = "1.2.840.113549.1.9.5"; public const string countersignature = "1.2.840.113549.1.9.6"; } public class ContentInfo { private string contentType; private ASN1 content; public ASN1 ASN1 => GetASN1(); public ASN1 Content { get { return content; } set { content = value; } } public string ContentType { get { return contentType; } set { contentType = value; } } public ContentInfo() { content = new ASN1(160); } public ContentInfo(string oid) : this() { contentType = oid; } public ContentInfo(byte[] data) : this(new ASN1(data)) { } public ContentInfo(ASN1 asn1) { if (asn1.Tag != 48 || (asn1.Count < 1 && asn1.Count > 2)) { throw new ArgumentException("Invalid ASN1"); } if (asn1[0].Tag != 6) { throw new ArgumentException("Invalid contentType"); } contentType = ASN1Convert.ToOid(asn1[0]); if (asn1.Count > 1) { if (asn1[1].Tag != 160) { throw new ArgumentException("Invalid content"); } content = asn1[1]; } } internal ASN1 GetASN1() { ASN1 aSN = new ASN1(48); aSN.Add(ASN1Convert.FromOid(contentType)); if (content != null && content.Count > 0) { aSN.Add(content); } return aSN; } public byte[] GetBytes() { return GetASN1().GetBytes(); } } public class EncryptedData { private byte _version; private ContentInfo _content; private ContentInfo _encryptionAlgorithm; private byte[] _encrypted; public ASN1 ASN1 => GetASN1(); public ContentInfo ContentInfo => _content; public ContentInfo EncryptionAlgorithm => _encryptionAlgorithm; public byte[] EncryptedContent { get { if (_encrypted == null) { return null; } return (byte[])_encrypted.Clone(); } } public byte Version { get { return _version; } set { _version = value; } } public EncryptedData() { _version = 0; } public EncryptedData(byte[] data) : this(new ASN1(data)) { } public EncryptedData(ASN1 asn1) : this() { if (asn1.Tag != 48 || asn1.Count < 2) { throw new ArgumentException("Invalid EncryptedData"); } if (asn1[0].Tag != 2) { throw new ArgumentException("Invalid version"); } _version = asn1[0].Value[0]; ASN1 aSN = asn1[1]; if (aSN.Tag != 48) { throw new ArgumentException("missing EncryptedContentInfo"); } ASN1 aSN2 = aSN[0]; if (aSN2.Tag != 6) { throw new ArgumentException("missing EncryptedContentInfo.ContentType"); } _content = new ContentInfo(ASN1Convert.ToOid(aSN2)); ASN1 aSN3 = aSN[1]; if (aSN3.Tag != 48) { throw new ArgumentException("missing EncryptedContentInfo.ContentEncryptionAlgorithmIdentifier"); } _encryptionAlgorithm = new ContentInfo(ASN1Convert.ToOid(aSN3[0])); _encryptionAlgorithm.Content = aSN3[1]; ASN1 aSN4 = aSN[2]; if (aSN4.Tag != 128) { throw new ArgumentException("missing EncryptedContentInfo.EncryptedContent"); } _encrypted = aSN4.Value; } internal ASN1 GetASN1() { return null; } public byte[] GetBytes() { return GetASN1().GetBytes(); } } public class EnvelopedData { private byte _version; private ContentInfo _content; private ContentInfo _encryptionAlgorithm; private ArrayList _recipientInfos; private byte[] _encrypted; public ArrayList RecipientInfos => _recipientInfos; public ASN1 ASN1 => GetASN1(); public ContentInfo ContentInfo => _content; public ContentInfo EncryptionAlgorithm => _encryptionAlgorithm; public byte[] EncryptedContent { get { if (_encrypted == null) { return null; } return (byte[])_encrypted.Clone(); } } public byte Version { get { return _version; } set { _version = value; } } public EnvelopedData() { _version = 0; _content = new ContentInfo(); _encryptionAlgorithm = new ContentInfo(); _recipientInfos = new ArrayList(); } public EnvelopedData(byte[] data) : this(new ASN1(data)) { } public EnvelopedData(ASN1 asn1) : this() { if (asn1[0].Tag != 48 || asn1[0].Count < 3) { throw new ArgumentException("Invalid EnvelopedData"); } if (asn1[0][0].Tag != 2) { throw new ArgumentException("Invalid version"); } _version = asn1[0][0].Value[0]; ASN1 aSN = asn1[0][1]; if (aSN.Tag != 49) { throw new ArgumentException("missing RecipientInfos"); } for (int i = 0; i < aSN.Count; i++) { ASN1 data = aSN[i]; _recipientInfos.Add(new RecipientInfo(data)); } ASN1 aSN2 = asn1[0][2]; if (aSN2.Tag != 48) { throw new ArgumentException("missing EncryptedContentInfo"); } ASN1 aSN3 = aSN2[0]; if (aSN3.Tag != 6) { throw new ArgumentException("missing EncryptedContentInfo.ContentType"); } _content = new ContentInfo(ASN1Convert.ToOid(aSN3)); ASN1 aSN4 = aSN2[1]; if (aSN4.Tag != 48) { throw new ArgumentException("missing EncryptedContentInfo.ContentEncryptionAlgorithmIdentifier"); } _encryptionAlgorithm = new ContentInfo(ASN1Convert.ToOid(aSN4[0])); _encryptionAlgorithm.Content = aSN4[1]; ASN1 aSN5 = aSN2[2]; if (aSN5.Tag != 128) { throw new ArgumentException("missing EncryptedContentInfo.EncryptedContent"); } _encrypted = aSN5.Value; } internal ASN1 GetASN1() { return new ASN1(48); } public byte[] GetBytes() { return GetASN1().GetBytes(); } } public class RecipientInfo { private int _version; private string _oid; private byte[] _key; private byte[] _ski; private string _issuer; private byte[] _serial; public string Oid => _oid; public byte[] Key { get { if (_key == null) { return null; } return (byte[])_key.Clone(); } } public byte[] SubjectKeyIdentifier { get { if (_ski == null) { return null; } return (byte[])_ski.Clone(); } } public string Issuer => _issuer; public byte[] Serial { get { if (_serial == null) { return null; } return (byte[])_serial.Clone(); } } public int Version => _version; public RecipientInfo() { } public RecipientInfo(ASN1 data) { if (data.Tag != 48) { throw new ArgumentException("Invalid RecipientInfo"); } ASN1 aSN = data[0]; if (aSN.Tag != 2) { throw new ArgumentException("missing Version"); } _version = aSN.Value[0]; ASN1 aSN2 = data[1]; if (aSN2.Tag == 128 && _version == 3) { _ski = aSN2.Value; } else { _issuer = X501.ToString(aSN2[0]); _serial = aSN2[1].Value; } ASN1 aSN3 = data[2]; _oid = ASN1Convert.ToOid(aSN3[0]); ASN1 aSN4 = data[3]; _key = aSN4.Value; } } public class SignedData { private byte version; private string hashAlgorithm; private ContentInfo contentInfo; private Mono.Security.X509.X509CertificateCollection certs; private ArrayList crls; private SignerInfo signerInfo; private bool mda; private bool signed; public ASN1 ASN1 => GetASN1(); public Mono.Security.X509.X509CertificateCollection Certificates => certs; public ContentInfo ContentInfo => contentInfo; public ArrayList Crls => crls; public string HashName { get { return hashAlgorithm; } set { hashAlgorithm = value; signerInfo.HashName = value; } } public SignerInfo SignerInfo => signerInfo; public byte Version { get { return version; } set { version = value; } } public bool UseAuthenticatedAttributes { get { return mda; } set { mda = value; } } public SignedData() { version = 1; contentInfo = new ContentInfo(); certs = new Mono.Security.X509.X509CertificateCollection(); crls = new ArrayList(); signerInfo = new SignerInfo(); mda = true; signed = false; } public SignedData(byte[] data) : this(new ASN1(data)) { } public SignedData(ASN1 asn1) { if (asn1[0].Tag != 48 || asn1[0].Count < 4) { throw new ArgumentException("Invalid SignedData"); } if (asn1[0][0].Tag != 2) { throw new ArgumentException("Invalid version"); } version = asn1[0][0].Value[0]; contentInfo = new ContentInfo(asn1[0][2]); int num = 3; certs = new Mono.Security.X509.X509CertificateCollection(); if (asn1[0][num].Tag == 160) { for (int i = 0; i < asn1[0][num].Count; i++) { certs.Add(new Mono.Security.X509.X509Certificate(asn1[0][num][i].GetBytes())); } num++; } crls = new ArrayList(); if (asn1[0][num].Tag == 161) { for (int j = 0; j < asn1[0][num].Count; j++) { crls.Add(asn1[0][num][j].GetBytes()); } num++; } if (asn1[0][num].Count > 0) { signerInfo = new SignerInfo(asn1[0][num]); } else { signerInfo = new SignerInfo(); } if (signerInfo.HashName != null) { HashName = OidToName(signerInfo.HashName); } mda = signerInfo.AuthenticatedAttributes.Count > 0; } public bool VerifySignature(AsymmetricAlgorithm aa) { if (aa == null) { return false; } RSAPKCS1SignatureDeformatter rSAPKCS1SignatureDeformatter = new RSAPKCS1SignatureDeformatter(aa); rSAPKCS1SignatureDeformatter.SetHashAlgorithm(this.hashAlgorithm); HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashAlgorithm); byte[] signature = signerInfo.Signature; byte[] array = null; if (mda) { ASN1 aSN = new ASN1(49); foreach (ASN1 authenticatedAttribute in signerInfo.AuthenticatedAttributes) { aSN.Add(authenticatedAttribute); } array = hashAlgorithm.ComputeHash(aSN.GetBytes()); } else { array = hashAlgorithm.ComputeHash(contentInfo.Content[0].Value); } if (array != null && signature != null) { return rSAPKCS1SignatureDeformatter.VerifySignature(array, signature); } return false; } internal string OidToName(string oid) { return oid switch { "1.3.14.3.2.26" => "SHA1", "1.2.840.113549.2.2" => "MD2", "1.2.840.113549.2.5" => "MD5", "2.16.840.1.101.3.4.1" => "SHA256", "2.16.840.1.101.3.4.2" => "SHA384", "2.16.840.1.101.3.4.3" => "SHA512", _ => oid, }; } internal ASN1 GetASN1() { ASN1 aSN = new ASN1(48); byte[] data = new byte[1] { version }; aSN.Add(new ASN1(2, data)); ASN1 aSN2 = aSN.Add(new ASN1(49)); if (hashAlgorithm != null) { string oid = CryptoConfig.MapNameToOID(hashAlgorithm); aSN2.Add(AlgorithmIdentifier(oid)); } ASN1 aSN3 = contentInfo.ASN1; aSN.Add(aSN3); if (!signed && hashAlgorithm != null) { if (mda) { ASN1 value = Attribute("1.2.840.113549.1.9.3", aSN3[0]); signerInfo.AuthenticatedAttributes.Add(value); byte[] data2 = HashAlgorithm.Create(hashAlgorithm).ComputeHash(aSN3[1][0].Value); ASN1 aSN4 = new ASN1(48); ASN1 value2 = Attribute("1.2.840.113549.1.9.4", aSN4.Add(new ASN1(4, data2))); signerInfo.AuthenticatedAttributes.Add(value2); } else { RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(signerInfo.Key); rSAPKCS1SignatureFormatter.SetHashAlgorithm(hashAlgorithm); byte[] rgbHash = HashAlgorithm.Create(hashAlgorithm).ComputeHash(aSN3[1][0].Value); signerInfo.Signature = rSAPKCS1SignatureFormatter.CreateSignature(rgbHash); } signed = true; } if (certs.Count > 0) { ASN1 aSN5 = aSN.Add(new ASN1(160)); foreach (Mono.Security.X509.X509Certificate cert in certs) { aSN5.Add(new ASN1(cert.RawData)); } } if (crls.Count > 0) { ASN1 aSN6 = aSN.Add(new ASN1(161)); foreach (byte[] crl in crls) { aSN6.Add(new ASN1(crl)); } } ASN1 aSN7 = aSN.Add(new ASN1(49)); if (signerInfo.Key != null) { aSN7.Add(signerInfo.ASN1); } return aSN; } public byte[] GetBytes() { return GetASN1().GetBytes(); } } public class SignerInfo { private byte version; private Mono.Security.X509.X509Certificate x509; private string hashAlgorithm; private AsymmetricAlgorithm key; private ArrayList authenticatedAttributes; private ArrayList unauthenticatedAttributes; private byte[] signature; private string issuer; private byte[] serial; private byte[] ski; public string IssuerName => issuer; public byte[] SerialNumber { get { if (serial == null) { return null; } return (byte[])serial.Clone(); } } public byte[] SubjectKeyIdentifier { get { if (ski == null) { return null; } return (byte[])ski.Clone(); } } public ASN1 ASN1 => GetASN1(); public ArrayList AuthenticatedAttributes => authenticatedAttributes; public Mono.Security.X509.X509Certificate Certificate { get { return x509; } set { x509 = value; } } public string HashName { get { return hashAlgorithm; } set { hashAlgorithm = value; } } public AsymmetricAlgorithm Key { get { return key; } set { key = value; } } public byte[] Signature { get { if (signature == null) { return null; } return (byte[])signature.Clone(); } set { if (value != null) { signature = (byte[])value.Clone(); } } } public ArrayList UnauthenticatedAttributes => unauthenticatedAttributes; public byte Version { get { return version; } set { version = value; } } public SignerInfo() { version = 1; authenticatedAttributes = new ArrayList(); unauthenticatedAttributes = new ArrayList(); } public SignerInfo(byte[] data) : this(new ASN1(data)) { } public SignerInfo(ASN1 asn1) : this() { if (asn1[0].Tag != 48 || asn1[0].Count < 5) { throw new ArgumentException("Invalid SignedData"); } if (asn1[0][0].Tag != 2) { throw new ArgumentException("Invalid version"); } version = asn1[0][0].Value[0]; ASN1 aSN = asn1[0][1]; if (aSN.Tag == 128 && version == 3) { ski = aSN.Value; } else { issuer = X501.ToString(aSN[0]); serial = aSN[1].Value; } ASN1 aSN2 = asn1[0][2]; hashAlgorithm = ASN1Convert.ToOid(aSN2[0]); int num = 3; ASN1 aSN3 = asn1[0][num]; if (aSN3.Tag == 160) { num++; for (int i = 0; i < aSN3.Count; i++) { authenticatedAttributes.Add(aSN3[i]); } } num++; ASN1 aSN4 = asn1[0][num++]; if (aSN4.Tag == 4) { signature = aSN4.Value; } ASN1 aSN5 = asn1[0][num]; if (aSN5 != null && aSN5.Tag == 161) { for (int j = 0; j < aSN5.Count; j++) { unauthenticatedAttributes.Add(aSN5[j]); } } } internal ASN1 GetASN1() { if (key == null || hashAlgorithm == null) { return null; } byte[] data = new byte[1] { version }; ASN1 aSN = new ASN1(48); aSN.Add(new ASN1(2, data)); aSN.Add(IssuerAndSerialNumber(x509)); string oid = CryptoConfig.MapNameToOID(hashAlgorithm); aSN.Add(AlgorithmIdentifier(oid)); ASN1 aSN2 = null; if (authenticatedAttributes.Count > 0) { aSN2 = aSN.Add(new ASN1(160)); authenticatedAttributes.Sort(new SortedSet()); foreach (ASN1 authenticatedAttribute in authenticatedAttributes) { aSN2.Add(authenticatedAttribute); } } if (key is RSA) { aSN.Add(AlgorithmIdentifier("1.2.840.113549.1.1.1")); if (aSN2 != null) { RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(key); rSAPKCS1SignatureFormatter.SetHashAlgorithm(hashAlgorithm); byte[] bytes = aSN2.GetBytes(); bytes[0] = 49; byte[] rgbHash = HashAlgorithm.Create(hashAlgorithm).ComputeHash(bytes); signature = rSAPKCS1SignatureFormatter.CreateSignature(rgbHash); } aSN.Add(new ASN1(4, signature)); if (unauthenticatedAttributes.Count > 0) { ASN1 aSN3 = aSN.Add(new ASN1(161)); unauthenticatedAttributes.Sort(new SortedSet()); foreach (ASN1 unauthenticatedAttribute in unauthenticatedAttributes) { aSN3.Add(unauthenticatedAttribute); } } return aSN; } if (key is DSA) { throw new NotImplementedException("not yet"); } throw new CryptographicException("Unknown assymetric algorithm"); } public byte[] GetBytes() { return GetASN1().GetBytes(); } } internal class SortedSet : IComparer { public int Compare(object x, object y) { if (x == null) { if (y != null) { return -1; } return 0; } if (y == null) { return 1; } ASN1 obj = x as ASN1; ASN1 aSN = y as ASN1; if (obj == null || aSN == null) { throw new ArgumentException(Locale.GetText("Invalid objects.")); } byte[] bytes = obj.GetBytes(); byte[] bytes2 = aSN.GetBytes(); for (int i = 0; i < bytes.Length && i != bytes2.Length; i++) { if (bytes[i] != bytes2[i]) { if (bytes[i] >= bytes2[i]) { return 1; } return -1; } } if (bytes.Length > bytes2.Length) { return 1; } if (bytes.Length < bytes2.Length) { return -1; } return 0; } } private PKCS7() { } public static ASN1 Attribute(string oid, ASN1 value) { ASN1 aSN = new ASN1(48); aSN.Add(ASN1Convert.FromOid(oid)); aSN.Add(new ASN1(49)).Add(value); return aSN; } public static ASN1 AlgorithmIdentifier(string oid) { ASN1 aSN = new ASN1(48); aSN.Add(ASN1Convert.FromOid(oid)); aSN.Add(new ASN1(5)); return aSN; } public static ASN1 AlgorithmIdentifier(string oid, ASN1 parameters) { ASN1 aSN = new ASN1(48); aSN.Add(ASN1Convert.FromOid(oid)); aSN.Add(parameters); return aSN; } public static ASN1 IssuerAndSerialNumber(Mono.Security.X509.X509Certificate x509) { ASN1 asn = null; ASN1 asn2 = null; ASN1 aSN = new ASN1(x509.RawData); int num = 0; bool flag = false; while (num < aSN[0].Count) { ASN1 aSN2 = aSN[0][num++]; if (aSN2.Tag == 2) { asn2 = aSN2; } else if (aSN2.Tag == 48) { if (flag) { asn = aSN2; break; } flag = true; } } ASN1 aSN3 = new ASN1(48); aSN3.Add(asn); aSN3.Add(asn2); return aSN3; } } public sealed class StrongName { internal class StrongNameSignature { private byte[] hash; private byte[] signature; private uint signaturePosition; private uint signatureLength; private uint metadataPosition; private uint metadataLength; private byte cliFlag; private uint cliFlagPosition; public byte[] Hash { get { return hash; } set { hash = value; } } public byte[] Signature { get { return signature; } set { signature = value; } } public uint MetadataPosition { get { return metadataPosition; } set { metadataPosition = value; } } public uint MetadataLength { get { return metadataLength; } set { metadataLength = value; } } public uint SignaturePosition { get { return signaturePosition; } set { signaturePosition = value; } } public uint SignatureLength { get { return signatureLength; } set { signatureLength = value; } } public byte CliFlag { get { return cliFlag; } set { cliFlag = value; } } public uint CliFlagPosition { get { return cliFlagPosition; } set { cliFlagPosition = value; } } } internal enum StrongNameOptions { Metadata, Signature } private RSA rsa; private byte[] publicKey; private byte[] keyToken; private string tokenAlgorithm; public bool CanSign { get { if (rsa == null) { return false; } if (RSA is RSAManaged) { return !(rsa as RSAManaged).PublicOnly; } try { RSAParameters rSAParameters = rsa.ExportParameters(includePrivateParameters: true); return rSAParameters.D != null && rSAParameters.P != null && rSAParameters.Q != null; } catch (CryptographicException) { return false; } } } public RSA RSA { get { if (rsa == null) { rsa = RSA.Create(); } return rsa; } set { rsa = value; InvalidateCache(); } } public byte[] PublicKey { get { if (publicKey == null) { byte[] array = CryptoConvert.ToCapiKeyBlob(rsa, includePrivateKey: false); publicKey = new byte[32 + (rsa.KeySize >> 3)]; publicKey[0] = array[4]; publicKey[1] = array[5]; publicKey[2] = array[6]; publicKey[3] = array[7]; publicKey[4] = 4; publicKey[5] = 128; publicKey[6] = 0; publicKey[7] = 0; byte[] bytes = BitConverterLE.GetBytes(publicKey.Length - 12); publicKey[8] = bytes[0]; publicKey[9] = bytes[1]; publicKey[10] = bytes[2]; publicKey[11] = bytes[3]; publicKey[12] = 6; Buffer.BlockCopy(array, 1, publicKey, 13, publicKey.Length - 13); publicKey[23] = 49; } return (byte[])publicKey.Clone(); } } public byte[] PublicKeyToken { get { if (keyToken == null) { byte[] array = PublicKey; if (array == null) { return null; } byte[] array2 = GetHashAlgorithm(TokenAlgorithm).ComputeHash(array); keyToken = new byte[8]; Buffer.BlockCopy(array2, array2.Length - 8, keyToken, 0, 8); Array.Reverse(keyToken, 0, 8); } return (byte[])keyToken.Clone(); } } public string TokenAlgorithm { get { if (tokenAlgorithm == null) { tokenAlgorithm = "SHA1"; } return tokenAlgorithm; } set { string text = value.ToUpper(CultureInfo.InvariantCulture); if (text == "SHA1" || text == "MD5") { tokenAlgorithm = value; InvalidateCache(); return; } throw new ArgumentException("Unsupported hash algorithm for token"); } } public StrongName() { } public StrongName(int keySize) { rsa = new RSAManaged(keySize); } public StrongName(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } if (data.Length == 16) { int num = 0; int num2 = 0; while (num < data.Length) { num2 += data[num++]; } if (num2 == 4) { publicKey = (byte[])data.Clone(); } } else { RSA = CryptoConvert.FromCapiKeyBlob(data); if (rsa == null) { throw new ArgumentException("data isn't a correctly encoded RSA public key"); } } } public StrongName(RSA rsa) { if (rsa == null) { throw new ArgumentNullException("rsa"); } RSA = rsa; } private void InvalidateCache() { publicKey = null; keyToken = null; } private static HashAlgorithm GetHashAlgorithm(string algorithm) { return HashAlgorithm.Create(algorithm); } public byte[] GetBytes() { return CryptoConvert.ToCapiPrivateKeyBlob(RSA); } private uint RVAtoPosition(uint r, int sections, byte[] headers) { for (int i = 0; i < sections; i++) { uint num = BitConverterLE.ToUInt32(headers, i * 40 + 20); uint num2 = BitConverterLE.ToUInt32(headers, i * 40 + 12); int num3 = (int)BitConverterLE.ToUInt32(headers, i * 40 + 8); if (num2 <= r && r < num2 + num3) { return num + r - num2; } } return 0u; } private static StrongNameSignature Error(string a) { return null; } private static byte[] ReadMore(Stream stream, byte[] a, int newSize) { int num = a.Length; Array.Resize(ref a, newSize); if (newSize <= num) { return a; } int num2 = newSize - num; if (stream.Read(a, num, num2) != num2) { return null; } return a; } internal StrongNameSignature StrongHash(Stream stream, StrongNameOptions options) { byte[] array = new byte[64]; int num = 0; int num2 = stream.Read(array, 0, 64); if (num2 == 64 && array[0] == 77 && array[1] == 90) { num = BitConverterLE.ToInt32(array, 60); if (num < 64) { return Error("peHeader_lt_64"); } array = ReadMore(stream, array, num); if (array == null) { return Error("read_mz2_failed"); } } else { if (num2 < 4 || array[0] != 80 || array[1] != 69 || array[2] != 0 || array[3] != 0) { return Error("read_mz_or_mzsig_failed"); } stream.Position = 0L; array = new byte[0]; } int num3 = 2; int num4 = 24 + num3; byte[] array2 = new byte[num4]; if (stream.Read(array2, 0, num4) != num4 || array2[0] != 80 || array2[1] != 69 || array2[2] != 0 || array2[3] != 0) { return Error("read_minimumHeadersSize_or_pesig_failed"); } num3 = BitConverterLE.ToUInt16(array2, 20); if (num3 < 2) { return Error($"sizeOfOptionalHeader_lt_2 ${num3}"); } int num5 = 24 + num3; if (num5 < 24) { return Error("headers_overflow"); } array2 = ReadMore(stream, array2, num5); if (array2 == null) { return Error("read_pe2_failed"); } uint num6 = BitConverterLE.ToUInt16(array2, 24); int num7 = 0; bool flag = false; switch (num6) { case 523u: num7 = 16; break; case 263u: flag = true; break; default: return Error("bad_magic_value"); case 267u: break; } uint num8 = 0u; if (!flag) { if (num3 >= 116 + num7 + 4) { num8 = BitConverterLE.ToUInt32(array2, 116 + num7); } for (int i = 64; i < num3 && i < 68; i++) { array2[24 + i] = 0; } for (int j = 128 + num7; j < num3 && j < 136 + num7; j++) { array2[24 + j] = 0; } } int num9 = BitConverterLE.ToUInt16(array2, 6); byte[] array3 = new byte[num9 * 40]; if (stream.Read(array3, 0, array3.Length) != array3.Length) { return Error("read_section_headers_failed"); } uint num10 = 0u; uint num11 = 0u; uint num12 = 0u; uint num13 = 0u; if (15 < num8 && num3 >= 216 + num7) { uint r = BitConverterLE.ToUInt32(array2, 232 + num7); uint num14 = RVAtoPosition(r, num9, array3); int num15 = BitConverterLE.ToInt32(array2, 236 + num7); byte[] array4 = new byte[num15]; stream.Position = num14; if (stream.Read(array4, 0, num15) != num15) { return Error("read_cli_header_failed"); } uint r2 = BitConverterLE.ToUInt32(array4, 32); num10 = RVAtoPosition(r2, num9, array3); num11 = BitConverterLE.ToUInt32(array4, 36); uint r3 = BitConverterLE.ToUInt32(array4, 8); num12 = RVAtoPosition(r3, num9, array3); num13 = BitConverterLE.ToUInt32(array4, 12); } StrongNameSignature strongNameSignature = new StrongNameSignature(); strongNameSignature.SignaturePosition = num10; strongNameSignature.SignatureLength = num11; strongNameSignature.MetadataPosition = num12; strongNameSignature.MetadataLength = num13; using HashAlgorithm hashAlgorithm = HashAlgorithm.Create(TokenAlgorithm); if (options == StrongNameOptions.Metadata) { hashAlgorithm.Initialize(); byte[] buffer = new byte[num13]; stream.Position = num12; if (stream.Read(buffer, 0, (int)num13) != (int)num13) { return Error("read_cli_metadata_failed"); } strongNameSignature.Hash = hashAlgorithm.ComputeHash(buffer); return strongNameSignature; } using (CryptoStream cryptoStream = new CryptoStream(Stream.Null, hashAlgorithm, CryptoStreamMode.Write)) { cryptoStream.Write(array, 0, array.Length); cryptoStream.Write(array2, 0, array2.Length); cryptoStream.Write(array3, 0, array3.Length); for (int k = 0; k < num9; k++) { uint num16 = BitConverterLE.ToUInt32(array3, k * 40 + 20); int num17 = BitConverterLE.ToInt32(array3, k * 40 + 16); byte[] array5 = new byte[num17]; stream.Position = num16; if (stream.Read(array5, 0, num17) != num17) { return Error("read_section_failed"); } if (num16 <= num10 && num10 < (uint)((int)num16 + num17)) { int num18 = (int)(num10 - num16); if (num18 > 0) { cryptoStream.Write(array5, 0, num18); } strongNameSignature.Signature = new byte[num11]; Buffer.BlockCopy(array5, num18, strongNameSignature.Signature, 0, (int)num11); Array.Reverse(strongNameSignature.Signature); int num19 = (int)(num18 + num11); int num20 = num17 - num19; if (num20 > 0) { cryptoStream.Write(array5, num19, num20); } } else { cryptoStream.Write(array5, 0, num17); } } } strongNameSignature.Hash = hashAlgorithm.Hash; return strongNameSignature; } public byte[] Hash(string fileName) { using FileStream stream = File.OpenRead(fileName); return StrongHash(stream, StrongNameOptions.Metadata).Hash; } public bool Sign(string fileName) { StrongNameSignature strongNameSignature; using (FileStream stream = File.OpenRead(fileName)) { strongNameSignature = StrongHash(stream, StrongNameOptions.Signature); } if (strongNameSignature.Hash == null) { return false; } byte[] array = null; try { RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(rsa); rSAPKCS1SignatureFormatter.SetHashAlgorithm(TokenAlgorithm); array = rSAPKCS1SignatureFormatter.CreateSignature(strongNameSignature.Hash); Array.Reverse(array); } catch (CryptographicException) { return false; } using (FileStream fileStream = File.OpenWrite(fileName)) { fileStream.Position = strongNameSignature.SignaturePosition; fileStream.Write(array, 0, array.Length); } return true; } public bool Verify(string fileName) { using FileStream stream = File.OpenRead(fileName); return Verify(stream); } public bool Verify(Stream stream) { StrongNameSignature strongNameSignature = StrongHash(stream, StrongNameOptions.Signature); if (strongNameSignature.Hash == null) { return false; } try { AssemblyHashAlgorithm algorithm = AssemblyHashAlgorithm.SHA1; if (tokenAlgorithm == "MD5") { algorithm = AssemblyHashAlgorithm.MD5; } return Verify(rsa, algorithm, strongNameSignature.Hash, strongNameSignature.Signature); } catch (CryptographicException) { return false; } } private static bool Verify(RSA rsa, AssemblyHashAlgorithm algorithm, byte[] hash, byte[] signature) { RSAPKCS1SignatureDeformatter rSAPKCS1SignatureDeformatter = new RSAPKCS1SignatureDeformatter(rsa); switch (algorithm) { case AssemblyHashAlgorithm.MD5: rSAPKCS1SignatureDeformatter.SetHashAlgorithm("MD5"); break; default: rSAPKCS1SignatureDeformatter.SetHashAlgorithm("SHA1"); break; } return rSAPKCS1SignatureDeformatter.VerifySignature(hash, signature); } } } namespace Mono.Security.X509 { public class PKCS5 { public const string pbeWithMD2AndDESCBC = "1.2.840.113549.1.5.1"; public const string pbeWithMD5AndDESCBC = "1.2.840.113549.1.5.3"; public const string pbeWithMD2AndRC2CBC = "1.2.840.113549.1.5.4"; public const string pbeWithMD5AndRC2CBC = "1.2.840.113549.1.5.6"; public const string pbeWithSHA1AndDESCBC = "1.2.840.113549.1.5.10"; public const string pbeWithSHA1AndRC2CBC = "1.2.840.113549.1.5.11"; } public class PKCS9 { public const string friendlyName = "1.2.840.113549.1.9.20"; public const string localKeyId = "1.2.840.113549.1.9.21"; } internal class SafeBag { private string _bagOID; private ASN1 _asn1; public string BagOID => _bagOID; public ASN1 ASN1 => _asn1; public SafeBag(string bagOID, ASN1 asn1) { _bagOID = bagOID; _asn1 = asn1; } } public class PKCS12 : ICloneable { public class DeriveBytes { public enum Purpose { Key, IV, MAC } private static byte[] keyDiversifier = new byte[64] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; private static byte[] ivDiversifier = new byte[64] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; private static byte[] macDiversifier = new byte[64] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }; private string _hashName; private int _iterations; private byte[] _password; private byte[] _salt; public string HashName { get { return _hashName; } set { _hashName = value; } } public int IterationCount { get { return _iterations; } set { _iterations = value; } } public byte[] Password { get { return (byte[])_password.Clone(); } set { if (value == null) { _password = new byte[0]; } else { _password = (byte[])value.Clone(); } } } public byte[] Salt { get { return (byte[])_salt.Clone(); } set { if (value != null) { _salt = (byte[])value.Clone(); } else { _salt = null; } } } private void Adjust(byte[] a, int aOff, byte[] b) { int num = (b[^1] & 0xFF) + (a[aOff + b.Length - 1] & 0xFF) + 1; a[aOff + b.Length - 1] = (byte)num; num >>= 8; for (int num2 = b.Length - 2; num2 >= 0; num2--) { num += (b[num2] & 0xFF) + (a[aOff + num2] & 0xFF); a[aOff + num2] = (byte)num; num >>= 8; } } private byte[] Derive(byte[] diversifier, int n) { HashAlgorithm hashAlgorithm = PKCS1.CreateFromName(_hashName); int num = hashAlgorithm.HashSize >> 3; int num2 = 64; byte[] array = new byte[n]; byte[] array2; if (_salt != null && _salt.Length != 0) { array2 = new byte[num2 * ((_salt.Length + num2 - 1) / num2)]; for (int i = 0; i != array2.Length; i++) { array2[i] = _salt[i % _salt.Length]; } } else { array2 = new byte[0]; } byte[] array3; if (_password != null && _password.Length != 0) { array3 = new byte[num2 * ((_password.Length + num2 - 1) / num2)]; for (int j = 0; j != array3.Length; j++) { array3[j] = _password[j % _password.Length]; } } else { array3 = new byte[0]; } byte[] array4 = new byte[array2.Length + array3.Length]; Buffer.BlockCopy(array2, 0, array4, 0, array2.Length); Buffer.BlockCopy(array3, 0, array4, array2.Length, array3.Length); byte[] array5 = new byte[num2]; int num3 = (n + num - 1) / num; for (int k = 1; k <= num3; k++) { hashAlgorithm.TransformBlock(diversifier, 0, diversifier.Length, diversifier, 0); hashAlgorithm.TransformFinalBlock(array4, 0, array4.Length); byte[] array6 = hashAlgorithm.Hash; hashAlgorithm.Initialize(); for (int l = 1; l != _iterations; l++) { array6 = hashAlgorithm.ComputeHash(array6, 0, array6.Length); } for (int m = 0; m != array5.Length; m++) { array5[m] = array6[m % array6.Length]; } for (int num4 = 0; num4 != array4.Length / num2; num4++) { Adjust(array4, num4 * num2, array5); } if (k == num3) { Buffer.BlockCopy(array6, 0, array, (k - 1) * num, array.Length - (k - 1) * num); } else { Buffer.BlockCopy(array6, 0, array, (k - 1) * num, array6.Length); } } return array; } public byte[] DeriveKey(int size) { return Derive(keyDiversifier, size); } public byte[] DeriveIV(int size) { return Derive(ivDiversifier, size); } public byte[] DeriveMAC(int size) { return Derive(macDiversifier, size); } } public const string pbeWithSHAAnd128BitRC4 = "1.2.840.113549.1.12.1.1"; public const string pbeWithSHAAnd40BitRC4 = "1.2.840.113549.1.12.1.2"; public const string pbeWithSHAAnd3KeyTripleDESCBC = "1.2.840.113549.1.12.1.3"; public const string pbeWithSHAAnd2KeyTripleDESCBC = "1.2.840.113549.1.12.1.4"; public const string pbeWithSHAAnd128BitRC2CBC = "1.2.840.113549.1.12.1.5"; public const string pbeWithSHAAnd40BitRC2CBC = "1.2.840.113549.1.12.1.6"; public const string keyBag = "1.2.840.113549.1.12.10.1.1"; public const string pkcs8ShroudedKeyBag = "1.2.840.113549.1.12.10.1.2"; public const string certBag = "1.2.840.113549.1.12.10.1.3"; public const string crlBag = "1.2.840.113549.1.12.10.1.4"; public const string secretBag = "1.2.840.113549.1.12.10.1.5"; public const string safeContentsBag = "1.2.840.113549.1.12.10.1.6"; public const string x509Certificate = "1.2.840.113549.1.9.22.1"; public const string sdsiCertificate = "1.2.840.113549.1.9.22.2"; public const string x509Crl = "1.2.840.113549.1.9.23.1"; private const int recommendedIterationCount = 2000; private byte[] _password; private ArrayList _keyBags; private ArrayList _secretBags; private X509CertificateCollection _certs; private bool _keyBagsChanged; private bool _secretBagsChanged; private bool _certsChanged; private int _iterations; private ArrayList _safeBags; private RandomNumberGenerator _rng; public const int CryptoApiPasswordLimit = 32; private static int password_max_length = int.MaxValue; public string Password { set { if (_password != null) { Array.Clear(_password, 0, _password.Length); } _password = null; if (value == null) { return; } if (value.Length > 0) { int num = value.Length; int num2 = 0; if (num < MaximumPasswordLength) { if (value[num - 1] != 0) { num2 = 1; } } else { num = MaximumPasswordLength; } _password = new byte[num + num2 << 1]; Encoding.BigEndianUnicode.GetBytes(value, 0, num, _password, 0); } else { _password = new byte[2]; } } } public int IterationCount { get { return _iterations; } set { _iterations = value; } } public ArrayList Keys { get { if (_keyBagsChanged) { _keyBags.Clear(); foreach (SafeBag safeBag in _safeBags) { if (safeBag.BagOID.Equals("1.2.840.113549.1.12.10.1.1")) { byte[] privateKey = new PKCS8.PrivateKeyInfo(safeBag.ASN1[1].Value).PrivateKey; switch (privateKey[0]) { case 2: _keyBags.Add(PKCS8.PrivateKeyInfo.DecodeDSA(privateKey, default(DSAParameters))); break; case 48: _keyBags.Add(PKCS8.PrivateKeyInfo.DecodeRSA(privateKey)); break; } Array.Clear(privateKey, 0, privateKey.Length); } else if (safeBag.BagOID.Equals("1.2.840.113549.1.12.10.1.2")) { PKCS8.EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new PKCS8.EncryptedPrivateKeyInfo(safeBag.ASN1[1].Value); byte[] array = Decrypt(encryptedPrivateKeyInfo.Algorithm, encryptedPrivateKeyInfo.Salt, encryptedPrivateKeyInfo.IterationCount, encryptedPrivateKeyInfo.EncryptedData); byte[] privateKey2 = new PKCS8.PrivateKeyInfo(array).PrivateKey; switch (privateKey2[0]) { case 2: _keyBags.Add(PKCS8.PrivateKeyInfo.DecodeDSA(privateKey2, default(DSAParameters))); break; case 48: _keyBags.Add(PKCS8.PrivateKeyInfo.DecodeRSA(privateKey2)); break; } Array.Clear(privateKey2, 0, privateKey2.Length); Array.Clear(array, 0, array.Length); } } _keyBagsChanged = false; } return ArrayList.ReadOnly(_keyBags); } } public ArrayList Secrets { get { if (_secretBagsChanged) { _secretBags.Clear(); foreach (SafeBag safeBag in _safeBags) { if (safeBag.BagOID.Equals("1.2.840.113549.1.12.10.1.5")) { byte[] value = safeBag.ASN1[1].Value; _secretBags.Add(value); } } _secretBagsChanged = false; } return ArrayList.ReadOnly(_secretBags); } } public X509CertificateCollection Certificates { get { if (_certsChanged) { _certs.Clear(); foreach (SafeBag safeBag in _safeBags) { if (safeBag.BagOID.Equals("1.2.840.113549.1.12.10.1.3")) { PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(safeBag.ASN1[1].Value); _certs.Add(new X509Certificate(contentInfo.Content[0].Value)); } } _certsChanged = false; } return _certs; } } internal RandomNumberGenerator RNG { get { if (_rng == null) { _rng = RandomNumberGenerator.Create(); } return _rng; } } public static int MaximumPasswordLength { get { return password_max_length; } set { if (value < 32) { throw new ArgumentOutOfRangeException(Locale.GetText("Maximum password length cannot be less than {0}.", 32)); } password_max_length = value; } } public PKCS12() { _iterations = 2000; _keyBags = new ArrayList(); _secretBags = new ArrayList(); _certs = new X509CertificateCollection(); _keyBagsChanged = false; _secretBagsChanged = false; _certsChanged = false; _safeBags = new ArrayList(); } public PKCS12(byte[] data) : this() { Password = null; Decode(data); } public PKCS12(byte[] data, string password) : this() { Password = password; Decode(data); } public PKCS12(byte[] data, byte[] password) : this() { _password = password; Decode(data); } private void Decode(byte[] data) { ASN1 aSN = new ASN1(data); if (aSN.Tag != 48) { throw new ArgumentException("invalid data"); } if (aSN[0].Tag != 2) { throw new ArgumentException("invalid PFX version"); } PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(aSN[1]); if (contentInfo.ContentType != "1.2.840.113549.1.7.1") { throw new ArgumentException("invalid authenticated safe"); } if (aSN.Count > 2) { ASN1 aSN2 = aSN[2]; if (aSN2.Tag != 48) { throw new ArgumentException("invalid MAC"); } ASN1 aSN3 = aSN2[0]; if (aSN3.Tag != 48) { throw new ArgumentException("invalid MAC"); } if (ASN1Convert.ToOid(aSN3[0][0]) != "1.3.14.3.2.26") { throw new ArgumentException("unsupported HMAC"); } byte[] value = aSN3[1].Value; ASN1 aSN4 = aSN2[1]; if (aSN4.Tag != 4) { throw new ArgumentException("missing MAC salt"); } _iterations = 1; if (aSN2.Count > 2) { ASN1 aSN5 = aSN2[2]; if (aSN5.Tag != 2) { throw new ArgumentException("invalid MAC iteration"); } _iterations = ASN1Convert.ToInt32(aSN5); } byte[] value2 = contentInfo.Content[0].Value; byte[] actual = MAC(_password, aSN4.Value, _iterations, value2); if (!Compare(value, actual)) { byte[] password = new byte[2]; actual = MAC(password, aSN4.Value, _iterations, value2); if (!Compare(value, actual)) { throw new CryptographicException("Invalid MAC - file may have been tampered with!"); } _password = password; } } ASN1 aSN6 = new ASN1(contentInfo.Content[0].Value); for (int i = 0; i < aSN6.Count; i++) { PKCS7.ContentInfo contentInfo2 = new PKCS7.ContentInfo(aSN6[i]); switch (contentInfo2.ContentType) { case "1.2.840.113549.1.7.1": { ASN1 aSN8 = new ASN1(contentInfo2.Content[0].Value); for (int k = 0; k < aSN8.Count; k++) { ASN1 safeBag2 = aSN8[k]; ReadSafeBag(safeBag2); } break; } case "1.2.840.113549.1.7.6": { PKCS7.EncryptedData ed = new PKCS7.EncryptedData(contentInfo2.Content[0]); ASN1 aSN7 = new ASN1(Decrypt(ed)); for (int j = 0; j < aSN7.Count; j++) { ASN1 safeBag = aSN7[j]; ReadSafeBag(safeBag); } break; } case "1.2.840.113549.1.7.3": throw new NotImplementedException("public key encrypted"); default: throw new ArgumentException("unknown authenticatedSafe"); } } } ~PKCS12() { if (_password != null) { Array.Clear(_password, 0, _password.Length); } _password = null; } private bool Compare(byte[] expected, byte[] actual) { bool result = false; if (expected.Length == actual.Length) { for (int i = 0; i < expected.Length; i++) { if (expected[i] != actual[i]) { return false; } } result = true; } return result; } private SymmetricAlgorithm GetSymmetricAlgorithm(string algorithmOid, byte[] salt, int iterationCount) { string text = null; int size = 8; int num = 8; DeriveBytes deriveBytes = new DeriveBytes(); deriveBytes.Password = _password; deriveBytes.Salt = salt; deriveBytes.IterationCount = iterationCount; switch (algorithmOid) { case "1.2.840.113549.1.5.1": deriveBytes.HashName = "MD2"; text = "DES"; break; case "1.2.840.113549.1.5.3": deriveBytes.HashName = "MD5"; text = "DES"; break; case "1.2.840.113549.1.5.4": deriveBytes.HashName = "MD2"; text = "RC2"; size = 4; break; case "1.2.840.113549.1.5.6": deriveBytes.HashName = "MD5"; text = "RC2"; size = 4; break; case "1.2.840.113549.1.5.10": deriveBytes.HashName = "SHA1"; text = "DES"; break; case "1.2.840.113549.1.5.11": deriveBytes.HashName = "SHA1"; text = "RC2"; size = 4; break; case "1.2.840.113549.1.12.1.1": deriveBytes.HashName = "SHA1"; text = "RC4"; size = 16; num = 0; break; case "1.2.840.113549.1.12.1.2": deriveBytes.HashName = "SHA1"; text = "RC4"; size = 5; num = 0; break; case "1.2.840.113549.1.12.1.3": deriveBytes.HashName = "SHA1"; text = "TripleDES"; size = 24; break; case "1.2.840.113549.1.12.1.4": deriveBytes.HashName = "SHA1"; text = "TripleDES"; size = 16; break; case "1.2.840.113549.1.12.1.5": deriveBytes.HashName = "SHA1"; text = "RC2"; size = 16; break; case "1.2.840.113549.1.12.1.6": deriveBytes.HashName = "SHA1"; text = "RC2"; size = 5; break; default: throw new NotSupportedException("unknown oid " + text); } SymmetricAlgorithm symmetricAlgorithm = null; symmetricAlgorithm = SymmetricAlgorithm.Create(text); symmetricAlgorithm.Key = deriveBytes.DeriveKey(size); if (num > 0) { symmetricAlgorithm.IV = deriveBytes.DeriveIV(num); symmetricAlgorithm.Mode = CipherMode.CBC; } return symmetricAlgorithm; } public byte[] Decrypt(string algorithmOid, byte[] salt, int iterationCount, byte[] encryptedData) { SymmetricAlgorithm symmetricAlgorithm = null; byte[] array = null; try { symmetricAlgorithm = GetSymmetricAlgorithm(algorithmOid, salt, iterationCount); return symmetricAlgorithm.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length); } finally { symmetricAlgorithm?.Clear(); } } public byte[] Decrypt(PKCS7.EncryptedData ed) { return Decrypt(ed.EncryptionAlgorithm.ContentType, ed.EncryptionAlgorithm.Content[0].Value, ASN1Convert.ToInt32(ed.EncryptionAlgorithm.Content[1]), ed.EncryptedContent); } public byte[] Encrypt(string algorithmOid, byte[] salt, int iterationCount, byte[] data) { byte[] array = null; using SymmetricAlgorithm symmetricAlgorithm = GetSymmetricAlgorithm(algorithmOid, salt, iterationCount); return symmetricAlgorithm.CreateEncryptor().TransformFinalBlock(data, 0, data.Length); } private DSAParameters GetExistingParameters(out bool found) { foreach (X509Certificate certificate in Certificates) { if (certificate.KeyAlgorithmParameters != null) { DSA dSA = certificate.DSA; if (dSA != null) { found = true; return dSA.ExportParameters(includePrivateParameters: false); } } } found = false; return default(DSAParameters); } private void AddPrivateKey(PKCS8.PrivateKeyInfo pki) { byte[] privateKey = pki.PrivateKey; try { switch (pki.Algorithm) { case "1.2.840.113549.1.1.1": _keyBags.Add(PKCS8.PrivateKeyInfo.DecodeRSA(privateKey)); break; case "1.2.840.10040.4.1": { bool found; DSAParameters existingParameters = GetExistingParameters(out found); if (found) { _keyBags.Add(PKCS8.PrivateKeyInfo.DecodeDSA(privateKey, existingParameters)); } break; } default: throw new CryptographicException("Unknown private key format"); } } finally { Array.Clear(privateKey, 0, privateKey.Length); } } private void ReadSafeBag(ASN1 safeBag) { if (safeBag.Tag != 48) { throw new ArgumentException("invalid safeBag"); } ASN1 aSN = safeBag[0]; if (aSN.Tag != 6) { throw new ArgumentException("invalid safeBag id"); } ASN1 aSN2 = safeBag[1]; string text = ASN1Convert.ToOid(aSN); switch (text) { case "1.2.840.113549.1.12.10.1.1": AddPrivateKey(new PKCS8.PrivateKeyInfo(aSN2.Value)); break; case "1.2.840.113549.1.12.10.1.2": { PKCS8.EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new PKCS8.EncryptedPrivateKeyInfo(aSN2.Value); byte[] array = Decrypt(encryptedPrivateKeyInfo.Algorithm, encryptedPrivateKeyInfo.Salt, encryptedPrivateKeyInfo.IterationCount, encryptedPrivateKeyInfo.EncryptedData); AddPrivateKey(new PKCS8.PrivateKeyInfo(array)); Array.Clear(array, 0, array.Length); break; } case "1.2.840.113549.1.12.10.1.3": { PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(aSN2.Value); if (contentInfo.ContentType != "1.2.840.113549.1.9.22.1") { throw new NotSupportedException("unsupport certificate type"); } X509Certificate value2 = new X509Certificate(contentInfo.Content[0].Value); _certs.Add(value2); break; } case "1.2.840.113549.1.12.10.1.5": { byte[] value = aSN2.Value; _secretBags.Add(value); break; } default: throw new ArgumentException("unknown safeBag oid"); case "1.2.840.113549.1.12.10.1.4": case "1.2.840.113549.1.12.10.1.6": break; } if (safeBag.Count > 2) { ASN1 aSN3 = safeBag[2]; if (aSN3.Tag != 49) { throw new ArgumentException("invalid safeBag attributes id"); } for (int i = 0; i < aSN3.Count; i++) { ASN1 aSN4 = aSN3[i]; if (aSN4.Tag != 48) { throw new ArgumentException("invalid PKCS12 attributes id"); } ASN1 aSN5 = aSN4[0]; if (aSN5.Tag != 6) { throw new ArgumentException("invalid attribute id"); } string text2 = ASN1Convert.ToOid(aSN5); ASN1 aSN6 = aSN4[1]; for (int j = 0; j < aSN6.Count; j++) { ASN1 aSN7 = aSN6[j]; if (!(text2 == "1.2.840.113549.1.9.20")) { if (text2 == "1.2.840.113549.1.9.21" && aSN7.Tag != 4) { throw new ArgumentException("invalid attribute value id"); } } else if (aSN7.Tag != 30) { throw new ArgumentException("invalid attribute value id"); } } } } _safeBags.Add(new SafeBag(text, safeBag)); } private ASN1 Pkcs8ShroudedKeyBagSafeBag(AsymmetricAlgorithm aa, IDictionary attributes) { PKCS8.PrivateKeyInfo privateKeyInfo = new PKCS8.PrivateKeyInfo(); if (aa is RSA) { privateKeyInfo.Algorithm = "1.2.840.113549.1.1.1"; privateKeyInfo.PrivateKey = PKCS8.PrivateKeyInfo.Encode((RSA)aa); } else { if (!(aa is DSA)) { throw new CryptographicException("Unknown asymmetric algorithm {0}", aa.ToString()); } privateKeyInfo.Algorithm = null; privateKeyInfo.PrivateKey = PKCS8.PrivateKeyInfo.Encode((DSA)aa); } PKCS8.EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new PKCS8.EncryptedPrivateKeyInfo(); encryptedPrivateKeyInfo.Algorithm = "1.2.840.113549.1.12.1.3"; encryptedPrivateKeyInfo.IterationCount = _iterations; encryptedPrivateKeyInfo.EncryptedData = Encrypt("1.2.840.113549.1.12.1.3", encryptedPrivateKeyInfo.Salt, _iterations, privateKeyInfo.GetBytes()); ASN1 aSN = new ASN1(48); aSN.Add(ASN1Convert.FromOid("1.2.840.113549.1.12.10.1.2")); ASN1 aSN2 = new ASN1(160); aSN2.Add(new ASN1(encryptedPrivateKeyInfo.GetBytes())); aSN.Add(aSN2); if (attributes != null) { ASN1 aSN3 = new ASN1(49); IDictionaryEnumerator enumerator = attributes.GetEnumerator(); while (enumerator.MoveNext()) { string text = (string)enumerator.Key; if (!(text == "1.2.840.113549.1.9.20")) { if (!(text == "1.2.840.113549.1.9.21")) { continue; } ArrayList arrayList = (ArrayList)enumerator.Value; if (arrayList.Count <= 0) { continue; } ASN1 aSN4 = new ASN1(48); aSN4.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.21")); ASN1 aSN5 = new ASN1(49); foreach (byte[] item in arrayList) { ASN1 aSN6 = new ASN1(4); aSN6.Value = item; aSN5.Add(aSN6); } aSN4.Add(aSN5); aSN3.Add(aSN4); continue; } ArrayList arrayList2 = (ArrayList)enumerator.Value; if (arrayList2.Count <= 0) { continue; } ASN1 aSN7 = new ASN1(48); aSN7.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.20")); ASN1 aSN8 = new ASN1(49); foreach (byte[] item2 in arrayList2) { ASN1 aSN9 = new ASN1(30); aSN9.Value = item2; aSN8.Add(aSN9); } aSN7.Add(aSN8); aSN3.Add(aSN7); } if (aSN3.Count > 0) { aSN.Add(aSN3); } } return aSN; } private ASN1 KeyBagSafeBag(AsymmetricAlgorithm aa, IDictionary attributes) { PKCS8.PrivateKeyInfo privateKeyInfo = new PKCS8.PrivateKeyInfo(); if (aa is RSA) { privateKeyInfo.Algorithm = "1.2.840.113549.1.1.1"; privateKeyInfo.PrivateKey = PKCS8.PrivateKeyInfo.Encode((RSA)aa); } else { if (!(aa is DSA)) { throw new CryptographicException("Unknown asymmetric algorithm {0}", aa.ToString()); } privateKeyInfo.Algorithm = null; privateKeyInfo.PrivateKey = PKCS8.PrivateKeyInfo.Encode((DSA)aa); } ASN1 aSN = new ASN1(48); aSN.Add(ASN1Convert.FromOid("1.2.840.113549.1.12.10.1.1")); ASN1 aSN2 = new ASN1(160); aSN2.Add(new ASN1(privateKeyInfo.GetBytes())); aSN.Add(aSN2); if (attributes != null) { ASN1 aSN3 = new ASN1(49); IDictionaryEnumerator enumerator = attributes.GetEnumerator(); while (enumerator.MoveNext()) { string text = (string)enumerator.Key; if (!(text == "1.2.840.113549.1.9.20")) { if (!(text == "1.2.840.113549.1.9.21")) { continue; } ArrayList arrayList = (ArrayList)enumerator.Value; if (arrayList.Count <= 0) { continue; } ASN1 aSN4 = new ASN1(48); aSN4.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.21")); ASN1 aSN5 = new ASN1(49); foreach (byte[] item in arrayList) { ASN1 aSN6 = new ASN1(4); aSN6.Value = item; aSN5.Add(aSN6); } aSN4.Add(aSN5); aSN3.Add(aSN4); continue; } ArrayList arrayList2 = (ArrayList)enumerator.Value; if (arrayList2.Count <= 0) { continue; } ASN1 aSN7 = new ASN1(48); aSN7.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.20")); ASN1 aSN8 = new ASN1(49); foreach (byte[] item2 in arrayList2) { ASN1 aSN9 = new ASN1(30); aSN9.Value = item2; aSN8.Add(aSN9); } aSN7.Add(aSN8); aSN3.Add(aSN7); } if (aSN3.Count > 0) { aSN.Add(aSN3); } } return aSN; } private ASN1 SecretBagSafeBag(byte[] secret, IDictionary attributes) { ASN1 aSN = new ASN1(48); aSN.Add(ASN1Convert.FromOid("1.2.840.113549.1.12.10.1.5")); ASN1 asn = new ASN1(128, secret); aSN.Add(asn); if (attributes != null) { ASN1 aSN2 = new ASN1(49); IDictionaryEnumerator enumerator = attributes.GetEnumerator(); while (enumerator.MoveNext()) { string text = (string)enumerator.Key; if (!(text == "1.2.840.113549.1.9.20")) { if (!(text == "1.2.840.113549.1.9.21")) { continue; } ArrayList arrayList = (ArrayList)enumerator.Value; if (arrayList.Count <= 0) { continue; } ASN1 aSN3 = new ASN1(48); aSN3.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.21")); ASN1 aSN4 = new ASN1(49); foreach (byte[] item in arrayList) { ASN1 aSN5 = new ASN1(4); aSN5.Value = item; aSN4.Add(aSN5); } aSN3.Add(aSN4); aSN2.Add(aSN3); continue; } ArrayList arrayList2 = (ArrayList)enumerator.Value; if (arrayList2.Count <= 0) { continue; } ASN1 aSN6 = new ASN1(48); aSN6.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.20")); ASN1 aSN7 = new ASN1(49); foreach (byte[] item2 in arrayList2) { ASN1 aSN8 = new ASN1(30); aSN8.Value = item2; aSN7.Add(aSN8); } aSN6.Add(aSN7); aSN2.Add(aSN6); } if (aSN2.Count > 0) { aSN.Add(aSN2); } } return aSN; } private ASN1 CertificateSafeBag(X509Certificate x509, IDictionary attributes) { ASN1 asn = new ASN1(4, x509.RawData); PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(); contentInfo.ContentType = "1.2.840.113549.1.9.22.1"; contentInfo.Content.Add(asn); ASN1 aSN = new ASN1(160); aSN.Add(contentInfo.ASN1); ASN1 aSN2 = new ASN1(48); aSN2.Add(ASN1Convert.FromOid("1.2.840.113549.1.12.10.1.3")); aSN2.Add(aSN); if (attributes != null) { ASN1 aSN3 = new ASN1(49); IDictionaryEnumerator enumerator = attributes.GetEnumerator(); while (enumerator.MoveNext()) { string text = (string)enumerator.Key; if (!(text == "1.2.840.113549.1.9.20")) { if (!(text == "1.2.840.113549.1.9.21")) { continue; } ArrayList arrayList = (ArrayList)enumerator.Value; if (arrayList.Count <= 0) { continue; } ASN1 aSN4 = new ASN1(48); aSN4.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.21")); ASN1 aSN5 = new ASN1(49); foreach (byte[] item in arrayList) { ASN1 aSN6 = new ASN1(4); aSN6.Value = item; aSN5.Add(aSN6); } aSN4.Add(aSN5); aSN3.Add(aSN4); continue; } ArrayList arrayList2 = (ArrayList)enumerator.Value; if (arrayList2.Count <= 0) { continue; } ASN1 aSN7 = new ASN1(48); aSN7.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.20")); ASN1 aSN8 = new ASN1(49); foreach (byte[] item2 in arrayList2) { ASN1 aSN9 = new ASN1(30); aSN9.Value = item2; aSN8.Add(aSN9); } aSN7.Add(aSN8); aSN3.Add(aSN7); } if (aSN3.Count > 0) { aSN2.Add(aSN3); } } return aSN2; } private byte[] MAC(byte[] password, byte[] salt, int iterations, byte[] data) { DeriveBytes deriveBytes = new DeriveBytes(); deriveBytes.HashName = "SHA1"; deriveBytes.Password = password; deriveBytes.Salt = salt; deriveBytes.IterationCount = iterations; HMACSHA1 obj = (HMACSHA1)System.Security.Cryptography.HMAC.Create(); obj.Key = deriveBytes.DeriveMAC(20); return obj.ComputeHash(data, 0, data.Length); } public byte[] GetBytes() { ASN1 aSN = new ASN1(48); ArrayList arrayList = new ArrayList(); foreach (SafeBag safeBag5 in _safeBags) { if (safeBag5.BagOID.Equals("1.2.840.113549.1.12.10.1.3")) { PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(safeBag5.ASN1[1].Value); arrayList.Add(new X509Certificate(contentInfo.Content[0].Value)); } } ArrayList arrayList2 = new ArrayList(); ArrayList arrayList3 = new ArrayList(); foreach (X509Certificate certificate in Certificates) { bool flag = false; foreach (X509Certificate item in arrayList) { if (Compare(certificate.RawData, item.RawData)) { flag = true; } } if (!flag) { arrayList2.Add(certificate); } } foreach (X509Certificate item2 in arrayList) { bool flag2 = false; foreach (X509Certificate certificate2 in Certificates) { if (Compare(item2.RawData, certificate2.RawData)) { flag2 = true; } } if (!flag2) { arrayList3.Add(item2); } } foreach (X509Certificate item3 in arrayList3) { RemoveCertificate(item3); } foreach (X509Certificate item4 in arrayList2) { AddCertificate(item4); } if (_safeBags.Count > 0) { ASN1 aSN2 = new ASN1(48); foreach (SafeBag safeBag6 in _safeBags) { if (safeBag6.BagOID.Equals("1.2.840.113549.1.12.10.
deps/Mono.WebBrowser.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Mono.Mozilla; using Mono.Mozilla.DOM; using Mono.WebBrowser; using Mono.WebBrowser.DOM; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Mono.WebBrowser")] [assembly: AssemblyDescription("Managed Wrapper for xulrunner engine, to support WebBrowser")] [assembly: AssemblyConfiguration("Development version")] [assembly: AssemblyProduct("Mono.WebBrowser")] [assembly: AssemblyCopyright("(c) 2007, 2008 Andreia Gaita")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyVersion("4.0.0.0")] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } namespace Mono.WebBrowser { public class Exception : System.Exception { internal enum ErrorCodes { Other, GluezillaInit, EngineNotSupported, ServiceManager, IOService, DirectoryService, PrefService, StreamNotOpen, Navigation, AccessibilityService, DocumentEncoderService } private ErrorCodes code; private static ArrayList messages; internal ErrorCodes ErrorCode => code; static Exception() { messages = new ArrayList(); messages.Insert(0, string.Intern("A critical error occurred.")); messages.Insert(1, string.Intern("An error occurred while initializing gluezilla. Please make sure you have libgluezilla installed.")); messages.Insert(2, string.Intern("Browser engine not supported at this time: ")); messages.Insert(3, string.Intern("Error obtaining a handle to the service manager.")); messages.Insert(4, string.Intern("Error obtaining a handle to the io service.")); messages.Insert(5, string.Intern("Error obtaining a handle to the directory service.")); messages.Insert(6, string.Intern("Error obtaining a handle to the preferences service.")); messages.Insert(7, string.Intern("Stream is not open for writing. Call OpenStream before appending.")); messages.Insert(8, string.Intern("An error occurred while initializing the navigation object.")); messages.Insert(9, string.Intern("Error obtaining a handle to the accessibility service.")); messages.Insert(10, string.Intern("Error obtaining a handle to the document encoder service.")); } internal Exception(ErrorCodes code) : base(GetMessage(code, string.Empty)) { this.code = code; } internal Exception(ErrorCodes code, string message) : base(GetMessage(code, message)) { this.code = code; } internal Exception(ErrorCodes code, System.Exception innerException) : base(GetMessage(code, string.Empty), innerException) { this.code = code; } internal Exception(ErrorCodes code, string message, Exception innerException) : base(GetMessage(code, message), innerException) { this.code = code; } private static string GetMessage(ErrorCodes code, string message) { return (messages[(int)code] as string) + " " + message; } } public interface IWebBrowser { bool Initialized { get; } IWindow Window { get; } IDocument Document { get; } bool Offline { get; set; } INavigation Navigation { get; } event NodeEventHandler KeyDown; event NodeEventHandler KeyPress; event NodeEventHandler KeyUp; event NodeEventHandler MouseClick; event NodeEventHandler MouseDoubleClick; event NodeEventHandler MouseDown; event NodeEventHandler MouseEnter; event NodeEventHandler MouseLeave; event NodeEventHandler MouseMove; event NodeEventHandler MouseUp; event EventHandler Focus; event CreateNewWindowEventHandler CreateNewWindow; event AlertEventHandler Alert; event LoadStartedEventHandler LoadStarted; event LoadCommitedEventHandler LoadCommited; event ProgressChangedEventHandler ProgressChanged; event LoadFinishedEventHandler LoadFinished; event StatusChangedEventHandler StatusChanged; event SecurityChangedEventHandler SecurityChanged; event ContextMenuEventHandler ContextMenuShown; event NavigationRequestedEventHandler NavigationRequested; bool Load(IntPtr handle, int width, int height); void Shutdown(); void FocusIn(FocusOption focus); void FocusOut(); void Activate(); void Deactivate(); void Resize(int width, int height); void Render(byte[] data); void Render(string html); void Render(string html, string uri, string contentType); void ExecuteScript(string script); } public enum ReloadOption : uint { None, Proxy, Full } public enum FocusOption { None, FocusFirstElement, FocusLastElement } [Flags] public enum DialogButtonFlags { BUTTON_POS_0 = 1, BUTTON_POS_1 = 0x100, BUTTON_POS_2 = 0x10000, BUTTON_TITLE_OK = 1, BUTTON_TITLE_CANCEL = 2, BUTTON_TITLE_YES = 3, BUTTON_TITLE_NO = 4, BUTTON_TITLE_SAVE = 5, BUTTON_TITLE_DONT_SAVE = 6, BUTTON_TITLE_REVERT = 7, BUTTON_TITLE_IS_STRING = 0x7F, BUTTON_POS_0_DEFAULT = 0, BUTTON_POS_1_DEFAULT = 0x1000000, BUTTON_POS_2_DEFAULT = 0x2000000, BUTTON_DELAY_ENABLE = 0x4000000, STD_OK_CANCEL_BUTTONS = 0x201 } public enum DialogType { Alert = 1, AlertCheck, Confirm, ConfirmEx, ConfirmCheck, Prompt, PromptUsernamePassword, PromptPassword, Select } public enum Platform { Unknown, Winforms, Gtk } public enum SecurityLevel { Insecure = 1, Mixed, Secure } public delegate bool CreateNewWindowEventHandler(object sender, CreateNewWindowEventArgs e); public class CreateNewWindowEventArgs : EventArgs { private bool isModal; public bool IsModal => isModal; public CreateNewWindowEventArgs(bool isModal) { this.isModal = isModal; } } public delegate void AlertEventHandler(object sender, AlertEventArgs e); public class AlertEventArgs : EventArgs { private DialogType type; private string title; private string text; private string text2; private string username; private string password; private string checkMsg; private bool checkState; private DialogButtonFlags dialogButtons; private StringCollection buttons; private StringCollection options; private object returnValue; public DialogType Type { get { return type; } set { type = value; } } public string Title { get { return title; } set { title = value; } } public string Text { get { return text; } set { text = value; } } public string Text2 { get { return text2; } set { text2 = value; } } public string CheckMessage { get { return checkMsg; } set { checkMsg = value; } } public bool CheckState { get { return checkState; } set { checkState = value; } } public DialogButtonFlags DialogButtons { get { return dialogButtons; } set { dialogButtons = value; } } public StringCollection Buttons { get { return buttons; } set { buttons = value; } } public StringCollection Options { get { return options; } set { options = value; } } public string Username { get { return username; } set { username = value; } } public string Password { get { return password; } set { password = value; } } public bool BoolReturn { get { if (returnValue is bool) { return (bool)returnValue; } return false; } set { returnValue = value; } } public int IntReturn { get { if (returnValue is int) { return (int)returnValue; } return -1; } set { returnValue = value; } } public string StringReturn { get { if (returnValue is string) { return (string)returnValue; } return string.Empty; } set { returnValue = value; } } } public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e); public class StatusChangedEventArgs : EventArgs { private string message; private int status; public string Message { get { return message; } set { message = value; } } public int Status { get { return status; } set { status = value; } } public StatusChangedEventArgs(string message, int status) { this.message = message; this.status = status; } } public delegate void ProgressChangedEventHandler(object sender, ProgressChangedEventArgs e); public class ProgressChangedEventArgs : EventArgs { private int progress; private int maxProgress; public int Progress => progress; public int MaxProgress => maxProgress; public ProgressChangedEventArgs(int progress, int maxProgress) { this.progress = progress; this.maxProgress = maxProgress; } } public delegate void LoadStartedEventHandler(object sender, LoadStartedEventArgs e); public class LoadStartedEventArgs : CancelEventArgs { private string uri; private string frameName; public string Uri => uri; public string FrameName => frameName; public LoadStartedEventArgs(string uri, string frameName) { this.uri = uri; this.frameName = frameName; } } public delegate void LoadCommitedEventHandler(object sender, LoadCommitedEventArgs e); public class LoadCommitedEventArgs : EventArgs { private string uri; public string Uri => uri; public LoadCommitedEventArgs(string uri) { this.uri = uri; } } public delegate void LoadFinishedEventHandler(object sender, LoadFinishedEventArgs e); public class LoadFinishedEventArgs : EventArgs { private string uri; public string Uri => uri; public LoadFinishedEventArgs(string uri) { this.uri = uri; } } public delegate void SecurityChangedEventHandler(object sender, SecurityChangedEventArgs e); public class SecurityChangedEventArgs : EventArgs { private SecurityLevel state; public SecurityLevel State { get { return state; } set { state = value; } } public SecurityChangedEventArgs(SecurityLevel state) { this.state = state; } } public delegate void ContextMenuEventHandler(object sender, ContextMenuEventArgs e); public class ContextMenuEventArgs : EventArgs { private int x; private int y; public int X => x; public int Y => y; public ContextMenuEventArgs(int x, int y) { this.x = x; this.y = y; } } public delegate void NavigationRequestedEventHandler(object sender, NavigationRequestedEventArgs e); public class NavigationRequestedEventArgs : CancelEventArgs { private string uri; public string Uri => uri; public NavigationRequestedEventArgs(string uri) { this.uri = uri; } } public sealed class Manager { public static IWebBrowser GetNewInstance() { return GetNewInstance(Platform.Winforms); } public static IWebBrowser GetNewInstance(Platform platform) { string text = Environment.GetEnvironmentVariable("MONO_BROWSER_ENGINE"); if (text == "webkit") { try { return (IWebBrowser)Assembly.LoadWithPartialName("mono-webkit").CreateInstance("Mono.WebKit.WebBrowser"); } catch { text = null; } } if (text == null || text == "mozilla") { return new Mono.Mozilla.WebBrowser(platform); } throw new Exception(Exception.ErrorCodes.EngineNotSupported, text); } } } namespace Mono.WebBrowser.DOM { public class NodeEventArgs : EventArgs { private INode node; public INode Node => node; public IElement Element { get { if (node is IElement) { return (IElement)node; } return null; } } public IDocument Document { get { if (node is IDocument) { return (IDocument)node; } return null; } } public NodeEventArgs(INode node) { this.node = node; } } public class WindowEventArgs : EventArgs { private IWindow window; public IWindow Window => window; public WindowEventArgs(IWindow window) { this.window = window; } } public delegate void NodeEventHandler(object sender, NodeEventArgs e); public delegate void WindowEventHandler(object sender, WindowEventArgs e); public interface IAttribute : INode { string Name { get; } new int GetHashCode(); } public interface IAttributeCollection : INodeList, IList, ICollection, IEnumerable { IAttribute this[string name] { get; } bool Exists(string name); new int GetHashCode(); } public interface IDOMImplementation { bool HasFeature(string feature, string version); IDocumentType CreateDocumentType(string qualifiedName, string publicId, string systemId); IDocument CreateDocument(string namespaceURI, string qualifiedName, IDocumentType doctype); } public interface IDocument : INode { IElement Active { get; } string ActiveLinkColor { get; set; } IElementCollection Anchors { get; } IElementCollection Applets { get; } string Background { get; set; } string BackColor { get; set; } IElement Body { get; } string Charset { get; set; } string Cookie { get; set; } IElement DocumentElement { get; } IDocumentType DocType { get; } string Domain { get; } string ForeColor { get; set; } IElementCollection Forms { get; } IElementCollection Images { get; } IDOMImplementation Implementation { get; } string LinkColor { get; set; } IElementCollection Links { get; } IStylesheetList Stylesheets { get; } string Title { get; set; } string Url { get; } string VisitedLinkColor { get; set; } IWindow Window { get; } event EventHandler LoadStopped; IAttribute CreateAttribute(string name); IElement CreateElement(string tagName); IElement GetElementById(string id); IElement GetElement(int x, int y); IElementCollection GetElementsByTagName(string id); void Write(string text); string InvokeScript(string script); new int GetHashCode(); } public interface IDocumentType : INode { string Name { get; } INamedNodeMap Entities { get; } INamedNodeMap Notations { get; } string PublicId { get; } string SystemId { get; } string InternalSubset { get; } } public interface IElement : INode { IElementCollection All { get; } IElementCollection Children { get; } int ClientWidth { get; } int ClientHeight { get; } int ScrollHeight { get; } int ScrollWidth { get; } int ScrollLeft { get; set; } int ScrollTop { get; set; } int OffsetHeight { get; } int OffsetWidth { get; } int OffsetLeft { get; } int OffsetTop { get; } IElement OffsetParent { get; } string InnerText { get; set; } string InnerHTML { get; set; } string OuterText { get; set; } string OuterHTML { get; set; } string Style { get; set; } int TabIndex { get; set; } string TagName { get; } bool Disabled { get; set; } System.IO.Stream ContentStream { get; } IElement AppendChild(IElement child); void Blur(); void Focus(); bool HasAttribute(string name); string GetAttribute(string name); IElementCollection GetElementsByTagName(string id); new int GetHashCode(); void ScrollIntoView(bool alignWithTop); void SetAttribute(string name, string value); } public interface IElementCollection : INodeList, IList, ICollection, IEnumerable { new IElement this[int index] { get; set; } new int GetHashCode(); } public interface IHistory { int Count { get; } void Back(int count); void Forward(int count); void GoToIndex(int index); void GoToUrl(string url); } public interface IMediaList { } public interface INamedNodeMap : IList, ICollection, IEnumerable { INode this[string name] { get; set; } new INode this[int index] { get; set; } INode this[string namespaceURI, string localName] { get; set; } INode RemoveNamedItem(string name); INode RemoveNamedItemNS(string namespaceURI, string localName); } public interface INavigation { bool CanGoBack { get; } bool CanGoForward { get; } int HistoryCount { get; } bool Back(); bool Forward(); void Home(); void Reload(); void Reload(ReloadOption option); void Stop(); void Go(int index); void Go(int index, bool relative); void Go(string url); void Go(string url, LoadFlags flags); } [Flags] public enum LoadFlags : uint { None = 0u, AsMetaRefresh = 0x10u, AsLinkClick = 0x20u, BypassHistory = 0x40u, ReplaceHistory = 0x80u, BypassLocalCache = 0x100u, BypassProxy = 0x200u, CharsetChange = 0x400u } public interface INode { IAttributeCollection Attributes { get; } INodeList ChildNodes { get; } INode FirstChild { get; } INode LastChild { get; } string LocalName { get; } INode Next { get; } IDocument Owner { get; } INode Parent { get; } INode Previous { get; } NodeType Type { get; } string Value { get; set; } IntPtr AccessibleObject { get; } event NodeEventHandler Click; event NodeEventHandler DoubleClick; event NodeEventHandler KeyDown; event NodeEventHandler KeyPress; event NodeEventHandler KeyUp; event NodeEventHandler MouseDown; event NodeEventHandler MouseEnter; event NodeEventHandler MouseLeave; event NodeEventHandler MouseMove; event NodeEventHandler MouseOver; event NodeEventHandler MouseUp; event NodeEventHandler OnFocus; event NodeEventHandler OnBlur; INode InsertBefore(INode newChild, INode refChild); INode ReplaceChild(INode newChild, INode oldChild); INode RemoveChild(INode child); INode AppendChild(INode child); void FireEvent(string eventName); new int GetHashCode(); new bool Equals(object obj); void AttachEventHandler(string eventName, EventHandler handler); void DetachEventHandler(string eventName, EventHandler handler); void AttachEventHandler(string eventName, Delegate handler); void DetachEventHandler(string eventName, Delegate handler); } public enum NodeType { Element = 1, Attribute, Text, CDataSection, EntityReference, Entity, ProcessingInstruction, Comment, Document, DocumentType, DocumentFragment, Notation } public interface INodeList : IList, ICollection, IEnumerable { new INode this[int index] { get; set; } new int GetHashCode(); } public interface IStylesheet { string Type { get; } bool Disabled { get; set; } INode OwnerNode { get; } IStylesheet ParentStyleSheet { get; } string Href { get; } string Title { get; } IMediaList Media { get; } } public interface IStylesheetList : IEnumerable { int Count { get; } IStylesheet this[int index] { get; set; } } public interface IWindow { IDocument Document { get; } IWindowCollection Frames { get; } string Name { get; set; } IWindow Parent { get; } string StatusText { get; } IWindow Top { get; } IHistory History { get; } event EventHandler Load; event EventHandler Unload; event EventHandler OnFocus; event EventHandler OnBlur; event EventHandler Error; event EventHandler Scroll; void AttachEventHandler(string eventName, EventHandler handler); void DetachEventHandler(string eventName, EventHandler handler); void Focus(); new bool Equals(object obj); new int GetHashCode(); void Open(string url); void ScrollTo(int x, int y); } public interface IWindowCollection : IList, ICollection, IEnumerable { new IWindow this[int index] { get; set; } } } namespace Mono.Mozilla { internal class AsciiString : IDisposable { [StructLayout(LayoutKind.Sequential)] private class nsStringContainer { private IntPtr v; private IntPtr d1; private uint d2; private IntPtr d3; } private bool disposed; private nsStringContainer unmanagedContainer; private HandleRef handle; private string str = string.Empty; private bool dirty; public HandleRef Handle { get { dirty = true; return handle; } } public string String { get { if (dirty) { Base.gluezilla_CStringGetData(handle, out var aBuf, out var _); str = Marshal.PtrToStringAnsi(aBuf); dirty = false; } return str; } set { if (str != value) { str = value; Base.gluezilla_CStringSetData(handle, str, (uint)str.Length); } } } public int Length => String.Length; public AsciiString(string value) { unmanagedContainer = new nsStringContainer(); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(nsStringContainer))); Marshal.StructureToPtr(unmanagedContainer, ptr, fDeleteOld: false); handle = new HandleRef(typeof(nsStringContainer), ptr); Base.gluezilla_CStringContainerInit(handle); String = value; } ~AsciiString() { Dispose(disposing: false); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { Base.gluezilla_CStringContainerFinish(handle); Marshal.FreeHGlobal(handle.Handle); } disposed = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public override string ToString() { return String; } } internal class Base { private class BindingInfo { public CallbackBinder callback; public IntPtr gluezilla; } private static Hashtable boundControls; private static bool initialized; private static object initLock; private static string monoMozDir; private static bool isInitialized() { if (!initialized) { return false; } return true; } private static BindingInfo getBinding(IWebBrowser control) { if (!boundControls.ContainsKey(control)) { return null; } return boundControls[control] as BindingInfo; } static Base() { initLock = new object(); boundControls = new Hashtable(); } public static void Debug(int signal) { gluezilla_debug(signal); } public static bool Init(WebBrowser control, Platform platform) { lock (initLock) { if (!initialized) { Platform mozPlatform; try { short num = gluezilla_init(platform, out mozPlatform); monoMozDir = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), ".mono"), "mozilla-" + num); if (!Directory.Exists(monoMozDir)) { Directory.CreateDirectory(monoMozDir); } } catch (DllNotFoundException) { Console.WriteLine("libgluezilla not found. To have webbrowser support, you need libgluezilla installed"); initialized = false; return false; } control.enginePlatform = mozPlatform; initialized = true; } } return initialized; } public static bool Bind(WebBrowser control, IntPtr handle, int width, int height) { if (!isInitialized()) { return false; } BindingInfo bindingInfo = new BindingInfo(); bindingInfo.callback = new CallbackBinder(control.callbacks); IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(bindingInfo.callback)); Marshal.StructureToPtr(bindingInfo.callback, intPtr, fDeleteOld: true); bindingInfo.gluezilla = gluezilla_bind(intPtr, handle, width, height, Environment.CurrentDirectory, monoMozDir, control.platform); lock (initLock) { if (bindingInfo.gluezilla == IntPtr.Zero) { Marshal.FreeHGlobal(intPtr); bindingInfo = null; initialized = false; return false; } } boundControls.Add(control, bindingInfo); return true; } public static bool Create(IWebBrowser control) { if (!isInitialized()) { return false; } gluezilla_createBrowserWindow(getBinding(control).gluezilla); return true; } public static void Shutdown(IWebBrowser control) { lock (initLock) { if (initialized) { gluezilla_shutdown(getBinding(control).gluezilla); boundControls.Remove(control); if (boundControls.Count == 0) { initialized = false; } } } } public static void Focus(IWebBrowser control, FocusOption focus) { if (isInitialized()) { gluezilla_focus(getBinding(control).gluezilla, focus); } } public static void Blur(IWebBrowser control) { if (isInitialized()) { gluezilla_blur(getBinding(control).gluezilla); } } public static void Activate(IWebBrowser control) { if (isInitialized()) { gluezilla_activate(getBinding(control).gluezilla); } } public static void Deactivate(IWebBrowser control) { if (isInitialized()) { gluezilla_deactivate(getBinding(control).gluezilla); } } public static void Resize(IWebBrowser control, int width, int height) { if (isInitialized()) { gluezilla_resize(getBinding(control).gluezilla, width, height); } } public static void Home(IWebBrowser control) { if (isInitialized()) { gluezilla_home(getBinding(control).gluezilla); } } public static nsIWebNavigation GetWebNavigation(IWebBrowser control) { if (!isInitialized()) { return null; } return gluezilla_getWebNavigation(getBinding(control).gluezilla); } public static IntPtr StringInit() { if (!isInitialized()) { return IntPtr.Zero; } return gluezilla_stringInit(); } public static void StringFinish(HandleRef str) { if (isInitialized()) { gluezilla_stringFinish(str); } } public static string StringGet(HandleRef str) { if (!isInitialized()) { return string.Empty; } return Marshal.PtrToStringUni(gluezilla_stringGet(str)); } public static void StringSet(HandleRef str, string text) { if (isInitialized()) { gluezilla_stringSet(str, text); } } public static object GetProxyForObject(IWebBrowser control, Guid iid, object obj) { if (!isInitialized()) { return null; } gluezilla_getProxyForObject(getBinding(control).gluezilla, iid, obj, out var ret); return Marshal.GetObjectForIUnknown(ret); } public static nsIServiceManager GetServiceManager(IWebBrowser control) { if (!isInitialized()) { return null; } return gluezilla_getServiceManager2(getBinding(control).gluezilla); } public static string EvalScript(IWebBrowser control, string script) { if (!isInitialized()) { return null; } return Marshal.PtrToStringAuto(gluezilla_evalScript(getBinding(control).gluezilla, script)); } [DllImport("gluezilla")] private static extern void gluezilla_debug(int signal); [DllImport("gluezilla")] private static extern short gluezilla_init(Platform platform, out Platform mozPlatform); [DllImport("gluezilla")] private static extern IntPtr gluezilla_bind(IntPtr events, IntPtr hwnd, int width, int height, string startDir, string dataDir, Platform platform); [DllImport("gluezilla")] private static extern int gluezilla_createBrowserWindow(IntPtr instance); [DllImport("gluezilla")] private static extern IntPtr gluezilla_shutdown(IntPtr instance); [DllImport("gluezilla")] private static extern int gluezilla_focus(IntPtr instance, FocusOption focus); [DllImport("gluezilla")] private static extern int gluezilla_blur(IntPtr instance); [DllImport("gluezilla")] private static extern int gluezilla_activate(IntPtr instance); [DllImport("gluezilla")] private static extern int gluezilla_deactivate(IntPtr instance); [DllImport("gluezilla")] private static extern int gluezilla_resize(IntPtr instance, int width, int height); [DllImport("gluezilla")] private static extern int gluezilla_home(IntPtr instance); [DllImport("gluezilla")] [return: MarshalAs(UnmanagedType.Interface)] private static extern nsIWebNavigation gluezilla_getWebNavigation(IntPtr instance); [DllImport("gluezilla")] private static extern IntPtr gluezilla_stringInit(); [DllImport("gluezilla")] private static extern int gluezilla_stringFinish(HandleRef str); [DllImport("gluezilla")] private static extern IntPtr gluezilla_stringGet(HandleRef str); [DllImport("gluezilla")] private static extern void gluezilla_stringSet(HandleRef str, [MarshalAs(UnmanagedType.LPWStr)] string text); [DllImport("gluezilla")] private static extern void gluezilla_getProxyForObject(IntPtr instance, [MarshalAs(UnmanagedType.LPStruct)] Guid iid, [MarshalAs(UnmanagedType.Interface)] object obj, out IntPtr ret); [DllImport("gluezilla")] public static extern uint gluezilla_StringContainerInit(HandleRef aStr); [DllImport("gluezilla")] public static extern void gluezilla_StringContainerFinish(HandleRef aStr); [DllImport("gluezilla")] public static extern uint gluezilla_StringGetData(HandleRef aStr, out IntPtr aBuf, out bool aTerm); [DllImport("gluezilla")] public static extern uint gluezilla_StringSetData(HandleRef aStr, [MarshalAs(UnmanagedType.LPWStr)] string aBuf, uint aCount); [DllImport("gluezilla")] public static extern uint gluezilla_CStringContainerInit(HandleRef aStr); [DllImport("gluezilla")] public static extern void gluezilla_CStringContainerFinish(HandleRef aStr); [DllImport("gluezilla")] public static extern uint gluezilla_CStringGetData(HandleRef aStr, out IntPtr aBuf, out bool aTerm); [DllImport("gluezilla")] public static extern uint gluezilla_CStringSetData(HandleRef aStr, string aBuf, uint aCount); [DllImport("gluezilla")] [return: MarshalAs(UnmanagedType.Interface)] public static extern nsIServiceManager gluezilla_getServiceManager2(IntPtr instance); [DllImport("gluezilla")] private static extern IntPtr gluezilla_evalScript(IntPtr instance, string script); } internal class Callback { private WebBrowser owner; private string currentUri; private bool calledLoadStarted; public Callback(WebBrowser owner) { this.owner = owner; } public void OnWidgetLoaded() { } public void OnStateChange(nsIWebProgress progress, nsIRequest request, int status, uint state) { if (!owner.created) { owner.created = true; } bool num = (state & 1) != 0; bool flag = (state & 4) != 0; bool flag2 = (state & 2) != 0; bool flag3 = (state & 0x10) != 0; bool flag4 = (state & 0x10000) != 0; bool flag5 = (state & 0x20000) != 0; bool flag6 = (state & 0x40000) != 0; bool flag7 = (state & 0x80000) != 0; if (num && flag4 && flag5 && !calledLoadStarted) { progress.getDOMWindow(out var ret); ((nsIChannel)request).getURI(out var ret2); if (ret2 == null) { currentUri = "about:blank"; } else { AsciiString asciiString = new AsciiString(string.Empty); ret2.getSpec(asciiString.Handle); currentUri = asciiString.ToString(); } calledLoadStarted = true; LoadStartedEventHandler loadStartedEventHandler = (LoadStartedEventHandler)owner.Events[WebBrowser.LoadStarted]; if (loadStartedEventHandler != null) { AsciiString asciiString2 = new AsciiString(string.Empty); ret.getName(asciiString2.Handle); LoadStartedEventArgs loadStartedEventArgs = new LoadStartedEventArgs(currentUri, asciiString2.ToString()); loadStartedEventHandler(this, loadStartedEventArgs); if (loadStartedEventArgs.Cancel) { request.cancel(2152398850u); } } } else if (flag5 && flag4 && flag) { progress.getDOMWindow(out var ret3); ((nsIChannel)request).getURI(out var ret4); if (ret4 == null) { currentUri = "about:blank"; } else { AsciiString asciiString3 = new AsciiString(string.Empty); ret4.getSpec(asciiString3.Handle); currentUri = asciiString3.ToString(); } ret3.getTop(out var ret5); if (ret5 == null || ret5.GetHashCode() == ret3.GetHashCode()) { owner.Reset(); ret3.getDocument(out var ret6); if (ret6 != null) { owner.document = new Document(owner, ret6); } } LoadCommitedEventHandler loadCommitedEventHandler = (LoadCommitedEventHandler)owner.Events[WebBrowser.LoadCommited]; if (loadCommitedEventHandler != null) { LoadCommitedEventArgs e = new LoadCommitedEventArgs(currentUri); loadCommitedEventHandler(this, e); } } else if (flag5 && flag4 && flag2) { progress.getDOMWindow(out var _); ((nsIChannel)request).getURI(out var ret8); if (ret8 == null) { currentUri = "about:blank"; return; } AsciiString asciiString4 = new AsciiString(string.Empty); ret8.getSpec(asciiString4.Handle); currentUri = asciiString4.ToString(); } else if (flag3 && !flag4 && !flag5 && flag6 && flag7) { calledLoadStarted = false; LoadFinishedEventHandler loadFinishedEventHandler = (LoadFinishedEventHandler)owner.Events[WebBrowser.LoadFinished]; if (loadFinishedEventHandler != null) { progress.getDOMWindow(out var _); LoadFinishedEventArgs e2 = new LoadFinishedEventArgs(currentUri); loadFinishedEventHandler(this, e2); } } else { if (!(flag3 && !flag4 && flag5) || flag6 || flag7) { return; } progress.getDOMWindow(out var ret10); ret10.getDocument(out var ret11); if (ret11 != null) { int hashCode = ret11.GetHashCode(); if (owner.documents.ContainsKey(hashCode)) { ((EventHandler)(owner.documents[hashCode] as Document).Events[Document.LoadStopped])?.Invoke(this, null); } } calledLoadStarted = false; } } public void OnProgress(nsIWebProgress progress, nsIRequest request, int currentTotalProgress, int maxTotalProgress) { Mono.WebBrowser.ProgressChangedEventHandler progressChangedEventHandler = (Mono.WebBrowser.ProgressChangedEventHandler)owner.Events[WebBrowser.ProgressChanged]; if (progressChangedEventHandler != null) { Mono.WebBrowser.ProgressChangedEventArgs e = new Mono.WebBrowser.ProgressChangedEventArgs(currentTotalProgress, maxTotalProgress); progressChangedEventHandler(this, e); } } public void OnLocationChanged(nsIWebProgress progress, nsIRequest request, nsIURI uri) { } public void OnStatusChange(nsIWebProgress progress, nsIRequest request, string message, int status) { StatusChangedEventHandler statusChangedEventHandler = (StatusChangedEventHandler)owner.Events[WebBrowser.StatusChanged]; if (statusChangedEventHandler != null) { StatusChangedEventArgs e = new StatusChangedEventArgs(message, status); statusChangedEventHandler(this, e); } } public void OnSecurityChange(nsIWebProgress progress, nsIRequest request, uint status) { SecurityChangedEventHandler securityChangedEventHandler = (SecurityChangedEventHandler)owner.Events[WebBrowser.SecurityChanged]; if (securityChangedEventHandler != null) { SecurityLevel state = SecurityLevel.Insecure; switch (status) { case 4u: state = SecurityLevel.Insecure; break; case 1u: state = SecurityLevel.Mixed; break; case 2u: state = SecurityLevel.Secure; break; } SecurityChangedEventArgs e = new SecurityChangedEventArgs(state); securityChangedEventHandler(this, e); } } public bool OnClientDomKeyDown(KeyInfo keyInfo, ModifierKeys modifiers, nsIDOMNode target) { INode node = new Node(owner, target); string key = string.Intern(node.GetHashCode() + ":keydown"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(node, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.KeyDown]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(node); nodeEventHandler(this, e2); return true; } return false; } public bool OnClientDomKeyUp(KeyInfo keyInfo, ModifierKeys modifiers, nsIDOMNode target) { INode node = new Node(owner, target); string key = string.Intern(node.GetHashCode() + ":keyup"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(node, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.KeyUp]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(node); nodeEventHandler(this, e2); return true; } return false; } public bool OnClientDomKeyPress(KeyInfo keyInfo, ModifierKeys modifiers, nsIDOMNode target) { INode node = new Node(owner, target); string key = string.Intern(node.GetHashCode() + ":keypress"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(node, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.KeyPress]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(node); nodeEventHandler(this, e2); return true; } return false; } public bool OnClientMouseDown(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target) { INode node = new Node(owner, target); string key = string.Intern(node.GetHashCode() + ":mousedown"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(node, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseDown]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(node); nodeEventHandler(this, e2); return true; } return false; } public bool OnClientMouseUp(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target) { INode node = new Node(owner, target); string key = string.Intern(node.GetHashCode() + ":mouseup"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(node, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseUp]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(node); nodeEventHandler(this, e2); return true; } return false; } public bool OnClientMouseClick(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target) { INode node = new Node(owner, target); string key = string.Intern(node.GetHashCode() + ":click"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(node, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseClick]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(node); nodeEventHandler(this, e2); return true; } return false; } public bool OnClientMouseDoubleClick(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target) { INode node = new Node(owner, target); string key = string.Intern(node.GetHashCode() + ":dblclick"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(node, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseDoubleClick]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(node); nodeEventHandler(this, e2); return true; } return false; } public bool OnClientMouseOver(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target) { INode typedNode = new DOMObject(owner).GetTypedNode(target); string key = string.Intern(typedNode.GetHashCode() + ":mouseover"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(typedNode, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseEnter]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(typedNode); nodeEventHandler(typedNode, e2); return true; } return false; } public bool OnClientMouseOut(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target) { INode node = new Node(owner, target); string key = string.Intern(node.GetHashCode() + ":mouseout"); EventHandler eventHandler = (EventHandler)owner.DomEvents[key]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(node, e); } NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseLeave]; if (nodeEventHandler != null) { NodeEventArgs e2 = new NodeEventArgs(node); nodeEventHandler(this, e2); return true; } return false; } public bool OnClientActivate() { return false; } public bool OnClientFocus() { EventHandler eventHandler = (EventHandler)owner.Events[WebBrowser.Focus]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(this, e); } return false; } public bool OnClientBlur() { EventHandler eventHandler = (EventHandler)owner.Events[WebBrowser.Blur]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(this, e); } return false; } public bool OnCreateNewWindow() { bool result = false; CreateNewWindowEventHandler createNewWindowEventHandler = (CreateNewWindowEventHandler)owner.Events[WebBrowser.CreateNewWindow]; if (createNewWindowEventHandler != null) { CreateNewWindowEventArgs e = new CreateNewWindowEventArgs(isModal: false); result = createNewWindowEventHandler(this, e); } return result; } public void OnAlert(IntPtr title, IntPtr text) { AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.Alert; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } alertEventHandler(this, alertEventArgs); } } public bool OnAlertCheck(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState) { AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.AlertCheck; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } if (chkMsg != IntPtr.Zero) { alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg); } alertEventArgs.CheckState = chkState; alertEventHandler(this, alertEventArgs); return alertEventArgs.BoolReturn; } return false; } public bool OnConfirm(IntPtr title, IntPtr text) { AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.Confirm; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } alertEventHandler(this, alertEventArgs); return alertEventArgs.BoolReturn; } return false; } public bool OnConfirmCheck(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState) { AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.ConfirmCheck; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } if (chkMsg != IntPtr.Zero) { alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg); } alertEventArgs.CheckState = chkState; alertEventHandler(this, alertEventArgs); chkState = alertEventArgs.CheckState; return alertEventArgs.BoolReturn; } return false; } public bool OnConfirmEx(IntPtr title, IntPtr text, DialogButtonFlags flags, IntPtr title0, IntPtr title1, IntPtr title2, IntPtr chkMsg, ref bool chkState, out int retVal) { retVal = -1; AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.ConfirmEx; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } if (chkMsg != IntPtr.Zero) { alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg); } alertEventArgs.CheckState = chkState; alertEventHandler(this, alertEventArgs); chkState = alertEventArgs.CheckState; return alertEventArgs.BoolReturn; } return false; } public bool OnPrompt(IntPtr title, IntPtr text, ref IntPtr retVal) { AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.Prompt; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } if (retVal != IntPtr.Zero) { alertEventArgs.Text2 = Marshal.PtrToStringUni(retVal); } alertEventHandler(this, alertEventArgs); retVal = Marshal.StringToHGlobalUni(alertEventArgs.StringReturn); return alertEventArgs.BoolReturn; } return false; } public bool OnPromptUsernameAndPassword(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState, out IntPtr username, out IntPtr password) { username = IntPtr.Zero; password = IntPtr.Zero; AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.PromptUsernamePassword; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } if (chkMsg != IntPtr.Zero) { alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg); } alertEventArgs.CheckState = chkState; alertEventHandler(this, alertEventArgs); return alertEventArgs.BoolReturn; } return false; } public bool OnPromptPassword(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState, out IntPtr password) { password = IntPtr.Zero; AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.PromptPassword; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } if (chkMsg != IntPtr.Zero) { alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg); } alertEventArgs.CheckState = chkState; alertEventHandler(this, alertEventArgs); return alertEventArgs.BoolReturn; } return false; } public bool OnSelect(IntPtr title, IntPtr text, uint count, IntPtr list, out int retVal) { retVal = 0; AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert]; if (alertEventHandler != null) { AlertEventArgs alertEventArgs = new AlertEventArgs(); alertEventArgs.Type = DialogType.Select; if (title != IntPtr.Zero) { alertEventArgs.Title = Marshal.PtrToStringUni(title); } if (text != IntPtr.Zero) { alertEventArgs.Text = Marshal.PtrToStringUni(text); } alertEventHandler(this, alertEventArgs); return alertEventArgs.BoolReturn; } return false; } public void OnLoad() { ((Window)owner.Window).OnLoad(); } public void OnUnload() { ((Window)owner.Window).OnUnload(); } public void OnShowContextMenu(uint contextFlags, [MarshalAs(UnmanagedType.Interface)] nsIDOMEvent eve, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode node) { ContextMenuEventHandler contextMenuEventHandler = (ContextMenuEventHandler)owner.Events[WebBrowser.ContextMenuEvent]; if (contextMenuEventHandler != null) { nsIDOMMouseEvent obj = (nsIDOMMouseEvent)eve; obj.getClientX(out var ret); obj.getClientY(out var ret2); ContextMenuEventArgs e = new ContextMenuEventArgs(ret, ret2); contextMenuEventHandler(owner, e); } } public void OnGeneric(string type) { EventHandler eventHandler = (EventHandler)owner.Events[WebBrowser.Generic]; if (eventHandler != null) { EventArgs e = new EventArgs(); eventHandler(type, e); } } } internal delegate void CallbackVoid(); internal delegate void CallbackString(string arg1); internal delegate void CallbackWString([MarshalAs(UnmanagedType.LPWStr)] string arg1); internal delegate void CallbackStringString(string arg1, string arg2); internal delegate void CallbackStringInt(string arg1, int arg2); internal delegate void CallbackWStringInt([MarshalAs(UnmanagedType.LPWStr)] string arg1, int arg2); internal delegate void CallbackStringIntInt(string arg1, int arg2, int arg3); internal delegate void CallbackStringIntUint(string arg1, int arg2, uint arg3); internal delegate void CallbackIntInt(int arg1, int arg2); internal delegate void CallbackIntUint(int arg2, uint arg3); internal delegate void CallbackUint(uint arg1); internal delegate void CallbackUintInt(uint arg1, int arg2); internal delegate void CallbackPtrPtr(IntPtr arg1, IntPtr arg2); internal delegate void CallbackBool(bool val); internal delegate bool KeyCallback(KeyInfo keyInfo, ModifierKeys modifiers, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode target); internal delegate bool MouseCallback(MouseInfo mouseInfo, ModifierKeys modifiers, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode target); internal delegate void GenericCallback(IntPtr type); internal delegate bool Callback2(); internal delegate bool Callback2String(string arg1); internal delegate bool CallbackOnAlertCheck(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState); internal delegate bool CallbackOnConfirm(IntPtr title, IntPtr text); internal delegate bool CallbackOnConfirmCheck(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState); internal delegate bool CallbackOnConfirmEx(IntPtr title, IntPtr text, DialogButtonFlags flags, IntPtr title0, IntPtr title1, IntPtr title2, IntPtr chkMsg, ref bool chkState, out int retVal); internal delegate bool CallbackOnPrompt(IntPtr title, IntPtr text, ref IntPtr retVal); internal delegate bool CallbackOnPromptUsernameAndPassword(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState, out IntPtr username, out IntPtr password); internal delegate bool CallbackOnPromptPassword(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState, out IntPtr password); internal delegate bool CallbackOnSelect(IntPtr title, IntPtr text, uint count, IntPtr list, out int retVal); internal delegate void CallbackOnLocationChanged([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, [MarshalAs(UnmanagedType.Interface)] nsIURI uri); internal delegate void CallbackOnStatusChange([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, [MarshalAs(UnmanagedType.LPWStr)] string message, int status); internal delegate void CallbackOnSecurityChange([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, uint status); internal delegate void CallbackOnStateChange([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, int arg2, uint arg3); internal delegate void CallbackOnProgress([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, int arg2, int arg3); internal delegate void CallbackOnShowContextMenu(uint contextFlags, [MarshalAs(UnmanagedType.Interface)] nsIDOMEvent eve, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode node); internal struct CallbackBinder { public CallbackVoid OnWidgetLoaded; public CallbackOnStateChange OnStateChange; public CallbackOnProgress OnProgress; public CallbackOnLocationChanged OnLocationChanged; public CallbackOnStatusChange OnStatusChange; public CallbackOnSecurityChange OnSecurityChange; public KeyCallback OnKeyDown; public KeyCallback OnKeyUp; public KeyCallback OnKeyPress; public MouseCallback OnMouseDown; public MouseCallback OnMouseUp; public MouseCallback OnMouseClick; public MouseCallback OnMouseDoubleClick; public MouseCallback OnMouseOver; public MouseCallback OnMouseOut; public Callback2 OnActivate; public Callback2 OnFocus; public Callback2 OnBlur; public CallbackPtrPtr OnAlert; public CallbackOnAlertCheck OnAlertCheck; public CallbackOnConfirm OnConfirm; public CallbackOnConfirmCheck OnConfirmCheck; public CallbackOnConfirmEx OnConfirmEx; public CallbackOnPrompt OnPrompt; public CallbackOnPromptUsernameAndPassword OnPromptUsernameAndPassword; public CallbackOnPromptPassword OnPromptPassword; public CallbackOnSelect OnSelect; public CallbackVoid OnLoad; public CallbackVoid OnUnload; public CallbackOnShowContextMenu OnShowContextMenu; public CallbackWString OnGeneric; internal CallbackBinder(Callback callback) { OnWidgetLoaded = callback.OnWidgetLoaded; OnStateChange = callback.OnStateChange; OnProgress = callback.OnProgress; OnLocationChanged = callback.OnLocationChanged; OnStatusChange = callback.OnStatusChange; OnSecurityChange = callback.OnSecurityChange; OnKeyDown = callback.OnClientDomKeyDown; OnKeyUp = callback.OnClientDomKeyUp; OnKeyPress = callback.OnClientDomKeyPress; OnMouseDown = callback.OnClientMouseDown; OnMouseUp = callback.OnClientMouseUp; OnMouseClick = callback.OnClientMouseClick; OnMouseDoubleClick = callback.OnClientMouseDoubleClick; OnMouseOver = callback.OnClientMouseOver; OnMouseOut = callback.OnClientMouseOut; OnActivate = callback.OnClientActivate; OnFocus = callback.OnClientFocus; OnBlur = callback.OnClientBlur; OnAlert = callback.OnAlert; OnAlertCheck = callback.OnAlertCheck; OnConfirm = callback.OnConfirm; OnConfirmCheck = callback.OnConfirmCheck; OnConfirmEx = callback.OnConfirmEx; OnPrompt = callback.OnPrompt; OnPromptUsernameAndPassword = callback.OnPromptUsernameAndPassword; OnPromptPassword = callback.OnPromptPassword; OnSelect = callback.OnSelect; OnLoad = callback.OnLoad; OnUnload = callback.OnUnload; OnShowContextMenu = callback.OnShowContextMenu; OnGeneric = callback.OnGeneric; } } internal struct SizeInfo { public uint width; public uint height; } internal struct ModifierKeys { public int altKey; public int ctrlKey; public int metaKey; public int shiftKey; } internal struct MouseInfo { public ushort button; public int clientX; public int clientY; public int screenX; public int screenY; } internal struct KeyInfo { public uint charCode; public uint keyCode; } [Flags] internal enum StateFlags { Start = 1, Redirecting = 2, Transferring = 4, Negotiating = 8, Stop = 0x10, IsRequest = 0x10000, IsDocument = 0x20000, IsNetwork = 0x40000, IsWindow = 0x80000, Restoring = 0x1000000, IsInsecure = 4, IsBroken = 1, IsSecure = 2, SecureHigh = 0x40000, SecureMed = 0x10000, SecureLow = 0x20000 } internal class DocumentEncoder : DOMObject { private nsIDocumentEncoder docEncoder; private string mimeType; private DocumentEncoderFlags flags; public string MimeType { get { if (mimeType == null) { mimeType = "text/html"; } return mimeType; } set { mimeType = value; } } public DocumentEncoderFlags Flags { get { return flags; } set { flags = value; } } public DocumentEncoder(WebBrowser control) : base(control) { IntPtr ret = IntPtr.Zero; base.control.ServiceManager.getServiceByContractID("@mozilla.org/layout/documentEncoder;1?type=text/html", typeof(nsIDocumentEncoder).GUID, out ret); if (ret == IntPtr.Zero) { throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.DocumentEncoderService); } try { docEncoder = (nsIDocumentEncoder)Marshal.GetObjectForIUnknown(ret); } catch (System.Exception) { throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.DocumentEncoderService); } if (control.platform != control.enginePlatform) { docEncoder = nsDocumentEncoder.GetProxy(control, docEncoder); } } protected override void Dispose(bool disposing) { if (!disposed) { if (disposing) { docEncoder = null; } disposed = true; } } private void Init(Document document, string mimeType, DocumentEncoderFlags flags) { UniString uniString = new UniString(mimeType); try { docEncoder.init((nsIDOMDocument)document.nodeNoProxy, uniString.Handle, (uint)flags); } catch (System.Exception innerException) { throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.DocumentEncoderService, innerException); } } public string EncodeToString(Document document) { Init(document, MimeType, Flags); docEncoder.encodeToString(storage); return Base.StringGet(storage); } public string EncodeToString(HTMLElement element) { Init((Document)element.Owner, MimeType, Flags); docEncoder.setNode(element.nodeNoProxy); docEncoder.encodeToString(storage); string text = Base.StringGet(storage); string tagName = element.TagName; string text2 = "<" + tagName; foreach (IAttribute attribute in element.Attributes) { text2 = text2 + " " + attribute.Name + "=\"" + attribute.Value + "\""; } return text2 + ">" + text + "</" + tagName + ">"; } public System.IO.Stream EncodeToStream(Document document) { Init(document, MimeType, Flags); Stream stream = new Stream(new MemoryStream()); docEncoder.encodeToStream(stream); return stream.BaseStream; } public System.IO.Stream EncodeToStream(HTMLElement element) { Init((Document)element.Owner, MimeType, Flags); docEncoder.setNode(element.nodeNoProxy); Stream stream = new Stream(new MemoryStream()); docEncoder.encodeToStream(stream); return stream.BaseStream; } } internal class Stream : nsIInputStream, nsIOutputStream { private System.IO.Stream back; public System.IO.Stream BaseStream => back; public Stream(System.IO.Stream stream) { back = stream; } public int close() { back.Close(); return 0; } public int flush() { back.Flush(); return 0; } public int write([MarshalAs(UnmanagedType.LPStr)] string str, uint count, out uint ret) { ret = count; if (count == 0) { return 0; } byte[] bytes = Encoding.ASCII.GetBytes(str); back.Write(bytes, 0, (int)count); return 0; } public int writeFrom([MarshalAs(UnmanagedType.Interface)] nsIInputStream aFromStream, uint aCount, out uint ret) { ret = 0u; return 0; } public int writeSegments(nsIReadSegmentFunDelegate aReader, IntPtr aClosure, uint aCount, out uint ret) { ret = 0u; return 0; } public int isNonBlocking(out bool ret) { ret = false; return 0; } public int available(out uint ret) { ret = 0u; return 0; } public int read(HandleRef str, uint count, out uint ret) { byte[] array = new byte[count]; ret = (uint)back.Read(array, 0, (int)count); string @string = Encoding.ASCII.GetString(array); Base.StringSet(str, @string); return 0; } public int readSegments(nsIWriteSegmentFunDelegate aWriter, IntPtr aClosure, uint aCount, out uint ret) { ret = 0u; return 0; } } internal class UniString : IDisposable { [StructLayout(LayoutKind.Sequential)] private class nsStringContainer { private IntPtr v; private IntPtr d1; private uint d2; private IntPtr d3; } private bool disposed; private nsStringContainer unmanagedContainer; private HandleRef handle; private string str = string.Empty; private bool dirty; public HandleRef Handle { get { dirty = true; return handle; } } public string String { get { if (dirty) { Base.gluezilla_StringGetData(handle, out var aBuf, out var _); str = Marshal.PtrToStringUni(aBuf); dirty = false; } return str; } set { if (str != value) { str = value; Base.gluezilla_StringSetData(handle, str, (uint)str.Length); } } } public int Length => String.Length; public UniString(string value) { unmanagedContainer = new nsStringContainer(); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(nsStringContainer))); Marshal.StructureToPtr(unmanagedContainer, ptr, fDeleteOld: false); handle = new HandleRef(typeof(nsStringContainer), ptr); Base.gluezilla_StringContainerInit(handle); String = value; } ~UniString() { Dispose(disposing: false); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { Base.gluezilla_StringContainerFinish(handle); Marshal.FreeHGlobal(handle.Handle); } disposed = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public override string ToString() { return String; } } internal class WebBrowser : IWebBrowser { private bool loaded; internal bool created; private bool creating; internal Document document; internal Navigation navigation; internal Platform platform; internal Platform enginePlatform; internal Callback callbacks; private EventHandlerList events; private EventHandlerList domEvents; private string statusText; private bool streamingMode; internal Hashtable documents; private int width; private int height; private bool isDirty; private ContentListener contentListener; private nsIServiceManager servMan; private nsIIOService ioService; private nsIAccessibilityService accessibilityService; private nsIErrorService errorService; private DocumentEncoder docEncoder; internal static object KeyDownEvent; internal static object KeyPressEvent; internal static object KeyUpEvent; internal static object MouseClickEvent; internal static object MouseDoubleClickEvent; internal static object MouseDownEvent; internal static object MouseEnterEvent; internal static object MouseLeaveEvent; internal static object MouseMoveEvent; internal static object MouseUpEvent; internal static object FocusEvent; internal static object BlurEvent; internal static object CreateNewWindowEvent; internal static object AlertEvent; internal static object LoadStartedEvent; internal static object LoadCommitedEvent; internal static object ProgressChangedEvent; internal static object LoadFinishedEvent; internal static object LoadEvent; internal static object UnloadEvent; internal static object StatusChangedEvent; internal static object SecurityChangedEvent; internal static object ProgressEvent; internal static object ContextMenuEvent; internal static object NavigationRequestedEvent; internal static object GenericEvent; private bool Created { get { if (!creating && !created) { creating = true; created = Base.Create(this); if (created && isDirty) { isDirty = false; Base.Resize(this, width, height); } } return created; } } public bool Initialized => loaded; public IWindow Window { get { if (Navigation != null) { ((nsIWebBrowserFocus)navigation.navigation).getFocusedWindow(out var ret); if (ret == null) { ((nsIWebBrowser)navigation.navigation).getContentDOMWindow(out ret); } if (ret != null) { return new Window(this, ret); } } return null; } } public IDocument Document { get { if (Navigation != null && document == null) { document = navigation.Document; } return document; } } public INavigation Navigation { get { if (!Created) { return null; } if (navigation == null) { nsIWebNavigation webNavigation = Base.GetWebNavigation(this); navigation = new Navigation(this, webNavigation); } return navigation; } } public string StatusText => statusText; public bool Offline { get { if (!Created) { return true; } IOService.getOffline(out var ret); return ret; } set { IOService.setOffline(value); } } internal EventHandlerList DomEvents { get { if (domEvents == null) { domEvents = new EventHandlerList(); } return domEvents; } } internal EventHandlerList Events { get { if (events == null) { events = new EventHandlerList(); } return events; } } private ContentListener ContentListener { get { if (contentListener == null) { contentListener = new ContentListener(this); } return contentListener; } } internal nsIServiceManager ServiceManager { get { if (servMan == null) { servMan = Base.GetServiceManager(this); } return servMan; } } internal nsIIOService IOService { get { if (ioService == null) { IntPtr ret = IntPtr.Zero; ServiceManager.getServiceByContractID("@mozilla.org/network/io-service;1", typeof(nsIIOService).GUID, out ret); if (ret == IntPtr.Zero) { throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.IOService); } try { ioService = (nsIIOService)Marshal.GetObjectForIUnknown(ret); } catch (System.Exception innerException) { throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.IOService, innerException); } } return ioService; } } internal nsIAccessibilityService AccessibilityService { get { if (accessibilityService == null) { IntPtr ret = IntPtr.Zero; ServiceManager.getServiceByContractID("@mozilla.org/accessibilityService;1", typeof(nsIAccessibilityService).GUID, out ret); if (ret == IntPtr.Zero) { throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.AccessibilityService); } try { accessibilityService = (nsIAccessibilityService)Marshal.GetObjectForIUnknown(ret); } catch (System.Exception innerException) { throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.AccessibilityService, innerException); } } return accessibilityService; } } internal nsIErrorService ErrorService { get { if (errorService == null) { IntPtr ret = IntPtr.Zero; ServiceManager.getServiceByContractID("@mozilla.org/xpcom/error-service;1", typeof(nsIErrorService).GUID, out ret); if (ret == IntPtr.Zero) { return null; } try { errorService = (nsIErrorService)Marshal.GetObjectForIUnknown(ret); } catch (System.Exception) { return null; } } return errorService; } } internal DocumentEncoder DocEncoder { get { if (docEncoder == null) { docEncoder = new DocumentEncoder(this); } return docEncoder; } } public event NodeEventHandler KeyDown { add { Events.AddHandler(KeyDownEvent, value); } remove { Events.RemoveHandler(KeyDownEvent, value); } } public event NodeEventHandler KeyPress { add { Events.AddHandler(KeyPressEvent, value); } remove { Events.RemoveHandler(KeyPressEvent, value); } } public event NodeEventHandler KeyUp { add { Events.AddHandler(KeyUpEvent, value); } remove { Events.RemoveHandler(KeyUpEvent, value); } } public event NodeEventHandler MouseClick { add { Events.AddHandler(MouseClickEvent, value); } remove { Events.RemoveHandler(MouseClickEvent, value); } } public event NodeEventHandler MouseDoubleClick { add { Events.AddHandler(MouseDoubleClickEvent, value); } remove { Events.RemoveHandler(MouseDoubleClickEvent, value); } } public event NodeEventHandler MouseDown { add { Events.AddHandler(MouseDownEvent, value); } remove { Events.RemoveHandler(MouseDownEvent, value); } } public event NodeEventHandler MouseEnter { add { Events.AddHandler(MouseEnterEvent, value); } remove { Events.RemoveHandler(MouseEnterEvent, value); } } public event NodeEventHandler MouseLeave { add { Events.AddHandler(MouseLeaveEvent, value); } remove { Events.RemoveHandler(MouseLeaveEvent, value); } } public event NodeEventHandler MouseMove { add { Events.AddHandler(MouseMoveEvent, value); } remove { Events.RemoveHandler(MouseMoveEvent, value); } } public event NodeEventHandler MouseUp { add { Events.AddHandler(MouseUpEvent, value); } remove { Events.RemoveHandler(MouseUpEvent, value); } } public event EventHandler Focus { add { Events.AddHandler(FocusEvent, value); } remove { Events.RemoveHandler(FocusEvent, value); } } public event EventHandler Blur { add { Events.AddHandler(BlurEvent, value); } remove { Events.RemoveHandler(BlurEvent, value); } } public event CreateNewWindowEventHandler CreateNewWindow { add { Events.AddHandler(CreateNewWindowEvent, value); } remove { Events.RemoveHandler(CreateNewWindowEvent, value); } } public event AlertEventHandler Alert { add { Events.AddHandler(AlertEvent, value); } remove { Events.RemoveHandler(AlertEvent, value); } } public event EventHandler Loaded { add { Events.AddHandler(LoadEvent, value); } remove { Events.RemoveHandler(LoadEvent, value); } } public event EventHandler Unloaded { add { Events.AddHandler(UnloadEvent, value); } remove { Events.RemoveHandler(UnloadEvent, value); } } public event StatusChangedEventHandler StatusChanged { add { Events.AddHandler(StatusChangedEvent, value); } remove { Events.RemoveHandler(StatusChangedEvent, value); } } public event SecurityChangedEventHandler SecurityChanged { add { Events.AddHandler(SecurityChangedEvent, value); } remove { Events.RemoveHandler(SecurityChangedEvent, value); } } public event LoadStartedEventHandler LoadStarted { add { Events.AddHandler(LoadStartedEvent, value); } remove { Events.RemoveHandler(LoadStartedEvent, value); } } public event LoadCommitedEventHandler LoadCommited { add { Events.AddHandler(LoadCommitedEvent, value); } remove { Events.RemoveHandler(LoadCommitedEvent, value); } } public event Mono.WebBrowser.ProgressChangedEventHandler ProgressChanged { add { Events.AddHandler(ProgressChangedEvent, value); } remove { Events.RemoveHandler(ProgressChangedEvent, value); } } public event LoadFinishedEventHandler LoadFinished { add { Events.AddHandler(LoadFinishedEvent, value); } remove { Events.RemoveHandler(LoadFinishedEvent, value); } } public event ContextMenuEventHandler ContextMenuShown { add { Events.AddHandler(ContextMenuEvent, value); } remove { Events.RemoveHandler(ContextMenuEvent, value); } } public event NavigationRequestedEventHandler NavigationRequested { add { ContentListener.AddHandler(value); } remove { ContentListener.RemoveHandler(value); } } internal event EventHandler Generic { add { Events.AddHandler(GenericEvent, value); } remove { Events.RemoveHandler(GenericEvent, value); } } public WebBrowser(Platform platform) { this.platform = platform; callbacks = new Callback(this); loaded = Base.Init(this, platform); documents = new Hashtable(); } public bool Load(IntPtr handle, int width, int height) { loaded = Base.Bind(this, handle, width, height); return loaded; } public void Shutdown() { Base.Shutdown(this); } internal void Reset() { document = null; DomEvents.Dispose(); domEvents = null; documents.Clear(); } public void FocusIn(FocusOption focus) { if (created) { Base.Focus(this, focus); } } public void FocusOut() { if (created) { Base.Blur(this); } } public void Activate() { if (Created) { Base.Activate(this); } } public void Deactivate() { if (created) { Base.Deactivate(this); } } public void Resize(int width, int height) { this.width = width; this.height = height; isDirty = true; if (created) { Base.Resize(this, width, height); } } public void Render(byte[] data) { if (Created) { if (data == null) { throw new ArgumentNullException("data"); } string @string = Encoding.UTF8.GetString(data); Render(@string); } } public void Render(string html) { if (Created) { Render(html, "file:///", "text/html"); } } public void Render(string html, string uri, string contentType) { if (Created) { if (Navigation == null) { throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.Navigation); } nsIWebBrowserStream nsIWebBrowserStream2 = (nsIWebBrowserStream)navigation.navigation; AsciiString asciiString = new AsciiString(uri); IOService.newURI(asciiString.Handle, null, null, out var ret); HandleRef handle = new AsciiString(contentType).Handle; nsIWebBrowserStream2.openStream(ret, handle); IntPtr intPtr = Marshal.StringToHGlobalAnsi(html); nsIWebBrowserStream2.appendToStream(intPtr, (uint)html.Length); Marshal.FreeHGlobal(intPtr); nsIWebBrowserStream2.closeStream(); } } public void ExecuteScript(string script) { if (Created) { Base.EvalScript(this, script); } } internal void AttachEvent(INode node, string eve, EventHandler handler) { string key = string.Intern(node.GetHashCode() + ":" + eve); DomEvents.AddHandler(key, handler); } internal void DetachEvent(INode node, string eve, EventHandler handler) { string key = string.Intern(node.GetHashCode() + ":" + eve); DomEvents.RemoveHandler(key, handler); } static WebBrowser() { KeyDown = new object(); KeyPress = new object(); KeyUp = new object(); MouseClick = new object(); MouseDoubleClick = new object(); MouseDown = new object(); MouseEnter = new object(); MouseLeave = new object(); MouseMove = new object(); MouseUp = new object(); Focus = new object(); Blur = new object(); CreateNewWindow = new object(); Alert = new object(); LoadStarted = new object(); LoadCommited = new object(); ProgressChanged = new object(); LoadFinished = new object(); LoadEvent = new object(); UnloadEvent = new object(); StatusChanged = new object(); SecurityChanged = new object(); ProgressEvent = new object(); ContextMenuEvent = new object(); NavigationRequested = new object(); Generic = new object(); } } internal enum StopOption : uint { Network = 1u, Content, All } internal delegate void nsIReadSegmentFunDelegate([MarshalAs(UnmanagedType.Interface)] nsIOutputStream aInStream, IntPtr aClosure, string aFromSegment, uint aCount, out uint aWriteCount); internal delegate void nsITimerCallbackDelegate([MarshalAs(UnmanagedType.Interface)] nsITimer timer, IntPtr closure); internal delegate void nsIWriteSegmentFunDelegate([MarshalAs(UnmanagedType.Interface)] nsIInputStream aInStream, IntPtr aClosure, string aFromSegment, uint aToOffset, uint aCount, out uint aWriteCount); [ComImport] [Guid("71a3b4e7-e83d-45cf-a20e-9ce292bcf19f")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface nsIAccessNode { [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getDOMNode([MarshalAs(UnmanagedType.Interface)] out nsIDOMNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getNumChildren(out int ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getChildNodeAt(int childNum, [MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getParentNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getFirstChildNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getLastChildNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getPreviousSiblingNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getNextSiblingNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getAccessibleDocument([MarshalAs(UnmanagedType.Interface)] out nsIAccessibleDocument ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getInnerHTML(HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int scrollTo(uint aScrollType); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int scrollToPoint(uint aCoordinateType, int aX, int aY); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getOwnerWindow(IntPtr ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getUniqueID(IntPtr ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getComputedStyleValue(HandleRef pseudoElt, HandleRef propertyName, HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getComputedStyleCSSValue(HandleRef pseudoElt, HandleRef propertyName, [MarshalAs(UnmanagedType.Interface)] out nsIDOMCSSPrimitiveValue ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getLanguage(HandleRef ret); } internal class nsAccessNode { public static nsIAccessNode GetProxy(IWebBrowser control, nsIAccessNode obj) { return Base.GetProxyForObject(control, typeof(nsIAccessNode).GUID, obj) as nsIAccessNode; } } [ComImport] [Guid("27386cf1-f27e-4d2d-9bf4-c4621d50d299")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface nsIAccessibilityService : nsIAccessibleRetrieval { [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getAccessibleFor([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getAttachedAccessibleFor([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getRelevantContentNodeFor([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] out nsIDOMNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getAccessibleInWindow([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIDOMWindow aDOMWin, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getAccessibleInWeakShell([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getAccessibleInShell([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, IntPtr aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getCachedAccessNode([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getCachedAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getStringRole(uint aRole, HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getStringStates(uint aStates, uint aExtraStates, [MarshalAs(UnmanagedType.Interface)] out nsIDOMDOMStringList ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getStringEventType(uint aEventType, HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] new int getStringRelationType(uint aRelationType, HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createOuterDocAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createRootAccessible(IntPtr aShell, IntPtr aDocument, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTML4ButtonAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHyperTextAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLBRAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLButtonAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLAccessibleByMarkup(IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aWeakShell, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode aDOMNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLLIAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] IntPtr aBulletFrame, HandleRef aBulletText, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLCheckboxAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLComboboxAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLGenericAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLGroupboxAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLHRAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLImageAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLLabelAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLListboxAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLObjectFrameAccessible(IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLRadioButtonAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLSelectOptionAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIAccessible aAccParent, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLTableAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLTableCellAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLTableHeadAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aDOMNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLTextAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLTextFieldAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int createHTMLCaptionAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, IntPtr aPresShell, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aWeakShell, out IntPtr frameHint, out bool aIsHidden, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int addNativeRootAccessible(IntPtr aAtkAccessible, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int removeNativeRootAccessible([MarshalAs(UnmanagedType.Interface)] nsIAccessible aRootAccessible); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int invalidateSubtreeFor(IntPtr aPresShell, IntPtr aChangedContent, uint aEvent); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int processDocLoadEvent([MarshalAs(UnmanagedType.Interface)] nsITimer aTimer, IntPtr aClosure, uint aEventType); } internal class nsAccessibilityService { public static nsIAccessibilityService GetProxy(IWebBrowser control, nsIAccessibilityService obj) { return Base.GetProxyForObject(control, typeof(nsIAccessibilityService).GUID, obj) as nsIAccessibilityService; } } [ComImport] [Guid("004b6882-2df1-49df-bb5f-0fb81a5b1edf")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface nsIAccessible { [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getParent([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getNextSibling([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getPreviousSibling([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getFirstChild([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getLastChild([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getChildren([MarshalAs(UnmanagedType.Interface)] out nsIArray ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getChildCount(out int ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getIndexInParent(out int ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getName(HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int setName(HandleRef value); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getValue(HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getDescription(HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getKeyboardShortcut(HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getDefaultKeyBinding(HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getKeyBindings(char aActionIndex, [MarshalAs(UnmanagedType.Interface)] out nsIDOMDOMStringList ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getRole(out uint ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getFinalRole(out uint ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getFinalState(out uint aState, out uint aExtraState); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getHelp(HandleRef ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getFocusedChild([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getAttributes([MarshalAs(UnmanagedType.Interface)] out nsIPersistentProperties ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int groupPosition(out int aGroupLevel, out int aSimilarItemsInGroup, out int aPositionInGroup); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getChildAtPoint(int x, int y, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret); [MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int getChildAt(in
deps/NAudio.Asio.dll
Decompiled a day agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using Microsoft.Win32; using NAudio.Wave.Asio; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Mark Heath")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Mark Heath 2023")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("NAudio.Asio")] [assembly: AssemblyTitle("NAudio.Asio")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.2.1.0")] [module: UnverifiableCode] namespace NAudio.Wave { public class AsioAudioAvailableEventArgs : EventArgs { public IntPtr[] InputBuffers { get; private set; } public IntPtr[] OutputBuffers { get; private set; } public bool WrittenToOutputBuffers { get; set; } public int SamplesPerBuffer { get; private set; } public AsioSampleType AsioSampleType { get; private set; } public AsioAudioAvailableEventArgs(IntPtr[] inputBuffers, IntPtr[] outputBuffers, int samplesPerBuffer, AsioSampleType asioSampleType) { InputBuffers = inputBuffers; OutputBuffers = outputBuffers; SamplesPerBuffer = samplesPerBuffer; AsioSampleType = asioSampleType; } public unsafe int GetAsInterleavedSamples(float[] samples) { int num = InputBuffers.Length; if (samples.Length < SamplesPerBuffer * num) { throw new ArgumentException("Buffer not big enough"); } int num2 = 0; if (AsioSampleType == AsioSampleType.Int32LSB) { for (int i = 0; i < SamplesPerBuffer; i++) { for (int j = 0; j < num; j++) { samples[num2++] = (float)(*(int*)((byte*)(void*)InputBuffers[j] + (nint)i * (nint)4)) / 2.1474836E+09f; } } } else if (AsioSampleType == AsioSampleType.Int16LSB) { for (int k = 0; k < SamplesPerBuffer; k++) { for (int l = 0; l < num; l++) { samples[num2++] = (float)(*(short*)((byte*)(void*)InputBuffers[l] + (nint)k * (nint)2)) / 32767f; } } } else if (AsioSampleType == AsioSampleType.Int24LSB) { for (int m = 0; m < SamplesPerBuffer; m++) { for (int n = 0; n < num; n++) { byte* ptr = (byte*)(void*)InputBuffers[n] + m * 3; int num3 = *ptr | (ptr[1] << 8) | ((sbyte)ptr[2] << 16); samples[num2++] = (float)num3 / 8388608f; } } } else { if (AsioSampleType != AsioSampleType.Float32LSB) { throw new NotImplementedException($"ASIO Sample Type {AsioSampleType} not supported"); } for (int num4 = 0; num4 < SamplesPerBuffer; num4++) { for (int num5 = 0; num5 < num; num5++) { samples[num2++] = *(float*)((byte*)(void*)InputBuffers[num5] + (nint)num4 * (nint)4); } } } return SamplesPerBuffer * num; } [Obsolete("Better performance if you use the overload that takes an array, and reuse the same one")] public float[] GetAsInterleavedSamples() { int num = InputBuffers.Length; float[] array = new float[SamplesPerBuffer * num]; GetAsInterleavedSamples(array); return array; } } public class AsioOut : IWavePlayer, IDisposable { private AsioDriverExt driver; private IWaveProvider sourceStream; private PlaybackState playbackState; private int nbSamples; private byte[] waveBuffer; private AsioSampleConvertor.SampleConvertor convertor; private string driverName; private readonly SynchronizationContext syncContext; private bool isInitialized; public int PlaybackLatency { get { driver.Driver.GetLatencies(out var _, out var outputLatency); return outputLatency; } } public bool AutoStop { get; set; } public bool HasReachedEnd { get; private set; } public PlaybackState PlaybackState => playbackState; public string DriverName => driverName; public int NumberOfOutputChannels { get; private set; } public int NumberOfInputChannels { get; private set; } public int DriverInputChannelCount => driver.Capabilities.NbInputChannels; public int DriverOutputChannelCount => driver.Capabilities.NbOutputChannels; public int FramesPerBuffer { get { if (!isInitialized) { throw new Exception("Not initialized yet. Call this after calling Init"); } return nbSamples; } } public int ChannelOffset { get; set; } public int InputChannelOffset { get; set; } [Obsolete("this function will be removed in a future NAudio as ASIO does not support setting the volume on the device")] public float Volume { get { return 1f; } set { if (value != 1f) { throw new InvalidOperationException("AsioOut does not support setting the device volume"); } } } public WaveFormat OutputWaveFormat { get; private set; } public event EventHandler<StoppedEventArgs> PlaybackStopped; public event EventHandler<AsioAudioAvailableEventArgs> AudioAvailable; public event EventHandler DriverResetRequest; public AsioOut() : this(0) { } public AsioOut(string driverName) { syncContext = SynchronizationContext.Current; InitFromName(driverName); } public AsioOut(int driverIndex) { syncContext = SynchronizationContext.Current; string[] driverNames = GetDriverNames(); if (driverNames.Length == 0) { throw new ArgumentException("There is no ASIO Driver installed on your system"); } if (driverIndex < 0 || driverIndex > driverNames.Length) { throw new ArgumentException($"Invalid device number. Must be in the range [0,{driverNames.Length}]"); } InitFromName(driverNames[driverIndex]); } ~AsioOut() { Dispose(); } public void Dispose() { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (driver != null) { if ((int)playbackState != 0) { driver.Stop(); } driver.ResetRequestCallback = null; driver.ReleaseDriver(); driver = null; } } public static string[] GetDriverNames() { return AsioDriver.GetAsioDriverNames(); } public static bool isSupported() { return GetDriverNames().Length != 0; } public bool IsSampleRateSupported(int sampleRate) { return driver.IsSampleRateSupported(sampleRate); } private void InitFromName(string driverName) { this.driverName = driverName; AsioDriver asioDriverByName = AsioDriver.GetAsioDriverByName(driverName); try { driver = new AsioDriverExt(asioDriverByName); } catch { ReleaseDriver(asioDriverByName); throw; } driver.ResetRequestCallback = OnDriverResetRequest; ChannelOffset = 0; } private void OnDriverResetRequest() { this.DriverResetRequest?.Invoke(this, EventArgs.Empty); } private void ReleaseDriver(AsioDriver driver) { driver.DisposeBuffers(); driver.ReleaseComAsioDriver(); } public void ShowControlPanel() { driver.ShowControlPanel(); } public void Play() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)playbackState != 1) { playbackState = (PlaybackState)1; HasReachedEnd = false; driver.Start(); } } public void Stop() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) playbackState = (PlaybackState)0; driver.Stop(); HasReachedEnd = false; RaisePlaybackStopped(null); } public void Pause() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) playbackState = (PlaybackState)2; driver.Stop(); } public void Init(IWaveProvider waveProvider) { InitRecordAndPlayback(waveProvider, 0, -1); } public void InitRecordAndPlayback(IWaveProvider waveProvider, int recordChannels, int recordOnlySampleRate) { //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Expected O, but got Unknown //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown if (isInitialized) { throw new InvalidOperationException("Already initialised this instance of AsioOut - dispose and create a new one"); } isInitialized = true; int num = ((waveProvider != null) ? waveProvider.WaveFormat.SampleRate : recordOnlySampleRate); if (waveProvider != null) { sourceStream = waveProvider; NumberOfOutputChannels = waveProvider.WaveFormat.Channels; AsioSampleType type = driver.Capabilities.OutputChannelInfos[0].type; convertor = AsioSampleConvertor.SelectSampleConvertor(waveProvider.WaveFormat, type); switch (type) { case AsioSampleType.Float32LSB: OutputWaveFormat = WaveFormat.CreateIeeeFloatWaveFormat(waveProvider.WaveFormat.SampleRate, waveProvider.WaveFormat.Channels); break; case AsioSampleType.Int32LSB: OutputWaveFormat = new WaveFormat(waveProvider.WaveFormat.SampleRate, 32, waveProvider.WaveFormat.Channels); break; case AsioSampleType.Int16LSB: OutputWaveFormat = new WaveFormat(waveProvider.WaveFormat.SampleRate, 16, waveProvider.WaveFormat.Channels); break; case AsioSampleType.Int24LSB: OutputWaveFormat = new WaveFormat(waveProvider.WaveFormat.SampleRate, 24, waveProvider.WaveFormat.Channels); break; default: throw new NotSupportedException($"{type} not currently supported"); } } else { NumberOfOutputChannels = 0; } if (!driver.IsSampleRateSupported(num)) { throw new ArgumentException("SampleRate is not supported"); } if (driver.Capabilities.SampleRate != (double)num) { driver.SetSampleRate(num); } driver.FillBufferCallback = driver_BufferUpdate; NumberOfInputChannels = recordChannels; nbSamples = driver.CreateBuffers(NumberOfOutputChannels, NumberOfInputChannels, useMaxBufferSize: false); driver.SetChannelOffset(ChannelOffset, InputChannelOffset); if (waveProvider != null) { waveBuffer = new byte[nbSamples * NumberOfOutputChannels * waveProvider.WaveFormat.BitsPerSample / 8]; } } private unsafe void driver_BufferUpdate(IntPtr[] inputChannels, IntPtr[] outputChannels) { if (NumberOfInputChannels > 0) { EventHandler<AsioAudioAvailableEventArgs> audioAvailable = this.AudioAvailable; if (audioAvailable != null) { AsioAudioAvailableEventArgs asioAudioAvailableEventArgs = new AsioAudioAvailableEventArgs(inputChannels, outputChannels, nbSamples, driver.Capabilities.InputChannelInfos[0].type); audioAvailable(this, asioAudioAvailableEventArgs); if (asioAudioAvailableEventArgs.WrittenToOutputBuffers) { return; } } } if (NumberOfOutputChannels <= 0) { return; } int num = sourceStream.Read(waveBuffer, 0, waveBuffer.Length); if (num < waveBuffer.Length) { Array.Clear(waveBuffer, num, waveBuffer.Length - num); } fixed (byte* ptr = &waveBuffer[0]) { void* value = ptr; convertor(new IntPtr(value), outputChannels, NumberOfOutputChannels, nbSamples); } if (num == 0) { if (AutoStop) { Stop(); } HasReachedEnd = true; } } private void RaisePlaybackStopped(Exception e) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown EventHandler<StoppedEventArgs> handler = this.PlaybackStopped; if (handler == null) { return; } if (syncContext == null) { handler(this, new StoppedEventArgs(e)); return; } syncContext.Post(delegate { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown handler(this, new StoppedEventArgs(e)); }, null); } public string AsioInputChannelName(int channel) { if (channel <= DriverInputChannelCount) { return driver.Capabilities.InputChannelInfos[channel].name; } return ""; } public string AsioOutputChannelName(int channel) { if (channel <= DriverOutputChannelCount) { return driver.Capabilities.OutputChannelInfos[channel].name; } return ""; } } } namespace NAudio.Wave.Asio { [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct Asio64Bit { public uint hi; public uint lo; } [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct AsioCallbacks { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void AsioBufferSwitchCallBack(int doubleBufferIndex, bool directProcess); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void AsioSampleRateDidChangeCallBack(double sRate); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int AsioAsioMessageCallBack(AsioMessageSelector selector, int value, IntPtr message, IntPtr opt); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr AsioBufferSwitchTimeInfoCallBack(IntPtr asioTimeParam, int doubleBufferIndex, bool directProcess); public AsioBufferSwitchCallBack pbufferSwitch; public AsioSampleRateDidChangeCallBack psampleRateDidChange; public AsioAsioMessageCallBack pasioMessage; public AsioBufferSwitchTimeInfoCallBack pbufferSwitchTimeInfo; } [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct AsioChannelInfo { public int channel; public bool isInput; public bool isActive; public int channelGroup; [MarshalAs(UnmanagedType.U4)] public AsioSampleType type; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string name; } public class AsioDriver { [StructLayout(LayoutKind.Sequential, Pack = 2)] private class AsioDriverVTable { [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate int ASIOInit(IntPtr _pUnknown, IntPtr sysHandle); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate void ASIOgetDriverName(IntPtr _pUnknown, StringBuilder name); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate int ASIOgetDriverVersion(IntPtr _pUnknown); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate void ASIOgetErrorMessage(IntPtr _pUnknown, StringBuilder errorMessage); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOstart(IntPtr _pUnknown); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOstop(IntPtr _pUnknown); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOgetChannels(IntPtr _pUnknown, out int numInputChannels, out int numOutputChannels); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOgetLatencies(IntPtr _pUnknown, out int inputLatency, out int outputLatency); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOgetBufferSize(IntPtr _pUnknown, out int minSize, out int maxSize, out int preferredSize, out int granularity); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOcanSampleRate(IntPtr _pUnknown, double sampleRate); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOgetSampleRate(IntPtr _pUnknown, out double sampleRate); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOsetSampleRate(IntPtr _pUnknown, double sampleRate); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOgetClockSources(IntPtr _pUnknown, out long clocks, int numSources); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOsetClockSource(IntPtr _pUnknown, int reference); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOgetSamplePosition(IntPtr _pUnknown, out long samplePos, ref Asio64Bit timeStamp); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOgetChannelInfo(IntPtr _pUnknown, ref AsioChannelInfo info); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOcreateBuffers(IntPtr _pUnknown, IntPtr bufferInfos, int numChannels, int bufferSize, IntPtr callbacks); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOdisposeBuffers(IntPtr _pUnknown); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOcontrolPanel(IntPtr _pUnknown); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOfuture(IntPtr _pUnknown, int selector, IntPtr opt); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] public delegate AsioError ASIOoutputReady(IntPtr _pUnknown); public ASIOInit init; public ASIOgetDriverName getDriverName; public ASIOgetDriverVersion getDriverVersion; public ASIOgetErrorMessage getErrorMessage; public ASIOstart start; public ASIOstop stop; public ASIOgetChannels getChannels; public ASIOgetLatencies getLatencies; public ASIOgetBufferSize getBufferSize; public ASIOcanSampleRate canSampleRate; public ASIOgetSampleRate getSampleRate; public ASIOsetSampleRate setSampleRate; public ASIOgetClockSources getClockSources; public ASIOsetClockSource setClockSource; public ASIOgetSamplePosition getSamplePosition; public ASIOgetChannelInfo getChannelInfo; public ASIOcreateBuffers createBuffers; public ASIOdisposeBuffers disposeBuffers; public ASIOcontrolPanel controlPanel; public ASIOfuture future; public ASIOoutputReady outputReady; } private IntPtr pAsioComObject; private IntPtr pinnedcallbacks; private AsioDriverVTable asioDriverVTable; private AsioDriver() { } public static string[] GetAsioDriverNames() { RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\ASIO"); string[] result = new string[0]; if (registryKey != null) { result = registryKey.GetSubKeyNames(); registryKey.Close(); } return result; } public static AsioDriver GetAsioDriverByName(string name) { return GetAsioDriverByGuid(new Guid((Registry.LocalMachine.OpenSubKey("SOFTWARE\\ASIO\\" + name) ?? throw new ArgumentException("Driver Name " + name + " doesn't exist")).GetValue("CLSID").ToString())); } public static AsioDriver GetAsioDriverByGuid(Guid guid) { AsioDriver asioDriver = new AsioDriver(); asioDriver.InitFromGuid(guid); return asioDriver; } public bool Init(IntPtr sysHandle) { return asioDriverVTable.init(pAsioComObject, sysHandle) == 1; } public string GetDriverName() { StringBuilder stringBuilder = new StringBuilder(256); asioDriverVTable.getDriverName(pAsioComObject, stringBuilder); return stringBuilder.ToString(); } public int GetDriverVersion() { return asioDriverVTable.getDriverVersion(pAsioComObject); } public string GetErrorMessage() { StringBuilder stringBuilder = new StringBuilder(256); asioDriverVTable.getErrorMessage(pAsioComObject, stringBuilder); return stringBuilder.ToString(); } public void Start() { HandleException(asioDriverVTable.start(pAsioComObject), "start"); } public AsioError Stop() { return asioDriverVTable.stop(pAsioComObject); } public void GetChannels(out int numInputChannels, out int numOutputChannels) { HandleException(asioDriverVTable.getChannels(pAsioComObject, out numInputChannels, out numOutputChannels), "getChannels"); } public AsioError GetLatencies(out int inputLatency, out int outputLatency) { return asioDriverVTable.getLatencies(pAsioComObject, out inputLatency, out outputLatency); } public void GetBufferSize(out int minSize, out int maxSize, out int preferredSize, out int granularity) { HandleException(asioDriverVTable.getBufferSize(pAsioComObject, out minSize, out maxSize, out preferredSize, out granularity), "getBufferSize"); } public bool CanSampleRate(double sampleRate) { AsioError asioError = asioDriverVTable.canSampleRate(pAsioComObject, sampleRate); switch (asioError) { case AsioError.ASE_NoClock: return false; case AsioError.ASE_OK: return true; default: HandleException(asioError, "canSampleRate"); return false; } } public double GetSampleRate() { HandleException(asioDriverVTable.getSampleRate(pAsioComObject, out var sampleRate), "getSampleRate"); return sampleRate; } public void SetSampleRate(double sampleRate) { HandleException(asioDriverVTable.setSampleRate(pAsioComObject, sampleRate), "setSampleRate"); } public void GetClockSources(out long clocks, int numSources) { HandleException(asioDriverVTable.getClockSources(pAsioComObject, out clocks, numSources), "getClockSources"); } public void SetClockSource(int reference) { HandleException(asioDriverVTable.setClockSource(pAsioComObject, reference), "setClockSources"); } public void GetSamplePosition(out long samplePos, ref Asio64Bit timeStamp) { HandleException(asioDriverVTable.getSamplePosition(pAsioComObject, out samplePos, ref timeStamp), "getSamplePosition"); } public AsioChannelInfo GetChannelInfo(int channelNumber, bool trueForInputInfo) { AsioChannelInfo asioChannelInfo = default(AsioChannelInfo); asioChannelInfo.channel = channelNumber; asioChannelInfo.isInput = trueForInputInfo; AsioChannelInfo info = asioChannelInfo; HandleException(asioDriverVTable.getChannelInfo(pAsioComObject, ref info), "getChannelInfo"); return info; } public void CreateBuffers(IntPtr bufferInfos, int numChannels, int bufferSize, ref AsioCallbacks callbacks) { pinnedcallbacks = Marshal.AllocHGlobal(Marshal.SizeOf(callbacks)); Marshal.StructureToPtr(callbacks, pinnedcallbacks, fDeleteOld: false); HandleException(asioDriverVTable.createBuffers(pAsioComObject, bufferInfos, numChannels, bufferSize, pinnedcallbacks), "createBuffers"); } public AsioError DisposeBuffers() { AsioError result = asioDriverVTable.disposeBuffers(pAsioComObject); Marshal.FreeHGlobal(pinnedcallbacks); return result; } public void ControlPanel() { HandleException(asioDriverVTable.controlPanel(pAsioComObject), "controlPanel"); } public void Future(int selector, IntPtr opt) { HandleException(asioDriverVTable.future(pAsioComObject, selector, opt), "future"); } public AsioError OutputReady() { return asioDriverVTable.outputReady(pAsioComObject); } public void ReleaseComAsioDriver() { Marshal.Release(pAsioComObject); } private void HandleException(AsioError error, string methodName) { if (error != 0 && error != AsioError.ASE_SUCCESS) { throw new AsioException("Error code [" + AsioException.getErrorName(error) + "] while calling ASIO method <" + methodName + ">, " + GetErrorMessage()) { Error = error }; } } private void InitFromGuid(Guid asioGuid) { int num = CoCreateInstance(ref asioGuid, IntPtr.Zero, 1u, ref asioGuid, out pAsioComObject); if (num != 0) { throw new COMException("Unable to instantiate ASIO. Check if STAThread is set", num); } IntPtr ptr = Marshal.ReadIntPtr(pAsioComObject); asioDriverVTable = new AsioDriverVTable(); FieldInfo[] fields = typeof(AsioDriverVTable).GetFields(); for (int i = 0; i < fields.Length; i++) { FieldInfo fieldInfo = fields[i]; object delegateForFunctionPointer = Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(ptr, (i + 3) * IntPtr.Size), fieldInfo.FieldType); fieldInfo.SetValue(asioDriverVTable, delegateForFunctionPointer); } } [DllImport("ole32.Dll")] private static extern int CoCreateInstance(ref Guid clsid, IntPtr inner, uint context, ref Guid uuid, out IntPtr rReturnedComObject); } public class AsioDriverCapability { public string DriverName; public int NbInputChannels; public int NbOutputChannels; public int InputLatency; public int OutputLatency; public int BufferMinSize; public int BufferMaxSize; public int BufferPreferredSize; public int BufferGranularity; public double SampleRate; public AsioChannelInfo[] InputChannelInfos; public AsioChannelInfo[] OutputChannelInfos; } public delegate void AsioFillBufferCallback(IntPtr[] inputChannels, IntPtr[] outputChannels); public class AsioDriverExt { private readonly AsioDriver driver; private AsioCallbacks callbacks; private AsioDriverCapability capability; private AsioBufferInfo[] bufferInfos; private bool isOutputReadySupported; private IntPtr[] currentOutputBuffers; private IntPtr[] currentInputBuffers; private int numberOfOutputChannels; private int numberOfInputChannels; private AsioFillBufferCallback fillBufferCallback; private int bufferSize; private int outputChannelOffset; private int inputChannelOffset; public Action ResetRequestCallback; public AsioDriver Driver => driver; public AsioFillBufferCallback FillBufferCallback { get { return fillBufferCallback; } set { fillBufferCallback = value; } } public AsioDriverCapability Capabilities => capability; public AsioDriverExt(AsioDriver driver) { this.driver = driver; if (!driver.Init(IntPtr.Zero)) { throw new InvalidOperationException(driver.GetErrorMessage()); } callbacks = default(AsioCallbacks); callbacks.pasioMessage = AsioMessageCallBack; callbacks.pbufferSwitch = BufferSwitchCallBack; callbacks.pbufferSwitchTimeInfo = BufferSwitchTimeInfoCallBack; callbacks.psampleRateDidChange = SampleRateDidChangeCallBack; BuildCapabilities(); } public void SetChannelOffset(int outputChannelOffset, int inputChannelOffset) { if (outputChannelOffset + numberOfOutputChannels <= Capabilities.NbOutputChannels) { this.outputChannelOffset = outputChannelOffset; if (inputChannelOffset + numberOfInputChannels <= Capabilities.NbInputChannels) { this.inputChannelOffset = inputChannelOffset; return; } throw new ArgumentException("Invalid channel offset"); } throw new ArgumentException("Invalid channel offset"); } public void Start() { driver.Start(); } public void Stop() { driver.Stop(); } public void ShowControlPanel() { driver.ControlPanel(); } public void ReleaseDriver() { try { driver.DisposeBuffers(); } catch (Exception ex) { Console.Out.WriteLine(ex.ToString()); } driver.ReleaseComAsioDriver(); } public bool IsSampleRateSupported(double sampleRate) { return driver.CanSampleRate(sampleRate); } public void SetSampleRate(double sampleRate) { driver.SetSampleRate(sampleRate); BuildCapabilities(); } public unsafe int CreateBuffers(int numberOfOutputChannels, int numberOfInputChannels, bool useMaxBufferSize) { if (numberOfOutputChannels < 0 || numberOfOutputChannels > capability.NbOutputChannels) { throw new ArgumentException($"Invalid number of channels {numberOfOutputChannels}, must be in the range [0,{capability.NbOutputChannels}]"); } if (numberOfInputChannels < 0 || numberOfInputChannels > capability.NbInputChannels) { throw new ArgumentException("numberOfInputChannels", $"Invalid number of input channels {numberOfInputChannels}, must be in the range [0,{capability.NbInputChannels}]"); } this.numberOfOutputChannels = numberOfOutputChannels; this.numberOfInputChannels = numberOfInputChannels; int num = capability.NbInputChannels + capability.NbOutputChannels; bufferInfos = new AsioBufferInfo[num]; currentOutputBuffers = new IntPtr[numberOfOutputChannels]; currentInputBuffers = new IntPtr[numberOfInputChannels]; int num2 = 0; int num3 = 0; while (num3 < capability.NbInputChannels) { bufferInfos[num2].isInput = true; bufferInfos[num2].channelNum = num3; bufferInfos[num2].pBuffer0 = IntPtr.Zero; bufferInfos[num2].pBuffer1 = IntPtr.Zero; num3++; num2++; } int num4 = 0; while (num4 < capability.NbOutputChannels) { bufferInfos[num2].isInput = false; bufferInfos[num2].channelNum = num4; bufferInfos[num2].pBuffer0 = IntPtr.Zero; bufferInfos[num2].pBuffer1 = IntPtr.Zero; num4++; num2++; } if (useMaxBufferSize) { bufferSize = capability.BufferMaxSize; } else { bufferSize = capability.BufferPreferredSize; } fixed (AsioBufferInfo* value = &bufferInfos[0]) { IntPtr intPtr = new IntPtr(value); driver.CreateBuffers(intPtr, num, bufferSize, ref callbacks); } isOutputReadySupported = driver.OutputReady() == AsioError.ASE_OK; return bufferSize; } private void BuildCapabilities() { capability = new AsioDriverCapability(); capability.DriverName = driver.GetDriverName(); driver.GetChannels(out capability.NbInputChannels, out capability.NbOutputChannels); capability.InputChannelInfos = new AsioChannelInfo[capability.NbInputChannels]; capability.OutputChannelInfos = new AsioChannelInfo[capability.NbOutputChannels]; for (int i = 0; i < capability.NbInputChannels; i++) { capability.InputChannelInfos[i] = driver.GetChannelInfo(i, trueForInputInfo: true); } for (int j = 0; j < capability.NbOutputChannels; j++) { capability.OutputChannelInfos[j] = driver.GetChannelInfo(j, trueForInputInfo: false); } capability.SampleRate = driver.GetSampleRate(); AsioError latencies = driver.GetLatencies(out capability.InputLatency, out capability.OutputLatency); if (latencies != 0 && latencies != AsioError.ASE_NotPresent) { throw new AsioException("ASIOgetLatencies") { Error = latencies }; } driver.GetBufferSize(out capability.BufferMinSize, out capability.BufferMaxSize, out capability.BufferPreferredSize, out capability.BufferGranularity); } private void BufferSwitchCallBack(int doubleBufferIndex, bool directProcess) { for (int i = 0; i < numberOfInputChannels; i++) { currentInputBuffers[i] = bufferInfos[i + inputChannelOffset].Buffer(doubleBufferIndex); } for (int j = 0; j < numberOfOutputChannels; j++) { currentOutputBuffers[j] = bufferInfos[j + outputChannelOffset + capability.NbInputChannels].Buffer(doubleBufferIndex); } fillBufferCallback?.Invoke(currentInputBuffers, currentOutputBuffers); if (isOutputReadySupported) { driver.OutputReady(); } } private void SampleRateDidChangeCallBack(double sRate) { capability.SampleRate = sRate; } private int AsioMessageCallBack(AsioMessageSelector selector, int value, IntPtr message, IntPtr opt) { switch (selector) { case AsioMessageSelector.kAsioSelectorSupported: switch ((AsioMessageSelector)Enum.ToObject(typeof(AsioMessageSelector), value)) { case AsioMessageSelector.kAsioEngineVersion: return 1; case AsioMessageSelector.kAsioResetRequest: ResetRequestCallback?.Invoke(); return 0; case AsioMessageSelector.kAsioBufferSizeChange: return 0; case AsioMessageSelector.kAsioResyncRequest: return 0; case AsioMessageSelector.kAsioLatenciesChanged: return 0; case AsioMessageSelector.kAsioSupportsTimeInfo: return 0; case AsioMessageSelector.kAsioSupportsTimeCode: return 0; } break; case AsioMessageSelector.kAsioEngineVersion: return 2; case AsioMessageSelector.kAsioResetRequest: ResetRequestCallback?.Invoke(); return 1; case AsioMessageSelector.kAsioBufferSizeChange: return 0; case AsioMessageSelector.kAsioResyncRequest: return 0; case AsioMessageSelector.kAsioLatenciesChanged: return 0; case AsioMessageSelector.kAsioSupportsTimeInfo: return 0; case AsioMessageSelector.kAsioSupportsTimeCode: return 0; } return 0; } private IntPtr BufferSwitchTimeInfoCallBack(IntPtr asioTimeParam, int doubleBufferIndex, bool directProcess) { return IntPtr.Zero; } } public enum AsioError { ASE_OK = 0, ASE_SUCCESS = 1061701536, ASE_NotPresent = -1000, ASE_HWMalfunction = -999, ASE_InvalidParameter = -998, ASE_InvalidMode = -997, ASE_SPNotAdvancing = -996, ASE_NoClock = -995, ASE_NoMemory = -994 } public enum AsioMessageSelector { kAsioSelectorSupported = 1, kAsioEngineVersion, kAsioResetRequest, kAsioBufferSizeChange, kAsioResyncRequest, kAsioLatenciesChanged, kAsioSupportsTimeInfo, kAsioSupportsTimeCode, kAsioMMCCommand, kAsioSupportsInputMonitor, kAsioSupportsInputGain, kAsioSupportsInputMeter, kAsioSupportsOutputGain, kAsioSupportsOutputMeter, kAsioOverload } internal class AsioSampleConvertor { public delegate void SampleConvertor(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples); public static SampleConvertor SelectSampleConvertor(WaveFormat waveFormat, AsioSampleType asioType) { //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Invalid comparison between Unknown and I4 //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Invalid comparison between Unknown and I4 //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Invalid comparison between Unknown and I4 //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Invalid comparison between Unknown and I4 SampleConvertor result = null; bool flag = waveFormat.Channels == 2; switch (asioType) { case AsioSampleType.Int32LSB: switch (waveFormat.BitsPerSample) { case 16: result = (flag ? new SampleConvertor(ConvertorShortToInt2Channels) : new SampleConvertor(ConvertorShortToIntGeneric)); break; case 32: result = (((int)waveFormat.Encoding != 3) ? (flag ? new SampleConvertor(ConvertorIntToInt2Channels) : new SampleConvertor(ConvertorIntToIntGeneric)) : (flag ? new SampleConvertor(ConvertorFloatToInt2Channels) : new SampleConvertor(ConvertorFloatToIntGeneric))); break; } break; case AsioSampleType.Int16LSB: switch (waveFormat.BitsPerSample) { case 16: result = (flag ? new SampleConvertor(ConvertorShortToShort2Channels) : new SampleConvertor(ConvertorShortToShortGeneric)); break; case 32: result = (((int)waveFormat.Encoding != 3) ? (flag ? new SampleConvertor(ConvertorIntToShort2Channels) : new SampleConvertor(ConvertorIntToShortGeneric)) : (flag ? new SampleConvertor(ConvertorFloatToShort2Channels) : new SampleConvertor(ConvertorFloatToShortGeneric))); break; } break; case AsioSampleType.Int24LSB: switch (waveFormat.BitsPerSample) { case 16: throw new ArgumentException("Not a supported conversion"); case 32: if ((int)waveFormat.Encoding == 3) { result = ConverterFloatTo24LSBGeneric; break; } throw new ArgumentException("Not a supported conversion"); } break; case AsioSampleType.Float32LSB: switch (waveFormat.BitsPerSample) { case 16: throw new ArgumentException("Not a supported conversion"); case 32: result = (((int)waveFormat.Encoding != 3) ? new SampleConvertor(ConvertorIntToFloatGeneric) : new SampleConvertor(ConverterFloatToFloatGeneric)); break; } break; default: throw new ArgumentException($"ASIO Buffer Type {Enum.GetName(typeof(AsioSampleType), asioType)} is not yet supported."); } return result; } public unsafe static void ConvertorShortToInt2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { short* ptr = (short*)(void*)inputInterleavedBuffer; short* ptr2 = (short*)(void*)asioOutputBuffers[0]; short* ptr3 = (short*)(void*)asioOutputBuffers[1]; ptr2++; ptr3++; for (int i = 0; i < nbSamples; i++) { *ptr2 = *ptr; *ptr3 = ptr[1]; ptr += 2; ptr2 += 2; ptr3 += 2; } } public unsafe static void ConvertorShortToIntGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { short* ptr = (short*)(void*)inputInterleavedBuffer; short*[] array = new short*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (short*)(void*)asioOutputBuffers[i]; int num = i; short* ptr2 = array[num]; array[num] = ptr2 + 1; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { *array[k] = *(ptr++); short*[] array2 = array; int num = k; array2[num] += 2; } } } public unsafe static void ConvertorFloatToInt2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { float* ptr = (float*)(void*)inputInterleavedBuffer; int* ptr2 = (int*)(void*)asioOutputBuffers[0]; int* ptr3 = (int*)(void*)asioOutputBuffers[1]; for (int i = 0; i < nbSamples; i++) { *(ptr2++) = clampToInt(*ptr); *(ptr3++) = clampToInt(ptr[1]); ptr += 2; } } public unsafe static void ConvertorFloatToIntGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { float* ptr = (float*)(void*)inputInterleavedBuffer; int*[] array = new int*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (int*)(void*)asioOutputBuffers[i]; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { int num = k; int* ptr2 = array[num]; array[num] = ptr2 + 1; *ptr2 = clampToInt(*(ptr++)); } } } public unsafe static void ConvertorIntToInt2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { int* ptr = (int*)(void*)inputInterleavedBuffer; int* ptr2 = (int*)(void*)asioOutputBuffers[0]; int* ptr3 = (int*)(void*)asioOutputBuffers[1]; for (int i = 0; i < nbSamples; i++) { *(ptr2++) = *ptr; *(ptr3++) = ptr[1]; ptr += 2; } } public unsafe static void ConvertorIntToIntGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { int* ptr = (int*)(void*)inputInterleavedBuffer; int*[] array = new int*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (int*)(void*)asioOutputBuffers[i]; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { int num = k; int* ptr2 = array[num]; array[num] = ptr2 + 1; *ptr2 = *(ptr++); } } } public unsafe static void ConvertorIntToShort2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { int* ptr = (int*)(void*)inputInterleavedBuffer; short* ptr2 = (short*)(void*)asioOutputBuffers[0]; short* ptr3 = (short*)(void*)asioOutputBuffers[1]; for (int i = 0; i < nbSamples; i++) { *(ptr2++) = (short)(*ptr / 65536); *(ptr3++) = (short)(ptr[1] / 65536); ptr += 2; } } public unsafe static void ConvertorIntToShortGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { int* ptr = (int*)(void*)inputInterleavedBuffer; int*[] array = new int*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (int*)(void*)asioOutputBuffers[i]; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { int num = k; int* ptr2 = array[num]; array[num] = ptr2 + 1; *ptr2 = (short)(*(ptr++) / 65536); } } } public unsafe static void ConvertorIntToFloatGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { int* ptr = (int*)(void*)inputInterleavedBuffer; float*[] array = new float*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (float*)(void*)asioOutputBuffers[i]; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { int num = k; float* ptr2 = array[num]; array[num] = ptr2 + 1; *ptr2 = *(ptr++) / int.MinValue; } } } public unsafe static void ConvertorShortToShort2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { short* ptr = (short*)(void*)inputInterleavedBuffer; short* ptr2 = (short*)(void*)asioOutputBuffers[0]; short* ptr3 = (short*)(void*)asioOutputBuffers[1]; for (int i = 0; i < nbSamples; i++) { *(ptr2++) = *ptr; *(ptr3++) = ptr[1]; ptr += 2; } } public unsafe static void ConvertorShortToShortGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { short* ptr = (short*)(void*)inputInterleavedBuffer; short*[] array = new short*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (short*)(void*)asioOutputBuffers[i]; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { int num = k; short* ptr2 = array[num]; array[num] = ptr2 + 1; *ptr2 = *(ptr++); } } } public unsafe static void ConvertorFloatToShort2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { float* ptr = (float*)(void*)inputInterleavedBuffer; short* ptr2 = (short*)(void*)asioOutputBuffers[0]; short* ptr3 = (short*)(void*)asioOutputBuffers[1]; for (int i = 0; i < nbSamples; i++) { *(ptr2++) = clampToShort(*ptr); *(ptr3++) = clampToShort(ptr[1]); ptr += 2; } } public unsafe static void ConvertorFloatToShortGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { float* ptr = (float*)(void*)inputInterleavedBuffer; short*[] array = new short*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (short*)(void*)asioOutputBuffers[i]; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { int num = k; short* ptr2 = array[num]; array[num] = ptr2 + 1; *ptr2 = clampToShort(*(ptr++)); } } } public unsafe static void ConverterFloatTo24LSBGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { float* ptr = (float*)(void*)inputInterleavedBuffer; byte*[] array = new byte*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (byte*)(void*)asioOutputBuffers[i]; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { int num = clampTo24Bit(*(ptr++)); int num2 = k; *(array[num2]++) = (byte)num; num2 = k; *(array[num2]++) = (byte)(num >> 8); num2 = k; *(array[num2]++) = (byte)(num >> 16); } } } public unsafe static void ConverterFloatToFloatGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples) { float* ptr = (float*)(void*)inputInterleavedBuffer; float*[] array = new float*[nbChannels]; for (int i = 0; i < nbChannels; i++) { array[i] = (float*)(void*)asioOutputBuffers[i]; } for (int j = 0; j < nbSamples; j++) { for (int k = 0; k < nbChannels; k++) { int num = k; float* ptr2 = array[num]; array[num] = ptr2 + 1; *ptr2 = *(ptr++); } } } private static int clampTo24Bit(double sampleValue) { sampleValue = ((sampleValue < -1.0) ? (-1.0) : ((sampleValue > 1.0) ? 1.0 : sampleValue)); return (int)(sampleValue * 8388607.0); } private static int clampToInt(double sampleValue) { sampleValue = ((sampleValue < -1.0) ? (-1.0) : ((sampleValue > 1.0) ? 1.0 : sampleValue)); return (int)(sampleValue * 2147483647.0); } private static short clampToShort(double sampleValue) { sampleValue = ((sampleValue < -1.0) ? (-1.0) : ((sampleValue > 1.0) ? 1.0 : sampleValue)); return (short)(sampleValue * 32767.0); } } public enum AsioSampleType { Int16MSB = 0, Int24MSB = 1, Int32MSB = 2, Float32MSB = 3, Float64MSB = 4, Int32MSB16 = 8, Int32MSB18 = 9, Int32MSB20 = 10, Int32MSB24 = 11, Int16LSB = 16, Int24LSB = 17, Int32LSB = 18, Float32LSB = 19, Float64LSB = 20, Int32LSB16 = 24, Int32LSB18 = 25, Int32LSB20 = 26, Int32LSB24 = 27, DSDInt8LSB1 = 32, DSDInt8MSB1 = 33, DSDInt8NER8 = 40 } internal class AsioException : Exception { private AsioError error; public AsioError Error { get { return error; } set { error = value; Data["ASIOError"] = error; } } public AsioException() { } public AsioException(string message) : base(message) { } public AsioException(string message, Exception innerException) : base(message, innerException) { } public static string getErrorName(AsioError error) { return Enum.GetName(typeof(AsioError), error); } } [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct AsioBufferInfo { public bool isInput; public int channelNum; public IntPtr pBuffer0; public IntPtr pBuffer1; public IntPtr Buffer(int bufferIndex) { if (bufferIndex != 0) { return pBuffer1; } return pBuffer0; } } [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct AsioTimeCode { public double speed; public Asio64Bit timeCodeSamples; public AsioTimeCodeFlags flags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string future; } [Flags] internal enum AsioTimeCodeFlags { kTcValid = 1, kTcRunning = 2, kTcReverse = 4, kTcOnspeed = 8, kTcStill = 0x10, kTcSpeedValid = 0x100 } [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct AsioTimeInfo { public double speed; public Asio64Bit systemTime; public Asio64Bit samplePosition; public double sampleRate; public AsioTimeInfoFlags flags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)] public string reserved; } [Flags] internal enum AsioTimeInfoFlags { kSystemTimeValid = 1, kSamplePositionValid = 2, kSampleRateValid = 4, kSpeedValid = 8, kSampleRateChanged = 0x10, kClockSourceChanged = 0x20 } [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct AsioTime { public int reserved1; public int reserved2; public int reserved3; public int reserved4; public AsioTimeInfo timeInfo; public AsioTimeCode timeCode; } }
deps/NAudio.Core.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using NAudio.Dmo; using NAudio.Dsp; using NAudio.FileFormats.Wav; using NAudio.Utils; using NAudio.Wave; using NAudio.Wave.SampleProviders; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Mark Heath")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Mark Heath 2023")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("NAudio.Core")] [assembly: AssemblyTitle("NAudio.Core")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.2.1.0")] [module: UnverifiableCode] namespace NAudio { public enum Manufacturers { Microsoft = 1, Creative = 2, Mediavision = 3, Fujitsu = 4, Artisoft = 20, TurtleBeach = 21, Ibm = 22, Vocaltec = 23, Roland = 24, DspSolutions = 25, Nec = 26, Ati = 27, Wanglabs = 28, Tandy = 29, Voyetra = 30, Antex = 31, IclPS = 32, Intel = 33, Gravis = 34, Val = 35, Interactive = 36, Yamaha = 37, Everex = 38, Echo = 39, Sierra = 40, Cat = 41, Apps = 42, DspGroup = 43, Melabs = 44, ComputerFriends = 45, Ess = 46, Audiofile = 47, Motorola = 48, Canopus = 49, Epson = 50, Truevision = 51, Aztech = 52, Videologic = 53, Scalacs = 54, Korg = 55, Apt = 56, Ics = 57, Iteratedsys = 58, Metheus = 59, Logitech = 60, Winnov = 61, Ncr = 62, Exan = 63, Ast = 64, Willowpond = 65, Sonicfoundry = 66, Vitec = 67, Moscom = 68, Siliconsoft = 69, Supermac = 73, Audiopt = 74, Speechcomp = 76, Ahead = 77, Dolby = 78, Oki = 79, Auravision = 80, Olivetti = 81, Iomagic = 82, Matsushita = 83, Controlres = 84, Xebec = 85, Newmedia = 86, Nms = 87, Lyrrus = 88, Compusic = 89, Opti = 90, Adlacc = 91, Compaq = 92, Dialogic = 93, Insoft = 94, Mptus = 95, Weitek = 96, LernoutAndHauspie = 97, Qciar = 98, Apple = 99, Digital = 100, Motu = 101, Workbit = 102, Ositech = 103, Miro = 104, Cirruslogic = 105, Isolution = 106, Horizons = 107, Concepts = 108, Vtg = 109, Radius = 110, Rockwell = 111, Xyz = 112, Opcode = 113, Voxware = 114, NorthernTelecom = 115, Apicom = 116, Grande = 117, Addx = 118, Wildcat = 119, Rhetorex = 120, Brooktree = 121, Ensoniq = 125, Fast = 126, Nvidia = 127, Oksori = 128, Diacoustics = 129, Gulbransen = 130, KayElemetrics = 131, Crystal = 132, SplashStudios = 133, Quarterdeck = 134, Tdk = 135, DigitalAudioLabs = 136, Seersys = 137, Picturetel = 138, AttMicroelectronics = 139, Osprey = 140, Mediatrix = 141, Soundesigns = 142, Aldigital = 143, SpectrumSignalProcessing = 144, Ecs = 145, Amd = 146, Coredynamics = 147, Canam = 148, Softsound = 149, Norris = 150, Ddd = 151, Euphonics = 152, Precept = 153, CrystalNet = 154, Chromatic = 155, Voiceinfo = 156, Viennasys = 157, Connectix = 158, Gadgetlabs = 159, Frontier = 160, Viona = 161, Casio = 162, Diamondmm = 163, S3 = 164, FraunhoferIis = 172 } public class MmException : Exception { public MmResult Result { get; } public string Function { get; } public MmException(MmResult result, string function) : base(ErrorMessage(result, function)) { Result = result; Function = function; } private static string ErrorMessage(MmResult result, string function) { return $"{result} calling {function}"; } public static void Try(MmResult result, string function) { if (result != 0) { throw new MmException(result, function); } } } public enum MmResult { NoError = 0, UnspecifiedError = 1, BadDeviceId = 2, NotEnabled = 3, AlreadyAllocated = 4, InvalidHandle = 5, NoDriver = 6, MemoryAllocationError = 7, NotSupported = 8, BadErrorNumber = 9, InvalidFlag = 10, InvalidParameter = 11, HandleBusy = 12, InvalidAlias = 13, BadRegistryDatabase = 14, RegistryKeyNotFound = 15, RegistryReadError = 16, RegistryWriteError = 17, RegistryDeleteError = 18, RegistryValueNotFound = 19, NoDriverCallback = 20, MoreData = 21, WaveBadFormat = 32, WaveStillPlaying = 33, WaveHeaderUnprepared = 34, WaveSync = 35, AcmNotPossible = 512, AcmBusy = 513, AcmHeaderUnprepared = 514, AcmCancelled = 515, MixerInvalidLine = 1024, MixerInvalidControl = 1025, MixerInvalidValue = 1026 } } namespace NAudio.CoreAudioApi { public enum CaptureState { Stopped, Starting, Capturing, Stopping } } namespace NAudio.Dmo { public class AudioMediaSubtypes { public static readonly Guid MEDIASUBTYPE_PCM = new Guid("00000001-0000-0010-8000-00AA00389B71"); public static readonly Guid MEDIASUBTYPE_PCMAudioObsolete = new Guid("e436eb8a-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_MPEG1Packet = new Guid("e436eb80-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_MPEG1Payload = new Guid("e436eb81-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_MPEG2_AUDIO = new Guid("e06d802b-db46-11cf-b4d1-00805f6cbbea"); public static readonly Guid MEDIASUBTYPE_DVD_LPCM_AUDIO = new Guid("e06d8032-db46-11cf-b4d1-00805f6cbbea"); public static readonly Guid MEDIASUBTYPE_DRM_Audio = new Guid("00000009-0000-0010-8000-00aa00389b71"); public static readonly Guid MEDIASUBTYPE_IEEE_FLOAT = new Guid("00000003-0000-0010-8000-00aa00389b71"); public static readonly Guid MEDIASUBTYPE_DOLBY_AC3 = new Guid("e06d802c-db46-11cf-b4d1-00805f6cbbea"); public static readonly Guid MEDIASUBTYPE_DOLBY_AC3_SPDIF = new Guid("00000092-0000-0010-8000-00aa00389b71"); public static readonly Guid MEDIASUBTYPE_RAW_SPORT = new Guid("00000240-0000-0010-8000-00aa00389b71"); public static readonly Guid MEDIASUBTYPE_SPDIF_TAG_241h = new Guid("00000241-0000-0010-8000-00aa00389b71"); public static readonly Guid MEDIASUBTYPE_I420 = new Guid("30323449-0000-0010-8000-00AA00389B71"); public static readonly Guid MEDIASUBTYPE_IYUV = new Guid("56555949-0000-0010-8000-00AA00389B71"); public static readonly Guid MEDIASUBTYPE_RGB1 = new Guid("e436eb78-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_RGB24 = new Guid("e436eb7d-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_RGB32 = new Guid("e436eb7e-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_RGB4 = new Guid("e436eb79-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_RGB555 = new Guid("e436eb7c-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_RGB565 = new Guid("e436eb7b-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_RGB8 = new Guid("e436eb7a-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_UYVY = new Guid("59565955-0000-0010-8000-00AA00389B71"); public static readonly Guid MEDIASUBTYPE_VIDEOIMAGE = new Guid("1d4a45f2-e5f6-4b44-8388-f0ae5c0e0c37"); public static readonly Guid MEDIASUBTYPE_YUY2 = new Guid("32595559-0000-0010-8000-00AA00389B71"); public static readonly Guid MEDIASUBTYPE_YV12 = new Guid("31313259-0000-0010-8000-00AA00389B71"); public static readonly Guid MEDIASUBTYPE_YVU9 = new Guid("39555659-0000-0010-8000-00AA00389B71"); public static readonly Guid MEDIASUBTYPE_YVYU = new Guid("55595659-0000-0010-8000-00AA00389B71"); public static readonly Guid WMFORMAT_MPEG2Video = new Guid("e06d80e3-db46-11cf-b4d1-00805f6cbbea"); public static readonly Guid WMFORMAT_Script = new Guid("5C8510F2-DEBE-4ca7-BBA5-F07A104F8DFF"); public static readonly Guid WMFORMAT_VideoInfo = new Guid("05589f80-c356-11ce-bf01-00aa0055595a"); public static readonly Guid WMFORMAT_WaveFormatEx = new Guid("05589f81-c356-11ce-bf01-00aa0055595a"); public static readonly Guid WMFORMAT_WebStream = new Guid("da1e6b13-8359-4050-b398-388e965bf00c"); public static readonly Guid WMMEDIASUBTYPE_ACELPnet = new Guid("00000130-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_Base = new Guid("00000000-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_DRM = new Guid("00000009-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_MP3 = new Guid("00000055-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_MP43 = new Guid("3334504D-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_MP4S = new Guid("5334504D-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_M4S2 = new Guid("3253344D-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_P422 = new Guid("32323450-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_MPEG2_VIDEO = new Guid("e06d8026-db46-11cf-b4d1-00805f6cbbea"); public static readonly Guid WMMEDIASUBTYPE_MSS1 = new Guid("3153534D-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_MSS2 = new Guid("3253534D-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_PCM = new Guid("00000001-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WebStream = new Guid("776257d4-c627-41cb-8f81-7ac7ff1c40cc"); public static readonly Guid WMMEDIASUBTYPE_WMAudio_Lossless = new Guid("00000163-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMAudioV2 = new Guid("00000161-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMAudioV7 = new Guid("00000161-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMAudioV8 = new Guid("00000161-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMAudioV9 = new Guid("00000162-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMSP1 = new Guid("0000000A-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMV1 = new Guid("31564D57-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMV2 = new Guid("32564D57-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMV3 = new Guid("33564D57-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMVA = new Guid("41564D57-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WMVP = new Guid("50564D57-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIASUBTYPE_WVP2 = new Guid("32505657-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIATYPE_Audio = new Guid("73647561-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIATYPE_FileTransfer = new Guid("D9E47579-930E-4427-ADFC-AD80F290E470"); public static readonly Guid WMMEDIATYPE_Image = new Guid("34A50FD8-8AA5-4386-81FE-A0EFE0488E31"); public static readonly Guid WMMEDIATYPE_Script = new Guid("73636d64-0000-0010-8000-00AA00389B71"); public static readonly Guid WMMEDIATYPE_Text = new Guid("9BBA1EA7-5AB2-4829-BA57-0940209BCF3E"); public static readonly Guid WMMEDIATYPE_Video = new Guid("73646976-0000-0010-8000-00AA00389B71"); public static readonly Guid WMSCRIPTTYPE_TwoStrings = new Guid("82f38a70-c29f-11d1-97ad-00a0c95ea850"); public static readonly Guid MEDIASUBTYPE_WAVE = new Guid("e436eb8b-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_AU = new Guid("e436eb8c-524f-11ce-9f53-0020af0ba770"); public static readonly Guid MEDIASUBTYPE_AIFF = new Guid("e436eb8d-524f-11ce-9f53-0020af0ba770"); public static readonly Guid[] AudioSubTypes = new Guid[13] { MEDIASUBTYPE_PCM, MEDIASUBTYPE_PCMAudioObsolete, MEDIASUBTYPE_MPEG1Packet, MEDIASUBTYPE_MPEG1Payload, MEDIASUBTYPE_MPEG2_AUDIO, MEDIASUBTYPE_DVD_LPCM_AUDIO, MEDIASUBTYPE_DRM_Audio, MEDIASUBTYPE_IEEE_FLOAT, MEDIASUBTYPE_DOLBY_AC3, MEDIASUBTYPE_DOLBY_AC3_SPDIF, MEDIASUBTYPE_RAW_SPORT, MEDIASUBTYPE_SPDIF_TAG_241h, WMMEDIASUBTYPE_MP3 }; public static readonly string[] AudioSubTypeNames = new string[13] { "PCM", "PCM Obsolete", "MPEG1Packet", "MPEG1Payload", "MPEG2_AUDIO", "DVD_LPCM_AUDIO", "DRM_Audio", "IEEE_FLOAT", "DOLBY_AC3", "DOLBY_AC3_SPDIF", "RAW_SPORT", "SPDIF_TAG_241h", "MP3" }; public static string GetAudioSubtypeName(Guid subType) { for (int i = 0; i < AudioSubTypes.Length; i++) { if (subType == AudioSubTypes[i]) { return AudioSubTypeNames[i]; } } return subType.ToString(); } } } namespace NAudio.Utils { public static class BufferHelpers { public static byte[] Ensure(byte[] buffer, int bytesRequired) { if (buffer == null || buffer.Length < bytesRequired) { buffer = new byte[bytesRequired]; } return buffer; } public static float[] Ensure(float[] buffer, int samplesRequired) { if (buffer == null || buffer.Length < samplesRequired) { buffer = new float[samplesRequired]; } return buffer; } } public static class ByteArrayExtensions { public static bool IsEntirelyNull(byte[] buffer) { for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != 0) { return false; } } return true; } public static string DescribeAsHex(byte[] buffer, string separator, int bytesPerLine) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; foreach (byte b in buffer) { stringBuilder.AppendFormat("{0:X2}{1}", b, separator); if (++num % bytesPerLine == 0) { stringBuilder.Append("\r\n"); } } stringBuilder.Append("\r\n"); return stringBuilder.ToString(); } public static string DecodeAsString(byte[] buffer, int offset, int length, Encoding encoding) { for (int i = 0; i < length; i++) { if (buffer[offset + i] == 0) { length = i; } } return encoding.GetString(buffer, offset, length); } public static byte[] Concat(params byte[][] byteArrays) { int num = 0; byte[][] array = byteArrays; foreach (byte[] array2 in array) { num += array2.Length; } if (num <= 0) { return new byte[0]; } byte[] array3 = new byte[num]; int num2 = 0; array = byteArrays; foreach (byte[] array4 in array) { Array.Copy(array4, 0, array3, num2, array4.Length); num2 += array4.Length; } return array3; } } public class ByteEncoding : Encoding { public static readonly ByteEncoding Instance = new ByteEncoding(); private ByteEncoding() { } public override int GetByteCount(char[] chars, int index, int count) { return count; } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { for (int i = 0; i < charCount; i++) { bytes[byteIndex + i] = (byte)chars[charIndex + i]; } return charCount; } public override int GetCharCount(byte[] bytes, int index, int count) { for (int i = 0; i < count; i++) { if (bytes[index + i] == 0) { return i; } } return count; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { for (int i = 0; i < byteCount; i++) { byte b = bytes[byteIndex + i]; if (b == 0) { return i; } chars[charIndex + i] = (char)b; } return byteCount; } public override int GetMaxCharCount(int byteCount) { return byteCount; } public override int GetMaxByteCount(int charCount) { return charCount; } } public class ChunkIdentifier { public static int ChunkIdentifierToInt32(string s) { if (s.Length != 4) { throw new ArgumentException("Must be a four character string"); } byte[] bytes = Encoding.UTF8.GetBytes(s); if (bytes.Length != 4) { throw new ArgumentException("Must encode to exactly four bytes"); } return BitConverter.ToInt32(bytes, 0); } } public class CircularBuffer { private readonly byte[] buffer; private readonly object lockObject; private int writePosition; private int readPosition; private int byteCount; public int MaxLength => buffer.Length; public int Count { get { lock (lockObject) { return byteCount; } } } public CircularBuffer(int size) { buffer = new byte[size]; lockObject = new object(); } public int Write(byte[] data, int offset, int count) { lock (lockObject) { int num = 0; if (count > buffer.Length - byteCount) { count = buffer.Length - byteCount; } int num2 = Math.Min(buffer.Length - writePosition, count); Array.Copy(data, offset, buffer, writePosition, num2); writePosition += num2; writePosition %= buffer.Length; num += num2; if (num < count) { Array.Copy(data, offset + num, buffer, writePosition, count - num); writePosition += count - num; num = count; } byteCount += num; return num; } } public int Read(byte[] data, int offset, int count) { lock (lockObject) { if (count > byteCount) { count = byteCount; } int num = 0; int num2 = Math.Min(buffer.Length - readPosition, count); Array.Copy(buffer, readPosition, data, offset, num2); num += num2; readPosition += num2; readPosition %= buffer.Length; if (num < count) { Array.Copy(buffer, readPosition, data, offset + num, count - num); readPosition += count - num; num = count; } byteCount -= num; return num; } } public void Reset() { lock (lockObject) { ResetInner(); } } private void ResetInner() { byteCount = 0; readPosition = 0; writePosition = 0; } public void Advance(int count) { lock (lockObject) { if (count >= byteCount) { ResetInner(); return; } byteCount -= count; readPosition += count; readPosition %= MaxLength; } } } public class Decibels { private const double LOG_2_DB = 8.685889638065037; private const double DB_2_LOG = 0.11512925464970228; public static double LinearToDecibels(double lin) { return Math.Log(lin) * 8.685889638065037; } public static double DecibelsToLinear(double dB) { return Math.Exp(dB * 0.11512925464970228); } } [AttributeUsage(AttributeTargets.Field)] public class FieldDescriptionAttribute : Attribute { public string Description { get; } public FieldDescriptionAttribute(string description) { Description = description; } public override string ToString() { return Description; } } public static class FieldDescriptionHelper { public static string Describe(Type t, Guid guid) { FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { if (!fieldInfo.IsPublic || !fieldInfo.IsStatic || !(fieldInfo.FieldType == typeof(Guid)) || !((Guid)fieldInfo.GetValue(null) == guid)) { continue; } object[] customAttributes = fieldInfo.GetCustomAttributes(inherit: false); for (int j = 0; j < customAttributes.Length; j++) { if (customAttributes[j] is FieldDescriptionAttribute fieldDescriptionAttribute) { return fieldDescriptionAttribute.Description; } } return fieldInfo.Name; } return guid.ToString(); } } public static class HResult { public const int S_OK = 0; public const int S_FALSE = 1; public const int E_INVALIDARG = -2147483645; private const int FACILITY_AAF = 18; private const int FACILITY_ACS = 20; private const int FACILITY_BACKGROUNDCOPY = 32; private const int FACILITY_CERT = 11; private const int FACILITY_COMPLUS = 17; private const int FACILITY_CONFIGURATION = 33; private const int FACILITY_CONTROL = 10; private const int FACILITY_DISPATCH = 2; private const int FACILITY_DPLAY = 21; private const int FACILITY_HTTP = 25; private const int FACILITY_INTERNET = 12; private const int FACILITY_ITF = 4; private const int FACILITY_MEDIASERVER = 13; private const int FACILITY_MSMQ = 14; private const int FACILITY_NULL = 0; private const int FACILITY_RPC = 1; private const int FACILITY_SCARD = 16; private const int FACILITY_SECURITY = 9; private const int FACILITY_SETUPAPI = 15; private const int FACILITY_SSPI = 9; private const int FACILITY_STORAGE = 3; private const int FACILITY_SXS = 23; private const int FACILITY_UMI = 22; private const int FACILITY_URT = 19; private const int FACILITY_WIN32 = 7; private const int FACILITY_WINDOWS = 8; private const int FACILITY_WINDOWS_CE = 24; public static int MAKE_HRESULT(int sev, int fac, int code) { return (sev << 31) | (fac << 16) | code; } public static int GetHResult(this COMException exception) { return exception.ErrorCode; } } public static class IEEE { private static double UnsignedToFloat(ulong u) { return (double)(long)(u - int.MaxValue - 1) + 2147483648.0; } private static double ldexp(double x, int exp) { return x * Math.Pow(2.0, exp); } private static double frexp(double x, out int exp) { exp = (int)Math.Floor(Math.Log(x) / Math.Log(2.0)) + 1; return 1.0 - (Math.Pow(2.0, exp) - x) / Math.Pow(2.0, exp); } private static ulong FloatToUnsigned(double f) { return (ulong)((long)(f - 2147483648.0) + int.MaxValue + 1); } public static byte[] ConvertToIeeeExtended(double num) { int num2; if (num < 0.0) { num2 = 32768; num *= -1.0; } else { num2 = 0; } ulong num4; ulong num5; int num3; if (num == 0.0) { num3 = 0; num4 = 0uL; num5 = 0uL; } else { double num6 = frexp(num, out num3); if (num3 > 16384 || !(num6 < 1.0)) { num3 = num2 | 0x7FFF; num4 = 0uL; num5 = 0uL; } else { num3 += 16382; if (num3 < 0) { num6 = ldexp(num6, num3); num3 = 0; } num3 |= num2; num6 = ldexp(num6, 32); double num7 = Math.Floor(num6); num4 = FloatToUnsigned(num7); num6 = ldexp(num6 - num7, 32); num7 = Math.Floor(num6); num5 = FloatToUnsigned(num7); } } return new byte[10] { (byte)(num3 >> 8), (byte)num3, (byte)(num4 >> 24), (byte)(num4 >> 16), (byte)(num4 >> 8), (byte)num4, (byte)(num5 >> 24), (byte)(num5 >> 16), (byte)(num5 >> 8), (byte)num5 }; } public static double ConvertFromIeeeExtended(byte[] bytes) { if (bytes.Length != 10) { throw new Exception("Incorrect length for IEEE extended."); } int num = ((bytes[0] & 0x7F) << 8) | bytes[1]; uint num2 = (uint)((bytes[2] << 24) | (bytes[3] << 16) | (bytes[4] << 8) | bytes[5]); uint num3 = (uint)((bytes[6] << 24) | (bytes[7] << 16) | (bytes[8] << 8) | bytes[9]); double num4; if (num == 0 && num2 == 0 && num3 == 0) { num4 = 0.0; } else if (num == 32767) { num4 = double.NaN; } else { num -= 16383; num4 = ldexp(UnsignedToFloat(num2), num -= 31); num4 += ldexp(UnsignedToFloat(num3), num -= 32); } if ((bytes[0] & 0x80) == 128) { return 0.0 - num4; } return num4; } } public class IgnoreDisposeStream : Stream { public Stream SourceStream { get; private set; } public bool IgnoreDispose { get; set; } public override bool CanRead => SourceStream.CanRead; public override bool CanSeek => SourceStream.CanSeek; public override bool CanWrite => SourceStream.CanWrite; public override long Length => SourceStream.Length; public override long Position { get { return SourceStream.Position; } set { SourceStream.Position = value; } } public IgnoreDisposeStream(Stream sourceStream) { SourceStream = sourceStream; IgnoreDispose = true; } public override void Flush() { SourceStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { return SourceStream.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return SourceStream.Seek(offset, origin); } public override void SetLength(long value) { SourceStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { SourceStream.Write(buffer, offset, count); } protected override void Dispose(bool disposing) { if (!IgnoreDispose) { SourceStream.Dispose(); SourceStream = null; } } } public static class NativeMethods { [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); [DllImport("kernel32.dll")] public static extern bool FreeLibrary(IntPtr hModule); } public static class WavePositionExtensions { public static TimeSpan GetPositionTimeSpan(this IWavePosition @this) { return TimeSpan.FromMilliseconds((double)(@this.GetPosition() / (@this.OutputWaveFormat.Channels * @this.OutputWaveFormat.BitsPerSample / 8)) * 1000.0 / (double)@this.OutputWaveFormat.SampleRate); } } } namespace NAudio.FileFormats.Wav { public class WaveFileChunkReader { private WaveFormat waveFormat; private long dataChunkPosition; private long dataChunkLength; private List<RiffChunk> riffChunks; private readonly bool strictMode; private bool isRf64; private readonly bool storeAllChunks; private long riffSize; public WaveFormat WaveFormat => waveFormat; public long DataChunkPosition => dataChunkPosition; public long DataChunkLength => dataChunkLength; public List<RiffChunk> RiffChunks => riffChunks; public WaveFileChunkReader() { storeAllChunks = true; strictMode = false; } public void ReadWaveHeader(Stream stream) { dataChunkPosition = -1L; waveFormat = null; riffChunks = new List<RiffChunk>(); dataChunkLength = 0L; BinaryReader binaryReader = new BinaryReader(stream); ReadRiffHeader(binaryReader); riffSize = binaryReader.ReadUInt32(); if (binaryReader.ReadInt32() != ChunkIdentifier.ChunkIdentifierToInt32("WAVE")) { throw new FormatException("Not a WAVE file - no WAVE header"); } if (isRf64) { ReadDs64Chunk(binaryReader); } int num = ChunkIdentifier.ChunkIdentifierToInt32("data"); int num2 = ChunkIdentifier.ChunkIdentifierToInt32("fmt "); long num3 = Math.Min(riffSize + 8, stream.Length); while (stream.Position <= num3 - 8) { int num4 = binaryReader.ReadInt32(); uint num5 = binaryReader.ReadUInt32(); if (num4 == num) { dataChunkPosition = stream.Position; if (!isRf64) { dataChunkLength = num5; } stream.Position += num5; } else if (num4 == num2) { if (num5 > int.MaxValue) { throw new InvalidDataException($"Format chunk length must be between 0 and {int.MaxValue}."); } waveFormat = WaveFormat.FromFormatChunk(binaryReader, (int)num5); } else { if (num5 > stream.Length - stream.Position) { if (!strictMode) { } break; } if (storeAllChunks) { if (num5 > int.MaxValue) { throw new InvalidDataException($"RiffChunk chunk length must be between 0 and {int.MaxValue}."); } riffChunks.Add(GetRiffChunk(stream, num4, (int)num5)); } stream.Position += num5; } if (num5 % 2 != 0 && binaryReader.PeekChar() == 0) { stream.Position++; } } if (waveFormat == null) { throw new FormatException("Invalid WAV file - No fmt chunk found"); } if (dataChunkPosition == -1) { throw new FormatException("Invalid WAV file - No data chunk found"); } } private void ReadDs64Chunk(BinaryReader reader) { int num = ChunkIdentifier.ChunkIdentifierToInt32("ds64"); if (reader.ReadInt32() != num) { throw new FormatException("Invalid RF64 WAV file - No ds64 chunk found"); } int num2 = reader.ReadInt32(); riffSize = reader.ReadInt64(); dataChunkLength = reader.ReadInt64(); reader.ReadInt64(); reader.ReadBytes(num2 - 24); } private static RiffChunk GetRiffChunk(Stream stream, int chunkIdentifier, int chunkLength) { return new RiffChunk(chunkIdentifier, chunkLength, stream.Position); } private void ReadRiffHeader(BinaryReader br) { int num = br.ReadInt32(); if (num == ChunkIdentifier.ChunkIdentifierToInt32("RF64")) { isRf64 = true; } else if (num != ChunkIdentifier.ChunkIdentifierToInt32("RIFF")) { throw new FormatException("Not a WAVE file - no RIFF header"); } } } } namespace NAudio.SoundFont { public class Generator { public GeneratorEnum GeneratorType { get; set; } public ushort UInt16Amount { get; set; } public short Int16Amount { get { return (short)UInt16Amount; } set { UInt16Amount = (ushort)value; } } public byte LowByteAmount { get { return (byte)(UInt16Amount & 0xFFu); } set { UInt16Amount &= 65280; UInt16Amount += value; } } public byte HighByteAmount { get { return (byte)((UInt16Amount & 0xFF00) >> 8); } set { UInt16Amount &= 255; UInt16Amount += (ushort)(value << 8); } } public Instrument Instrument { get; set; } public SampleHeader SampleHeader { get; set; } public override string ToString() { if (GeneratorType == GeneratorEnum.Instrument) { return "Generator Instrument " + Instrument.Name; } if (GeneratorType == GeneratorEnum.SampleID) { return $"Generator SampleID {SampleHeader}"; } return $"Generator {GeneratorType} {UInt16Amount}"; } } internal class GeneratorBuilder : StructureBuilder<Generator> { public override int Length => 4; public Generator[] Generators => data.ToArray(); public override Generator Read(BinaryReader br) { Generator generator = new Generator(); generator.GeneratorType = (GeneratorEnum)br.ReadUInt16(); generator.UInt16Amount = br.ReadUInt16(); data.Add(generator); return generator; } public override void Write(BinaryWriter bw, Generator o) { } public void Load(Instrument[] instruments) { Generator[] generators = Generators; foreach (Generator generator in generators) { if (generator.GeneratorType == GeneratorEnum.Instrument) { generator.Instrument = instruments[generator.UInt16Amount]; } } } public void Load(SampleHeader[] sampleHeaders) { Generator[] generators = Generators; foreach (Generator generator in generators) { if (generator.GeneratorType == GeneratorEnum.SampleID) { generator.SampleHeader = sampleHeaders[generator.UInt16Amount]; } } } } public enum GeneratorEnum { StartAddressOffset, EndAddressOffset, StartLoopAddressOffset, EndLoopAddressOffset, StartAddressCoarseOffset, ModulationLFOToPitch, VibratoLFOToPitch, ModulationEnvelopeToPitch, InitialFilterCutoffFrequency, InitialFilterQ, ModulationLFOToFilterCutoffFrequency, ModulationEnvelopeToFilterCutoffFrequency, EndAddressCoarseOffset, ModulationLFOToVolume, Unused1, ChorusEffectsSend, ReverbEffectsSend, Pan, Unused2, Unused3, Unused4, DelayModulationLFO, FrequencyModulationLFO, DelayVibratoLFO, FrequencyVibratoLFO, DelayModulationEnvelope, AttackModulationEnvelope, HoldModulationEnvelope, DecayModulationEnvelope, SustainModulationEnvelope, ReleaseModulationEnvelope, KeyNumberToModulationEnvelopeHold, KeyNumberToModulationEnvelopeDecay, DelayVolumeEnvelope, AttackVolumeEnvelope, HoldVolumeEnvelope, DecayVolumeEnvelope, SustainVolumeEnvelope, ReleaseVolumeEnvelope, KeyNumberToVolumeEnvelopeHold, KeyNumberToVolumeEnvelopeDecay, Instrument, Reserved1, KeyRange, VelocityRange, StartLoopAddressCoarseOffset, KeyNumber, Velocity, InitialAttenuation, Reserved2, EndLoopAddressCoarseOffset, CoarseTune, FineTune, SampleID, SampleModes, Reserved3, ScaleTuning, ExclusiveClass, OverridingRootKey, Unused5, UnusedEnd } public class InfoChunk { public SFVersion SoundFontVersion { get; } public string WaveTableSoundEngine { get; set; } public string BankName { get; set; } public string DataROM { get; set; } public string CreationDate { get; set; } public string Author { get; set; } public string TargetProduct { get; set; } public string Copyright { get; set; } public string Comments { get; set; } public string Tools { get; set; } public SFVersion ROMVersion { get; set; } internal InfoChunk(RiffChunk chunk) { bool flag = false; bool flag2 = false; if (chunk.ReadChunkID() != "INFO") { throw new InvalidDataException("Not an INFO chunk"); } RiffChunk nextSubChunk; while ((nextSubChunk = chunk.GetNextSubChunk()) != null) { switch (nextSubChunk.ChunkID) { case "ifil": flag = true; SoundFontVersion = nextSubChunk.GetDataAsStructure(new SFVersionBuilder()); break; case "isng": WaveTableSoundEngine = nextSubChunk.GetDataAsString(); break; case "INAM": flag2 = true; BankName = nextSubChunk.GetDataAsString(); break; case "irom": DataROM = nextSubChunk.GetDataAsString(); break; case "iver": ROMVersion = nextSubChunk.GetDataAsStructure(new SFVersionBuilder()); break; case "ICRD": CreationDate = nextSubChunk.GetDataAsString(); break; case "IENG": Author = nextSubChunk.GetDataAsString(); break; case "IPRD": TargetProduct = nextSubChunk.GetDataAsString(); break; case "ICOP": Copyright = nextSubChunk.GetDataAsString(); break; case "ICMT": Comments = nextSubChunk.GetDataAsString(); break; case "ISFT": Tools = nextSubChunk.GetDataAsString(); break; default: throw new InvalidDataException("Unknown chunk type " + nextSubChunk.ChunkID); } } if (!flag) { throw new InvalidDataException("Missing SoundFont version information"); } if (!flag2) { throw new InvalidDataException("Missing SoundFont name information"); } } public override string ToString() { return string.Format("Bank Name: {0}\r\nAuthor: {1}\r\nCopyright: {2}\r\nCreation Date: {3}\r\nTools: {4}\r\nComments: {5}\r\nSound Engine: {6}\r\nSoundFont Version: {7}\r\nTarget Product: {8}\r\nData ROM: {9}\r\nROM Version: {10}", BankName, Author, Copyright, CreationDate, Tools, "TODO-fix comments", WaveTableSoundEngine, SoundFontVersion, TargetProduct, DataROM, ROMVersion); } } public class Instrument { internal ushort startInstrumentZoneIndex; internal ushort endInstrumentZoneIndex; public string Name { get; set; } public Zone[] Zones { get; set; } public override string ToString() { return Name; } } internal class InstrumentBuilder : StructureBuilder<Instrument> { private Instrument lastInstrument; public override int Length => 22; public Instrument[] Instruments => data.ToArray(); public override Instrument Read(BinaryReader br) { Instrument instrument = new Instrument(); string text = Encoding.UTF8.GetString(br.ReadBytes(20), 0, 20); if (text.IndexOf('\0') >= 0) { text = text.Substring(0, text.IndexOf('\0')); } instrument.Name = text; instrument.startInstrumentZoneIndex = br.ReadUInt16(); if (lastInstrument != null) { lastInstrument.endInstrumentZoneIndex = (ushort)(instrument.startInstrumentZoneIndex - 1); } data.Add(instrument); lastInstrument = instrument; return instrument; } public override void Write(BinaryWriter bw, Instrument instrument) { } public void LoadZones(Zone[] zones) { for (int i = 0; i < data.Count - 1; i++) { Instrument instrument = data[i]; instrument.Zones = new Zone[instrument.endInstrumentZoneIndex - instrument.startInstrumentZoneIndex + 1]; Array.Copy(zones, instrument.startInstrumentZoneIndex, instrument.Zones, 0, instrument.Zones.Length); } data.RemoveAt(data.Count - 1); } } public enum TransformEnum { Linear } public class Modulator { public ModulatorType SourceModulationData { get; set; } public GeneratorEnum DestinationGenerator { get; set; } public short Amount { get; set; } public ModulatorType SourceModulationAmount { get; set; } public TransformEnum SourceTransform { get; set; } public override string ToString() { return $"Modulator {SourceModulationData} {DestinationGenerator} {Amount} {SourceModulationAmount} {SourceTransform}"; } } internal class ModulatorBuilder : StructureBuilder<Modulator> { public override int Length => 10; public Modulator[] Modulators => data.ToArray(); public override Modulator Read(BinaryReader br) { Modulator modulator = new Modulator(); modulator.SourceModulationData = new ModulatorType(br.ReadUInt16()); modulator.DestinationGenerator = (GeneratorEnum)br.ReadUInt16(); modulator.Amount = br.ReadInt16(); modulator.SourceModulationAmount = new ModulatorType(br.ReadUInt16()); modulator.SourceTransform = (TransformEnum)br.ReadUInt16(); data.Add(modulator); return modulator; } public override void Write(BinaryWriter bw, Modulator o) { } } public enum ControllerSourceEnum { NoController = 0, NoteOnVelocity = 2, NoteOnKeyNumber = 3, PolyPressure = 10, ChannelPressure = 13, PitchWheel = 14, PitchWheelSensitivity = 16 } public enum SourceTypeEnum { Linear, Concave, Convex, Switch } public class ModulatorType { private bool polarity; private bool direction; private bool midiContinuousController; private ControllerSourceEnum controllerSource; private SourceTypeEnum sourceType; private ushort midiContinuousControllerNumber; internal ModulatorType(ushort raw) { polarity = (raw & 0x200) == 512; direction = (raw & 0x100) == 256; midiContinuousController = (raw & 0x80) == 128; sourceType = (SourceTypeEnum)((raw & 0xFC00) >> 10); controllerSource = (ControllerSourceEnum)(raw & 0x7F); midiContinuousControllerNumber = (ushort)(raw & 0x7Fu); } public override string ToString() { if (midiContinuousController) { return $"{sourceType} CC{midiContinuousControllerNumber}"; } return $"{sourceType} {controllerSource}"; } } public class Preset { internal ushort startPresetZoneIndex; internal ushort endPresetZoneIndex; internal uint library; internal uint genre; internal uint morphology; public string Name { get; set; } public ushort PatchNumber { get; set; } public ushort Bank { get; set; } public Zone[] Zones { get; set; } public override string ToString() { return $"{Bank}-{PatchNumber} {Name}"; } } internal class PresetBuilder : StructureBuilder<Preset> { private Preset lastPreset; public override int Length => 38; public Preset[] Presets => data.ToArray(); public override Preset Read(BinaryReader br) { Preset preset = new Preset(); string text = Encoding.UTF8.GetString(br.ReadBytes(20), 0, 20); if (text.IndexOf('\0') >= 0) { text = text.Substring(0, text.IndexOf('\0')); } preset.Name = text; preset.PatchNumber = br.ReadUInt16(); preset.Bank = br.ReadUInt16(); preset.startPresetZoneIndex = br.ReadUInt16(); preset.library = br.ReadUInt32(); preset.genre = br.ReadUInt32(); preset.morphology = br.ReadUInt32(); if (lastPreset != null) { lastPreset.endPresetZoneIndex = (ushort)(preset.startPresetZoneIndex - 1); } data.Add(preset); lastPreset = preset; return preset; } public override void Write(BinaryWriter bw, Preset preset) { } public void LoadZones(Zone[] presetZones) { for (int i = 0; i < data.Count - 1; i++) { Preset preset = data[i]; preset.Zones = new Zone[preset.endPresetZoneIndex - preset.startPresetZoneIndex + 1]; Array.Copy(presetZones, preset.startPresetZoneIndex, preset.Zones, 0, preset.Zones.Length); } data.RemoveAt(data.Count - 1); } } public class PresetsChunk { private PresetBuilder presetHeaders = new PresetBuilder(); private ZoneBuilder presetZones = new ZoneBuilder(); private ModulatorBuilder presetZoneModulators = new ModulatorBuilder(); private GeneratorBuilder presetZoneGenerators = new GeneratorBuilder(); private InstrumentBuilder instruments = new InstrumentBuilder(); private ZoneBuilder instrumentZones = new ZoneBuilder(); private ModulatorBuilder instrumentZoneModulators = new ModulatorBuilder(); private GeneratorBuilder instrumentZoneGenerators = new GeneratorBuilder(); private SampleHeaderBuilder sampleHeaders = new SampleHeaderBuilder(); public Preset[] Presets => presetHeaders.Presets; public Instrument[] Instruments => instruments.Instruments; public SampleHeader[] SampleHeaders => sampleHeaders.SampleHeaders; internal PresetsChunk(RiffChunk chunk) { string text = chunk.ReadChunkID(); if (text != "pdta") { throw new InvalidDataException($"Not a presets data chunk ({text})"); } RiffChunk nextSubChunk; while ((nextSubChunk = chunk.GetNextSubChunk()) != null) { switch (nextSubChunk.ChunkID) { case "phdr": case "PHDR": nextSubChunk.GetDataAsStructureArray(presetHeaders); break; case "pbag": case "PBAG": nextSubChunk.GetDataAsStructureArray(presetZones); break; case "pmod": case "PMOD": nextSubChunk.GetDataAsStructureArray(presetZoneModulators); break; case "pgen": case "PGEN": nextSubChunk.GetDataAsStructureArray(presetZoneGenerators); break; case "inst": case "INST": nextSubChunk.GetDataAsStructureArray(instruments); break; case "ibag": case "IBAG": nextSubChunk.GetDataAsStructureArray(instrumentZones); break; case "imod": case "IMOD": nextSubChunk.GetDataAsStructureArray(instrumentZoneModulators); break; case "igen": case "IGEN": nextSubChunk.GetDataAsStructureArray(instrumentZoneGenerators); break; case "shdr": case "SHDR": nextSubChunk.GetDataAsStructureArray(sampleHeaders); break; default: throw new InvalidDataException($"Unknown chunk type {nextSubChunk.ChunkID}"); } } instrumentZoneGenerators.Load(sampleHeaders.SampleHeaders); instrumentZones.Load(instrumentZoneModulators.Modulators, instrumentZoneGenerators.Generators); instruments.LoadZones(instrumentZones.Zones); presetZoneGenerators.Load(instruments.Instruments); presetZones.Load(presetZoneModulators.Modulators, presetZoneGenerators.Generators); presetHeaders.LoadZones(presetZones.Zones); sampleHeaders.RemoveEOS(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Preset Headers:\r\n"); Preset[] presets = presetHeaders.Presets; foreach (Preset arg in presets) { stringBuilder.AppendFormat("{0}\r\n", arg); } stringBuilder.Append("Instruments:\r\n"); Instrument[] array = instruments.Instruments; foreach (Instrument arg2 in array) { stringBuilder.AppendFormat("{0}\r\n", arg2); } return stringBuilder.ToString(); } } internal class RiffChunk { private string chunkID; private BinaryReader riffFile; public string ChunkID { get { return chunkID; } set { if (value == null) { throw new ArgumentNullException("ChunkID may not be null"); } if (value.Length != 4) { throw new ArgumentException("ChunkID must be four characters"); } chunkID = value; } } public uint ChunkSize { get; private set; } public long DataOffset { get; private set; } public static RiffChunk GetTopLevelChunk(BinaryReader file) { RiffChunk riffChunk = new RiffChunk(file); riffChunk.ReadChunk(); return riffChunk; } private RiffChunk(BinaryReader file) { riffFile = file; chunkID = "????"; ChunkSize = 0u; DataOffset = 0L; } public string ReadChunkID() { byte[] array = riffFile.ReadBytes(4); if (array.Length != 4) { throw new InvalidDataException("Couldn't read Chunk ID"); } return ByteEncoding.Instance.GetString(array, 0, array.Length); } private void ReadChunk() { chunkID = ReadChunkID(); ChunkSize = riffFile.ReadUInt32(); DataOffset = riffFile.BaseStream.Position; } public RiffChunk GetNextSubChunk() { if (riffFile.BaseStream.Position + 8 < DataOffset + ChunkSize) { RiffChunk riffChunk = new RiffChunk(riffFile); riffChunk.ReadChunk(); return riffChunk; } return null; } public byte[] GetData() { riffFile.BaseStream.Position = DataOffset; byte[] array = riffFile.ReadBytes((int)ChunkSize); if (array.Length != ChunkSize) { throw new InvalidDataException($"Couldn't read chunk's data Chunk: {this}, read {array.Length} bytes"); } return array; } public string GetDataAsString() { byte[] data = GetData(); if (data == null) { return null; } return ByteEncoding.Instance.GetString(data, 0, data.Length); } public T GetDataAsStructure<T>(StructureBuilder<T> s) { riffFile.BaseStream.Position = DataOffset; if (s.Length != ChunkSize) { throw new InvalidDataException($"Chunk size is: {ChunkSize} so can't read structure of: {s.Length}"); } return s.Read(riffFile); } public T[] GetDataAsStructureArray<T>(StructureBuilder<T> s) { riffFile.BaseStream.Position = DataOffset; if (ChunkSize % s.Length != 0L) { throw new InvalidDataException($"Chunk size is: {ChunkSize} not a multiple of structure size: {s.Length}"); } int num = (int)(ChunkSize / s.Length); T[] array = new T[num]; for (int i = 0; i < num; i++) { array[i] = s.Read(riffFile); } return array; } public override string ToString() { return $"RiffChunk ID: {ChunkID} Size: {ChunkSize} Data Offset: {DataOffset}"; } } internal class SampleDataChunk { public byte[] SampleData { get; private set; } public SampleDataChunk(RiffChunk chunk) { string text = chunk.ReadChunkID(); if (text != "sdta") { throw new InvalidDataException("Not a sample data chunk (" + text + ")"); } SampleData = chunk.GetData(); } } public class SampleHeader { public string SampleName; public uint Start; public uint End; public uint StartLoop; public uint EndLoop; public uint SampleRate; public byte OriginalPitch; public sbyte PitchCorrection; public ushort SampleLink; public SFSampleLink SFSampleLink; public override string ToString() { return SampleName; } } internal class SampleHeaderBuilder : StructureBuilder<SampleHeader> { public override int Length => 46; public SampleHeader[] SampleHeaders => data.ToArray(); public override SampleHeader Read(BinaryReader br) { SampleHeader sampleHeader = new SampleHeader(); byte[] array = br.ReadBytes(20); sampleHeader.SampleName = ByteEncoding.Instance.GetString(array, 0, array.Length); sampleHeader.Start = br.ReadUInt32(); sampleHeader.End = br.ReadUInt32(); sampleHeader.StartLoop = br.ReadUInt32(); sampleHeader.EndLoop = br.ReadUInt32(); sampleHeader.SampleRate = br.ReadUInt32(); sampleHeader.OriginalPitch = br.ReadByte(); sampleHeader.PitchCorrection = br.ReadSByte(); sampleHeader.SampleLink = br.ReadUInt16(); sampleHeader.SFSampleLink = (SFSampleLink)br.ReadUInt16(); data.Add(sampleHeader); return sampleHeader; } public override void Write(BinaryWriter bw, SampleHeader sampleHeader) { } internal void RemoveEOS() { data.RemoveAt(data.Count - 1); } } public enum SampleMode { NoLoop, LoopContinuously, ReservedNoLoop, LoopAndContinue } public enum SFSampleLink : ushort { MonoSample = 1, RightSample = 2, LeftSample = 4, LinkedSample = 8, RomMonoSample = 32769, RomRightSample = 32770, RomLeftSample = 32772, RomLinkedSample = 32776 } public class SFVersion { public short Major { get; set; } public short Minor { get; set; } } internal class SFVersionBuilder : StructureBuilder<SFVersion> { public override int Length => 4; public override SFVersion Read(BinaryReader br) { SFVersion sFVersion = new SFVersion(); sFVersion.Major = br.ReadInt16(); sFVersion.Minor = br.ReadInt16(); data.Add(sFVersion); return sFVersion; } public override void Write(BinaryWriter bw, SFVersion v) { bw.Write(v.Major); bw.Write(v.Minor); } } public class SoundFont { private InfoChunk info; private PresetsChunk presetsChunk; private SampleDataChunk sampleData; public InfoChunk FileInfo => info; public Preset[] Presets => presetsChunk.Presets; public Instrument[] Instruments => presetsChunk.Instruments; public SampleHeader[] SampleHeaders => presetsChunk.SampleHeaders; public byte[] SampleData => sampleData.SampleData; public SoundFont(string fileName) : this(new FileStream(fileName, FileMode.Open, FileAccess.Read)) { } public SoundFont(Stream sfFile) { using (sfFile) { RiffChunk topLevelChunk = RiffChunk.GetTopLevelChunk(new BinaryReader(sfFile)); if (topLevelChunk.ChunkID == "RIFF") { string text = topLevelChunk.ReadChunkID(); if (text != "sfbk") { throw new InvalidDataException($"Not a SoundFont ({text})"); } RiffChunk nextSubChunk = topLevelChunk.GetNextSubChunk(); if (nextSubChunk.ChunkID == "LIST") { info = new InfoChunk(nextSubChunk); RiffChunk nextSubChunk2 = topLevelChunk.GetNextSubChunk(); sampleData = new SampleDataChunk(nextSubChunk2); nextSubChunk2 = topLevelChunk.GetNextSubChunk(); presetsChunk = new PresetsChunk(nextSubChunk2); return; } throw new InvalidDataException($"Not info list found ({nextSubChunk.ChunkID})"); } throw new InvalidDataException("Not a RIFF file"); } } public override string ToString() { return $"Info Chunk:\r\n{info}\r\nPresets Chunk:\r\n{presetsChunk}"; } } internal abstract class StructureBuilder<T> { protected List<T> data; public abstract int Length { get; } public T[] Data => data.ToArray(); public StructureBuilder() { Reset(); } public abstract T Read(BinaryReader br); public abstract void Write(BinaryWriter bw, T o); public void Reset() { data = new List<T>(); } } public class Zone { internal ushort generatorIndex; internal ushort modulatorIndex; internal ushort generatorCount; internal ushort modulatorCount; public Modulator[] Modulators { get; set; } public Generator[] Generators { get; set; } public override string ToString() { return $"Zone {generatorCount} Gens:{generatorIndex} {modulatorCount} Mods:{modulatorIndex}"; } } internal class ZoneBuilder : StructureBuilder<Zone> { private Zone lastZone; public Zone[] Zones => data.ToArray(); public override int Length => 4; public override Zone Read(BinaryReader br) { Zone zone = new Zone(); zone.generatorIndex = br.ReadUInt16(); zone.modulatorIndex = br.ReadUInt16(); if (lastZone != null) { lastZone.generatorCount = (ushort)(zone.generatorIndex - lastZone.generatorIndex); lastZone.modulatorCount = (ushort)(zone.modulatorIndex - lastZone.modulatorIndex); } data.Add(zone); lastZone = zone; return zone; } public override void Write(BinaryWriter bw, Zone zone) { } public void Load(Modulator[] modulators, Generator[] generators) { for (int i = 0; i < data.Count - 1; i++) { Zone zone = data[i]; zone.Generators = new Generator[zone.generatorCount]; Array.Copy(generators, zone.generatorIndex, zone.Generators, 0, zone.generatorCount); zone.Modulators = new Modulator[zone.modulatorCount]; Array.Copy(modulators, zone.modulatorIndex, zone.Modulators, 0, zone.modulatorCount); } data.RemoveAt(data.Count - 1); } } } namespace NAudio.Wave { public enum ChannelMode { Stereo, JointStereo, DualChannel, Mono } public class Id3v2Tag { private long tagStartPosition; private long tagEndPosition; private byte[] rawData; public byte[] RawData => rawData; public static Id3v2Tag ReadTag(Stream input) { try { return new Id3v2Tag(input); } catch (FormatException) { return null; } } public static Id3v2Tag Create(IEnumerable<KeyValuePair<string, string>> tags) { return ReadTag(CreateId3v2TagStream(tags)); } private static byte[] FrameSizeToBytes(int n) { byte[] bytes = BitConverter.GetBytes(n); Array.Reverse((Array)bytes); return bytes; } private static byte[] CreateId3v2Frame(string key, string value) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } if (key.Length != 4) { throw new ArgumentOutOfRangeException("key", "key " + key + " must be 4 characters long"); } byte[] array = new byte[2] { 255, 254 }; byte[] array2 = new byte[3]; byte[] array3 = new byte[2]; byte[] array4 = ((!(key == "COMM")) ? ByteArrayExtensions.Concat(new byte[1] { 1 }, array, Encoding.Unicode.GetBytes(value)) : ByteArrayExtensions.Concat(new byte[1] { 1 }, array2, array3, array, Encoding.Unicode.GetBytes(value))); return ByteArrayExtensions.Concat(Encoding.UTF8.GetBytes(key), FrameSizeToBytes(array4.Length), new byte[2], array4); } private static byte[] GetId3TagHeaderSize(int size) { byte[] array = new byte[4]; for (int num = array.Length - 1; num >= 0; num--) { array[num] = (byte)(size % 128); size /= 128; } return array; } private static byte[] CreateId3v2TagHeader(IEnumerable<byte[]> frames) { int num = 0; foreach (byte[] frame in frames) { num += frame.Length; } return ByteArrayExtensions.Concat(Encoding.UTF8.GetBytes("ID3"), new byte[2] { 3, 0 }, new byte[1], GetId3TagHeaderSize(num)); } private static Stream CreateId3v2TagStream(IEnumerable<KeyValuePair<string, string>> tags) { List<byte[]> list = new List<byte[]>(); foreach (KeyValuePair<string, string> tag in tags) { list.Add(CreateId3v2Frame(tag.Key, tag.Value)); } byte[] array = CreateId3v2TagHeader(list); MemoryStream memoryStream = new MemoryStream(); memoryStream.Write(array, 0, array.Length); foreach (byte[] item in list) { memoryStream.Write(item, 0, item.Length); } memoryStream.Position = 0L; return memoryStream; } private Id3v2Tag(Stream input) { tagStartPosition = input.Position; BinaryReader binaryReader = new BinaryReader(input); byte[] array = binaryReader.ReadBytes(10); if (array.Length >= 3 && array[0] == 73 && array[1] == 68 && array[2] == 51) { if ((array[5] & 0x40) == 64) { byte[] array2 = binaryReader.ReadBytes(4); _ = array2[0] * 2097152 + array2[1] * 16384 + array2[2] * 128; _ = array2[3]; } int num = array[6] * 2097152; num += array[7] * 16384; num += array[8] * 128; num += array[9]; binaryReader.ReadBytes(num); if ((array[5] & 0x10) == 16) { binaryReader.ReadBytes(10); } tagEndPosition = input.Position; input.Position = tagStartPosition; rawData = binaryReader.ReadBytes((int)(tagEndPosition - tagStartPosition)); return; } input.Position = tagStartPosition; throw new FormatException("Not an ID3v2 tag"); } } public interface IMp3FrameDecompressor : IDisposable { WaveFormat OutputFormat { get; } int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset); void Reset(); } public class Mp3Frame { private static readonly int[,,] bitRates = new int[2, 3, 15] { { { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 }, { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 }, { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 } }, { { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 } } }; private static readonly int[,] samplesPerFrame = new int[2, 3] { { 384, 1152, 1152 }, { 384, 1152, 576 } }; private static readonly int[] sampleRatesVersion1 = new int[3] { 44100, 48000, 32000 }; private static readonly int[] sampleRatesVersion2 = new int[3] { 22050, 24000, 16000 }; private static readonly int[] sampleRatesVersion25 = new int[3] { 11025, 12000, 8000 }; private const int MaxFrameLength = 16384; public int SampleRate { get; private set; } public int FrameLength { get; private set; } public int BitRate { get; private set; } public byte[] RawData { get; private set; } public MpegVersion MpegVersion { get; private set; } public MpegLayer MpegLayer { get; private set; } public ChannelMode ChannelMode { get; private set; } public int SampleCount { get; private set; } public int ChannelExtension { get; private set; } public int BitRateIndex { get; private set; } public bool Copyright { get; private set; } public bool CrcPresent { get; private set; } public long FileOffset { get; private set; } public static Mp3Frame LoadFromStream(Stream input) { return LoadFromStream(input, readData: true); } public static Mp3Frame LoadFromStream(Stream input, bool readData) { Mp3Frame mp3Frame = new Mp3Frame(); mp3Frame.FileOffset = input.Position; byte[] array = new byte[4]; if (input.Read(array, 0, array.Length) < array.Length) { return null; } while (!IsValidHeader(array, mp3Frame)) { array[0] = array[1]; array[1] = array[2]; array[2] = array[3]; if (input.Read(array, 3, 1) < 1) { return null; } mp3Frame.FileOffset++; } int num = mp3Frame.FrameLength - 4; if (readData) { mp3Frame.RawData = new byte[mp3Frame.FrameLength]; Array.Copy(array, mp3Frame.RawData, 4); if (input.Read(mp3Frame.RawData, 4, num) < num) { throw new EndOfStreamException("Unexpected end of stream before frame complete"); } } else { input.Position += num; } return mp3Frame; } private Mp3Frame() { } private static bool IsValidHeader(byte[] headerBytes, Mp3Frame frame) { if (headerBytes[0] == byte.MaxValue && (headerBytes[1] & 0xE0) == 224) { frame.MpegVersion = (MpegVersion)((headerBytes[1] & 0x18) >> 3); if (frame.MpegVersion == MpegVersion.Reserved) { return false; } frame.MpegLayer = (MpegLayer)((headerBytes[1] & 6) >> 1); if (frame.MpegLayer == MpegLayer.Reserved) { return false; } int num = ((frame.MpegLayer != MpegLayer.Layer1) ? ((frame.MpegLayer == MpegLayer.Layer2) ? 1 : 2) : 0); frame.CrcPresent = (headerBytes[1] & 1) == 0; frame.BitRateIndex = (headerBytes[2] & 0xF0) >> 4; if (frame.BitRateIndex == 15) { return false; } int num2 = ((frame.MpegVersion != MpegVersion.Version1) ? 1 : 0); frame.BitRate = bitRates[num2, num, frame.BitRateIndex] * 1000; if (frame.BitRate == 0) { return false; } int num3 = (headerBytes[2] & 0xC) >> 2; if (num3 == 3) { return false; } if (frame.MpegVersion == MpegVersion.Version1) { frame.SampleRate = sampleRatesVersion1[num3]; } else if (frame.MpegVersion == MpegVersion.Version2) { frame.SampleRate = sampleRatesVersion2[num3]; } else { frame.SampleRate = sampleRatesVersion25[num3]; } bool flag = (headerBytes[2] & 2) == 2; _ = headerBytes[2]; frame.ChannelMode = (ChannelMode)((headerBytes[3] & 0xC0) >> 6); frame.ChannelExtension = (headerBytes[3] & 0x30) >> 4; if (frame.ChannelExtension != 0 && frame.ChannelMode != ChannelMode.JointStereo) { return false; } frame.Copyright = (headerBytes[3] & 8) == 8; _ = headerBytes[3]; _ = headerBytes[3]; int num4 = (flag ? 1 : 0); frame.SampleCount = samplesPerFrame[num2, num]; int num5 = frame.SampleCount / 8; if (frame.MpegLayer == MpegLayer.Layer1) { frame.FrameLength = (num5 * frame.BitRate / frame.SampleRate + num4) * 4; } else { frame.FrameLength = num5 * frame.BitRate / frame.SampleRate + num4; } if (frame.FrameLength > 16384) { return false; } return true; } return false; } } public enum MpegLayer { Reserved, Layer3, Layer2, Layer1 } public enum MpegVersion { Version25, Reserved, Version2, Version1 } public class XingHeader { [Flags] private enum XingHeaderOptions { Frames = 1, Bytes = 2, Toc = 4, VbrScale = 8 } private static int[] sr_table = new int[4] { 44100, 48000, 32000, 99999 }; private int vbrScale = -1; private int startOffset; private int endOffset; private int tocOffset = -1; private int framesOffset = -1; private int bytesOffset = -1; private Mp3Frame frame; public int Frames { get { if (framesOffset == -1) { return -1; } return ReadBigEndian(frame.RawData, framesOffset); } set { if (framesOffset == -1) { throw new InvalidOperationException("Frames flag is not set"); } WriteBigEndian(frame.RawData, framesOffset, value); } } public int Bytes { get { if (bytesOffset == -1) { return -1; } return ReadBigEndian(frame.RawData, bytesOffset); } set { if (framesOffset == -1) { throw new InvalidOperationException("Bytes flag is not set"); } WriteBigEndian(frame.RawData, bytesOffset, value); } } public int VbrScale => vbrScale; public Mp3Frame Mp3Frame => frame; private static int ReadBigEndian(byte[] buffer, int offset) { return (((((buffer[offset] << 8) | buffer[offset + 1]) << 8) | buffer[offset + 2]) << 8) | buffer[offset + 3]; } private void WriteBigEndian(byte[] buffer, int offset, int value) { byte[] bytes = BitConverter.GetBytes(value); for (int i = 0; i < 4; i++) { buffer[offset + 3 - i] = bytes[i]; } } public static XingHeader LoadXingHeader(Mp3Frame frame) { XingHeader xingHeader = new XingHeader(); xingHeader.frame = frame; int num = 0; if (frame.MpegVersion == MpegVersion.Version1) { num = ((frame.ChannelMode == ChannelMode.Mono) ? 21 : 36); } else { if (frame.MpegVersion != MpegVersion.Version2) { return null; } num = ((frame.ChannelMode == ChannelMode.Mono) ? 13 : 21); } if (frame.RawData[num] == 88 && frame.RawData[num + 1] == 105 && frame.RawData[num + 2] == 110 && frame.RawData[num + 3] == 103) { xingHeader.startOffset = num; num += 4; } else { if (frame.RawData[num] != 73 || frame.RawData[num + 1] != 110 || frame.RawData[num + 2] != 102 || frame.RawData[num + 3] != 111) { return null; } xingHeader.startOffset = num; num += 4; } int num2 = ReadBigEndian(frame.RawData, num); num += 4; if (((uint)num2 & (true ? 1u : 0u)) != 0) { xingHeader.framesOffset = num; num += 4; } if (((uint)num2 & 2u) != 0) { xingHeader.bytesOffset = num; num += 4; } if (((uint)num2 & 4u) != 0) { xingHeader.tocOffset = num; num += 100; } if (((uint)num2 & 8u) != 0) { xingHeader.vbrScale = ReadBigEndian(frame.RawData, num); num += 4; } xingHeader.endOffset = num; return xingHeader; } private XingHeader() { } } public static class WaveExtensionMethods { public static ISampleProvider ToSampleProvider(this IWaveProvider waveProvider) { return SampleProviderConverters.ConvertWaveProviderIntoSampleProvider(waveProvider); } public static void Init(this IWavePlayer wavePlayer, ISampleProvider sampleProvider, bool convertTo16Bit = false) { IWaveProvider waveProvider2; if (!convertTo16Bit) { IWaveProvider waveProvider = new SampleToWaveProvider(sampleProvider); waveProvider2 = waveProvider; } else { IWaveProvider waveProvider = new SampleToWaveProvider16(sampleProvider); waveProvider2 = waveProvider; } IWaveProvider waveProvider3 = waveProvider2; wavePlayer.Init(waveProvider3); } public static WaveFormat AsStandardWaveFormat(this WaveFormat waveFormat) { if (!(waveFormat is WaveFormatExtensible waveFormatExtensible)) { return waveFormat; } return waveFormatExtensible.ToStandardWaveFormat(); } public static IWaveProvider ToWaveProvider(this ISampleProvider sampleProvider) { return new SampleToWaveProvider(sampleProvider); } public static IWaveProvider ToWaveProvider16(this ISampleProvider sampleProvider) { return new SampleToWaveProvider16(sampleProvider); } public static ISampleProvider FollowedBy(this ISampleProvider sampleProvider, ISampleProvider next) { return new ConcatenatingSampleProvider(new ISampleProvider[2] { sampleProvider, next }); } public static ISampleProvider FollowedBy(this ISampleProvider sampleProvider, TimeSpan silenceDuration, ISampleProvider next) { OffsetSampleProvider offsetSampleProvider = new OffsetSampleProvider(sampleProvider) { LeadOut = silenceDuration }; return new ConcatenatingSampleProvider(new ISampleProvider[2] { offsetSampleProvider, next }); } public static ISampleProvider Skip(this ISampleProvider sampleProvider, TimeSpan skipDuration) { return new OffsetSampleProvider(sampleProvider) { SkipOver = skipDuration }; } public static ISampleProvider Take(this ISampleProvider sampleProvider, TimeSpan takeDuration) { return new OffsetSampleProvider(sampleProvider) { Take = takeDuration }; } public static ISampleProvider ToMono(this ISampleProvider sourceProvider, float leftVol = 0.5f, float rightVol = 0.5f) { if (sourceProvider.WaveFormat.Channels == 1) { return sourceProvider; } return new StereoToMonoSampleProvider(sourceProvider) { LeftVolume = leftVol, RightVolume = rightVol }; } public static ISampleProvider ToStereo(this ISampleProvider sourceProvider, float leftVol = 1f, float rightVol = 1f) { if (sourceProvider.WaveFormat.Channels == 2) { return sourceProvider; } return new MonoToStereoSampleProvider(sourceProvider) { LeftVolume = leftVol, RightVolume = rightVol }; } } [StructLayout(LayoutKind.Sequential, Pack = 2)] public class AdpcmWaveFormat : WaveFormat { private short samplesPerBlock; private short numCoeff; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)] private short[] coefficients; public int SamplesPerBlock => samplesPerBlock; public int NumCoefficients => numCoeff; public short[] Coefficients => coefficients; private AdpcmWaveFormat() : this(8000, 1) { } public AdpcmWaveFormat(int sampleRate, int channels) : base(sampleRate, 0, channels) { waveFormatTag = WaveFormatEncoding.Adpcm; extraSize = 32; switch (base.sampleRate) { case 8000: case 11025: blockAlign = 256; break; case 22050: blockAlign = 512; break; default: blockAlign = 1024; break; } bitsPerSample = 4; samplesPerBlock = (short)((blockAlign - 7 * channels) * 8 / (bitsPerSample * channels) + 2); averageBytesPerSecond = base.SampleRate * blockAlign / samplesPerBlock; numCoeff = 7; coefficients = new short[14] { 256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232 }; } public override void Serialize(BinaryWriter writer) { base.Serialize(writer); writer.Write(samplesPerBlock); writer.Write(numCoeff); short[] array = coefficients; foreach (short value in array) { writer.Write(value); } } public override string ToString() { return $"Microsoft ADPCM {base.SampleRate} Hz {channels} channels {bitsPerSample} bits per sample {samplesPerBlock} samples per block"; } } [StructLayout(LayoutKind.Sequential, Pack = 2)] public class Gsm610WaveFormat : WaveFormat { private readonly short samplesPerBlock; public short SamplesPerBlock => samplesPerBlock; public Gsm610WaveFormat() { waveFormatTag = WaveFormatEncoding.Gsm610; channels = 1; averageBytesPerSecond = 1625; bitsPerSample = 0; blockAlign = 65; sampleRate = 8000; extraSize = 2; samplesPerBlock = 320; } public override void Serialize(BinaryWriter writer) { base.Serialize(writer); writer.Write(samplesPerBlock); } } [StructLayout(LayoutKind.Sequential, Pack = 2)] public class ImaAdpcmWaveFormat : WaveFormat { private short samplesPerBlock; private ImaAdpcmWaveFormat() { } public ImaAdpcmWaveFormat(int sampleRate, int channels, int bitsPerSample) { waveFormatTag = WaveFormatEncoding.DviAdpcm; base.sampleRate = sampleRate; base.channels = (short)channels; base.bitsPerSample = (short)bitsPerSample; extraSize = 2; blockAlign = 0; averageBytesPerSecond = 0; samplesPerBlock = 0; } } [StructLayout(LayoutKind.Sequential, Pack = 2)] public class Mp3WaveFormat : WaveFormat { public Mp3WaveFormatId id; public Mp3WaveFormatFlags flags; public ushort blockSize; public ushort framesPerBlock; public ushort codecDelay; private const short Mp3WaveFormatExtraBytes = 12; public Mp3WaveFormat(int sampleRate, int channels, int blockSize, int bitRate) { waveFormatTag = WaveFormatEncoding.MpegLayer3; base.channels = (short)channels; averageBytesPerSecond = bitRate / 8; bitsPerSample = 0; blockAlign = 1; base.sampleRate = sampleRate; extraSize = 12; id = Mp3WaveFormatId.Mpeg; flags = Mp3WaveFormatFlags.PaddingIso; this.blockSize = (ushort)blockSize; framesPerBlock = 1; codecDelay = 0; } } [Flags] public enum Mp3WaveFormatFlags { PaddingIso = 0, PaddingOn = 1, PaddingOff = 2 } public enum Mp3WaveFormatId : ushort { Unknown, Mpeg, ConstantFrameSize } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal class OggWaveFormat : WaveFormat { public uint dwVorbisACMVersion; public uint dwLibVorbisVersion; } [StructLayout(LayoutKind.Sequential, Pack = 2)] public class TrueSpeechWaveFormat : WaveFormat { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] private short[] unknown; public TrueSpeechWaveFormat() { waveFormatTag = WaveFormatEncoding.DspGroupTrueSpeech; channels = 1; averageBytesPerSecond = 1067; bitsPerSample = 1; blockAlign = 32; sampleRate = 8000; extraSize = 32; unknown = new short[16]; unknown[0] = 1; unknown[1] = 240; } public override void Serialize(BinaryWriter writer) { base.Serialize(writer); short[] array = unknown; foreach (short value in array) { writer.Write(value); } } } [StructLayout(LayoutKind.Sequential, Pack = 2)] public class WaveFormat { protected WaveFormatEncoding waveFormatTag; protected short channels; protected int sampleRate; protected int averageBytesPerSecond; protected short blockAlign; protected short bitsPerSample; protected short extraSize; public WaveFormatEncoding Encoding => waveFormatTag; public int Channels => channels; public int SampleRate => sampleRate; public int AverageBytesPerSecond => averageBytesPerSecond; public virtual int BlockAlign => blockAlign; public int BitsPerSample => bitsPerSample; public int ExtraSize => extraSize; public WaveFormat() : this(44100, 16, 2) { } public WaveFormat(int sampleRate, int channels) : this(sampleRate, 16, channels) { } public int ConvertLatencyToByteSize(int milliseconds) { int num = (int)((double)AverageBytesPerSecond / 1000.0 * (double)milliseconds); if (num % BlockAlign != 0) { num = num + BlockAlign - num % BlockAlign; } return num; } public static WaveFormat CreateCustomFormat(WaveFormatEncoding tag, int sampleRate, int channels, int averageBytesPerSecond, int blockAlign, int bitsPerSample) { return new WaveFormat { waveFormatTag = tag, channels = (short)channels, sampleRate = sampleRate, averageBytesPerSecond = averageBytesPerSecond, blockAlign = (short)blockAlign, bitsPerSample = (short)bitsPerSample, extraSize = 0 }; } public static WaveFormat CreateALawFormat(int sampleRate, int channels) { return CreateCustomFormat(WaveFormatEncoding.ALaw, sampleRate, channels, sampleRate * channels, channels, 8); } public static WaveFormat CreateMuLawFormat(int sampleRate, int channels) { return CreateCustomFormat(WaveFormatEncoding.MuLaw, sampleRate, channels, sampleRate * channels, channels, 8); } public WaveFormat(int rate, int bits, int channels) { if (channels < 1) { throw new ArgumentOutOfRangeException("channels", "Channels must be 1 or greater"); } waveFormatTag = WaveFormatEncoding.Pcm; this.channels = (short)channels; sampleRate = rate; bitsPerSample = (short)bits; extraSize = 0; blockAlign = (short)(channels * (bits / 8)); averageBytesPerSecond = sampleRate * blockAlign; } public static WaveFormat CreateIeeeFloatWaveFormat(int sampleRate, int channels) { WaveFormat waveFormat = new WaveFormat(); waveFormat.waveFormatTag = WaveFormatEncoding.IeeeFloat; waveFormat.channels = (short)channels; waveFormat.bitsPerSample = 32; waveFormat.sampleRate = sampleRate; waveFormat.blockAlign = (short)(4 * channels); waveFormat.averageBytesPerSecond = sampleRate * waveFormat.blockAlign; waveFormat.extraSize = 0; return waveFormat; } public static WaveFormat MarshalFromPtr(IntPtr pointer) { WaveFormat waveFormat = Marshal.PtrToStructure<WaveFormat>(pointer); switch (waveFormat.Encoding) { case WaveFormatEncoding.Pcm: waveFormat.extraSize = 0; break; case WaveFormatEncoding.Extensible: waveFormat = Marshal.PtrToStructure<WaveFormatExtensible>(pointer); break; case WaveFormatEncoding.Adpcm: waveFormat = Marshal.PtrToStructure<AdpcmWaveFormat>(pointer); break; case WaveFormatEncoding.Gsm610: waveFormat = Marshal.PtrToStructure<Gsm610WaveFormat>(pointer); break; default: if (waveFormat.ExtraSize > 0) { waveFormat = Marshal.PtrToStructure<WaveFormatExtraData>(pointer); } break; } return waveFormat; } public static IntPtr MarshalToPtr(WaveFormat format) { IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(format)); Marshal.StructureToPtr(format, intPtr, fDeleteOld: false); return intPtr; } public static WaveFormat FromFormatChunk(BinaryReader br, int formatChunkLength) { WaveFormatExtraData waveFormatExtraData = new WaveFormatExtraData(); waveFormatExtraData.ReadWaveFormat(br, formatChunkLength); waveFormatExtraData.ReadExtraData(br); return waveFormatExtraData; } private void ReadWaveFormat(BinaryReader br, int formatChunkLength) { if (formatChunkLength < 16) { throw new InvalidDataException("Invalid WaveFormat Structure"); } waveFormatTag = (WaveFormatEncoding)br.ReadUInt16(); channels = br.ReadInt16(); sampleRate = br.ReadInt32(); averageBytesPerSecond = br.ReadInt32(); blockAlign = br.ReadInt16(); bitsPerSample = br.ReadInt16(); if (formatChunkLength > 16) { extraSize = br.ReadInt16(); if (extraSize != formatChunkLength - 18) { extraSize = (short)(formatChunkLength - 18); } } } public WaveFormat(BinaryReader br) { int formatChunkLength = br.ReadInt32(); ReadWaveFormat(br, formatChunkLength); } public override string ToString() { switch (waveFormatTag) { case WaveFormatEncoding.Pcm: case WaveFormatEncoding.Extensible: return $"{bitsPerSample} bit PCM: {sampleRate}Hz {channels} channels"; case WaveFormatEncoding.IeeeFloat: return $"{bitsPerSample} bit IEEFloat: {sampleRate}Hz {channels} channels"; default: return waveFormatTag.ToString(); } } public override bool Equals(object obj) { if (obj is WaveFormat waveFormat) { if (waveFormatTag == waveFormat.waveFormatTag && channels == waveFormat.channels && sampleRate == waveFormat.sampleRate && averageBytesPerSecond == waveFormat.averageBytesPerSecond && blockAlign == waveFormat.blockAlign) { return bitsPerSample == waveFormat.bitsPerSample; } return false; } return false; } public override int GetHashCode() { return (int)waveFormatTag ^ (int)channels ^ sampleRate ^ averageBytesPerSecond ^ blockAlign ^ bitsPerSample; } public virtual void Serialize(BinaryWriter writer) { writer.Write(18 + extraSize); writer.Write((short)Encoding); writer.Write((short)Channels); writer.Write(SampleRate); writer.Write(AverageBytesPerSecond); writer.Write((short)BlockAlign); writer.Write((short)BitsPerSample); writer.Write(extraSize); } } public sealed class WaveFormatCustomMarshaler : ICustomMarshaler { private static WaveFormatCustomMarshaler marshaler; public static ICustomMarshaler GetInstance(string cookie) { if (marshaler == null) { marshaler = new WaveFormatCustomMarshaler(); } return marshaler; } public void CleanUpManagedData(object ManagedObj) { } public void CleanUpNativeData(IntPtr pNativeData) { Marshal.FreeHGlobal(pNativeData); } public int GetNativeDataSize() { throw new NotImplementedException(); } public IntPtr MarshalManagedToNative(object ManagedObj) { return WaveFormat.MarshalToPtr((WaveFormat)ManagedObj); } public object MarshalNativeToManaged(IntPtr pNativeData) { return WaveFormat.MarshalFromPtr(pNativeData); } } public enum WaveFormatEncoding : ushort { Unknown = 0, Pcm = 1, Adpcm = 2, IeeeFloat = 3, Vselp = 4, IbmCvsd = 5, ALaw = 6, MuLaw = 7, Dts = 8, Drm = 9, WmaVoice9 = 10, OkiAdpcm = 16, DviAdpcm = 17, ImaAdpcm = 17, MediaspaceAdpcm = 18, SierraAdpcm = 19, G723Adpcm = 20, DigiStd = 21, DigiFix = 22, DialogicOkiAdpcm = 23, MediaVisionAdpcm = 24, CUCodec = 25, YamahaAdpcm = 32, SonarC = 33, DspGroupTrueSpeech = 34, EchoSpeechCorporation1 = 35, AudioFileAf36 = 36, Aptx = 37, AudioFileAf10 = 38, Prosody1612 = 39, Lrc = 40, DolbyAc2 = 48, Gsm610 = 49, MsnAudio = 50, AntexAdpcme = 51, ControlResVqlpc = 52, DigiReal = 53, DigiAdpcm = 54, ControlResCr10 = 55, WAVE_FORMAT_NMS_VBXADPCM = 56, WAVE_FORMAT_CS_IMAADPCM = 57, WAVE_FORMAT_ECHOSC3 = 58, WAVE_FORMAT_ROCKWELL_ADPCM = 59, WAVE_FORMAT_ROCKWELL_DIGITALK = 60, WAVE_FORMAT_XEBEC = 61, WAVE_FORMAT_G721_ADPCM = 64, WAVE_FORMAT_G728_CELP = 65, WAVE_FORMAT_MSG723 = 66, Mpeg = 80, WAVE_FORMAT_RT24 = 82, WAVE_FORMAT_PAC = 83, MpegLayer3 = 85, WAVE_FORMAT_LUCENT_G723 = 89, WAVE_FORMAT_CIRRUS = 96, WAVE_FORMAT_ESPCM = 97, WAVE_FORMAT_VOXWARE = 98, WAVE_FORMAT_CANOPUS_ATRAC = 99, WAVE_FORMAT_G726_ADPCM = 100, WAVE_FORMAT_G722_ADPCM = 101, WAVE_FORMAT_DSAT_DISPLAY = 103, WAVE_FORMAT_VOXWARE_BYTE_ALIGNED = 105, WAVE_FORMAT_VOXWARE_AC8 = 112, WAVE_FORMAT_VOXWARE_AC10 = 113, WAVE_FORMAT_VOXWARE_AC16 = 114, WAVE_FORMAT_VOXWARE_AC20 = 115, WAVE_FORMAT_VOXWARE_RT24 = 116, WAVE_FORMAT_VOXWARE_RT29 = 117, WAVE_FORMAT_VOXWARE_RT29HW = 118, WAVE_FORMAT_VOXWARE_VR12 = 119, WAVE_FORMAT_VOXWARE_VR18 = 120, WAVE_FORMAT_VOXWARE_TQ40 = 121, WAVE_FORMAT_SOFTSOUND = 128, WAVE_FORMAT_VOXWARE_TQ60 = 129, WAVE_FORMAT_MSRT24 = 130, WAVE_FORMAT_G729A = 131, WAVE_FORMAT_MVI_MVI2 = 132, WAVE_FORMAT_DF_G726 = 133, WAVE_FORMAT_DF_GSM610 = 134, WAVE_FORMAT_ISIAUDIO = 136, WAVE_FORMAT_ONLIVE = 137, WAVE_FORMAT_SBC24 = 145, WAVE_FORMAT_DOLBY_AC3_SPDIF = 146, WAVE_FORMAT_MEDIASONIC_G723 = 147, WAVE_FORMAT_PROSODY_8KBPS = 148, WAVE_FORMAT_ZYXEL_ADPCM = 151, WAVE_FORMAT_PHILIPS_LPCBB = 152, WAVE_FORMAT_PACKED = 153, WAVE_FORMAT_MALDEN_PHONYTALK = 160, Gsm = 161, G729 = 162, G723 = 163, Acelp = 164, RawAac = 255, WAVE_FORMAT_RHETOREX_ADPCM = 256, WAVE_FORMAT_IRAT = 257, WAVE_FORMAT_VIVO_G723 = 273, WAVE_FORMAT_VIVO_SIREN = 274, WAVE_FORMAT_DIGITAL_G723 = 291, WAVE_FORMAT_SANYO_LD_ADPCM = 293, WAVE_FORMAT_SIPROLAB_ACEPLNET = 304, WAVE_FORMAT_SIPROLAB_ACELP4800 = 305, WAVE_FORMAT_SIPROLAB_ACELP8V3 = 306, WAVE_FORMAT_SIPROLAB_G729 = 307, WAVE_FORMAT_SIPROLAB_G729A = 308, WAVE_FORMAT_SIPROLAB_KELVIN = 309, WAVE_FORMAT_G726ADPCM = 320, WAVE_FORMAT_QUALCOMM_PUREVOICE = 336, WAVE_FORMAT_QUALCOMM_HALFRATE = 337, WAVE_FORMAT_TUBGSM = 341, WAVE_FORMAT_MSAUDIO1 = 352, WindowsMediaAudio = 353, WindowsMediaAudioProfessional = 354, WindowsMediaAudioLosseless = 355, WindowsMediaAudioSpdif = 356, WAVE_FORMAT_UNISYS_NAP_ADPCM = 368, WAVE_FORMAT_UNISYS_NAP_ULAW = 369, WAVE_FORMAT_UNISYS_NAP_ALAW = 370, WAVE_FORMAT_UNISYS_NAP_16K = 371, WAVE_FORMAT_CREATIVE_ADPCM = 512, WAVE_FORMAT_CREATIVE_FASTSPEECH8 = 514, WAVE_FORMAT_CREATIVE_FASTSPEECH10 = 515, WAVE_FORMAT_UHER_ADPCM = 528, WAVE_FORMAT_QUARTERDECK = 544, WAVE_FORMAT_ILINK_VC = 560, WAVE_FORMAT_RAW_SPORT = 576, WAVE_FORMAT_ESST_AC3 = 577, WAVE_FORMAT_IPI_HSX = 592, WAVE_FORMAT_IPI_RPELP = 593, WAVE_FORMAT_CS2 = 608, WAVE_FORMAT_SONY_SCX = 624, WAVE_FORMAT_FM_TOWNS_SND = 768, WAVE_FORMAT_BTV_DIGITAL = 1024, WAVE_FORMAT_QDESIGN_MUSIC = 1104, WAVE_FORMAT_VME_VMPCM = 1664, WAVE_FORMAT_TPC = 1665, WAVE_FORMAT_OLIGSM = 4096, WAVE_FORMAT_OLIADPCM = 4097, WAVE_FORMAT_OLICELP = 4098, WAVE_FORMAT_OLISBC = 4099, WAVE_FORMAT_OLIOPR = 4100, WAVE_FORMAT_LH_CODEC = 4352, WAVE_FORMAT_NORRIS = 5120, WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS = 5376, MPEG_ADTS_AAC = 5632, MPEG_RAW_AAC = 5633, MPEG_LOAS = 5634, NOKIA_MPEG_ADTS_AAC = 5640, NOKIA_MPEG_RAW_AAC = 5641, VODAFONE_MPEG_ADTS_AAC = 5642, VODAFONE_MPEG_RAW_AAC = 5643, MPEG_HEAAC = 5648, WAVE_FORMAT_DVM = 8192, Vorbis1 = 26447, Vorbis2 = 26448, Vorbis3 = 26449, Vorbis1P = 26479, Vorbis2P = 26480, Vorbis3P = 26481, Extensible = 65534, WAVE_FORMAT_DEVELOPMENT = ushort.MaxValue } [StructLayout(LayoutKind.Sequential, Pack = 2)] public class WaveFormatExtensible : WaveFormat { private short wValidBitsPerSample; private int dwChannelMask; private Guid subFormat; public Guid SubFormat => subFormat; private WaveFormatExtensible() { } public WaveFormatExtensible(int rate, int bits, int channels) : base(rate, bits, channels) { waveFormatTag = WaveFormatEncoding.Extensible; extraSize = 22; wValidBitsPerSample = (short)bits; for (int i = 0; i < channels; i++) { dwChannelMask |= 1 << i; } if (bits == 32) { subFormat = AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT; } else { subFormat = AudioMediaSubtypes.MEDIASUBTYPE_PCM; } } public WaveFormat ToStandardWaveFormat() { if (subFormat == AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT && bitsPerSample == 32) { return WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels); } if (subFormat == AudioMediaSubtypes.MEDIASUBTYPE_PCM) { return new WaveFormat(sampleRate, bitsPerSample, channels); } return this; } public override void Serialize(BinaryWriter writer) { base.Serialize(writer); writer.Write(wValidBitsPerSample); writer.Write(dwChannelMask); byte[] array = subFormat.ToByteArray(); writer.Write(array, 0, array.Length); } public override string ToString() { return "WAVE_FORMAT_EXTENSIBLE " + AudioMediaSubtypes.GetAudioSubtypeName(subFormat) + " " + $"{base.SampleRate}Hz {base.Channels} channels {base.BitsPerSample} bit"; } } [StructLayout(LayoutKind.Sequential, Pack = 2)] public class WaveFormatExtraData : WaveFormat { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)] private byte[] extraData = new byte[100]; public byte[] ExtraData => extraData; internal WaveFormatExtraData() { } public WaveFormatExtraData(BinaryReader reader) : base(reader) { ReadExtraData(reader); } internal void ReadExtraData(BinaryReader reader) { if (extraSize > 0) { reader.Read(extraData, 0, extraSize); } } public override void Serialize(BinaryWriter writer) { base.Serialize(writer); if (extraSize > 0) { writer.Write(extraData, 0, extraSize); } } } public interface IWaveIn : IDisposable { WaveFormat WaveFormat { get; set; } event EventHandler<WaveInEventArgs> DataAvailable; event EventHandler<StoppedEventArgs> RecordingStopped; void StartRecording(); void StopRecording(); } public class WaveInEventArgs : EventArgs { private byte[] buffer; private int bytes; public byte[] Buffer => buffer; public int BytesRecorded => bytes; public WaveInEventArgs(byte[] buffer, int bytes) { this.buffer = buffer; this.bytes = bytes; } } public class AiffFileWriter : Stream { private Stream outStream; private BinaryWriter writer; private long dataSizePos; private long commSampleCountPos; private long dataChunkSize = 8L; private WaveFormat format; private string filename; private byte[] value24 = new byte[3]; public string Filename => filename; public override long Length => dataChunkSize; public WaveFormat WaveFormat => format; public override bool CanRead => false; public override bool CanWrite => true; public override bool CanSeek => false; public override long Position { get { return dataChunkSize; } set { throw new InvalidOperationException("Repositioning an AiffFileWriter is not supported"); } } public static void CreateAiffFile(string filename, WaveStream sourceProvider) { using AiffFileWriter aiffFileWriter = new AiffFileWriter(filename, sourceProvider.WaveFormat); byte[] array = new byte[16384]; while (sourceProvider.Position < sourceProvider.Length) { int count = Math.Min((int)(sourceProvider.Length - sourceProvider.Position), array.Length); int num = sourceProvider.Read(array, 0, count); if (num == 0) { break; } aiffFileWriter.Write(array, 0, num); } } public AiffFileWriter(Stream outStream, WaveFormat format) { this.outStream = outStream; this.format = format; writer = new BinaryWriter(outStream, Encoding.UTF8); writer.Write(Encoding.UTF8.GetBytes("FORM")); writer.Write(0); writer.Write(Encoding.UTF8.GetBytes("AIFF")); CreateCommChunk(); WriteSsndChunkHeader(); } public AiffFileWriter(string filename, WaveFormat format) : this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), format) { this.filename = filename; } private void WriteSsndChunkHeader() { writer.Write(Encoding.UTF8.GetBytes("SSND")); dataSizePos = outStream.Position; writer.Write(0); writer.Write(0); writer.Write(SwapEndian(format.BlockAlign)); } private byte[] SwapEndian(short n) { return new byte[2] { (byte)(n >> 8), (byte)((uint)n & 0xFFu) }; } private byte[] SwapEndian(int n) { return new byte[4] { (byte)((uint)(n >> 24) & 0xFFu), (byte)((uint)(n >> 16) & 0xFFu), (byte)((uint)(n >> 8) & 0xFFu), (byte)((uint)n & 0xFFu) }; } private void CreateCommChunk() { writer.Write(Encoding.UTF8.GetBytes("COMM")); writer.Write(SwapEndian(18)); writer.Write(SwapEndian((short)format.Channels)); commSampleCountPos = outStream.Position; writer.Write(0); writer.Write(SwapEndian((short)format.BitsPerSample)); writer.Write(IEEE.ConvertToIeeeExtended(format.SampleRate)); } public override int Read(byte[] buffer, int offset, int count) { throw new InvalidOperationException("Cannot read from an AiffFileWriter"); } public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException("Cannot seek within an AiffFileWriter"); } public override void SetLength(long value) { throw new InvalidOperationException("Cannot set length of an AiffFileWriter"); } public override void Write(byte[] data, int offset, int count) { byte[] array = new byte[data.Length]; int num = format.BitsPerSample / 8; for (int i = 0; i < data.Length; i++) { int num2 = (int)Math.Floor((double)i / (double)num) * num + (num - i % num - 1); array[i] = data[num2]; } outStream.Write(array, offset, count); dataChunkSize += count; } public void WriteSample(float sample) { if (WaveFormat.BitsPerSample == 16) { writer.Write(SwapEndian((short)(32767f * sample))); dataChunkSize += 2L; } else if (WaveFormat.BitsPerSample == 24) { byte[] bytes = BitConverter.GetBytes((int)(2.1474836E+09f * sample)); value24[2] = bytes[1]; value24[1] = bytes[2]; value24[0] = bytes[3]; writer.Write(value24); dataChunkSize += 3L; } else { if (WaveFormat.BitsPerSample != 32 || WaveFormat.Encoding != WaveFormatEncoding.Extensible) { throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported"); } writer.Write(SwapEndian(65535 * (int)sample)); dataChunkSize += 4L; } } public void WriteSamples(float[] samples, int offset, int count) { for (int i = 0; i < count; i++) { WriteSample(samples[offset + i]); } } public void WriteSamples(short[] samples, int offset, int count) { if (WaveFormat.BitsPerSample == 16) { for (int i = 0; i < count; i++) { writer.Write(SwapEndian(samples[i + offset])); } dataChunkSize += count * 2; } else if (WaveFormat.BitsPerSample == 24) { for (int j = 0; j < count; j++) { byte[] bytes = BitConverter.GetBytes(65535 * samples[j + offset]); value24[2] = bytes[1]; value24[1] = bytes[2]; value24[0] = bytes[3]; writer.Write(value24); } dataChunkSize += count * 3; } else { if (WaveFormat.BitsPerSample != 32 || WaveFormat.Encoding != WaveFormatEncoding.Extensible) { throw new InvalidOperationException("Only 16, 24 or 32 bit PCM audio data supported"); } for (int k = 0; k < count; k++) { writer.Write(SwapEndian(65535 * samples[k + offset])); } dataChunkSize += count * 4; } } public override void Flush() { writer.Flush(); } protected override void Dispose(bool disposing) { if (disposing && outStream != null) { try { UpdateHeader(writer); } finally { outStream.Dispose(); outStream = null; } } } protected virtual void UpdateHeader(BinaryWriter writer) { Flush(); writer.Seek(4, SeekOrigin.Begin); writer.Write(SwapEndian((int)(outStream.Length - 8))); UpdateCommChunk(writer); UpdateSsndChunk(writer); } private void UpdateCommChunk(BinaryWriter writer) { writer.Seek((int)commSampleCountPos, SeekOrigin.Begin); writer.Write(SwapEndian((int)(dataChunkSize * 8 / format.BitsPerSample / format.Channels))); } private void UpdateSsndChunk(BinaryWriter writer) { writer.Seek((int)dataSizePos, SeekOrigin.Begin); writer.Write(SwapEndian((int)dataChunkSize)); } ~AiffFileWriter() { Dispose(disposing: false); } } public class BextChunkInfo { public string Description { get; set; } public string Originator { get; set; } public string OriginatorReference { get; set; } public DateTime OriginationDateTime { get; set; } public string OriginationDate => OriginationDateTime.ToString("yyyy-MM-dd"); public string OriginationTime => OriginationDateTime.ToString("HH:mm:ss"); public long TimeReference { get; set; } public ushort Version => 1; public string UniqueMaterialIdentifier { get; set; } public byte[] Reserved { get; } public string CodingHistory { get; set; } public BextChunkInfo() { Reserved = new byte[190]; } } public class BwfWriter : IDisposable { private readonly WaveFormat format; private readonly BinaryWriter writer; private readonly long dataChunkSizePosition; private long dataLength; private bool isDisposed; public BwfWriter(string filename, WaveFormat format, BextChunkInfo bextChunkInfo) { this.format = format; writer = new BinaryWriter(File.OpenWrite(filename)); writer.Write(Encoding.UTF8.GetBytes("RIFF")); writer.Write(0); writer.Write(Encoding.UTF8.GetBytes("WAVE")); writer.Write(Encoding.UTF8.GetBytes("JUNK")); writer.Write(28); writer.Write(0L); writer.Write(0L); writer.Write(0L); writer.Write(0); writer.Write(Encoding.UTF8.GetBytes("bext")); byte[] bytes = Encoding.ASCII.GetBytes(bextChunkInfo.CodingHistory ?? ""); int num = 602 + bytes.Length; if (num % 2 != 0) { num++; } writer.Write(num); _ = writer.BaseStream.Position; writer.Write(GetAsBytes(bextChunkInfo.Description, 256)); writer.Write(GetAsBytes(bextChunkInfo.Originator, 32)); writer.Write(GetAsBytes(bextChunkInfo.OriginatorReference, 32)); writer.Write(GetAsBytes(bextChunkInfo.OriginationDate, 10)); writer.Write(GetAsBytes(bextChunkInfo.OriginationTime, 8)); writer.Write(bextChunkInfo.TimeReference); writer.Write(bextChunkInfo.Version); writer.Write(GetAsBytes(bextChunkInfo.UniqueMaterialIdentifier, 64)); writer.Write(bextChunkInfo.Reserved); writer.Write(bytes); if (bytes.Length % 2 != 0) { writer.Write((byte)0); } writer.Write(Encoding.UTF8.GetBytes("fmt ")); format.Serialize(writer); writer.Write(Encoding.UTF8.GetBytes("data")); dataChunkSizePosition = writer.BaseStream.Position; writer.Write(-1); } public void Write(byte[] buffer, int offset, int count) { if (isDisposed) { throw new ObjectDisposedException("This BWF Writer already disposed"); } writer.Write(buffer, offset, count); dataLength += count; } public void Flush() { if (isDisposed) { throw new ObjectDisposedException("This BWF Writer already disposed"); } writer.Flush(); FixUpChunkSizes(restorePosition: true); } private void FixUpChunkSizes(bool restorePosition) { long position = writer.BaseStream.Position; bool num = dataLength > int.MaxValue; long num2 = writer.BaseStream.Length - 8; if (num) { int num3 = format.BitsPerSample / 8 * format.Channels; writer.BaseStream.Position = 0L; writer.Write(Encoding.UTF8.GetBytes("RF64")); writer.Write(-1); writer.BaseStream.Position += 4L; writer.Write(Encoding.UTF8.GetBytes("ds64")); writer.BaseStream.Position += 4L; writer.Write(num2); writer.Write(dataLength); writer.Write(dataLength / num3); } else { writer.BaseStream.Position = 4L; writer.Write((uint)num2); writer.BaseStream.Position = dataChunkSizePosition; writer.Write((uint)dataLength); } if (restorePosition) { writer.BaseStream.Position = position; } } public void Dispose() { if (!isDisposed) { FixUpChunkSizes(restorePosition: false); writer.Dispose(); isDisposed = true; } } private static byte[] GetAsBytes(string message, int byteSize) { byte[] array = new byte[byteSize]; byte[] bytes = Encoding.ASCII.GetBytes(message ?? ""); Array.Copy(bytes, array, Math.Min(bytes.Length, byteSize)); return array; } } public class CueWaveFileWriter : WaveFileWriter { private CueList cues; public CueWaveFileWriter(string fileName, WaveFormat waveFormat) : base(fileName, waveFormat) { } public void AddCue(int position, string label) { if (cues == null) { cues = new CueList(); } cues.Add(new Cue(position, label)); } private void WriteCues(BinaryWriter w) { if (cues != null) { int count = cues.GetRiffChunks().Length; w.Seek(0, SeekOrigin.End); if (w.BaseStream.Length % 2 == 1) { w.Write((byte)0); } w.Write(cues.GetRiffChunks(), 0, count); w.Seek(4, SeekOrigin.Begin); w.Write((int)(w.BaseStream.Length - 8)); } } protected override void UpdateHeader(BinaryWriter writer) { base.UpdateHeader(writer); WriteCues(writer); } } public class DirectSoundOut : IWavePlayer, IDisposable { [StructLayout(LayoutKind.Sequential, Pack = 2)] internal class BufferDescription { public int dwSize; [MarshalAs(UnmanagedType.U4)] public DirectSoundBufferCaps dwFlags; public uint dwBufferBytes; public int dwReserved; public IntPtr lpwfxFormat; public Guid guidAlgo; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal class BufferCaps { public int dwSize; public int dwFlags; public int dwBufferBytes; public int dwUnlockTransferRate; public int dwPlayCpuOverhead; } internal enum DirectSoundCooperativeLevel : uint { DSSCL_NORMAL = 1u, DSSCL_PRIORITY, DSSCL_EXCLUSIVE, DSSCL_WRITEPRIMARY } [Flags] internal enum DirectSoundPlayFlags : uint { DSBPLAY_LOOPING = 1u, DSBPLAY_LOCHARDWARE = 2u, DSBPLAY_LOCSOFTWARE = 4u, DSBPLAY_TERMINATEBY_TIME = 8u, DSBPLAY_TERMINATEBY_DISTANCE = 0x10u, DSBPLAY_TERMINATEBY_PRIORITY = 0x20u } internal enum DirectSoundBufferLockFlag : uint { None, FromWriteCursor, EntireBuffer } [Flags] internal enum DirectSoundBufferStatus : uint { DSBSTATUS_PLAYING = 1u, DSBSTATUS_BUFFERLOST = 2u, DSBSTATUS_LOOPING = 4u, DSBSTATUS_LOCHARDWARE = 8u, DSBSTATUS_LOCSOFTWARE = 0x10u, DSBSTATUS_TERMINATED = 0x20u } [Flags] internal enum DirectSoundBufferCaps : uint { DSBCAPS_PRIMARYBUFFER = 1u, DSBCAPS_STATIC = 2u, DSBCAPS_LOCHARDWARE = 4u, DSBCAPS_LOCSOFTWARE = 8u, DSBCAPS_CTRL3D = 0x10u, DSBCAPS_CTRLFREQUENCY = 0x20u, DSBCAPS_CTRLPAN = 0x40u, DSBCAPS_CTRLVOLUME = 0x80u, DSBCAPS_CTRLPOSITIONNOTIFY = 0x100u, DSBCAPS_CTRLFX = 0x200u, DSBCAPS_STICKYFOCUS = 0x4000u, DSBCAPS_GLOBALFOCUS = 0x8000u, DSBCAPS_GETCURRENTPOSITION2 = 0x10000u, DSBCAPS_MUTE3DATMAXDISTANCE = 0x20000u, DSBCAPS_LOCDEFER = 0x40000u } internal struct DirectSoundBufferPositionNotify { public uint dwOffset; public IntPtr hEventNotify; } [ComImport] [Guid("279AFA83-4981-11CE-A521-0020AF0BE560")] [SuppressUnmanagedCodeSecurity] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IDirectSound { void CreateSoundBuffer([In] BufferDescription desc, [MarshalAs(UnmanagedType.Interface)] out object dsDSoundBuffer, IntPtr pUnkOuter); void GetCaps(IntPtr caps); void DuplicateSoundBuffer([In][MarshalAs(UnmanagedType.Interface)] IDirectSoundBuffer bufferOriginal, [In][MarshalAs(UnmanagedType.Interface)] IDirectSoundBuffer bufferDuplicate); void SetCooperativeLevel(IntPtr HWND, [In][MarshalAs(UnmanagedType.U4)] DirectSoundCooperativeLevel dwLevel); void Compact(); void GetSpeakerConfig(IntPtr pdwSpeakerConfig); void SetSpeakerConfig(uint pdwSpeakerConfig); void Initialize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guid); } [ComImport] [Guid("279AFA85-4981-11CE-A521-0020AF0BE560")] [SuppressUnmanagedCodeSecurity] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IDirectSoundBuffer { void GetCaps([MarshalAs(UnmanagedType.LPStruct)] BufferCaps pBufferCaps); void GetCurrentPosition(out uint currentPlayCursor, out uint currentWriteCursor); void GetFormat(); [return: MarshalAs(UnmanagedType.I4)] int GetVolume(); void GetPan(out uint pan); [return: MarshalAs(UnmanagedType.I4)] int GetFrequency(); [return: MarshalAs(UnmanagedType.U4)] DirectSoundBufferStatus GetStatus(); void Initialize([In][MarshalAs(UnmanagedType.Interface)] IDirectSound directSound, [In] BufferDescription desc); void Lock(int dwOffset, uint dwBytes, out IntPtr audioPtr1, out int audioBytes1, out IntPtr audioPtr2, out int audioBytes2, [MarshalAs(UnmanagedType.U4)] DirectSoundBufferLockFlag dwFlags); void Play(uint dwReserved1, uint dwPriority, [In][MarshalAs(UnmanagedType.U4)] DirectSoundPlayFlags dwFlags); void SetCurrentPosition(uint dwNewPosition); void SetFormat([In] WaveFormat pcfxFormat); void SetVolume(int volume); void SetPan(uint pan); void SetFrequency(uint frequency); void Stop(); void Unlock(IntPtr pvAudioPtr1, int dwAudioBytes1, IntPtr pvAudioPtr2, int dwAudioBytes2); void Restore(); } [ComImport] [Guid("b0210783-89cd-11d0-af08-00a0c925cd16")] [SuppressUnmanagedCodeSecurity] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IDirectSoundNotify { void SetNotificationPositions(uint dwPositionNotifies, [In][MarshalAs(UnmanagedType.LPArray)] DirectSoundBufferPositionNotify[] pcPositionNotifies); } private delegate bool DSEnumCallback(IntPtr lpGuid, IntPtr lpcstrDescription, IntPtr lpcstrModule, IntPtr lpContext); private PlaybackState playbackState; private WaveFormat waveFormat; private int samplesTotalSize; private int samplesFrameSize; private int nextSamplesWriteIndex; private int desiredLatency; private Guid device; private byte[] samples; private IWaveProvider waveStream; private IDirectSound directSound; private IDirectSoundBuffer primarySoundBuffer; private IDirectSoundBuffer sec
deps/NAudio.dll
Decompiled a day agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using NAudio.Wave.SampleProviders; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("Mark Heath & Contributors")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Mark Heath 2023")] [assembly: AssemblyDescription("NAudio, an audio library for .NET")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("NAudio")] [assembly: AssemblyTitle("NAudio")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.2.1.0")] [module: UnverifiableCode] namespace NAudio.Wave; public class AudioFileReader : WaveStream, ISampleProvider { private WaveStream readerStream; private readonly SampleChannel sampleChannel; private readonly int destBytesPerSample; private readonly int sourceBytesPerSample; private readonly long length; private readonly object lockObject; public string FileName { get; } public override WaveFormat WaveFormat => sampleChannel.WaveFormat; public override long Length => length; public override long Position { get { return SourceToDest(((Stream)(object)readerStream).Position); } set { lock (lockObject) { ((Stream)(object)readerStream).Position = DestToSource(value); } } } public float Volume { get { return sampleChannel.Volume; } set { sampleChannel.Volume = value; } } public AudioFileReader(string fileName) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown lockObject = new object(); FileName = fileName; CreateReaderStream(fileName); sourceBytesPerSample = readerStream.WaveFormat.BitsPerSample / 8 * readerStream.WaveFormat.Channels; sampleChannel = new SampleChannel((IWaveProvider)(object)readerStream, false); destBytesPerSample = 4 * sampleChannel.WaveFormat.Channels; length = SourceToDest(((Stream)(object)readerStream).Length); } private void CreateReaderStream(string fileName) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Invalid comparison between Unknown and I4 //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown if (fileName.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)) { readerStream = (WaveStream)new WaveFileReader(fileName); if ((int)readerStream.WaveFormat.Encoding != 1 && (int)readerStream.WaveFormat.Encoding != 3) { readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream); readerStream = (WaveStream)new BlockAlignReductionStream(readerStream); } } else if (fileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) { if (Environment.OSVersion.Version.Major < 6) { readerStream = (WaveStream)(object)new Mp3FileReader(fileName); } else { readerStream = (WaveStream)new MediaFoundationReader(fileName); } } else if (fileName.EndsWith(".aiff", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith(".aif", StringComparison.OrdinalIgnoreCase)) { readerStream = (WaveStream)new AiffFileReader(fileName); } else { readerStream = (WaveStream)new MediaFoundationReader(fileName); } } public override int Read(byte[] buffer, int offset, int count) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown WaveBuffer val = new WaveBuffer(buffer); int count2 = count / 4; return Read(val.FloatBuffer, offset / 4, count2) * 4; } public int Read(float[] buffer, int offset, int count) { lock (lockObject) { return sampleChannel.Read(buffer, offset, count); } } private long SourceToDest(long sourceBytes) { return destBytesPerSample * (sourceBytes / sourceBytesPerSample); } private long DestToSource(long destBytes) { return sourceBytesPerSample * (destBytes / destBytesPerSample); } protected override void Dispose(bool disposing) { if (disposing && readerStream != null) { ((Stream)(object)readerStream).Dispose(); readerStream = null; } ((Stream)this).Dispose(disposing); } } public class Mp3FileReader : Mp3FileReaderBase { public Mp3FileReader(string mp3FileName) : base((Stream)File.OpenRead(mp3FileName), new FrameDecompressorBuilder(CreateAcmFrameDecompressor), true) { }//IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown public Mp3FileReader(Stream inputStream) : base(inputStream, new FrameDecompressorBuilder(CreateAcmFrameDecompressor), false) { }//IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown public static IMp3FrameDecompressor CreateAcmFrameDecompressor(WaveFormat mp3Format) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return (IMp3FrameDecompressor)new AcmMp3FrameDecompressor(mp3Format); } }
deps/NAudio.Midi.dll
Decompiled a day agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using NAudio.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Mark Heath")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Mark Heath 2023")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("NAudio.Midi")] [assembly: AssemblyTitle("NAudio.Midi")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")] [assembly: AssemblyVersion("2.2.1.0")] namespace NAudio.Midi { public class ChannelAfterTouchEvent : MidiEvent { private byte afterTouchPressure; public int AfterTouchPressure { get { return afterTouchPressure; } set { if (value < 0 || value > 127) { throw new ArgumentOutOfRangeException("value", "After touch pressure must be in the range 0-127"); } afterTouchPressure = (byte)value; } } public ChannelAfterTouchEvent(BinaryReader br) { afterTouchPressure = br.ReadByte(); if ((afterTouchPressure & 0x80u) != 0) { throw new FormatException("Invalid afterTouchPressure"); } } public ChannelAfterTouchEvent(long absoluteTime, int channel, int afterTouchPressure) : base(absoluteTime, channel, MidiCommandCode.ChannelAfterTouch) { AfterTouchPressure = afterTouchPressure; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write(afterTouchPressure); } public override int GetAsShortMessage() { return base.GetAsShortMessage() + (afterTouchPressure << 8); } public override string ToString() { return $"{base.ToString()} {afterTouchPressure}"; } } public class ControlChangeEvent : MidiEvent { private MidiController controller; private byte controllerValue; public MidiController Controller { get { return controller; } set { if ((int)value < 0 || (int)value > 127) { throw new ArgumentOutOfRangeException("value", "Controller number must be in the range 0-127"); } controller = value; } } public int ControllerValue { get { return controllerValue; } set { if (value < 0 || value > 127) { throw new ArgumentOutOfRangeException("value", "Controller Value must be in the range 0-127"); } controllerValue = (byte)value; } } public ControlChangeEvent(BinaryReader br) { byte b = br.ReadByte(); controllerValue = br.ReadByte(); if ((b & 0x80u) != 0) { throw new InvalidDataException("Invalid controller"); } controller = (MidiController)b; if ((controllerValue & 0x80u) != 0) { throw new InvalidDataException($"Invalid controllerValue {controllerValue} for controller {controller}, Pos 0x{br.BaseStream.Position:X}"); } } public ControlChangeEvent(long absoluteTime, int channel, MidiController controller, int controllerValue) : base(absoluteTime, channel, MidiCommandCode.ControlChange) { Controller = controller; ControllerValue = controllerValue; } public override string ToString() { return $"{base.ToString()} Controller {controller} Value {controllerValue}"; } public override int GetAsShortMessage() { byte b = (byte)controller; return base.GetAsShortMessage() + (b << 8) + (controllerValue << 16); } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write((byte)controller); writer.Write(controllerValue); } } public class KeySignatureEvent : MetaEvent { private readonly byte sharpsFlats; private readonly byte majorMinor; public int SharpsFlats => (sbyte)sharpsFlats; public int MajorMinor => majorMinor; public KeySignatureEvent(BinaryReader br, int length) { if (length != 2) { throw new FormatException("Invalid key signature length"); } sharpsFlats = br.ReadByte(); majorMinor = br.ReadByte(); } public KeySignatureEvent(int sharpsFlats, int majorMinor, long absoluteTime) : base(MetaEventType.KeySignature, 2, absoluteTime) { this.sharpsFlats = (byte)sharpsFlats; this.majorMinor = (byte)majorMinor; } public override MidiEvent Clone() { return (KeySignatureEvent)MemberwiseClone(); } public override string ToString() { return $"{base.ToString()} {SharpsFlats} {majorMinor}"; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write(sharpsFlats); writer.Write(majorMinor); } } public class MetaEvent : MidiEvent { private MetaEventType metaEvent; internal int metaDataLength; public MetaEventType MetaEventType => metaEvent; protected MetaEvent() { } public MetaEvent(MetaEventType metaEventType, int metaDataLength, long absoluteTime) : base(absoluteTime, 1, MidiCommandCode.MetaEvent) { metaEvent = metaEventType; this.metaDataLength = metaDataLength; } public override MidiEvent Clone() { return new MetaEvent(metaEvent, metaDataLength, base.AbsoluteTime); } public static MetaEvent ReadMetaEvent(BinaryReader br) { MetaEventType metaEventType = (MetaEventType)br.ReadByte(); int num = MidiEvent.ReadVarInt(br); MetaEvent metaEvent = new MetaEvent(); if (metaEventType <= MetaEventType.SetTempo) { if (metaEventType <= MetaEventType.DeviceName) { if (metaEventType != 0) { if (metaEventType - 1 > MetaEventType.ProgramName) { goto IL_00a6; } metaEvent = new TextEvent(br, num); } else { metaEvent = new TrackSequenceNumberEvent(br, num); } } else if (metaEventType != MetaEventType.EndTrack) { if (metaEventType != MetaEventType.SetTempo) { goto IL_00a6; } metaEvent = new TempoEvent(br, num); } else if (num != 0) { throw new FormatException("End track length"); } } else if (metaEventType <= MetaEventType.TimeSignature) { if (metaEventType != MetaEventType.SmpteOffset) { if (metaEventType != MetaEventType.TimeSignature) { goto IL_00a6; } metaEvent = new TimeSignatureEvent(br, num); } else { metaEvent = new SmpteOffsetEvent(br, num); } } else if (metaEventType != MetaEventType.KeySignature) { if (metaEventType != MetaEventType.SequencerSpecific) { goto IL_00a6; } metaEvent = new SequencerSpecificEvent(br, num); } else { metaEvent = new KeySignatureEvent(br, num); } metaEvent.metaEvent = metaEventType; metaEvent.metaDataLength = num; return metaEvent; IL_00a6: byte[] array = br.ReadBytes(num); if (array.Length != num) { throw new FormatException("Failed to read metaevent's data fully"); } return new RawMetaEvent(metaEventType, 0L, array); } public override string ToString() { return $"{base.AbsoluteTime} {metaEvent}"; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write((byte)metaEvent); MidiEvent.WriteVarInt(writer, metaDataLength); } } public enum MetaEventType : byte { TrackSequenceNumber = 0, TextEvent = 1, Copyright = 2, SequenceTrackName = 3, TrackInstrumentName = 4, Lyric = 5, Marker = 6, CuePoint = 7, ProgramName = 8, DeviceName = 9, MidiChannel = 32, MidiPort = 33, EndTrack = 47, SetTempo = 81, SmpteOffset = 84, TimeSignature = 88, KeySignature = 89, SequencerSpecific = 127 } public enum MidiCommandCode : byte { NoteOff = 128, NoteOn = 144, KeyAfterTouch = 160, ControlChange = 176, PatchChange = 192, ChannelAfterTouch = 208, PitchWheelChange = 224, Sysex = 240, Eox = 247, TimingClock = 248, StartSequence = 250, ContinueSequence = 251, StopSequence = 252, AutoSensing = 254, MetaEvent = byte.MaxValue } public enum MidiController : byte { BankSelect = 0, Modulation = 1, BreathController = 2, FootController = 4, MainVolume = 7, Pan = 10, Expression = 11, BankSelectLsb = 32, Sustain = 64, Portamento = 65, Sostenuto = 66, SoftPedal = 67, LegatoFootswitch = 68, ResetAllControllers = 121, AllNotesOff = 123 } public class MidiEvent : ICloneable { private MidiCommandCode commandCode; private int channel; private int deltaTime; private long absoluteTime; public virtual int Channel { get { return channel; } set { if (value < 1 || value > 16) { throw new ArgumentOutOfRangeException("value", value, $"Channel must be 1-16 (Got {value})"); } channel = value; } } public int DeltaTime => deltaTime; public long AbsoluteTime { get { return absoluteTime; } set { absoluteTime = value; } } public MidiCommandCode CommandCode => commandCode; public static MidiEvent FromRawMessage(int rawMessage) { long num = 0L; int num2 = rawMessage & 0xFF; int num3 = (rawMessage >> 8) & 0xFF; int num4 = (rawMessage >> 16) & 0xFF; int num5 = 1; MidiCommandCode midiCommandCode; if ((num2 & 0xF0) == 240) { midiCommandCode = (MidiCommandCode)num2; } else { midiCommandCode = (MidiCommandCode)((uint)num2 & 0xF0u); num5 = (num2 & 0xF) + 1; } switch (midiCommandCode) { case MidiCommandCode.NoteOff: case MidiCommandCode.NoteOn: case MidiCommandCode.KeyAfterTouch: if (num4 > 0 && midiCommandCode == MidiCommandCode.NoteOn) { return new NoteOnEvent(num, num5, num3, num4, 0); } return new NoteEvent(num, num5, midiCommandCode, num3, num4); case MidiCommandCode.ControlChange: return new ControlChangeEvent(num, num5, (MidiController)num3, num4); case MidiCommandCode.PatchChange: return new PatchChangeEvent(num, num5, num3); case MidiCommandCode.ChannelAfterTouch: return new ChannelAfterTouchEvent(num, num5, num3); case MidiCommandCode.PitchWheelChange: return new PitchWheelChangeEvent(num, num5, num3 + (num4 << 7)); case MidiCommandCode.TimingClock: case MidiCommandCode.StartSequence: case MidiCommandCode.ContinueSequence: case MidiCommandCode.StopSequence: case MidiCommandCode.AutoSensing: return new MidiEvent(num, num5, midiCommandCode); default: throw new FormatException($"Unsupported MIDI Command Code for Raw Message {midiCommandCode}"); } } public static MidiEvent ReadNextEvent(BinaryReader br, MidiEvent previous) { int num = ReadVarInt(br); int num2 = 1; byte b = br.ReadByte(); MidiCommandCode midiCommandCode; if ((b & 0x80) == 0) { midiCommandCode = previous.CommandCode; num2 = previous.Channel; br.BaseStream.Position--; } else if ((b & 0xF0) == 240) { midiCommandCode = (MidiCommandCode)b; } else { midiCommandCode = (MidiCommandCode)(b & 0xF0u); num2 = (b & 0xF) + 1; } MidiEvent midiEvent; switch (midiCommandCode) { case MidiCommandCode.NoteOn: midiEvent = new NoteOnEvent(br); break; case MidiCommandCode.NoteOff: case MidiCommandCode.KeyAfterTouch: midiEvent = new NoteEvent(br); break; case MidiCommandCode.ControlChange: midiEvent = new ControlChangeEvent(br); break; case MidiCommandCode.PatchChange: midiEvent = new PatchChangeEvent(br); break; case MidiCommandCode.ChannelAfterTouch: midiEvent = new ChannelAfterTouchEvent(br); break; case MidiCommandCode.PitchWheelChange: midiEvent = new PitchWheelChangeEvent(br); break; case MidiCommandCode.TimingClock: case MidiCommandCode.StartSequence: case MidiCommandCode.ContinueSequence: case MidiCommandCode.StopSequence: midiEvent = new MidiEvent(); break; case MidiCommandCode.Sysex: midiEvent = SysexEvent.ReadSysexEvent(br); break; case MidiCommandCode.MetaEvent: midiEvent = MetaEvent.ReadMetaEvent(br); break; default: throw new FormatException($"Unsupported MIDI Command Code {(byte)midiCommandCode:X2}"); } midiEvent.channel = num2; midiEvent.deltaTime = num; midiEvent.commandCode = midiCommandCode; return midiEvent; } public virtual int GetAsShortMessage() { return channel - 1 + (int)commandCode; } protected MidiEvent() { } public MidiEvent(long absoluteTime, int channel, MidiCommandCode commandCode) { this.absoluteTime = absoluteTime; Channel = channel; this.commandCode = commandCode; } public virtual MidiEvent Clone() { return (MidiEvent)MemberwiseClone(); } object ICloneable.Clone() { return Clone(); } public static bool IsNoteOff(MidiEvent midiEvent) { if (midiEvent != null) { if (midiEvent.CommandCode == MidiCommandCode.NoteOn) { return ((NoteEvent)midiEvent).Velocity == 0; } return midiEvent.CommandCode == MidiCommandCode.NoteOff; } return false; } public static bool IsNoteOn(MidiEvent midiEvent) { if (midiEvent != null && midiEvent.CommandCode == MidiCommandCode.NoteOn) { return ((NoteEvent)midiEvent).Velocity > 0; } return false; } public static bool IsEndTrack(MidiEvent midiEvent) { if (midiEvent != null && midiEvent is MetaEvent metaEvent) { return metaEvent.MetaEventType == MetaEventType.EndTrack; } return false; } public override string ToString() { if ((int)commandCode >= 240) { return $"{absoluteTime} {commandCode}"; } return $"{absoluteTime} {commandCode} Ch: {channel}"; } public static int ReadVarInt(BinaryReader br) { int num = 0; for (int i = 0; i < 4; i++) { byte b = br.ReadByte(); num <<= 7; num += b & 0x7F; if ((b & 0x80) == 0) { return num; } } throw new FormatException("Invalid Var Int"); } public static void WriteVarInt(BinaryWriter writer, int value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", value, "Cannot write a negative Var Int"); } if (value > 268435455) { throw new ArgumentOutOfRangeException("value", value, "Maximum allowed Var Int is 0x0FFFFFFF"); } int num = 0; byte[] array = new byte[4]; do { array[num++] = (byte)((uint)value & 0x7Fu); value >>= 7; } while (value > 0); while (num > 0) { num--; if (num > 0) { writer.Write((byte)(array[num] | 0x80u)); } else { writer.Write(array[num]); } } } public virtual void Export(ref long absoluteTime, BinaryWriter writer) { if (this.absoluteTime < absoluteTime) { throw new FormatException("Can't export unsorted MIDI events"); } WriteVarInt(writer, (int)(this.absoluteTime - absoluteTime)); absoluteTime = this.absoluteTime; int num = (int)commandCode; if (commandCode != MidiCommandCode.MetaEvent) { num += channel - 1; } writer.Write((byte)num); } } public class MidiEventCollection : IEnumerable<IList<MidiEvent>>, IEnumerable { private int midiFileType; private readonly List<IList<MidiEvent>> trackEvents; public int Tracks => trackEvents.Count; public long StartAbsoluteTime { get; set; } public int DeltaTicksPerQuarterNote { get; } public IList<MidiEvent> this[int trackNumber] => trackEvents[trackNumber]; public int MidiFileType { get { return midiFileType; } set { if (midiFileType != value) { midiFileType = value; if (value == 0) { FlattenToOneTrack(); } else { ExplodeToManyTracks(); } } } } public MidiEventCollection(int midiFileType, int deltaTicksPerQuarterNote) { this.midiFileType = midiFileType; DeltaTicksPerQuarterNote = deltaTicksPerQuarterNote; StartAbsoluteTime = 0L; trackEvents = new List<IList<MidiEvent>>(); } public IList<MidiEvent> GetTrackEvents(int trackNumber) { return trackEvents[trackNumber]; } public IList<MidiEvent> AddTrack() { return AddTrack(null); } public IList<MidiEvent> AddTrack(IList<MidiEvent> initialEvents) { List<MidiEvent> list = new List<MidiEvent>(); if (initialEvents != null) { list.AddRange(initialEvents); } trackEvents.Add(list); return list; } public void RemoveTrack(int track) { trackEvents.RemoveAt(track); } public void Clear() { trackEvents.Clear(); } public void AddEvent(MidiEvent midiEvent, int originalTrack) { if (midiFileType == 0) { EnsureTracks(1); trackEvents[0].Add(midiEvent); } else if (originalTrack == 0) { switch (midiEvent.CommandCode) { case MidiCommandCode.NoteOff: case MidiCommandCode.NoteOn: case MidiCommandCode.KeyAfterTouch: case MidiCommandCode.ControlChange: case MidiCommandCode.PatchChange: case MidiCommandCode.ChannelAfterTouch: case MidiCommandCode.PitchWheelChange: EnsureTracks(midiEvent.Channel + 1); trackEvents[midiEvent.Channel].Add(midiEvent); break; default: EnsureTracks(1); trackEvents[0].Add(midiEvent); break; } } else { EnsureTracks(originalTrack + 1); trackEvents[originalTrack].Add(midiEvent); } } private void EnsureTracks(int count) { for (int i = trackEvents.Count; i < count; i++) { trackEvents.Add(new List<MidiEvent>()); } } private void ExplodeToManyTracks() { IList<MidiEvent> list = trackEvents[0]; Clear(); foreach (MidiEvent item in list) { AddEvent(item, 0); } PrepareForExport(); } private void FlattenToOneTrack() { bool flag = false; for (int i = 1; i < trackEvents.Count; i++) { foreach (MidiEvent item in trackEvents[i]) { if (!MidiEvent.IsEndTrack(item)) { trackEvents[0].Add(item); flag = true; } } } for (int num = trackEvents.Count - 1; num > 0; num--) { RemoveTrack(num); } if (flag) { PrepareForExport(); } } public void PrepareForExport() { MidiEventComparer comparer = new MidiEventComparer(); foreach (IList<MidiEvent> trackEvent in trackEvents) { MergeSort.Sort(trackEvent, comparer); int num = 0; while (num < trackEvent.Count - 1) { if (MidiEvent.IsEndTrack(trackEvent[num])) { trackEvent.RemoveAt(num); } else { num++; } } } int num2 = 0; while (num2 < trackEvents.Count) { IList<MidiEvent> list = trackEvents[num2]; if (list.Count == 0) { RemoveTrack(num2); continue; } if (list.Count == 1 && MidiEvent.IsEndTrack(list[0])) { RemoveTrack(num2); continue; } if (!MidiEvent.IsEndTrack(list[list.Count - 1])) { list.Add(new MetaEvent(MetaEventType.EndTrack, 0, list[list.Count - 1].AbsoluteTime)); } num2++; } } public IEnumerator<IList<MidiEvent>> GetEnumerator() { return trackEvents.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return trackEvents.GetEnumerator(); } } public class MidiEventComparer : IComparer<MidiEvent> { public int Compare(MidiEvent x, MidiEvent y) { long num = x.AbsoluteTime; long num2 = y.AbsoluteTime; if (num == num2) { MetaEvent metaEvent = x as MetaEvent; MetaEvent metaEvent2 = y as MetaEvent; if (metaEvent != null) { num = ((metaEvent.MetaEventType != MetaEventType.EndTrack) ? long.MinValue : long.MaxValue); } if (metaEvent2 != null) { num2 = ((metaEvent2.MetaEventType != MetaEventType.EndTrack) ? long.MinValue : long.MaxValue); } } return num.CompareTo(num2); } } public class MidiFile { private readonly MidiEventCollection events; private readonly ushort fileFormat; private readonly ushort deltaTicksPerQuarterNote; private readonly bool strictChecking; public int FileFormat => fileFormat; public MidiEventCollection Events => events; public int Tracks => events.Tracks; public int DeltaTicksPerQuarterNote => deltaTicksPerQuarterNote; public MidiFile(string filename) : this(filename, strictChecking: true) { } public MidiFile(string filename, bool strictChecking) : this(File.OpenRead(filename), strictChecking, ownInputStream: true) { } public MidiFile(Stream inputStream, bool strictChecking) : this(inputStream, strictChecking, ownInputStream: false) { } private MidiFile(Stream inputStream, bool strictChecking, bool ownInputStream) { this.strictChecking = strictChecking; BinaryReader binaryReader = new BinaryReader(inputStream); try { if (Encoding.UTF8.GetString(binaryReader.ReadBytes(4)) != "MThd") { throw new FormatException("Not a MIDI file - header chunk missing"); } uint num = SwapUInt32(binaryReader.ReadUInt32()); if (num != 6) { throw new FormatException("Unexpected header chunk length"); } fileFormat = SwapUInt16(binaryReader.ReadUInt16()); int num2 = SwapUInt16(binaryReader.ReadUInt16()); deltaTicksPerQuarterNote = SwapUInt16(binaryReader.ReadUInt16()); events = new MidiEventCollection((fileFormat != 0) ? 1 : 0, deltaTicksPerQuarterNote); for (int i = 0; i < num2; i++) { events.AddTrack(); } long num3 = 0L; for (int j = 0; j < num2; j++) { if (fileFormat == 1) { num3 = 0L; } if (Encoding.UTF8.GetString(binaryReader.ReadBytes(4)) != "MTrk") { throw new FormatException("Invalid chunk header"); } num = SwapUInt32(binaryReader.ReadUInt32()); long position = binaryReader.BaseStream.Position; MidiEvent midiEvent = null; List<NoteOnEvent> list = new List<NoteOnEvent>(); while (binaryReader.BaseStream.Position < position + num) { try { midiEvent = MidiEvent.ReadNextEvent(binaryReader, midiEvent); } catch (InvalidDataException) { if (strictChecking) { throw; } continue; } catch (FormatException) { if (strictChecking) { throw; } continue; } num3 = (midiEvent.AbsoluteTime = num3 + midiEvent.DeltaTime); events[j].Add(midiEvent); if (midiEvent.CommandCode == MidiCommandCode.NoteOn) { NoteEvent noteEvent = (NoteEvent)midiEvent; if (noteEvent.Velocity > 0) { list.Add((NoteOnEvent)noteEvent); } else { FindNoteOn(noteEvent, list); } } else if (midiEvent.CommandCode == MidiCommandCode.NoteOff) { FindNoteOn((NoteEvent)midiEvent, list); } else if (midiEvent.CommandCode == MidiCommandCode.MetaEvent && ((MetaEvent)midiEvent).MetaEventType == MetaEventType.EndTrack && strictChecking && binaryReader.BaseStream.Position < position + num) { throw new FormatException($"End Track event was not the last MIDI event on track {j}"); } } if (list.Count > 0 && strictChecking) { throw new FormatException($"Note ons without note offs {list.Count} (file format {fileFormat})"); } if (binaryReader.BaseStream.Position != position + num) { throw new FormatException($"Read too far {num}+{position}!={binaryReader.BaseStream.Position}"); } } } finally { if (ownInputStream) { binaryReader.Dispose(); } } } private void FindNoteOn(NoteEvent offEvent, List<NoteOnEvent> outstandingNoteOns) { bool flag = false; foreach (NoteOnEvent outstandingNoteOn in outstandingNoteOns) { if (outstandingNoteOn.Channel == offEvent.Channel && outstandingNoteOn.NoteNumber == offEvent.NoteNumber) { outstandingNoteOn.OffEvent = offEvent; outstandingNoteOns.Remove(outstandingNoteOn); flag = true; break; } } if (!flag && strictChecking) { throw new FormatException($"Got an off without an on {offEvent}"); } } private static uint SwapUInt32(uint i) { return ((i & 0xFF000000u) >> 24) | ((i & 0xFF0000) >> 8) | ((i & 0xFF00) << 8) | ((i & 0xFF) << 24); } private static ushort SwapUInt16(ushort i) { return (ushort)(((i & 0xFF00) >> 8) | ((i & 0xFF) << 8)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("Format {0}, Tracks {1}, Delta Ticks Per Quarter Note {2}\r\n", fileFormat, Tracks, deltaTicksPerQuarterNote); for (int i = 0; i < Tracks; i++) { foreach (MidiEvent item in events[i]) { stringBuilder.AppendFormat("{0}\r\n", item); } } return stringBuilder.ToString(); } public static void Export(string filename, MidiEventCollection events) { if (events.MidiFileType == 0 && events.Tracks > 1) { throw new ArgumentException("Can't export more than one track to a type 0 file"); } using BinaryWriter binaryWriter = new BinaryWriter(File.Create(filename)); binaryWriter.Write(Encoding.UTF8.GetBytes("MThd")); binaryWriter.Write(SwapUInt32(6u)); binaryWriter.Write(SwapUInt16((ushort)events.MidiFileType)); binaryWriter.Write(SwapUInt16((ushort)events.Tracks)); binaryWriter.Write(SwapUInt16((ushort)events.DeltaTicksPerQuarterNote)); for (int i = 0; i < events.Tracks; i++) { IList<MidiEvent> list = events[i]; binaryWriter.Write(Encoding.UTF8.GetBytes("MTrk")); long position = binaryWriter.BaseStream.Position; binaryWriter.Write(SwapUInt32(0u)); long absoluteTime = events.StartAbsoluteTime; MergeSort.Sort(list, new MidiEventComparer()); _ = list.Count; _ = 0; foreach (MidiEvent item in list) { item.Export(ref absoluteTime, binaryWriter); } uint num = (uint)((int)(binaryWriter.BaseStream.Position - position) - 4); binaryWriter.BaseStream.Position = position; binaryWriter.Write(SwapUInt32(num)); binaryWriter.BaseStream.Position += num; } } } public class MidiIn : IDisposable { private IntPtr hMidiIn = IntPtr.Zero; private bool disposeIsRunning; private bool disposed; private MidiInterop.MidiInCallback callback; private IntPtr[] SysexBufferHeaders = new IntPtr[0]; public static int NumberOfDevices => MidiInterop.midiInGetNumDevs(); public event EventHandler<MidiInMessageEventArgs> MessageReceived; public event EventHandler<MidiInMessageEventArgs> ErrorReceived; public event EventHandler<MidiInSysexMessageEventArgs> SysexMessageReceived; public MidiIn(int deviceNo) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) callback = Callback; MmException.Try(MidiInterop.midiInOpen(out hMidiIn, (IntPtr)deviceNo, callback, IntPtr.Zero, 196608), "midiInOpen"); } public void Close() { Dispose(); } public void Dispose() { GC.KeepAlive(callback); Dispose(disposing: true); GC.SuppressFinalize(this); } public void Start() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) MmException.Try(MidiInterop.midiInStart(hMidiIn), "midiInStart"); } public void Stop() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) MmException.Try(MidiInterop.midiInStop(hMidiIn), "midiInStop"); } public void Reset() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) MmException.Try(MidiInterop.midiInReset(hMidiIn), "midiInReset"); } public void CreateSysexBuffers(int bufferSize, int numberOfBuffers) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) SysexBufferHeaders = new IntPtr[numberOfBuffers]; int cb = Marshal.SizeOf(typeof(MidiInterop.MIDIHDR)); for (int i = 0; i < numberOfBuffers; i++) { MidiInterop.MIDIHDR structure = default(MidiInterop.MIDIHDR); structure.dwBufferLength = bufferSize; structure.dwBytesRecorded = 0; structure.lpData = Marshal.AllocHGlobal(bufferSize); structure.dwFlags = 0; IntPtr intPtr = Marshal.AllocHGlobal(cb); Marshal.StructureToPtr(structure, intPtr, fDeleteOld: false); MmException.Try(MidiInterop.midiInPrepareHeader(hMidiIn, intPtr, Marshal.SizeOf(typeof(MidiInterop.MIDIHDR))), "midiInPrepareHeader"); MmException.Try(MidiInterop.midiInAddBuffer(hMidiIn, intPtr, Marshal.SizeOf(typeof(MidiInterop.MIDIHDR))), "midiInAddBuffer"); SysexBufferHeaders[i] = intPtr; } } private void Callback(IntPtr midiInHandle, MidiInterop.MidiInMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2) { //IL_010d: Unknown result type (might be due to invalid IL or missing references) switch (message) { case MidiInterop.MidiInMessage.Data: if (this.MessageReceived != null) { this.MessageReceived(this, new MidiInMessageEventArgs(messageParameter1.ToInt32(), messageParameter2.ToInt32())); } break; case MidiInterop.MidiInMessage.Error: if (this.ErrorReceived != null) { this.ErrorReceived(this, new MidiInMessageEventArgs(messageParameter1.ToInt32(), messageParameter2.ToInt32())); } break; case MidiInterop.MidiInMessage.LongData: if (this.SysexMessageReceived != null) { MidiInterop.MIDIHDR mIDIHDR = (MidiInterop.MIDIHDR)Marshal.PtrToStructure(messageParameter1, typeof(MidiInterop.MIDIHDR)); byte[] array = new byte[mIDIHDR.dwBytesRecorded]; Marshal.Copy(mIDIHDR.lpData, array, 0, mIDIHDR.dwBytesRecorded); if (array.Length != 0) { this.SysexMessageReceived(this, new MidiInSysexMessageEventArgs(array, messageParameter2.ToInt32())); } if (!disposeIsRunning) { MidiInterop.midiInAddBuffer(hMidiIn, messageParameter1, Marshal.SizeOf(typeof(MidiInterop.MIDIHDR))); } } break; case MidiInterop.MidiInMessage.Open: case MidiInterop.MidiInMessage.Close: case MidiInterop.MidiInMessage.LongError: case (MidiInterop.MidiInMessage)967: case (MidiInterop.MidiInMessage)968: case (MidiInterop.MidiInMessage)969: case (MidiInterop.MidiInMessage)970: case (MidiInterop.MidiInMessage)971: case MidiInterop.MidiInMessage.MoreData: break; } } public static MidiInCapabilities DeviceInfo(int midiInDeviceNumber) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) MidiInCapabilities capabilities = default(MidiInCapabilities); int size = Marshal.SizeOf(capabilities); MmException.Try(MidiInterop.midiInGetDevCaps((IntPtr)midiInDeviceNumber, out capabilities, size), "midiInGetDevCaps"); return capabilities; } protected virtual void Dispose(bool disposing) { //IL_00a8: 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) //IL_006d: Unknown result type (might be due to invalid IL or missing references) if (!disposed) { disposeIsRunning = true; if (SysexBufferHeaders.Length != 0) { MmException.Try(MidiInterop.midiInReset(hMidiIn), "midiInReset"); IntPtr[] sysexBufferHeaders = SysexBufferHeaders; foreach (IntPtr intPtr in sysexBufferHeaders) { MidiInterop.MIDIHDR obj = (MidiInterop.MIDIHDR)Marshal.PtrToStructure(intPtr, typeof(MidiInterop.MIDIHDR)); MmException.Try(MidiInterop.midiInUnprepareHeader(hMidiIn, intPtr, Marshal.SizeOf(typeof(MidiInterop.MIDIHDR))), "midiInPrepareHeader"); Marshal.FreeHGlobal(obj.lpData); Marshal.FreeHGlobal(intPtr); } SysexBufferHeaders = new IntPtr[0]; } MidiInterop.midiInClose(hMidiIn); } disposed = true; disposeIsRunning = false; } ~MidiIn() { Dispose(disposing: false); } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct MidiInCapabilities { private ushort manufacturerId; private ushort productId; private uint driverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] private string productName; private int support; private const int MaxProductNameLength = 32; public Manufacturers Manufacturer => (Manufacturers)manufacturerId; public int ProductId => productId; public string ProductName => productName; } public class MidiInMessageEventArgs : EventArgs { public int RawMessage { get; private set; } public MidiEvent MidiEvent { get; private set; } public int Timestamp { get; private set; } public MidiInMessageEventArgs(int message, int timestamp) { RawMessage = message; Timestamp = timestamp; try { MidiEvent = MidiEvent.FromRawMessage(message); } catch (Exception) { } } } public class MidiInSysexMessageEventArgs : EventArgs { public byte[] SysexBytes { get; private set; } public int Timestamp { get; private set; } public MidiInSysexMessageEventArgs(byte[] sysexBytes, int timestamp) { SysexBytes = sysexBytes; Timestamp = timestamp; } } internal class MidiInterop { public enum MidiInMessage { Open = 961, Close = 962, Data = 963, LongData = 964, Error = 965, LongError = 966, MoreData = 972 } public enum MidiOutMessage { Open = 967, Close, Done } public delegate void MidiInCallback(IntPtr midiInHandle, MidiInMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2); public delegate void MidiOutCallback(IntPtr midiInHandle, MidiOutMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2); public struct MMTIME { public int wType; public int u; } public struct MIDIEVENT { public int dwDeltaTime; public int dwStreamID; public int dwEvent; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public int dwParms; } public struct MIDIHDR { public IntPtr lpData; public int dwBufferLength; public int dwBytesRecorded; public IntPtr dwUser; public int dwFlags; public IntPtr lpNext; public IntPtr reserved; public int dwOffset; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public IntPtr[] dwReserved; } public struct MIDIPROPTEMPO { public int cbStruct; public int dwTempo; } public const int CALLBACK_FUNCTION = 196608; public const int CALLBACK_NULL = 0; [DllImport("winmm.dll")] public static extern MmResult midiConnect(IntPtr hMidiIn, IntPtr hMidiOut, IntPtr pReserved); [DllImport("winmm.dll")] public static extern MmResult midiDisconnect(IntPtr hMidiIn, IntPtr hMidiOut, IntPtr pReserved); [DllImport("winmm.dll")] public static extern MmResult midiInAddBuffer(IntPtr hMidiIn, IntPtr lpMidiInHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiInClose(IntPtr hMidiIn); [DllImport("winmm.dll", CharSet = CharSet.Auto)] public static extern MmResult midiInGetDevCaps(IntPtr deviceId, out MidiInCapabilities capabilities, int size); [DllImport("winmm.dll")] public static extern MmResult midiInGetErrorText(int err, string lpText, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiInGetID(IntPtr hMidiIn, out int lpuDeviceId); [DllImport("winmm.dll")] public static extern int midiInGetNumDevs(); [DllImport("winmm.dll")] public static extern MmResult midiInMessage(IntPtr hMidiIn, int msg, IntPtr dw1, IntPtr dw2); [DllImport("winmm.dll")] public static extern MmResult midiInOpen(out IntPtr hMidiIn, IntPtr uDeviceID, MidiInCallback callback, IntPtr dwInstance, int dwFlags); [DllImport("winmm.dll", EntryPoint = "midiInOpen")] public static extern MmResult midiInOpenWindow(out IntPtr hMidiIn, IntPtr uDeviceID, IntPtr callbackWindowHandle, IntPtr dwInstance, int dwFlags); [DllImport("winmm.dll")] public static extern MmResult midiInPrepareHeader(IntPtr hMidiIn, IntPtr lpMidiInHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiInReset(IntPtr hMidiIn); [DllImport("winmm.dll")] public static extern MmResult midiInStart(IntPtr hMidiIn); [DllImport("winmm.dll")] public static extern MmResult midiInStop(IntPtr hMidiIn); [DllImport("winmm.dll")] public static extern MmResult midiInUnprepareHeader(IntPtr hMidiIn, IntPtr lpMidiInHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiOutCacheDrumPatches(IntPtr hMidiOut, int uPatch, IntPtr lpKeyArray, int uFlags); [DllImport("winmm.dll")] public static extern MmResult midiOutCachePatches(IntPtr hMidiOut, int uBank, IntPtr lpPatchArray, int uFlags); [DllImport("winmm.dll")] public static extern MmResult midiOutClose(IntPtr hMidiOut); [DllImport("winmm.dll", CharSet = CharSet.Auto)] public static extern MmResult midiOutGetDevCaps(IntPtr deviceNumber, out MidiOutCapabilities caps, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiOutGetErrorText(IntPtr err, string lpText, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiOutGetID(IntPtr hMidiOut, out int lpuDeviceID); [DllImport("winmm.dll")] public static extern int midiOutGetNumDevs(); [DllImport("winmm.dll")] public static extern MmResult midiOutGetVolume(IntPtr uDeviceID, ref int lpdwVolume); [DllImport("winmm.dll")] public static extern MmResult midiOutLongMsg(IntPtr hMidiOut, ref MIDIHDR lpMidiOutHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiOutMessage(IntPtr hMidiOut, int msg, IntPtr dw1, IntPtr dw2); [DllImport("winmm.dll")] public static extern MmResult midiOutOpen(out IntPtr lphMidiOut, IntPtr uDeviceID, MidiOutCallback dwCallback, IntPtr dwInstance, int dwFlags); [DllImport("winmm.dll")] public static extern MmResult midiOutPrepareHeader(IntPtr hMidiOut, ref MIDIHDR lpMidiOutHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiOutReset(IntPtr hMidiOut); [DllImport("winmm.dll")] public static extern MmResult midiOutSetVolume(IntPtr hMidiOut, int dwVolume); [DllImport("winmm.dll")] public static extern MmResult midiOutShortMsg(IntPtr hMidiOut, int dwMsg); [DllImport("winmm.dll")] public static extern MmResult midiOutUnprepareHeader(IntPtr hMidiOut, ref MIDIHDR lpMidiOutHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult midiStreamClose(IntPtr hMidiStream); [DllImport("winmm.dll")] public static extern MmResult midiStreamOpen(out IntPtr hMidiStream, IntPtr puDeviceID, int cMidi, IntPtr dwCallback, IntPtr dwInstance, int fdwOpen); [DllImport("winmm.dll")] public static extern MmResult midiStreamOut(IntPtr hMidiStream, ref MIDIHDR pmh, int cbmh); [DllImport("winmm.dll")] public static extern MmResult midiStreamPause(IntPtr hMidiStream); [DllImport("winmm.dll")] public static extern MmResult midiStreamPosition(IntPtr hMidiStream, ref MMTIME lpmmt, int cbmmt); [DllImport("winmm.dll")] public static extern MmResult midiStreamProperty(IntPtr hMidiStream, IntPtr lppropdata, int dwProperty); [DllImport("winmm.dll")] public static extern MmResult midiStreamRestart(IntPtr hMidiStream); [DllImport("winmm.dll")] public static extern MmResult midiStreamStop(IntPtr hMidiStream); } public class MidiMessage { private int rawData; public int RawData => rawData; public MidiMessage(int status, int data1, int data2) { rawData = status + (data1 << 8) + (data2 << 16); } public MidiMessage(int rawData) { this.rawData = rawData; } public static MidiMessage StartNote(int note, int volume, int channel) { ValidateNoteParameters(note, volume, channel); return new MidiMessage(144 + channel - 1, note, volume); } private static void ValidateNoteParameters(int note, int volume, int channel) { ValidateChannel(channel); if (note < 0 || note > 127) { throw new ArgumentOutOfRangeException("note", "Note number must be in the range 0-127"); } if (volume < 0 || volume > 127) { throw new ArgumentOutOfRangeException("volume", "Velocity must be in the range 0-127"); } } private static void ValidateChannel(int channel) { if (channel < 1 || channel > 16) { throw new ArgumentOutOfRangeException("channel", channel, $"Channel must be 1-16 (Got {channel})"); } } public static MidiMessage StopNote(int note, int volume, int channel) { ValidateNoteParameters(note, volume, channel); return new MidiMessage(128 + channel - 1, note, volume); } public static MidiMessage ChangePatch(int patch, int channel) { ValidateChannel(channel); return new MidiMessage(192 + channel - 1, patch, 0); } public static MidiMessage ChangeControl(int controller, int value, int channel) { ValidateChannel(channel); return new MidiMessage(176 + channel - 1, controller, value); } } public class MidiOut : IDisposable { private IntPtr hMidiOut = IntPtr.Zero; private bool disposed; private MidiInterop.MidiOutCallback callback; public static int NumberOfDevices => MidiInterop.midiOutGetNumDevs(); public int Volume { get { //IL_000a: Unknown result type (might be due to invalid IL or missing references) int lpdwVolume = 0; MmException.Try(MidiInterop.midiOutGetVolume(hMidiOut, ref lpdwVolume), "midiOutGetVolume"); return lpdwVolume; } set { //IL_0007: Unknown result type (might be due to invalid IL or missing references) MmException.Try(MidiInterop.midiOutSetVolume(hMidiOut, value), "midiOutSetVolume"); } } public static MidiOutCapabilities DeviceInfo(int midiOutDeviceNumber) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) MidiOutCapabilities caps = default(MidiOutCapabilities); int uSize = Marshal.SizeOf(caps); MmException.Try(MidiInterop.midiOutGetDevCaps((IntPtr)midiOutDeviceNumber, out caps, uSize), "midiOutGetDevCaps"); return caps; } public MidiOut(int deviceNo) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) callback = Callback; MmException.Try(MidiInterop.midiOutOpen(out hMidiOut, (IntPtr)deviceNo, callback, IntPtr.Zero, 196608), "midiOutOpen"); } public void Close() { Dispose(); } public void Dispose() { GC.KeepAlive(callback); Dispose(disposing: true); GC.SuppressFinalize(this); } public void Reset() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) MmException.Try(MidiInterop.midiOutReset(hMidiOut), "midiOutReset"); } public void SendDriverMessage(int message, int param1, int param2) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) MmException.Try(MidiInterop.midiOutMessage(hMidiOut, message, (IntPtr)param1, (IntPtr)param2), "midiOutMessage"); } public void Send(int message) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) MmException.Try(MidiInterop.midiOutShortMsg(hMidiOut, message), "midiOutShortMsg"); } protected virtual void Dispose(bool disposing) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (!disposed) { MidiInterop.midiOutClose(hMidiOut); } disposed = true; } private void Callback(IntPtr midiInHandle, MidiInterop.MidiOutMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2) { } public void SendBuffer(byte[] byteBuffer) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_005a: 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) MidiInterop.MIDIHDR lpMidiOutHdr = default(MidiInterop.MIDIHDR); lpMidiOutHdr.lpData = Marshal.AllocHGlobal(byteBuffer.Length); Marshal.Copy(byteBuffer, 0, lpMidiOutHdr.lpData, byteBuffer.Length); lpMidiOutHdr.dwBufferLength = byteBuffer.Length; lpMidiOutHdr.dwBytesRecorded = byteBuffer.Length; int uSize = Marshal.SizeOf(lpMidiOutHdr); MidiInterop.midiOutPrepareHeader(hMidiOut, ref lpMidiOutHdr, uSize); if ((int)MidiInterop.midiOutLongMsg(hMidiOut, ref lpMidiOutHdr, uSize) != 0) { MidiInterop.midiOutUnprepareHeader(hMidiOut, ref lpMidiOutHdr, uSize); } Marshal.FreeHGlobal(lpMidiOutHdr.lpData); } ~MidiOut() { Dispose(disposing: false); } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct MidiOutCapabilities { [Flags] private enum MidiOutCapabilityFlags { Volume = 1, LeftRightVolume = 2, PatchCaching = 4, Stream = 8 } private short manufacturerId; private short productId; private int driverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] private string productName; private short wTechnology; private short wVoices; private short wNotes; private ushort wChannelMask; private MidiOutCapabilityFlags dwSupport; private const int MaxProductNameLength = 32; public Manufacturers Manufacturer => (Manufacturers)manufacturerId; public short ProductId => productId; public string ProductName => productName; public int Voices => wVoices; public int Notes => wNotes; public bool SupportsAllChannels => wChannelMask == ushort.MaxValue; public bool SupportsPatchCaching => (dwSupport & MidiOutCapabilityFlags.PatchCaching) != 0; public bool SupportsSeparateLeftAndRightVolume => (dwSupport & MidiOutCapabilityFlags.LeftRightVolume) != 0; public bool SupportsMidiStreamOut => (dwSupport & MidiOutCapabilityFlags.Stream) != 0; public bool SupportsVolumeControl => (dwSupport & MidiOutCapabilityFlags.Volume) != 0; public MidiOutTechnology Technology => (MidiOutTechnology)wTechnology; public bool SupportsChannel(int channel) { return (wChannelMask & (1 << channel - 1)) > 0; } } public enum MidiOutTechnology { MidiPort = 1, Synth, SquareWaveSynth, FMSynth, MidiMapper, WaveTableSynth, SoftwareSynth } public class NoteEvent : MidiEvent { private int noteNumber; private int velocity; private static readonly string[] NoteNames = new string[12] { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; public virtual int NoteNumber { get { return noteNumber; } set { if (value < 0 || value > 127) { throw new ArgumentOutOfRangeException("value", "Note number must be in the range 0-127"); } noteNumber = value; } } public int Velocity { get { return velocity; } set { if (value < 0 || value > 127) { throw new ArgumentOutOfRangeException("value", "Velocity must be in the range 0-127"); } velocity = value; } } public string NoteName { get { if (Channel == 16 || Channel == 10) { return noteNumber switch { 35 => "Acoustic Bass Drum", 36 => "Bass Drum 1", 37 => "Side Stick", 38 => "Acoustic Snare", 39 => "Hand Clap", 40 => "Electric Snare", 41 => "Low Floor Tom", 42 => "Closed Hi-Hat", 43 => "High Floor Tom", 44 => "Pedal Hi-Hat", 45 => "Low Tom", 46 => "Open Hi-Hat", 47 => "Low-Mid Tom", 48 => "Hi-Mid Tom", 49 => "Crash Cymbal 1", 50 => "High Tom", 51 => "Ride Cymbal 1", 52 => "Chinese Cymbal", 53 => "Ride Bell", 54 => "Tambourine", 55 => "Splash Cymbal", 56 => "Cowbell", 57 => "Crash Cymbal 2", 58 => "Vibraslap", 59 => "Ride Cymbal 2", 60 => "Hi Bongo", 61 => "Low Bongo", 62 => "Mute Hi Conga", 63 => "Open Hi Conga", 64 => "Low Conga", 65 => "High Timbale", 66 => "Low Timbale", 67 => "High Agogo", 68 => "Low Agogo", 69 => "Cabasa", 70 => "Maracas", 71 => "Short Whistle", 72 => "Long Whistle", 73 => "Short Guiro", 74 => "Long Guiro", 75 => "Claves", 76 => "Hi Wood Block", 77 => "Low Wood Block", 78 => "Mute Cuica", 79 => "Open Cuica", 80 => "Mute Triangle", 81 => "Open Triangle", _ => $"Drum {noteNumber}", }; } int num = noteNumber / 12; return $"{NoteNames[noteNumber % 12]}{num}"; } } public NoteEvent(BinaryReader br) { NoteNumber = br.ReadByte(); velocity = br.ReadByte(); if (velocity > 127) { velocity = 127; } } public NoteEvent(long absoluteTime, int channel, MidiCommandCode commandCode, int noteNumber, int velocity) : base(absoluteTime, channel, commandCode) { NoteNumber = noteNumber; Velocity = velocity; } public override int GetAsShortMessage() { return base.GetAsShortMessage() + (noteNumber << 8) + (velocity << 16); } public override string ToString() { return $"{base.ToString()} {NoteName} Vel:{Velocity}"; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write((byte)noteNumber); writer.Write((byte)velocity); } } public class NoteOnEvent : NoteEvent { private NoteEvent offEvent; public NoteEvent OffEvent { get { return offEvent; } set { if (!MidiEvent.IsNoteOff(value)) { throw new ArgumentException("OffEvent must be a valid MIDI note off event"); } if (value.NoteNumber != NoteNumber) { throw new ArgumentException("Note Off Event must be for the same note number"); } if (value.Channel != Channel) { throw new ArgumentException("Note Off Event must be for the same channel"); } offEvent = value; } } public override int NoteNumber { get { return base.NoteNumber; } set { base.NoteNumber = value; if (OffEvent != null) { OffEvent.NoteNumber = NoteNumber; } } } public override int Channel { get { return base.Channel; } set { base.Channel = value; if (OffEvent != null) { OffEvent.Channel = Channel; } } } public int NoteLength { get { return (int)(offEvent.AbsoluteTime - base.AbsoluteTime); } set { if (value < 0) { throw new ArgumentException("NoteLength must be 0 or greater"); } offEvent.AbsoluteTime = base.AbsoluteTime + value; } } public NoteOnEvent(BinaryReader br) : base(br) { } public NoteOnEvent(long absoluteTime, int channel, int noteNumber, int velocity, int duration) : base(absoluteTime, channel, MidiCommandCode.NoteOn, noteNumber, velocity) { OffEvent = new NoteEvent(absoluteTime, channel, MidiCommandCode.NoteOff, noteNumber, 0); NoteLength = duration; } public override MidiEvent Clone() { return new NoteOnEvent(base.AbsoluteTime, Channel, NoteNumber, base.Velocity, NoteLength); } public override string ToString() { if (base.Velocity == 0 && OffEvent == null) { return $"{base.ToString()} (Note Off)"; } return string.Format("{0} Len: {1}", base.ToString(), (OffEvent == null) ? "?" : NoteLength.ToString()); } } public class PatchChangeEvent : MidiEvent { private byte patch; private static readonly string[] patchNames = new string[128] { "Acoustic Grand", "Bright Acoustic", "Electric Grand", "Honky-Tonk", "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clav", "Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ", "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accoridan", "Harmonica", "Tango Accordian", "Acoustic Guitar(nylon)", "Acoustic Guitar(steel)", "Electric Guitar(jazz)", "Electric Guitar(clean)", "Electric Guitar(muted)", "Overdriven Guitar", "Distortion Guitar", "Guitar Harmonics", "Acoustic Bass", "Electric Bass(finger)", "Electric Bass(pick)", "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Strings", "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2", "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet", "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Skakuhachi", "Whistle", "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)", "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)", "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)", "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)", "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bagpipe", "Fiddle", "Shanai", "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal", "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter", "Applause", "Gunshot" }; public int Patch { get { return patch; } set { if (value < 0 || value > 127) { throw new ArgumentOutOfRangeException("value", "Patch number must be in the range 0-127"); } patch = (byte)value; } } public static string GetPatchName(int patchNumber) { return patchNames[patchNumber]; } public PatchChangeEvent(BinaryReader br) { patch = br.ReadByte(); if ((patch & 0x80u) != 0) { throw new FormatException("Invalid patch"); } } public PatchChangeEvent(long absoluteTime, int channel, int patchNumber) : base(absoluteTime, channel, MidiCommandCode.PatchChange) { Patch = patchNumber; } public override string ToString() { return $"{base.ToString()} {GetPatchName(patch)}"; } public override int GetAsShortMessage() { return base.GetAsShortMessage() + (patch << 8); } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write(patch); } } public class PitchWheelChangeEvent : MidiEvent { private int pitch; public int Pitch { get { return pitch; } set { if (value < 0 || value >= 16384) { throw new ArgumentOutOfRangeException("value", "Pitch value must be in the range 0 - 0x3FFF"); } pitch = value; } } public PitchWheelChangeEvent(BinaryReader br) { byte b = br.ReadByte(); byte b2 = br.ReadByte(); if ((b & 0x80u) != 0) { throw new FormatException("Invalid pitchwheelchange byte 1"); } if ((b2 & 0x80u) != 0) { throw new FormatException("Invalid pitchwheelchange byte 2"); } pitch = b + (b2 << 7); } public PitchWheelChangeEvent(long absoluteTime, int channel, int pitchWheel) : base(absoluteTime, channel, MidiCommandCode.PitchWheelChange) { Pitch = pitchWheel; } public override string ToString() { return $"{base.ToString()} Pitch {pitch} ({pitch - 8192})"; } public override int GetAsShortMessage() { return base.GetAsShortMessage() + ((pitch & 0x7F) << 8) + (((pitch >> 7) & 0x7F) << 16); } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write((byte)((uint)pitch & 0x7Fu)); writer.Write((byte)((uint)(pitch >> 7) & 0x7Fu)); } } public class RawMetaEvent : MetaEvent { public byte[] Data { get; set; } public RawMetaEvent(MetaEventType metaEventType, long absoluteTime, byte[] data) : base(metaEventType, (data != null) ? data.Length : 0, absoluteTime) { Data = data; } public override MidiEvent Clone() { return new RawMetaEvent(base.MetaEventType, base.AbsoluteTime, (byte[])Data?.Clone()); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder().Append(base.ToString()); byte[] data = Data; foreach (byte b in data) { stringBuilder.AppendFormat(" {0:X2}", b); } return stringBuilder.ToString(); } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); if (Data != null) { writer.Write(Data, 0, Data.Length); } } } public class SequencerSpecificEvent : MetaEvent { private byte[] data; public byte[] Data { get { return data; } set { data = value; metaDataLength = data.Length; } } public SequencerSpecificEvent(BinaryReader br, int length) { data = br.ReadBytes(length); } public SequencerSpecificEvent(byte[] data, long absoluteTime) : base(MetaEventType.SequencerSpecific, data.Length, absoluteTime) { this.data = data; } public override MidiEvent Clone() { return new SequencerSpecificEvent((byte[])data.Clone(), base.AbsoluteTime); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.ToString()); stringBuilder.Append(" "); byte[] array = data; foreach (byte b in array) { stringBuilder.AppendFormat("{0:X2} ", b); } stringBuilder.Length--; return stringBuilder.ToString(); } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write(data); } } public class SmpteOffsetEvent : MetaEvent { private readonly byte hours; private readonly byte minutes; private readonly byte seconds; private readonly byte frames; private readonly byte subFrames; public int Hours => hours; public int Minutes => minutes; public int Seconds => seconds; public int Frames => frames; public int SubFrames => subFrames; public SmpteOffsetEvent(byte hours, byte minutes, byte seconds, byte frames, byte subFrames) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; this.frames = frames; this.subFrames = subFrames; } public SmpteOffsetEvent(BinaryReader br, int length) { if (length != 5) { throw new FormatException($"Invalid SMPTE Offset length: Got {length}, expected 5"); } hours = br.ReadByte(); minutes = br.ReadByte(); seconds = br.ReadByte(); frames = br.ReadByte(); subFrames = br.ReadByte(); } public override MidiEvent Clone() { return (SmpteOffsetEvent)MemberwiseClone(); } public override string ToString() { return $"{base.ToString()} {hours}:{minutes}:{seconds}:{frames}:{subFrames}"; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write(hours); writer.Write(minutes); writer.Write(seconds); writer.Write(frames); writer.Write(subFrames); } } public class SysexEvent : MidiEvent { private byte[] data; public static SysexEvent ReadSysexEvent(BinaryReader br) { SysexEvent sysexEvent = new SysexEvent(); List<byte> list = new List<byte>(); bool flag = true; while (flag) { byte b = br.ReadByte(); if (b == 247) { flag = false; } else { list.Add(b); } } sysexEvent.data = list.ToArray(); return sysexEvent; } public override MidiEvent Clone() { return new SysexEvent { data = (byte[])data?.Clone() }; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); byte[] array = data; foreach (byte b in array) { stringBuilder.AppendFormat("{0:X2} ", b); } return $"{base.AbsoluteTime} Sysex: {data.Length} bytes\r\n{stringBuilder.ToString()}"; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write(data, 0, data.Length); writer.Write((byte)247); } } public class TempoEvent : MetaEvent { private int microsecondsPerQuarterNote; public int MicrosecondsPerQuarterNote { get { return microsecondsPerQuarterNote; } set { microsecondsPerQuarterNote = value; } } public double Tempo { get { return 60000000.0 / (double)microsecondsPerQuarterNote; } set { microsecondsPerQuarterNote = (int)(60000000.0 / value); } } public TempoEvent(BinaryReader br, int length) { if (length != 3) { throw new FormatException("Invalid tempo length"); } microsecondsPerQuarterNote = (br.ReadByte() << 16) + (br.ReadByte() << 8) + br.ReadByte(); } public TempoEvent(int microsecondsPerQuarterNote, long absoluteTime) : base(MetaEventType.SetTempo, 3, absoluteTime) { this.microsecondsPerQuarterNote = microsecondsPerQuarterNote; } public override MidiEvent Clone() { return (TempoEvent)MemberwiseClone(); } public override string ToString() { return string.Format("{0} {2}bpm ({1})", base.ToString(), microsecondsPerQuarterNote, 60000000 / microsecondsPerQuarterNote); } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write((byte)((uint)(microsecondsPerQuarterNote >> 16) & 0xFFu)); writer.Write((byte)((uint)(microsecondsPerQuarterNote >> 8) & 0xFFu)); writer.Write((byte)((uint)microsecondsPerQuarterNote & 0xFFu)); } } public class TextEvent : MetaEvent { private byte[] data; public string Text { get { return ((Encoding)(object)ByteEncoding.Instance).GetString(data); } set { Encoding instance = (Encoding)(object)ByteEncoding.Instance; data = instance.GetBytes(value); metaDataLength = data.Length; } } public byte[] Data { get { return data; } set { data = value; metaDataLength = data.Length; } } public TextEvent(BinaryReader br, int length) { data = br.ReadBytes(length); } public TextEvent(string text, MetaEventType metaEventType, long absoluteTime) : base(metaEventType, text.Length, absoluteTime) { Text = text; } public override MidiEvent Clone() { return (TextEvent)MemberwiseClone(); } public override string ToString() { return $"{base.ToString()} {Text}"; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write(data); } } public class TimeSignatureEvent : MetaEvent { private byte numerator; private byte denominator; private byte ticksInMetronomeClick; private byte no32ndNotesInQuarterNote; public int Numerator => numerator; public int Denominator => denominator; public int TicksInMetronomeClick => ticksInMetronomeClick; public int No32ndNotesInQuarterNote => no32ndNotesInQuarterNote; public string TimeSignature { get { string arg = $"Unknown ({denominator})"; switch (denominator) { case 1: arg = "2"; break; case 2: arg = "4"; break; case 3: arg = "8"; break; case 4: arg = "16"; break; case 5: arg = "32"; break; } return $"{numerator}/{arg}"; } } public TimeSignatureEvent(BinaryReader br, int length) { if (length != 4) { throw new FormatException($"Invalid time signature length: Got {length}, expected 4"); } numerator = br.ReadByte(); denominator = br.ReadByte(); ticksInMetronomeClick = br.ReadByte(); no32ndNotesInQuarterNote = br.ReadByte(); } public TimeSignatureEvent(long absoluteTime, int numerator, int denominator, int ticksInMetronomeClick, int no32ndNotesInQuarterNote) : base(MetaEventType.TimeSignature, 4, absoluteTime) { this.numerator = (byte)numerator; this.denominator = (byte)denominator; this.ticksInMetronomeClick = (byte)ticksInMetronomeClick; this.no32ndNotesInQuarterNote = (byte)no32ndNotesInQuarterNote; } public override MidiEvent Clone() { return (TimeSignatureEvent)MemberwiseClone(); } public override string ToString() { return $"{base.ToString()} {TimeSignature} TicksInClick:{ticksInMetronomeClick} 32ndsInQuarterNote:{no32ndNotesInQuarterNote}"; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write(numerator); writer.Write(denominator); writer.Write(ticksInMetronomeClick); writer.Write(no32ndNotesInQuarterNote); } } public class TrackSequenceNumberEvent : MetaEvent { private ushort sequenceNumber; public TrackSequenceNumberEvent(ushort sequenceNumber) { this.sequenceNumber = sequenceNumber; } public TrackSequenceNumberEvent(BinaryReader br, int length) { if (length != 2) { throw new FormatException("Invalid sequence number length"); } sequenceNumber = (ushort)((br.ReadByte() << 8) + br.ReadByte()); } public override MidiEvent Clone() { return (TrackSequenceNumberEvent)MemberwiseClone(); } public override string ToString() { return $"{base.ToString()} {sequenceNumber}"; } public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); writer.Write((byte)((uint)(sequenceNumber >> 8) & 0xFFu)); writer.Write((byte)(sequenceNumber & 0xFFu)); } } } namespace NAudio.Utils { internal class MergeSort { private static void Sort<T>(IList<T> list, int lowIndex, int highIndex, IComparer<T> comparer) { if (lowIndex >= highIndex) { return; } int num = (lowIndex + highIndex) / 2; Sort(list, lowIndex, num, comparer); Sort(list, num + 1, highIndex, comparer); int num2 = num; int num3 = num + 1; while (lowIndex <= num2 && num3 <= highIndex) { if (comparer.Compare(list[lowIndex], list[num3]) <= 0) { lowIndex++; continue; } T value = list[num3]; for (int num4 = num3 - 1; num4 >= lowIndex; num4--) { list[num4 + 1] = list[num4]; } list[lowIndex] = value; lowIndex++; num2++; num3++; } } public static void Sort<T>(IList<T> list) where T : IComparable<T> { Sort(list, 0, list.Count - 1, Comparer<T>.Default); } public static void Sort<T>(IList<T> list, IComparer<T> comparer) { Sort(list, 0, list.Count - 1, comparer); } } }
deps/NAudio.Wasapi.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using NAudio.CoreAudioApi; using NAudio.CoreAudioApi.Interfaces; using NAudio.Dmo; using NAudio.Dmo.Effect; using NAudio.MediaFoundation; using NAudio.Utils; using NAudio.Wasapi.CoreAudioApi; using NAudio.Wasapi.CoreAudioApi.Interfaces; using NAudio.Wave; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Mark Heath")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Mark Heath 2023")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("NAudio.Wasapi")] [assembly: AssemblyTitle("NAudio.Wasapi")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.2.1.0")] [module: UnverifiableCode] namespace NAudio.MediaFoundation { public static class AudioSubtypes { [FieldDescription("AAC")] public static readonly Guid MFAudioFormat_AAC = new Guid("00001610-0000-0010-8000-00aa00389b71"); [FieldDescription("ADTS")] public static readonly Guid MFAudioFormat_ADTS = new Guid("00001600-0000-0010-8000-00aa00389b71"); [FieldDescription("Dolby AC3 SPDIF")] public static readonly Guid MFAudioFormat_Dolby_AC3_SPDIF = new Guid("00000092-0000-0010-8000-00aa00389b71"); [FieldDescription("DRM")] public static readonly Guid MFAudioFormat_DRM = new Guid("00000009-0000-0010-8000-00aa00389b71"); [FieldDescription("DTS")] public static readonly Guid MFAudioFormat_DTS = new Guid("00000008-0000-0010-8000-00aa00389b71"); [FieldDescription("IEEE floating-point")] public static readonly Guid MFAudioFormat_Float = new Guid("00000003-0000-0010-8000-00aa00389b71"); [FieldDescription("MP3")] public static readonly Guid MFAudioFormat_MP3 = new Guid("00000055-0000-0010-8000-00aa00389b71"); [FieldDescription("MPEG")] public static readonly Guid MFAudioFormat_MPEG = new Guid("00000050-0000-0010-8000-00aa00389b71"); [FieldDescription("WMA 9 Voice codec")] public static readonly Guid MFAudioFormat_MSP1 = new Guid("0000000a-0000-0010-8000-00aa00389b71"); [FieldDescription("PCM")] public static readonly Guid MFAudioFormat_PCM = new Guid("00000001-0000-0010-8000-00aa00389b71"); [FieldDescription("WMA SPDIF")] public static readonly Guid MFAudioFormat_WMASPDIF = new Guid("00000164-0000-0010-8000-00aa00389b71"); [FieldDescription("WMAudio Lossless")] public static readonly Guid MFAudioFormat_WMAudio_Lossless = new Guid("00000163-0000-0010-8000-00aa00389b71"); [FieldDescription("Windows Media Audio")] public static readonly Guid MFAudioFormat_WMAudioV8 = new Guid("00000161-0000-0010-8000-00aa00389b71"); [FieldDescription("Windows Media Audio Professional")] public static readonly Guid MFAudioFormat_WMAudioV9 = new Guid("00000162-0000-0010-8000-00aa00389b71"); [FieldDescription("Dolby AC3")] public static readonly Guid MFAudioFormat_Dolby_AC3 = new Guid("e06d802c-db46-11cf-b4d1-00805f6cbbea"); public static readonly Guid MFAudioFormat_FLAC = new Guid("0000f1ac-0000-0010-8000-00aa00389b71"); public static readonly Guid MFAudioFormat_ALAC = new Guid("63616c61-0000-0010-8000-00aa00389b71"); [FieldDescription("MPEG-4 and AAC Audio Types")] public static readonly Guid MEDIASUBTYPE_RAW_AAC1 = new Guid("000000ff-0000-0010-8000-00aa00389b71"); [FieldDescription("Dolby Audio Types")] public static readonly Guid MEDIASUBTYPE_DVM = new Guid("00002000-0000-0010-8000-00aa00389b71"); [FieldDescription("Dolby Audio Types")] public static readonly Guid MEDIASUBTYPE_DOLBY_DDPLUS = new Guid("a7fb87af-2d02-42fb-a4d4-05cd93843bdd"); [FieldDescription("μ-law")] public static readonly Guid KSDATAFORMAT_SUBTYPE_MULAW = new Guid("00000007-0000-0010-8000-00aa00389b71"); [FieldDescription("ADPCM")] public static readonly Guid KSDATAFORMAT_SUBTYPE_ADPCM = new Guid("00000002-0000-0010-8000-00aa00389b71"); [FieldDescription("Dolby Digital Plus for HDMI")] public static readonly Guid KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS = new Guid("0000000a-0cea-0010-8000-00aa00389b71"); [FieldDescription("MSAudio1")] public static readonly Guid MEDIASUBTYPE_MSAUDIO1 = new Guid("00000160-0000-0010-8000-00aa00389b71"); [FieldDescription("IMA ADPCM")] public static readonly Guid ImaAdpcm = new Guid("00000011-0000-0010-8000-00aa00389b71"); [FieldDescription("WMSP2")] public static readonly Guid WMMEDIASUBTYPE_WMSP2 = new Guid("0000000b-0000-0010-8000-00aa00389b71"); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("7FEE9E9A-4A89-47a6-899C-B6A53A70FB67")] public interface IMFActivate : IMFAttributes { new void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue); new void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType); new void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); new void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); new void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue); new void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue); new void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue); new void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue); new void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength); new void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength); new void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength); new void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize); new void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize); new void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize); new void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); new void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value); new void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey); new void DeleteAllItems(); new void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue); new void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue); new void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue); new void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue); new void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue); new void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize); new void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown); new void LockStore(); new void UnlockStore(); new void GetCount(out int pcItems); new void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue); new void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest); void ActivateObject([In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv); void ShutdownObject(); void DetachObject(); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("2CD2D921-C447-44A7-A13C-4ADABFC247E3")] public interface IMFAttributes { void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue); void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType); void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue); void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue); void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue); void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue); void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength); void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength); void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength); void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize); void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize); void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize); void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr Value); void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey); void DeleteAllItems(); void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue); void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue); void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue); void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue); void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue); void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize); void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown); void LockStore(); void UnlockStore(); void GetCount(out int pcItems); void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue); void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("ad4c1b00-4bf7-422f-9175-756693d9130d")] public interface IMFByteStream { void GetCapabilities(ref int pdwCapabiities); void GetLength(ref long pqwLength); void SetLength(long qwLength); void GetCurrentPosition(ref long pqwPosition); void SetCurrentPosition(long qwPosition); void IsEndOfStream([MarshalAs(UnmanagedType.Bool)] ref bool pfEndOfStream); void Read(IntPtr pb, int cb, ref int pcbRead); void BeginRead(IntPtr pb, int cb, IntPtr pCallback, IntPtr punkState); void EndRead(IntPtr pResult, ref int pcbRead); void Write(IntPtr pb, int cb, ref int pcbWritten); void BeginWrite(IntPtr pb, int cb, IntPtr pCallback, IntPtr punkState); void EndWrite(IntPtr pResult, ref int pcbWritten); void Seek(int SeekOrigin, long llSeekOffset, int dwSeekFlags, ref long pqwCurrentPosition); void Flush(); void Close(); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("5BC8A76B-869A-46A3-9B03-FA218A66AEBE")] public interface IMFCollection { void GetElementCount(out int pcElements); void GetElement([In] int dwElementIndex, [MarshalAs(UnmanagedType.IUnknown)] out object ppUnkElement); void AddElement([In][MarshalAs(UnmanagedType.IUnknown)] object pUnkElement); void RemoveElement([In] int dwElementIndex, [MarshalAs(UnmanagedType.IUnknown)] out object ppUnkElement); void InsertElementAt([In] int dwIndex, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown); void RemoveAllElements(); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("045FA593-8799-42b8-BC8D-8968C6453507")] public interface IMFMediaBuffer { void Lock(out IntPtr ppbBuffer, out int pcbMaxLength, out int pcbCurrentLength); void Unlock(); void GetCurrentLength(out int pcbCurrentLength); void SetCurrentLength(int cbCurrentLength); void GetMaxLength(out int pcbMaxLength); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("DF598932-F10C-4E39-BBA2-C308F101DAA3")] public interface IMFMediaEvent : IMFAttributes { new void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue); new void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType); new void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); new void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); new void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue); new void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue); new void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue); new void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue); new void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength); new void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength); new void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength); new void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize); new void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize); new void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize); new void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); new void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value); new void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey); new void DeleteAllItems(); new void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue); new void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue); new void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue); new void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue); new void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue); new void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize); new void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown); new void LockStore(); new void UnlockStore(); new void GetCount(out int pcItems); new void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue); new void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest); void GetType(out MediaEventType pmet); void GetExtendedType(out Guid pguidExtendedType); void GetStatus([MarshalAs(UnmanagedType.Error)] out int phrStatus); void GetValue([Out] IntPtr pvValue); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("44AE0FA8-EA31-4109-8D2E-4CAE4997C555")] public interface IMFMediaType : IMFAttributes { new void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue); new void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType); new void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); new void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); new void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue); new void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue); new void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue); new void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue); new void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength); new void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength); new void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength); new void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize); new void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize); new void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize); new void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); new void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value); new void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey); new void DeleteAllItems(); new void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue); new void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue); new void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue); new void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue); new void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue); new void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize); new void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown); new void LockStore(); new void UnlockStore(); new void GetCount(out int pcItems); new void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue); new void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest); void GetMajorType(out Guid pguidMajorType); void IsCompressedFormat([MarshalAs(UnmanagedType.Bool)] out bool pfCompressed); [PreserveSig] int IsEqual([In][MarshalAs(UnmanagedType.Interface)] IMFMediaType pIMediaType, ref int pdwFlags); void GetRepresentation([In] Guid guidRepresentation, ref IntPtr ppvRepresentation); void FreeRepresentation([In] Guid guidRepresentation, [In] IntPtr pvRepresentation); } [ComImport] [Guid("E7FE2E12-661C-40DA-92F9-4F002AB67627")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMFReadWriteClassFactory { void CreateInstanceFromURL([In][MarshalAs(UnmanagedType.LPStruct)] Guid clsid, [In][MarshalAs(UnmanagedType.LPWStr)] string pwszURL, [In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pAttributes, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject); void CreateInstanceFromObject([In][MarshalAs(UnmanagedType.LPStruct)] Guid clsid, [In][MarshalAs(UnmanagedType.IUnknown)] object punkObject, [In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pAttributes, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject); } [ComImport] [Guid("48e2ed0f-98c2-4a37-bed5-166312ddd83f")] public class MFReadWriteClassFactory { } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("c40a00f2-b93a-4d80-ae8c-5a1c634f58e4")] public interface IMFSample : IMFAttributes { new void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue); new void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType); new void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); new void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); new void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue); new void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue); new void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue); new void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue); new void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength); new void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength); new void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength); new void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize); new void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize); new void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize); new void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); new void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value); new void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey); new void DeleteAllItems(); new void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue); new void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue); new void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue); new void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue); new void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue); new void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize); new void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown); new void LockStore(); new void UnlockStore(); new void GetCount(out int pcItems); new void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue); new void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest); void GetSampleFlags(out int pdwSampleFlags); void SetSampleFlags(int dwSampleFlags); void GetSampleTime(out long phnsSampletime); void SetSampleTime(long hnsSampleTime); void GetSampleDuration(out long phnsSampleDuration); void SetSampleDuration(long hnsSampleDuration); void GetBufferCount(out int pdwBufferCount); void GetBufferByIndex(int dwIndex, out IMFMediaBuffer ppBuffer); void ConvertToContiguousBuffer(out IMFMediaBuffer ppBuffer); void AddBuffer(IMFMediaBuffer pBuffer); void RemoveBufferByIndex(int dwIndex); void RemoveAllBuffers(); void GetTotalLength(out int pcbTotalLength); void CopyToBuffer(IMFMediaBuffer pBuffer); } [ComImport] [Guid("3137f1cd-fe5e-4805-a5d8-fb477448cb3d")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMFSinkWriter { void AddStream([In][MarshalAs(UnmanagedType.Interface)] IMFMediaType pTargetMediaType, out int pdwStreamIndex); void SetInputMediaType([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.Interface)] IMFMediaType pInputMediaType, [In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pEncodingParameters); void BeginWriting(); void WriteSample([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.Interface)] IMFSample pSample); void SendStreamTick([In] int dwStreamIndex, [In] long llTimestamp); void PlaceMarker([In] int dwStreamIndex, [In] IntPtr pvContext); void NotifyEndOfSegment([In] int dwStreamIndex); void Flush([In] int dwStreamIndex); void DoFinalize(); void GetServiceForStream([In] int dwStreamIndex, [In] ref Guid guidService, [In] ref Guid riid, out IntPtr ppvObject); void GetStatistics([In] int dwStreamIndex, [In][Out] MF_SINK_WRITER_STATISTICS pStats); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("70ae66f2-c809-4e4f-8915-bdcb406b7993")] public interface IMFSourceReader { void GetStreamSelection([In] int dwStreamIndex, [MarshalAs(UnmanagedType.Bool)] out bool pSelected); void SetStreamSelection([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.Bool)] bool pSelected); void GetNativeMediaType([In] int dwStreamIndex, [In] int dwMediaTypeIndex, out IMFMediaType ppMediaType); void GetCurrentMediaType([In] int dwStreamIndex, out IMFMediaType ppMediaType); void SetCurrentMediaType([In] int dwStreamIndex, IntPtr pdwReserved, [In] IMFMediaType pMediaType); void SetCurrentPosition([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidTimeFormat, [In] IntPtr varPosition); void ReadSample([In] int dwStreamIndex, [In] int dwControlFlags, out int pdwActualStreamIndex, out MF_SOURCE_READER_FLAG pdwStreamFlags, out ulong pllTimestamp, out IMFSample ppSample); void Flush([In] int dwStreamIndex); void GetServiceForStream([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidService, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IntPtr ppvObject); [PreserveSig] int GetPresentationAttribute([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidAttribute, [Out] IntPtr pvarAttribute); } [Flags] public enum MF_SOURCE_READER_FLAG { None = 0, MF_SOURCE_READERF_ERROR = 1, MF_SOURCE_READERF_ENDOFSTREAM = 2, MF_SOURCE_READERF_NEWSTREAM = 4, MF_SOURCE_READERF_NATIVEMEDIATYPECHANGED = 0x10, MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED = 0x20, MF_SOURCE_READERF_STREAMTICK = 0x100, MF_SOURCE_READERF_ALLEFFECTSREMOVED = 0x200 } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("bf94c121-5b05-4e6f-8000-ba598961414d")] public interface IMFTransform { void GetStreamLimits(out int pdwInputMinimum, out int pdwInputMaximum, out int pdwOutputMinimum, out int pdwOutputMaximum); void GetStreamCount(out int pcInputStreams, out int pcOutputStreams); void GetStreamIds([In] int dwInputIdArraySize, [In][Out] IntPtr pdwInputIDs, [In] int dwOutputIdArraySize, [In][Out] IntPtr pdwOutputIDs); void GetInputStreamInfo([In] int dwInputStreamId, out MFT_INPUT_STREAM_INFO pStreamInfo); void GetOutputStreamInfo([In] int dwOutputStreamId, out MFT_OUTPUT_STREAM_INFO pStreamInfo); void GetAttributes(out IMFAttributes pAttributes); void GetInputStreamAttributes([In] int dwInputStreamId, out IMFAttributes pAttributes); void GetOutputStreamAttributes([In] int dwOutputStreamId, out IMFAttributes pAttributes); void DeleteInputStream([In] int dwOutputStreamId); void AddInputStreams([In] int cStreams, [In] IntPtr adwStreamIDs); void GetInputAvailableType([In] int dwInputStreamId, [In] int dwTypeIndex, out IMFMediaType ppType); void GetOutputAvailableType([In] int dwOutputStreamId, [In] int dwTypeIndex, out IMFMediaType ppType); void SetInputType([In] int dwInputStreamId, [In] IMFMediaType pType, [In] _MFT_SET_TYPE_FLAGS dwFlags); void SetOutputType([In] int dwOutputStreamId, [In] IMFMediaType pType, [In] _MFT_SET_TYPE_FLAGS dwFlags); void GetInputCurrentType([In] int dwInputStreamId, out IMFMediaType ppType); void GetOutputCurrentType([In] int dwOutputStreamId, out IMFMediaType ppType); void GetInputStatus([In] int dwInputStreamId, out _MFT_INPUT_STATUS_FLAGS pdwFlags); void GetOutputStatus([In] int dwInputStreamId, out _MFT_OUTPUT_STATUS_FLAGS pdwFlags); void SetOutputBounds([In] long hnsLowerBound, [In] long hnsUpperBound); void ProcessEvent([In] int dwInputStreamId, [In] IMFMediaEvent pEvent); void ProcessMessage([In] MFT_MESSAGE_TYPE eMessage, [In] IntPtr ulParam); void ProcessInput([In] int dwInputStreamId, [In] IMFSample pSample, int dwFlags); [PreserveSig] int ProcessOutput([In] _MFT_PROCESS_OUTPUT_FLAGS dwFlags, [In] int cOutputBufferCount, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] MFT_OUTPUT_DATA_BUFFER[] pOutputSamples, out _MFT_PROCESS_OUTPUT_STATUS pdwStatus); } public enum MediaEventType { MEUnknown = 0, MEError = 1, MEExtendedType = 2, MENonFatalError = 3, MESessionUnknown = 100, MESessionTopologySet = 101, MESessionTopologiesCleared = 102, MESessionStarted = 103, MESessionPaused = 104, MESessionStopped = 105, MESessionClosed = 106, MESessionEnded = 107, MESessionRateChanged = 108, MESessionScrubSampleComplete = 109, MESessionCapabilitiesChanged = 110, MESessionTopologyStatus = 111, MESessionNotifyPresentationTime = 112, MENewPresentation = 113, MELicenseAcquisitionStart = 114, MELicenseAcquisitionCompleted = 115, MEIndividualizationStart = 116, MEIndividualizationCompleted = 117, MEEnablerProgress = 118, MEEnablerCompleted = 119, MEPolicyError = 120, MEPolicyReport = 121, MEBufferingStarted = 122, MEBufferingStopped = 123, MEConnectStart = 124, MEConnectEnd = 125, MEReconnectStart = 126, MEReconnectEnd = 127, MERendererEvent = 128, MESessionStreamSinkFormatChanged = 129, MESourceUnknown = 200, MESourceStarted = 201, MEStreamStarted = 202, MESourceSeeked = 203, MEStreamSeeked = 204, MENewStream = 205, MEUpdatedStream = 206, MESourceStopped = 207, MEStreamStopped = 208, MESourcePaused = 209, MEStreamPaused = 210, MEEndOfPresentation = 211, MEEndOfStream = 212, MEMediaSample = 213, MEStreamTick = 214, MEStreamThinMode = 215, MEStreamFormatChanged = 216, MESourceRateChanged = 217, MEEndOfPresentationSegment = 218, MESourceCharacteristicsChanged = 219, MESourceRateChangeRequested = 220, MESourceMetadataChanged = 221, MESequencerSourceTopologyUpdated = 222, MESinkUnknown = 300, MEStreamSinkStarted = 301, MEStreamSinkStopped = 302, MEStreamSinkPaused = 303, MEStreamSinkRateChanged = 304, MEStreamSinkRequestSample = 305, MEStreamSinkMarker = 306, MEStreamSinkPrerolled = 307, MEStreamSinkScrubSampleComplete = 308, MEStreamSinkFormatChanged = 309, MEStreamSinkDeviceChanged = 310, MEQualityNotify = 311, MESinkInvalidated = 312, MEAudioSessionNameChanged = 313, MEAudioSessionVolumeChanged = 314, MEAudioSessionDeviceRemoved = 315, MEAudioSessionServerShutdown = 316, MEAudioSessionGroupingParamChanged = 317, MEAudioSessionIconChanged = 318, MEAudioSessionFormatChanged = 319, MEAudioSessionDisconnected = 320, MEAudioSessionExclusiveModeOverride = 321, METrustUnknown = 400, MEPolicyChanged = 401, MEContentProtectionMessage = 402, MEPolicySet = 403, MEWMDRMLicenseBackupCompleted = 500, MEWMDRMLicenseBackupProgress = 501, MEWMDRMLicenseRestoreCompleted = 502, MEWMDRMLicenseRestoreProgress = 503, MEWMDRMLicenseAcquisitionCompleted = 506, MEWMDRMIndividualizationCompleted = 508, MEWMDRMIndividualizationProgress = 513, MEWMDRMProximityCompleted = 514, MEWMDRMLicenseStoreCleaned = 515, MEWMDRMRevocationDownloadCompleted = 516, METransformUnknown = 600, METransformNeedInput = 601, METransformHaveOutput = 602, METransformDrainComplete = 603, METransformMarker = 604 } public static class MediaFoundationAttributes { public static readonly Guid MF_TRANSFORM_ASYNC = new Guid("f81a699a-649a-497d-8c73-29f8fed6ad7a"); public static readonly Guid MF_TRANSFORM_ASYNC_UNLOCK = new Guid("e5666d6b-3422-4eb6-a421-da7db1f8e207"); [FieldDescription("Transform Flags")] public static readonly Guid MF_TRANSFORM_FLAGS_Attribute = new Guid("9359bb7e-6275-46c4-a025-1c01e45f1a86"); [FieldDescription("Transform Category")] public static readonly Guid MF_TRANSFORM_CATEGORY_Attribute = new Guid("ceabba49-506d-4757-a6ff-66c184987e4e"); [FieldDescription("Class identifier")] public static readonly Guid MFT_TRANSFORM_CLSID_Attribute = new Guid("6821c42b-65a4-4e82-99bc-9a88205ecd0c"); [FieldDescription("Container type")] public static readonly Guid MF_TRANSCODE_CONTAINERTYPE = new Guid(353366591, 19132, 18315, 172, 79, 225, 145, 111, 186, 28, 202); [FieldDescription("Input Types")] public static readonly Guid MFT_INPUT_TYPES_Attributes = new Guid("4276c9b1-759d-4bf3-9cd0-0d723d138f96"); [FieldDescription("Output Types")] public static readonly Guid MFT_OUTPUT_TYPES_Attributes = new Guid("8eae8cf3-a44f-4306-ba5c-bf5dda242818"); public static readonly Guid MFT_ENUM_HARDWARE_URL_Attribute = new Guid("2fb866ac-b078-4942-ab6c-003d05cda674"); [FieldDescription("Name")] public static readonly Guid MFT_FRIENDLY_NAME_Attribute = new Guid("314ffbae-5b41-4c95-9c19-4e7d586face3"); public static readonly Guid MFT_CONNECTED_STREAM_ATTRIBUTE = new Guid("71eeb820-a59f-4de2-bcec-38db1dd611a4"); public static readonly Guid MFT_CONNECTED_TO_HW_STREAM = new Guid("34e6e728-06d6-4491-a553-4795650db912"); [FieldDescription("Preferred Output Format")] public static readonly Guid MFT_PREFERRED_OUTPUTTYPE_Attribute = new Guid("7e700499-396a-49ee-b1b4-f628021e8c9d"); public static readonly Guid MFT_PROCESS_LOCAL_Attribute = new Guid("543186e4-4649-4e65-b588-4aa352aff379"); public static readonly Guid MFT_PREFERRED_ENCODER_PROFILE = new Guid("53004909-1ef5-46d7-a18e-5a75f8b5905f"); public static readonly Guid MFT_HW_TIMESTAMP_WITH_QPC_Attribute = new Guid("8d030fb8-cc43-4258-a22e-9210bef89be4"); public static readonly Guid MFT_FIELDOFUSE_UNLOCK_Attribute = new Guid("8ec2e9fd-9148-410d-831e-702439461a8e"); public static readonly Guid MFT_CODEC_MERIT_Attribute = new Guid("88a7cb15-7b07-4a34-9128-e64c6703c4d3"); public static readonly Guid MFT_ENUM_TRANSCODE_ONLY_ATTRIBUTE = new Guid("111ea8cd-b62a-4bdb-89f6-67ffcdc2458b"); [FieldDescription("PMP Host Context")] public static readonly Guid MF_PD_PMPHOST_CONTEXT = new Guid("6c990d31-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("App Context")] public static readonly Guid MF_PD_APP_CONTEXT = new Guid("6c990d32-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Duration")] public static readonly Guid MF_PD_DURATION = new Guid("6c990d33-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Total File Size")] public static readonly Guid MF_PD_TOTAL_FILE_SIZE = new Guid("6c990d34-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Audio encoding bitrate")] public static readonly Guid MF_PD_AUDIO_ENCODING_BITRATE = new Guid("6c990d35-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Video Encoding Bitrate")] public static readonly Guid MF_PD_VIDEO_ENCODING_BITRATE = new Guid("6c990d36-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("MIME Type")] public static readonly Guid MF_PD_MIME_TYPE = new Guid("6c990d37-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Last Modified Time")] public static readonly Guid MF_PD_LAST_MODIFIED_TIME = new Guid("6c990d38-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Element ID")] public static readonly Guid MF_PD_PLAYBACK_ELEMENT_ID = new Guid("6c990d39-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Preferred Language")] public static readonly Guid MF_PD_PREFERRED_LANGUAGE = new Guid("6c990d3a-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Playback boundary time")] public static readonly Guid MF_PD_PLAYBACK_BOUNDARY_TIME = new Guid("6c990d3b-bb8e-477a-8598-0d5d96fcd88a"); [FieldDescription("Audio is variable bitrate")] public static readonly Guid MF_PD_AUDIO_ISVARIABLEBITRATE = new Guid("33026ee0-e387-4582-ae0a-34a2ad3baa18"); [FieldDescription("Major Media Type")] public static readonly Guid MF_MT_MAJOR_TYPE = new Guid("48eba18e-f8c9-4687-bf11-0a74c9f96a8f"); [FieldDescription("Media Subtype")] public static readonly Guid MF_MT_SUBTYPE = new Guid("f7e34c9a-42e8-4714-b74b-cb29d72c35e5"); [FieldDescription("Audio block alignment")] public static readonly Guid MF_MT_AUDIO_BLOCK_ALIGNMENT = new Guid("322de230-9eeb-43bd-ab7a-ff412251541d"); [FieldDescription("Audio average bytes per second")] public static readonly Guid MF_MT_AUDIO_AVG_BYTES_PER_SECOND = new Guid("1aab75c8-cfef-451c-ab95-ac034b8e1731"); [FieldDescription("Audio number of channels")] public static readonly Guid MF_MT_AUDIO_NUM_CHANNELS = new Guid("37e48bf5-645e-4c5b-89de-ada9e29b696a"); [FieldDescription("Audio samples per second")] public static readonly Guid MF_MT_AUDIO_SAMPLES_PER_SECOND = new Guid("5faeeae7-0290-4c31-9e8a-c534f68d9dba"); [FieldDescription("Audio bits per sample")] public static readonly Guid MF_MT_AUDIO_BITS_PER_SAMPLE = new Guid("f2deb57f-40fa-4764-aa33-ed4f2d1ff669"); [FieldDescription("Enable Hardware Transforms")] public static readonly Guid MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS = new Guid("a634a91c-822b-41b9-a494-4de4643612b0"); [FieldDescription("Disable Sink Writer Throttling")] public static readonly Guid MF_SINK_WRITER_DISABLE_THROTTLING = new Guid("08b845d8-2b74-4afe-9d53-be16d2d5ae4f"); [FieldDescription("User data")] public static readonly Guid MF_MT_USER_DATA = new Guid("b6bc765f-4c3b-40a4-bd51-2535b66fe09d"); [FieldDescription("All samples independent")] public static readonly Guid MF_MT_ALL_SAMPLES_INDEPENDENT = new Guid("c9173739-5e56-461c-b713-46fb995cb95f"); [FieldDescription("Fixed size samples")] public static readonly Guid MF_MT_FIXED_SIZE_SAMPLES = new Guid("b8ebefaf-b718-4e04-b0a9-116775e3321b"); [FieldDescription("DirectShow Format Guid")] public static readonly Guid MF_MT_AM_FORMAT_TYPE = new Guid("73d1072d-1870-4174-a063-29ff4ff6c11e"); [FieldDescription("Preferred legacy format structure")] public static readonly Guid MF_MT_AUDIO_PREFER_WAVEFORMATEX = new Guid("a901aaba-e037-458a-bdf6-545be2074042"); [FieldDescription("Is Compressed")] public static readonly Guid MF_MT_COMPRESSED = new Guid("3afd0cee-18f2-4ba5-a110-8bea502e1f92"); [FieldDescription("Average bitrate")] public static readonly Guid MF_MT_AVG_BITRATE = new Guid("20332624-fb0d-4d9e-bd0d-cbf6786c102e"); [FieldDescription("AAC payload type")] public static readonly Guid MF_MT_AAC_PAYLOAD_TYPE = new Guid("bfbabe79-7434-4d1c-94f0-72a3b9e17188"); [FieldDescription("AAC Audio Profile Level Indication")] public static readonly Guid MF_MT_AAC_AUDIO_PROFILE_LEVEL_INDICATION = new Guid("7632f0e6-9538-4d61-acda-ea29c8c14456"); } public static class MediaFoundationErrors { public const int MF_E_PLATFORM_NOT_INITIALIZED = -1072875856; public const int MF_E_BUFFERTOOSMALL = -1072875855; public const int MF_E_INVALIDREQUEST = -1072875854; public const int MF_E_INVALIDSTREAMNUMBER = -1072875853; public const int MF_E_INVALIDMEDIATYPE = -1072875852; public const int MF_E_NOTACCEPTING = -1072875851; public const int MF_E_NOT_INITIALIZED = -1072875850; public const int MF_E_UNSUPPORTED_REPRESENTATION = -1072875849; public const int MF_E_NO_MORE_TYPES = -1072875847; public const int MF_E_UNSUPPORTED_SERVICE = -1072875846; public const int MF_E_UNEXPECTED = -1072875845; public const int MF_E_INVALIDNAME = -1072875844; public const int MF_E_INVALIDTYPE = -1072875843; public const int MF_E_INVALID_FILE_FORMAT = -1072875842; public const int MF_E_INVALIDINDEX = -1072875841; public const int MF_E_INVALID_TIMESTAMP = -1072875840; public const int MF_E_UNSUPPORTED_SCHEME = -1072875837; public const int MF_E_UNSUPPORTED_BYTESTREAM_TYPE = -1072875836; public const int MF_E_UNSUPPORTED_TIME_FORMAT = -1072875835; public const int MF_E_NO_SAMPLE_TIMESTAMP = -1072875832; public const int MF_E_NO_SAMPLE_DURATION = -1072875831; public const int MF_E_INVALID_STREAM_DATA = -1072875829; public const int MF_E_RT_UNAVAILABLE = -1072875825; public const int MF_E_UNSUPPORTED_RATE = -1072875824; public const int MF_E_THINNING_UNSUPPORTED = -1072875823; public const int MF_E_REVERSE_UNSUPPORTED = -1072875822; public const int MF_E_UNSUPPORTED_RATE_TRANSITION = -1072875821; public const int MF_E_RATE_CHANGE_PREEMPTED = -1072875820; public const int MF_E_NOT_FOUND = -1072875819; public const int MF_E_NOT_AVAILABLE = -1072875818; public const int MF_E_NO_CLOCK = -1072875817; public const int MF_S_MULTIPLE_BEGIN = 866008; public const int MF_E_MULTIPLE_BEGIN = -1072875815; public const int MF_E_MULTIPLE_SUBSCRIBERS = -1072875814; public const int MF_E_TIMER_ORPHANED = -1072875813; public const int MF_E_STATE_TRANSITION_PENDING = -1072875812; public const int MF_E_UNSUPPORTED_STATE_TRANSITION = -1072875811; public const int MF_E_UNRECOVERABLE_ERROR_OCCURRED = -1072875810; public const int MF_E_SAMPLE_HAS_TOO_MANY_BUFFERS = -1072875809; public const int MF_E_SAMPLE_NOT_WRITABLE = -1072875808; public const int MF_E_INVALID_KEY = -1072875806; public const int MF_E_BAD_STARTUP_VERSION = -1072875805; public const int MF_E_UNSUPPORTED_CAPTION = -1072875804; public const int MF_E_INVALID_POSITION = -1072875803; public const int MF_E_ATTRIBUTENOTFOUND = -1072875802; public const int MF_E_PROPERTY_TYPE_NOT_ALLOWED = -1072875801; public const int MF_E_PROPERTY_TYPE_NOT_SUPPORTED = -1072875800; public const int MF_E_PROPERTY_EMPTY = -1072875799; public const int MF_E_PROPERTY_NOT_EMPTY = -1072875798; public const int MF_E_PROPERTY_VECTOR_NOT_ALLOWED = -1072875797; public const int MF_E_PROPERTY_VECTOR_REQUIRED = -1072875796; public const int MF_E_OPERATION_CANCELLED = -1072875795; public const int MF_E_BYTESTREAM_NOT_SEEKABLE = -1072875794; public const int MF_E_DISABLED_IN_SAFEMODE = -1072875793; public const int MF_E_CANNOT_PARSE_BYTESTREAM = -1072875792; public const int MF_E_SOURCERESOLVER_MUTUALLY_EXCLUSIVE_FLAGS = -1072875791; public const int MF_E_MEDIAPROC_WRONGSTATE = -1072875790; public const int MF_E_RT_THROUGHPUT_NOT_AVAILABLE = -1072875789; public const int MF_E_RT_TOO_MANY_CLASSES = -1072875788; public const int MF_E_RT_WOULDBLOCK = -1072875787; public const int MF_E_NO_BITPUMP = -1072875786; public const int MF_E_RT_OUTOFMEMORY = -1072875785; public const int MF_E_RT_WORKQUEUE_CLASS_NOT_SPECIFIED = -1072875784; public const int MF_E_INSUFFICIENT_BUFFER = -1072860816; public const int MF_E_CANNOT_CREATE_SINK = -1072875782; public const int MF_E_BYTESTREAM_UNKNOWN_LENGTH = -1072875781; public const int MF_E_SESSION_PAUSEWHILESTOPPED = -1072875780; public const int MF_S_ACTIVATE_REPLACED = 866045; public const int MF_E_FORMAT_CHANGE_NOT_SUPPORTED = -1072875778; public const int MF_E_INVALID_WORKQUEUE = -1072875777; public const int MF_E_DRM_UNSUPPORTED = -1072875776; public const int MF_E_UNAUTHORIZED = -1072875775; public const int MF_E_OUT_OF_RANGE = -1072875774; public const int MF_E_INVALID_CODEC_MERIT = -1072875773; public const int MF_E_HW_MFT_FAILED_START_STREAMING = -1072875772; public const int MF_S_ASF_PARSEINPROGRESS = 1074608792; public const int MF_E_ASF_PARSINGINCOMPLETE = -1072874856; public const int MF_E_ASF_MISSINGDATA = -1072874855; public const int MF_E_ASF_INVALIDDATA = -1072874854; public const int MF_E_ASF_OPAQUEPACKET = -1072874853; public const int MF_E_ASF_NOINDEX = -1072874852; public const int MF_E_ASF_OUTOFRANGE = -1072874851; public const int MF_E_ASF_INDEXNOTLOADED = -1072874850; public const int MF_E_ASF_TOO_MANY_PAYLOADS = -1072874849; public const int MF_E_ASF_UNSUPPORTED_STREAM_TYPE = -1072874848; public const int MF_E_ASF_DROPPED_PACKET = -1072874847; public const int MF_E_NO_EVENTS_AVAILABLE = -1072873856; public const int MF_E_INVALID_STATE_TRANSITION = -1072873854; public const int MF_E_END_OF_STREAM = -1072873852; public const int MF_E_SHUTDOWN = -1072873851; public const int MF_E_MP3_NOTFOUND = -1072873850; public const int MF_E_MP3_OUTOFDATA = -1072873849; public const int MF_E_MP3_NOTMP3 = -1072873848; public const int MF_E_MP3_NOTSUPPORTED = -1072873847; public const int MF_E_NO_DURATION = -1072873846; public const int MF_E_INVALID_FORMAT = -1072873844; public const int MF_E_PROPERTY_NOT_FOUND = -1072873843; public const int MF_E_PROPERTY_READ_ONLY = -1072873842; public const int MF_E_PROPERTY_NOT_ALLOWED = -1072873841; public const int MF_E_MEDIA_SOURCE_NOT_STARTED = -1072873839; public const int MF_E_UNSUPPORTED_FORMAT = -1072873832; public const int MF_E_MP3_BAD_CRC = -1072873831; public const int MF_E_NOT_PROTECTED = -1072873830; public const int MF_E_MEDIA_SOURCE_WRONGSTATE = -1072873829; public const int MF_E_MEDIA_SOURCE_NO_STREAMS_SELECTED = -1072873828; public const int MF_E_CANNOT_FIND_KEYFRAME_SAMPLE = -1072873827; public const int MF_E_NETWORK_RESOURCE_FAILURE = -1072872856; public const int MF_E_NET_WRITE = -1072872855; public const int MF_E_NET_READ = -1072872854; public const int MF_E_NET_REQUIRE_NETWORK = -1072872853; public const int MF_E_NET_REQUIRE_ASYNC = -1072872852; public const int MF_E_NET_BWLEVEL_NOT_SUPPORTED = -1072872851; public const int MF_E_NET_STREAMGROUPS_NOT_SUPPORTED = -1072872850; public const int MF_E_NET_MANUALSS_NOT_SUPPORTED = -1072872849; public const int MF_E_NET_INVALID_PRESENTATION_DESCRIPTOR = -1072872848; public const int MF_E_NET_CACHESTREAM_NOT_FOUND = -1072872847; public const int MF_I_MANUAL_PROXY = 1074610802; public const int MF_E_NET_REQUIRE_INPUT = -1072872844; public const int MF_E_NET_REDIRECT = -1072872843; public const int MF_E_NET_REDIRECT_TO_PROXY = -1072872842; public const int MF_E_NET_TOO_MANY_REDIRECTS = -1072872841; public const int MF_E_NET_TIMEOUT = -1072872840; public const int MF_E_NET_CLIENT_CLOSE = -1072872839; public const int MF_E_NET_BAD_CONTROL_DATA = -1072872838; public const int MF_E_NET_INCOMPATIBLE_SERVER = -1072872837; public const int MF_E_NET_UNSAFE_URL = -1072872836; public const int MF_E_NET_CACHE_NO_DATA = -1072872835; public const int MF_E_NET_EOL = -1072872834; public const int MF_E_NET_BAD_REQUEST = -1072872833; public const int MF_E_NET_INTERNAL_SERVER_ERROR = -1072872832; public const int MF_E_NET_SESSION_NOT_FOUND = -1072872831; public const int MF_E_NET_NOCONNECTION = -1072872830; public const int MF_E_NET_CONNECTION_FAILURE = -1072872829; public const int MF_E_NET_INCOMPATIBLE_PUSHSERVER = -1072872828; public const int MF_E_NET_SERVER_ACCESSDENIED = -1072872827; public const int MF_E_NET_PROXY_ACCESSDENIED = -1072872826; public const int MF_E_NET_CANNOTCONNECT = -1072872825; public const int MF_E_NET_INVALID_PUSH_TEMPLATE = -1072872824; public const int MF_E_NET_INVALID_PUSH_PUBLISHING_POINT = -1072872823; public const int MF_E_NET_BUSY = -1072872822; public const int MF_E_NET_RESOURCE_GONE = -1072872821; public const int MF_E_NET_ERROR_FROM_PROXY = -1072872820; public const int MF_E_NET_PROXY_TIMEOUT = -1072872819; public const int MF_E_NET_SERVER_UNAVAILABLE = -1072872818; public const int MF_E_NET_TOO_MUCH_DATA = -1072872817; public const int MF_E_NET_SESSION_INVALID = -1072872816; public const int MF_E_OFFLINE_MODE = -1072872815; public const int MF_E_NET_UDP_BLOCKED = -1072872814; public const int MF_E_NET_UNSUPPORTED_CONFIGURATION = -1072872813; public const int MF_E_NET_PROTOCOL_DISABLED = -1072872812; public const int MF_E_ALREADY_INITIALIZED = -1072871856; public const int MF_E_BANDWIDTH_OVERRUN = -1072871855; public const int MF_E_LATE_SAMPLE = -1072871854; public const int MF_E_FLUSH_NEEDED = -1072871853; public const int MF_E_INVALID_PROFILE = -1072871852; public const int MF_E_INDEX_NOT_COMMITTED = -1072871851; public const int MF_E_NO_INDEX = -1072871850; public const int MF_E_CANNOT_INDEX_IN_PLACE = -1072871849; public const int MF_E_MISSING_ASF_LEAKYBUCKET = -1072871848; public const int MF_E_INVALID_ASF_STREAMID = -1072871847; public const int MF_E_STREAMSINK_REMOVED = -1072870856; public const int MF_E_STREAMSINKS_OUT_OF_SYNC = -1072870854; public const int MF_E_STREAMSINKS_FIXED = -1072870853; public const int MF_E_STREAMSINK_EXISTS = -1072870852; public const int MF_E_SAMPLEALLOCATOR_CANCELED = -1072870851; public const int MF_E_SAMPLEALLOCATOR_EMPTY = -1072870850; public const int MF_E_SINK_ALREADYSTOPPED = -1072870849; public const int MF_E_ASF_FILESINK_BITRATE_UNKNOWN = -1072870848; public const int MF_E_SINK_NO_STREAMS = -1072870847; public const int MF_S_SINK_NOT_FINALIZED = 870978; public const int MF_E_METADATA_TOO_LONG = -1072870845; public const int MF_E_SINK_NO_SAMPLES_PROCESSED = -1072870844; public const int MF_E_VIDEO_REN_NO_PROCAMP_HW = -1072869856; public const int MF_E_VIDEO_REN_NO_DEINTERLACE_HW = -1072869855; public const int MF_E_VIDEO_REN_COPYPROT_FAILED = -1072869854; public const int MF_E_VIDEO_REN_SURFACE_NOT_SHARED = -1072869853; public const int MF_E_VIDEO_DEVICE_LOCKED = -1072869852; public const int MF_E_NEW_VIDEO_DEVICE = -1072869851; public const int MF_E_NO_VIDEO_SAMPLE_AVAILABLE = -1072869850; public const int MF_E_NO_AUDIO_PLAYBACK_DEVICE = -1072869756; public const int MF_E_AUDIO_PLAYBACK_DEVICE_IN_USE = -1072869755; public const int MF_E_AUDIO_PLAYBACK_DEVICE_INVALIDATED = -1072869754; public const int MF_E_AUDIO_SERVICE_NOT_RUNNING = -1072869753; public const int MF_E_TOPO_INVALID_OPTIONAL_NODE = -1072868850; public const int MF_E_TOPO_CANNOT_FIND_DECRYPTOR = -1072868847; public const int MF_E_TOPO_CODEC_NOT_FOUND = -1072868846; public const int MF_E_TOPO_CANNOT_CONNECT = -1072868845; public const int MF_E_TOPO_UNSUPPORTED = -1072868844; public const int MF_E_TOPO_INVALID_TIME_ATTRIBUTES = -1072868843; public const int MF_E_TOPO_LOOPS_IN_TOPOLOGY = -1072868842; public const int MF_E_TOPO_MISSING_PRESENTATION_DESCRIPTOR = -1072868841; public const int MF_E_TOPO_MISSING_STREAM_DESCRIPTOR = -1072868840; public const int MF_E_TOPO_STREAM_DESCRIPTOR_NOT_SELECTED = -1072868839; public const int MF_E_TOPO_MISSING_SOURCE = -1072868838; public const int MF_E_TOPO_SINK_ACTIVATES_UNSUPPORTED = -1072868837; public const int MF_E_SEQUENCER_UNKNOWN_SEGMENT_ID = -1072864852; public const int MF_S_SEQUENCER_CONTEXT_CANCELED = 876973; public const int MF_E_NO_SOURCE_IN_CACHE = -1072864850; public const int MF_S_SEQUENCER_SEGMENT_AT_END_OF_STREAM = 876975; public const int MF_E_TRANSFORM_TYPE_NOT_SET = -1072861856; public const int MF_E_TRANSFORM_STREAM_CHANGE = -1072861855; public const int MF_E_TRANSFORM_INPUT_REMAINING = -1072861854; public const int MF_E_TRANSFORM_PROFILE_MISSING = -1072861853; public const int MF_E_TRANSFORM_PROFILE_INVALID_OR_CORRUPT = -1072861852; public const int MF_E_TRANSFORM_PROFILE_TRUNCATED = -1072861851; public const int MF_E_TRANSFORM_PROPERTY_PID_NOT_RECOGNIZED = -1072861850; public const int MF_E_TRANSFORM_PROPERTY_VARIANT_TYPE_WRONG = -1072861849; public const int MF_E_TRANSFORM_PROPERTY_NOT_WRITEABLE = -1072861848; public const int MF_E_TRANSFORM_PROPERTY_ARRAY_VALUE_WRONG_NUM_DIM = -1072861847; public const int MF_E_TRANSFORM_PROPERTY_VALUE_SIZE_WRONG = -1072861846; public const int MF_E_TRANSFORM_PROPERTY_VALUE_OUT_OF_RANGE = -1072861845; public const int MF_E_TRANSFORM_PROPERTY_VALUE_INCOMPATIBLE = -1072861844; public const int MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_OUTPUT_MEDIATYPE = -1072861843; public const int MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_INPUT_MEDIATYPE = -1072861842; public const int MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_MEDIATYPE_COMBINATION = -1072861841; public const int MF_E_TRANSFORM_CONFLICTS_WITH_OTHER_CURRENTLY_ENABLED_FEATURES = -1072861840; public const int MF_E_TRANSFORM_NEED_MORE_INPUT = -1072861838; public const int MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_SPKR_CONFIG = -1072861837; public const int MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING = -1072861836; public const int MF_S_TRANSFORM_DO_NOT_PROPAGATE_EVENT = 879989; public const int MF_E_UNSUPPORTED_D3D_TYPE = -1072861834; public const int MF_E_TRANSFORM_ASYNC_LOCKED = -1072861833; public const int MF_E_TRANSFORM_CANNOT_INITIALIZE_ACM_DRIVER = -1072861832; public const int MF_E_LICENSE_INCORRECT_RIGHTS = -1072860856; public const int MF_E_LICENSE_OUTOFDATE = -1072860855; public const int MF_E_LICENSE_REQUIRED = -1072860854; public const int MF_E_DRM_HARDWARE_INCONSISTENT = -1072860853; public const int MF_E_NO_CONTENT_PROTECTION_MANAGER = -1072860852; public const int MF_E_LICENSE_RESTORE_NO_RIGHTS = -1072860851; public const int MF_E_BACKUP_RESTRICTED_LICENSE = -1072860850; public const int MF_E_LICENSE_RESTORE_NEEDS_INDIVIDUALIZATION = -1072860849; public const int MF_S_PROTECTION_NOT_REQUIRED = 880976; public const int MF_E_COMPONENT_REVOKED = -1072860847; public const int MF_E_TRUST_DISABLED = -1072860846; public const int MF_E_WMDRMOTA_NO_ACTION = -1072860845; public const int MF_E_WMDRMOTA_ACTION_ALREADY_SET = -1072860844; public const int MF_E_WMDRMOTA_DRM_HEADER_NOT_AVAILABLE = -1072860843; public const int MF_E_WMDRMOTA_DRM_ENCRYPTION_SCHEME_NOT_SUPPORTED = -1072860842; public const int MF_E_WMDRMOTA_ACTION_MISMATCH = -1072860841; public const int MF_E_WMDRMOTA_INVALID_POLICY = -1072860840; public const int MF_E_POLICY_UNSUPPORTED = -1072860839; public const int MF_E_OPL_NOT_SUPPORTED = -1072860838; public const int MF_E_TOPOLOGY_VERIFICATION_FAILED = -1072860837; public const int MF_E_SIGNATURE_VERIFICATION_FAILED = -1072860836; public const int MF_E_DEBUGGING_NOT_ALLOWED = -1072860835; public const int MF_E_CODE_EXPIRED = -1072860834; public const int MF_E_GRL_VERSION_TOO_LOW = -1072860833; public const int MF_E_GRL_RENEWAL_NOT_FOUND = -1072860832; public const int MF_E_GRL_EXTENSIBLE_ENTRY_NOT_FOUND = -1072860831; public const int MF_E_KERNEL_UNTRUSTED = -1072860830; public const int MF_E_PEAUTH_UNTRUSTED = -1072860829; public const int MF_E_NON_PE_PROCESS = -1072860827; public const int MF_E_REBOOT_REQUIRED = -1072860825; public const int MF_S_WAIT_FOR_POLICY_SET = 881000; public const int MF_S_VIDEO_DISABLED_WITH_UNKNOWN_SOFTWARE_OUTPUT = 881001; public const int MF_E_GRL_INVALID_FORMAT = -1072860822; public const int MF_E_GRL_UNRECOGNIZED_FORMAT = -1072860821; public const int MF_E_ALL_PROCESS_RESTART_REQUIRED = -1072860820; public const int MF_E_PROCESS_RESTART_REQUIRED = -1072860819; public const int MF_E_USERMODE_UNTRUSTED = -1072860818; public const int MF_E_PEAUTH_SESSION_NOT_STARTED = -1072860817; public const int MF_E_PEAUTH_PUBLICKEY_REVOKED = -1072860815; public const int MF_E_GRL_ABSENT = -1072860814; public const int MF_S_PE_TRUSTED = 881011; public const int MF_E_PE_UNTRUSTED = -1072860812; public const int MF_E_PEAUTH_NOT_STARTED = -1072860811; public const int MF_E_INCOMPATIBLE_SAMPLE_PROTECTION = -1072860810; public const int MF_E_PE_SESSIONS_MAXED = -1072860809; public const int MF_E_HIGH_SECURITY_LEVEL_CONTENT_NOT_ALLOWED = -1072860808; public const int MF_E_TEST_SIGNED_COMPONENTS_NOT_ALLOWED = -1072860807; public const int MF_E_ITA_UNSUPPORTED_ACTION = -1072860806; public const int MF_E_ITA_ERROR_PARSING_SAP_PARAMETERS = -1072860805; public const int MF_E_POLICY_MGR_ACTION_OUTOFBOUNDS = -1072860804; public const int MF_E_BAD_OPL_STRUCTURE_FORMAT = -1072860803; public const int MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_PROTECTION_GUID = -1072860802; public const int MF_E_NO_PMP_HOST = -1072860801; public const int MF_E_ITA_OPL_DATA_NOT_INITIALIZED = -1072860800; public const int MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_OUTPUT = -1072860799; public const int MF_E_ITA_UNRECOGNIZED_DIGITAL_VIDEO_OUTPUT = -1072860798; public const int MF_E_CLOCK_INVALID_CONTINUITY_KEY = -1072849856; public const int MF_E_CLOCK_NO_TIME_SOURCE = -1072849855; public const int MF_E_CLOCK_STATE_ALREADY_SET = -1072849854; public const int MF_E_CLOCK_NOT_SIMPLE = -1072849853; public const int MF_S_CLOCK_STOPPED = 891972; public const int MF_E_NO_MORE_DROP_MODES = -1072848856; public const int MF_E_NO_MORE_QUALITY_LEVELS = -1072848855; public const int MF_E_DROPTIME_NOT_SUPPORTED = -1072848854; public const int MF_E_QUALITYKNOB_WAIT_LONGER = -1072848853; public const int MF_E_QM_INVALIDSTATE = -1072848852; public const int MF_E_TRANSCODE_NO_CONTAINERTYPE = -1072847856; public const int MF_E_TRANSCODE_PROFILE_NO_MATCHING_STREAMS = -1072847855; public const int MF_E_TRANSCODE_NO_MATCHING_ENCODER = -1072847854; public const int MF_E_ALLOCATOR_NOT_INITIALIZED = -1072846856; public const int MF_E_ALLOCATOR_NOT_COMMITED = -1072846855; public const int MF_E_ALLOCATOR_ALREADY_COMMITED = -1072846854; public const int MF_E_STREAM_ERROR = -1072846853; public const int MF_E_INVALID_STREAM_STATE = -1072846852; public const int MF_E_HW_STREAM_NOT_CONNECTED = -1072846851; } public static class MediaFoundationApi { private static bool initialized; public static void Startup() { if (!initialized) { int num = 2; OperatingSystem oSVersion = Environment.OSVersion; if (oSVersion.Version.Major == 6 && oSVersion.Version.Minor == 0) { num = 1; } MediaFoundationInterop.MFStartup((num << 16) | 0x70); initialized = true; } } public static IEnumerable<IMFActivate> EnumerateTransforms(Guid category) { MediaFoundationInterop.MFTEnumEx(category, _MFT_ENUM_FLAG.MFT_ENUM_FLAG_ALL, null, null, out var interfacesPointer, out var pcMFTActivate); IMFActivate[] array = new IMFActivate[pcMFTActivate]; for (int i = 0; i < pcMFTActivate; i++) { IntPtr pUnk = Marshal.ReadIntPtr(new IntPtr(interfacesPointer.ToInt64() + i * Marshal.SizeOf(interfacesPointer))); array[i] = (IMFActivate)Marshal.GetObjectForIUnknown(pUnk); } IMFActivate[] array2 = array; for (int j = 0; j < array2.Length; j++) { yield return array2[j]; } Marshal.FreeCoTaskMem(interfacesPointer); } public static void Shutdown() { if (initialized) { MediaFoundationInterop.MFShutdown(); initialized = false; } } public static IMFMediaType CreateMediaType() { MediaFoundationInterop.MFCreateMediaType(out var ppMFType); return ppMFType; } public static IMFMediaType CreateMediaTypeFromWaveFormat(WaveFormat waveFormat) { IMFMediaType iMFMediaType = CreateMediaType(); try { MediaFoundationInterop.MFInitMediaTypeFromWaveFormatEx(iMFMediaType, waveFormat, Marshal.SizeOf<WaveFormat>(waveFormat)); return iMFMediaType; } catch (Exception) { Marshal.ReleaseComObject(iMFMediaType); throw; } } public static IMFMediaBuffer CreateMemoryBuffer(int bufferSize) { MediaFoundationInterop.MFCreateMemoryBuffer(bufferSize, out var ppBuffer); return ppBuffer; } public static IMFSample CreateSample() { MediaFoundationInterop.MFCreateSample(out var ppIMFSample); return ppIMFSample; } public static IMFAttributes CreateAttributes(int initialSize) { MediaFoundationInterop.MFCreateAttributes(out var ppMFAttributes, initialSize); return ppMFAttributes; } public static IMFByteStream CreateByteStream(object stream) { if (stream is IStream) { MediaFoundationInterop.MFCreateMFByteStreamOnStream(stream as IStream, out var ppByteStream); return ppByteStream; } throw new ArgumentException("Stream must be IStream in desktop apps"); } public static IMFSourceReader CreateSourceReaderFromByteStream(IMFByteStream byteStream) { MediaFoundationInterop.MFCreateSourceReaderFromByteStream(byteStream, null, out var ppSourceReader); return ppSourceReader; } } public static class MediaFoundationInterop { public const int MF_SOURCE_READER_ALL_STREAMS = -2; public const int MF_SOURCE_READER_FIRST_AUDIO_STREAM = -3; public const int MF_SOURCE_READER_FIRST_VIDEO_STREAM = -4; public const int MF_SOURCE_READER_MEDIASOURCE = -1; public const int MF_SDK_VERSION = 2; public const int MF_API_VERSION = 112; public const int MF_VERSION = 131184; [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFStartup(int version, int dwFlags = 0); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFShutdown(); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] internal static extern void MFCreateMediaType(out IMFMediaType ppMFType); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] internal static extern void MFInitMediaTypeFromWaveFormatEx([In] IMFMediaType pMFType, [In] WaveFormat pWaveFormat, [In] int cbBufSize); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] internal static extern void MFCreateWaveFormatExFromMFMediaType(IMFMediaType pMFType, ref IntPtr ppWF, ref int pcbSize, int flags = 0); [DllImport("mfreadwrite.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFCreateSourceReaderFromURL([In][MarshalAs(UnmanagedType.LPWStr)] string pwszURL, [In] IMFAttributes pAttributes, [MarshalAs(UnmanagedType.Interface)] out IMFSourceReader ppSourceReader); [DllImport("mfreadwrite.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFCreateSourceReaderFromByteStream([In] IMFByteStream pByteStream, [In] IMFAttributes pAttributes, [MarshalAs(UnmanagedType.Interface)] out IMFSourceReader ppSourceReader); [DllImport("mfreadwrite.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFCreateSinkWriterFromURL([In][MarshalAs(UnmanagedType.LPWStr)] string pwszOutputURL, [In] IMFByteStream pByteStream, [In] IMFAttributes pAttributes, out IMFSinkWriter ppSinkWriter); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFCreateMFByteStreamOnStreamEx([MarshalAs(UnmanagedType.IUnknown)] object punkStream, out IMFByteStream ppByteStream); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFCreateMFByteStreamOnStream([In] IStream punkStream, out IMFByteStream ppByteStream); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFTEnumEx([In] Guid guidCategory, [In] _MFT_ENUM_FLAG flags, [In] MFT_REGISTER_TYPE_INFO pInputType, [In] MFT_REGISTER_TYPE_INFO pOutputType, out IntPtr pppMFTActivate, out int pcMFTActivate); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] internal static extern void MFCreateSample(out IMFSample ppIMFSample); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] internal static extern void MFCreateMemoryBuffer(int cbMaxLength, out IMFMediaBuffer ppBuffer); [DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)] internal static extern void MFCreateAttributes([MarshalAs(UnmanagedType.Interface)] out IMFAttributes ppMFAttributes, [In] int cInitialSize); [DllImport("mf.dll", ExactSpelling = true, PreserveSig = false)] public static extern void MFTranscodeGetAudioOutputAvailableTypes([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidSubType, [In] _MFT_ENUM_FLAG dwMFTFlags, [In] IMFAttributes pCodecConfig, [MarshalAs(UnmanagedType.Interface)] out IMFCollection ppAvailableTypes); } public abstract class MediaFoundationTransform : IWaveProvider, IDisposable { protected readonly IWaveProvider sourceProvider; protected readonly WaveFormat outputWaveFormat; private readonly byte[] sourceBuffer; private byte[] outputBuffer; private int outputBufferOffset; private int outputBufferCount; private IMFTransform transform; private bool disposed; private long inputPosition; private long outputPosition; private bool initializedForStreaming; public WaveFormat WaveFormat => outputWaveFormat; public MediaFoundationTransform(IWaveProvider sourceProvider, WaveFormat outputFormat) { outputWaveFormat = outputFormat; this.sourceProvider = sourceProvider; sourceBuffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond]; outputBuffer = new byte[outputWaveFormat.AverageBytesPerSecond + outputWaveFormat.BlockAlign]; } private void InitializeTransformForStreaming() { transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_COMMAND_FLUSH, IntPtr.Zero); transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, IntPtr.Zero); transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_NOTIFY_START_OF_STREAM, IntPtr.Zero); initializedForStreaming = true; } protected abstract IMFTransform CreateTransform(); protected virtual void Dispose(bool disposing) { if (transform != null) { Marshal.ReleaseComObject(transform); } } public void Dispose() { if (!disposed) { disposed = true; Dispose(disposing: true); GC.SuppressFinalize(this); } } ~MediaFoundationTransform() { Dispose(disposing: false); } public int Read(byte[] buffer, int offset, int count) { if (transform == null) { transform = CreateTransform(); InitializeTransformForStreaming(); } int i = 0; if (outputBufferCount > 0) { i += ReadFromOutputBuffer(buffer, offset, count - i); } for (; i < count; i += ReadFromOutputBuffer(buffer, offset + i, count - i)) { IMFSample iMFSample = ReadFromSource(); if (iMFSample == null) { EndStreamAndDrain(); i += ReadFromOutputBuffer(buffer, offset + i, count - i); ClearOutputBuffer(); break; } if (!initializedForStreaming) { InitializeTransformForStreaming(); } transform.ProcessInput(0, iMFSample, 0); Marshal.ReleaseComObject(iMFSample); ReadFromTransform(); } return i; } private void EndStreamAndDrain() { transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_NOTIFY_END_OF_STREAM, IntPtr.Zero); transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_COMMAND_DRAIN, IntPtr.Zero); int num; do { num = ReadFromTransform(); } while (num > 0); inputPosition = 0L; outputPosition = 0L; transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_NOTIFY_END_STREAMING, IntPtr.Zero); initializedForStreaming = false; } private void ClearOutputBuffer() { outputBufferCount = 0; outputBufferOffset = 0; } private int ReadFromTransform() { MFT_OUTPUT_DATA_BUFFER[] array = new MFT_OUTPUT_DATA_BUFFER[1]; IMFSample iMFSample = MediaFoundationApi.CreateSample(); IMFMediaBuffer iMFMediaBuffer = MediaFoundationApi.CreateMemoryBuffer(outputBuffer.Length); iMFSample.AddBuffer(iMFMediaBuffer); iMFSample.SetSampleTime(outputPosition); array[0].pSample = iMFSample; _MFT_PROCESS_OUTPUT_STATUS pdwStatus; int num = transform.ProcessOutput(_MFT_PROCESS_OUTPUT_FLAGS.None, 1, array, out pdwStatus); switch (num) { case -1072861838: Marshal.ReleaseComObject(iMFMediaBuffer); Marshal.ReleaseComObject(iMFSample); return 0; default: Marshal.ThrowExceptionForHR(num); break; case 0: break; } array[0].pSample.ConvertToContiguousBuffer(out var ppBuffer); ppBuffer.Lock(out var ppbBuffer, out var _, out var pcbCurrentLength); outputBuffer = BufferHelpers.Ensure(outputBuffer, pcbCurrentLength); Marshal.Copy(ppbBuffer, outputBuffer, 0, pcbCurrentLength); outputBufferOffset = 0; outputBufferCount = pcbCurrentLength; ppBuffer.Unlock(); outputPosition += BytesToNsPosition(outputBufferCount, WaveFormat); Marshal.ReleaseComObject(iMFMediaBuffer); iMFSample.RemoveAllBuffers(); Marshal.ReleaseComObject(iMFSample); Marshal.ReleaseComObject(ppBuffer); return pcbCurrentLength; } private static long BytesToNsPosition(int bytes, WaveFormat waveFormat) { return 10000000L * (long)bytes / waveFormat.AverageBytesPerSecond; } private IMFSample ReadFromSource() { int num = sourceProvider.Read(sourceBuffer, 0, sourceBuffer.Length); if (num == 0) { return null; } IMFMediaBuffer iMFMediaBuffer = MediaFoundationApi.CreateMemoryBuffer(num); iMFMediaBuffer.Lock(out var ppbBuffer, out var _, out var _); Marshal.Copy(sourceBuffer, 0, ppbBuffer, num); iMFMediaBuffer.Unlock(); iMFMediaBuffer.SetCurrentLength(num); IMFSample iMFSample = MediaFoundationApi.CreateSample(); iMFSample.AddBuffer(iMFMediaBuffer); iMFSample.SetSampleTime(inputPosition); long num2 = BytesToNsPosition(num, sourceProvider.WaveFormat); iMFSample.SetSampleDuration(num2); inputPosition += num2; Marshal.ReleaseComObject(iMFMediaBuffer); return iMFSample; } private int ReadFromOutputBuffer(byte[] buffer, int offset, int needed) { int num = Math.Min(needed, outputBufferCount); Array.Copy(outputBuffer, outputBufferOffset, buffer, offset, num); outputBufferOffset += num; outputBufferCount -= num; if (outputBufferCount == 0) { outputBufferOffset = 0; } return num; } public void Reposition() { if (initializedForStreaming) { EndStreamAndDrain(); ClearOutputBuffer(); InitializeTransformForStreaming(); } } } public static class MediaFoundationTransformCategories { [FieldDescription("Video Decoder")] public static readonly Guid VideoDecoder = new Guid("{d6c02d4b-6833-45b4-971a-05a4b04bab91}"); [FieldDescription("Video Encoder")] public static readonly Guid VideoEncoder = new Guid("{f79eac7d-e545-4387-bdee-d647d7bde42a}"); [FieldDescription("Video Effect")] public static readonly Guid VideoEffect = new Guid("{12e17c21-532c-4a6e-8a1c-40825a736397}"); [FieldDescription("Multiplexer")] public static readonly Guid Multiplexer = new Guid("{059c561e-05ae-4b61-b69d-55b61ee54a7b}"); [FieldDescription("Demultiplexer")] public static readonly Guid Demultiplexer = new Guid("{a8700a7a-939b-44c5-99d7-76226b23b3f1}"); [FieldDescription("Audio Decoder")] public static readonly Guid AudioDecoder = new Guid("{9ea73fb4-ef7a-4559-8d5d-719d8f0426c7}"); [FieldDescription("Audio Encoder")] public static readonly Guid AudioEncoder = new Guid("{91c64bd0-f91e-4d8c-9276-db248279d975}"); [FieldDescription("Audio Effect")] public static readonly Guid AudioEffect = new Guid("{11064c48-3648-4ed0-932e-05ce8ac811b7}"); [FieldDescription("Video Processor")] public static readonly Guid VideoProcessor = new Guid("{302EA3FC-AA5F-47f9-9F7A-C2188BB16302}"); [FieldDescription("Other")] public static readonly Guid Other = new Guid("{90175d57-b7ea-4901-aeb3-933a8747756f}"); } public class MediaType { private readonly IMFMediaType mediaType; public int SampleRate { get { return GetUInt32(MediaFoundationAttributes.MF_MT_AUDIO_SAMPLES_PER_SECOND); } set { mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_SAMPLES_PER_SECOND, value); } } public int ChannelCount { get { return GetUInt32(MediaFoundationAttributes.MF_MT_AUDIO_NUM_CHANNELS); } set { mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_NUM_CHANNELS, value); } } public int BitsPerSample { get { return GetUInt32(MediaFoundationAttributes.MF_MT_AUDIO_BITS_PER_SAMPLE); } set { mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_BITS_PER_SAMPLE, value); } } public int AverageBytesPerSecond => GetUInt32(MediaFoundationAttributes.MF_MT_AUDIO_AVG_BYTES_PER_SECOND); public Guid SubType { get { return GetGuid(MediaFoundationAttributes.MF_MT_SUBTYPE); } set { mediaType.SetGUID(MediaFoundationAttributes.MF_MT_SUBTYPE, value); } } public Guid MajorType { get { return GetGuid(MediaFoundationAttributes.MF_MT_MAJOR_TYPE); } set { mediaType.SetGUID(MediaFoundationAttributes.MF_MT_MAJOR_TYPE, value); } } public IMFMediaType MediaFoundationObject => mediaType; public MediaType(IMFMediaType mediaType) { this.mediaType = mediaType; } public MediaType() { mediaType = MediaFoundationApi.CreateMediaType(); } public MediaType(WaveFormat waveFormat) { mediaType = MediaFoundationApi.CreateMediaTypeFromWaveFormat(waveFormat); } private int GetUInt32(Guid key) { mediaType.GetUINT32(key, out var punValue); return punValue; } private Guid GetGuid(Guid key) { mediaType.GetGUID(key, out var pguidValue); return pguidValue; } public int TryGetUInt32(Guid key, int defaultValue = -1) { int punValue = defaultValue; try { mediaType.GetUINT32(key, out punValue); } catch (COMException ex) { if (HResult.GetHResult(ex) != -1072875802) { if (HResult.GetHResult(ex) == -1072875843) { throw new ArgumentException("Not a UINT32 parameter"); } throw; } } return punValue; } public void SetUInt32(Guid key, int value) { mediaType.SetUINT32(key, value); } } public static class MediaTypes { public static readonly Guid MFMediaType_Default = new Guid("81A412E6-8103-4B06-857F-1862781024AC"); [FieldDescription("Audio")] public static readonly Guid MFMediaType_Audio = new Guid("73647561-0000-0010-8000-00aa00389b71"); [FieldDescription("Video")] public static readonly Guid MFMediaType_Video = new Guid("73646976-0000-0010-8000-00aa00389b71"); [FieldDescription("Protected Media")] public static readonly Guid MFMediaType_Protected = new Guid("7b4b6fe6-9d04-4494-be14-7e0bd076c8e4"); [FieldDescription("SAMI captions")] public static readonly Guid MFMediaType_SAMI = new Guid("e69669a0-3dcd-40cb-9e2e-3708387c0616"); [FieldDescription("Script stream")] public static readonly Guid MFMediaType_Script = new Guid("72178c22-e45b-11d5-bc2a-00b0d0f3f4ab"); [FieldDescription("Still image stream")] public static readonly Guid MFMediaType_Image = new Guid("72178c23-e45b-11d5-bc2a-00b0d0f3f4ab"); [FieldDescription("HTML stream")] public static readonly Guid MFMediaType_HTML = new Guid("72178c24-e45b-11d5-bc2a-00b0d0f3f4ab"); [FieldDescription("Binary stream")] public static readonly Guid MFMediaType_Binary = new Guid("72178c25-e45b-11d5-bc2a-00b0d0f3f4ab"); [FieldDescription("File transfer")] public static readonly Guid MFMediaType_FileTransfer = new Guid("72178c26-e45b-11d5-bc2a-00b0d0f3f4ab"); } public struct MFT_INPUT_STREAM_INFO { public long hnsMaxLatency; public _MFT_INPUT_STREAM_INFO_FLAGS dwFlags; public int cbSize; public int cbMaxLookahead; public int cbAlignment; } public enum MFT_MESSAGE_TYPE { MFT_MESSAGE_COMMAND_FLUSH = 0, MFT_MESSAGE_COMMAND_DRAIN = 1, MFT_MESSAGE_SET_D3D_MANAGER = 2, MFT_MESSAGE_DROP_SAMPLES = 3, MFT_MESSAGE_COMMAND_TICK = 4, MFT_MESSAGE_NOTIFY_BEGIN_STREAMING = 268435456, MFT_MESSAGE_NOTIFY_END_STREAMING = 268435457, MFT_MESSAGE_NOTIFY_END_OF_STREAM = 268435458, MFT_MESSAGE_NOTIFY_START_OF_STREAM = 268435459, MFT_MESSAGE_COMMAND_MARKER = 536870912 } public struct MFT_OUTPUT_DATA_BUFFER { public int dwStreamID; public IMFSample pSample; public _MFT_OUTPUT_DATA_BUFFER_FLAGS dwStatus; public IMFCollection pEvents; } public struct MFT_OUTPUT_STREAM_INFO { public _MFT_OUTPUT_STREAM_INFO_FLAGS dwFlags; public int cbSize; public int cbAlignment; } [StructLayout(LayoutKind.Sequential)] public class MFT_REGISTER_TYPE_INFO { public Guid guidMajorType; public Guid guidSubtype; } [StructLayout(LayoutKind.Sequential)] public class MF_SINK_WRITER_STATISTICS { public int cb; public long llLastTimestampReceived; public long llLastTimestampEncoded; public long llLastTimestampProcessed; public long llLastStreamTickReceived; public long llLastSinkSampleRequest; public long qwNumSamplesReceived; public long qwNumSamplesEncoded; public long qwNumSamplesProcessed; public long qwNumStreamTicksReceived; public int dwByteCountQueued; public long qwByteCountProcessed; public int dwNumOutstandingSinkSampleRequests; public int dwAverageSampleRateReceived; public int dwAverageSampleRateEncoded; public int dwAverageSampleRateProcessed; } public static class TranscodeContainerTypes { public static readonly Guid MFTranscodeContainerType_ASF = new Guid(1125085038u, 46783, 20417, 160, 189, 158, 228, 110, 238, 42, 251); public static readonly Guid MFTranscodeContainerType_MPEG4 = new Guid(3698118749u, 47568, 16623, 189, 53, 250, 98, 44, 26, 178, 138); public static readonly Guid MFTranscodeContainerType_MP3 = new Guid(3828922642u, 33777, 19942, 158, 58, 159, 251, 198, 221, 36, 209); public static readonly Guid MFTranscodeContainerType_3GP = new Guid(885326183, 17522, 20276, 158, 160, 196, 159, 186, 207, 3, 125); public static readonly Guid MFTranscodeContainerType_AC3 = new Guid(1837994435u, 35985, 20177, 135, 66, 140, 52, 125, 91, 68, 208); public static readonly Guid MFTranscodeContainerType_ADTS = new Guid(321901181, 3842, 17374, 163, 1, 56, 251, 187, 179, 131, 78); public static readonly Guid MFTranscodeContainerType_MPEG2 = new Guid(3217218553u, 31668, 20367, 175, 222, 225, 18, 196, 75, 168, 130); public static readonly Guid MFTranscodeContainerType_FMPEG4 = new Guid(2611508977u, 16799, 19319, 161, 224, 53, 149, 157, 157, 64, 4); public static readonly Guid MFTranscodeContainerType_WAVE = new Guid(1690518844, 3878, 18241, 190, 99, 135, 189, 248, 187, 147, 91); public static readonly Guid MFTranscodeContainerType_AVI = new Guid(2128603311, 16431, 19830, 163, 60, 97, 159, 209, 87, 208, 241); public static readonly Guid MFTranscodeContainerType_AMR = new Guid(39672531, 25114, 18267, 150, 77, 102, 177, 200, 36, 240, 121); } [Flags] public enum _MFT_ENUM_FLAG { None = 0, MFT_ENUM_FLAG_SYNCMFT = 1, MFT_ENUM_FLAG_ASYNCMFT = 2, MFT_ENUM_FLAG_HARDWARE = 4, MFT_ENUM_FLAG_FIELDOFUSE = 8, MFT_ENUM_FLAG_LOCALMFT = 0x10, MFT_ENUM_FLAG_TRANSCODE_ONLY = 0x20, MFT_ENUM_FLAG_SORTANDFILTER = 0x40, MFT_ENUM_FLAG_ALL = 0x3F } [Flags] public enum _MFT_INPUT_STATUS_FLAGS { None = 0, MFT_INPUT_STATUS_ACCEPT_DATA = 1 } [Flags] public enum _MFT_INPUT_STREAM_INFO_FLAGS { None = 0, MFT_INPUT_STREAM_WHOLE_SAMPLES = 1, MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER = 2, MFT_INPUT_STREAM_FIXED_SAMPLE_SIZE = 4, MFT_INPUT_STREAM_HOLDS_BUFFERS = 8, MFT_INPUT_STREAM_DOES_NOT_ADDREF = 0x100, MFT_INPUT_STREAM_REMOVABLE = 0x200, MFT_INPUT_STREAM_OPTIONAL = 0x400, MFT_INPUT_STREAM_PROCESSES_IN_PLACE = 0x800 } [Flags] public enum _MFT_OUTPUT_DATA_BUFFER_FLAGS { None = 0, MFT_OUTPUT_DATA_BUFFER_INCOMPLETE = 0x1000000, MFT_OUTPUT_DATA_BUFFER_FORMAT_CHANGE = 0x100, MFT_OUTPUT_DATA_BUFFER_STREAM_END = 0x200, MFT_OUTPUT_DATA_BUFFER_NO_SAMPLE = 0x300 } [Flags] public enum _MFT_OUTPUT_STATUS_FLAGS { None = 0, MFT_OUTPUT_STATUS_SAMPLE_READY = 1 } [Flags] public enum _MFT_OUTPUT_STREAM_INFO_FLAGS { None = 0, MFT_OUTPUT_STREAM_WHOLE_SAMPLES = 1, MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER = 2, MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE = 4, MFT_OUTPUT_STREAM_DISCARDABLE = 8, MFT_OUTPUT_STREAM_OPTIONAL = 0x10, MFT_OUTPUT_STREAM_PROVIDES_SAMPLES = 0x100, MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES = 0x200, MFT_OUTPUT_STREAM_LAZY_READ = 0x400, MFT_OUTPUT_STREAM_REMOVABLE = 0x800 } [Flags] public enum _MFT_PROCESS_OUTPUT_FLAGS { None = 0, MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER = 1, MFT_PROCESS_OUTPUT_REGENERATE_LAST_OUTPUT = 2 } [Flags] public enum _MFT_PROCESS_OUTPUT_STATUS { None = 0, MFT_PROCESS_OUTPUT_STATUS_NEW_STREAMS = 0x100 } [Flags] public enum _MFT_SET_TYPE_FLAGS { None = 0, MFT_SET_TYPE_TEST_ONLY = 1 } } namespace NAudio.Dmo { public class DmoDescriptor { public string Name { get; private set; } public Guid Clsid { get; private set; } public DmoDescriptor(string name, Guid clsid) { Name = name; Clsid = clsid; } } public class DmoEnumerator { public static IEnumerable<DmoDescriptor> GetAudioEffectNames() { return GetDmos(DmoGuids.DMOCATEGORY_AUDIO_EFFECT); } public static IEnumerable<DmoDescriptor> GetAudioEncoderNames() { return GetDmos(DmoGuids.DMOCATEGORY_AUDIO_ENCODER); } public static IEnumerable<DmoDescriptor> GetAudioDecoderNames() { return GetDmos(DmoGuids.DMOCATEGORY_AUDIO_DECODER); } private static IEnumerable<DmoDescriptor> GetDmos(Guid category) { Marshal.ThrowExceptionForHR(DmoInterop.DMOEnum(ref category, DmoEnumFlags.None, 0, null, 0, null, out var enumDmo)); int itemsFetched; do { enumDmo.Next(1, out var clsid, out var name, out itemsFetched); if (itemsFetched == 1) { string name2 = Marshal.PtrToStringUni(name); Marshal.FreeCoTaskMem(name); yield return new DmoDescriptor(name2, clsid); } } while (itemsFetched > 0); } } [Flags] internal enum DmoEnumFlags { None = 0, DMO_ENUMF_INCLUDE_KEYED = 1 } internal static class DmoGuids { public static readonly Guid DMOCATEGORY_AUDIO_DECODER = new Guid("57f2db8b-e6bb-4513-9d43-dcd2a6593125"); public static readonly Guid DMOCATEGORY_AUDIO_ENCODER = new Guid("33D9A761-90C8-11d0-BD43-00A0C911CE86"); public static readonly Guid DMOCATEGORY_VIDEO_DECODER = new Guid("4a69b442-28be-4991-969c-b500adf5d8a8"); public static readonly Guid DMOCATEGORY_VIDEO_ENCODER = new Guid("33D9A760-90C8-11d0-BD43-00A0C911CE86"); public static readonly Guid DMOCATEGORY_AUDIO_EFFECT = new Guid("f3602b3f-0592-48df-a4cd-674721e7ebeb"); public static readonly Guid DMOCATEGORY_VIDEO_EFFECT = new Guid("d990ee14-776c-4723-be46-3da2f56f10b9"); public static readonly Guid DMOCATEGORY_AUDIO_CAPTURE_EFFECT = new Guid("f665aaba-3e09-4920-aa5f-219811148f09"); } internal static class DmoMediaTypeGuids { public static readonly Guid FORMAT_None = new Guid("0F6417D6-C318-11D0-A43F-00A0C9223196"); public static readonly Guid FORMAT_VideoInfo = new Guid("05589f80-c356-11ce-bf01-00aa0055595a"); public static readonly Guid FORMAT_VideoInfo2 = new Guid("F72A76A0-EB0A-11d0-ACE4-0000C0CC16BA"); public static readonly Guid FORMAT_WaveFormatEx = new Guid("05589f81-c356-11ce-bf01-00aa0055595a"); public static readonly Guid FORMAT_MPEGVideo = new Guid("05589f82-c356-11ce-bf01-00aa0055595a"); public static readonly Guid FORMAT_MPEGStreams = new Guid("05589f83-c356-11ce-bf01-00aa0055595a"); public static readonly Guid FORMAT_DvInfo = new Guid("05589f84-c356-11ce-bf01-00aa0055595a"); public static readonly Guid FORMAT_525WSS = new Guid("C7ECF04D-4582-4869-9ABB-BFB523B62EDF"); } internal enum DmoHResults { DMO_E_INVALIDSTREAMINDEX = -2147220991, DMO_E_INVALIDTYPE, DMO_E_TYPE_NOT_SET, DMO_E_NOTACCEPTING, DMO_E_TYPE_NOT_ACCEPTED, DMO_E_NO_MORE_ITEMS } [Flags] public enum DmoInPlaceProcessFlags { Normal = 0, Zero = 1 } public enum DmoInPlaceProcessReturn { Normal, HasEffectTail } [Flags] public enum DmoInputDataBufferFlags { None = 0, SyncPoint = 1, Time = 2, TimeLength = 4 } [Flags] internal enum DmoInputStatusFlags { None = 0, DMO_INPUT_STATUSF_ACCEPT_DATA = 1 } internal static class DmoInterop { [DllImport("msdmo.dll")] public static extern int DMOEnum([In] ref Guid guidCategory, DmoEnumFlags flags, int inTypes, [In] DmoPartialMediaType[] inTypesArray, int outTypes, [In] DmoPartialMediaType[] outTypesArray, out IEnumDmo enumDmo); [DllImport("msdmo.dll")] public static extern int MoFreeMediaType([In] ref DmoMediaType mediaType); [DllImport("msdmo.dll")] public static extern int MoInitMediaType([In][Out] ref DmoMediaType mediaType, int formatBlockBytes); [DllImport("msdmo.dll")] public static extern int DMOGetName([In] ref Guid clsidDMO, [Out] StringBuilder name); } public struct DmoMediaType { private Guid majortype; private Guid subtype; private bool bFixedSizeSamples; private bool bTemporalCompression; private int lSampleSize; private Guid formattype; private IntPtr pUnk; private int cbFormat; private IntPtr pbFormat; public Guid MajorType => majortype; public string MajorTypeName => MediaTypes.GetMediaTypeName(majortype); public Guid SubType => subtype; public string SubTypeName { get { if (majortype == MediaTypes.MEDIATYPE_Audio) { return AudioMediaSubtypes.GetAudioSubtypeName(subtype); } return subtype.ToString(); } } public bool FixedSizeSamples => bFixedSizeSamples; public int SampleSize => lSampleSize; public Guid FormatType => formattype; public string FormatTypeName { get { if (formattype == DmoMediaTypeGuids.FORMAT_None) { return "None"; } if (formattype == Guid.Empty) { return "Null"; } if (formattype == DmoMediaTypeGuids.FORMAT_WaveFormatEx) { return "WaveFormatEx"; } return FormatType.ToString(); } } public WaveFormat GetWaveFormat() { if (formattype == DmoMediaTypeGuids.FORMAT_WaveFormatEx) { return WaveFormat.MarshalFromPtr(pbFormat); } throw new InvalidOperationException("Not a WaveFormat type"); } public void SetWaveFormat(WaveFormat waveFormat) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Invalid comparison between Unknown and I4 //IL_0066: Unknown result type (might be due to invalid IL or missing references) majortype = MediaTypes.MEDIATYPE_Audio; WaveFormatExtensible val = (WaveFormatExtensible)(object)((waveFormat is WaveFormatExtensible) ? waveFormat : null); if (val != null) { subtype = val.SubFormat; } else { WaveFormatEncoding encoding = waveFormat.Encoding; if ((int)encoding != 1) { if ((int)encoding != 3) { if ((int)encoding != 85) { throw new ArgumentException($"Not a supported encoding {waveFormat.Encoding}"); } subtype = AudioMediaSubtypes.WMMEDIASUBTYPE_MP3; } else { subtype = AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT; } } else { subtype = AudioMediaSubtypes.MEDIASUBTYPE_PCM; } } bFixedSizeSamples = SubType == AudioMediaSubtypes.MEDIASUBTYPE_PCM || SubType == AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT; formattype = DmoMediaTypeGuids.FORMAT_WaveFormatEx; if (cbFormat < Marshal.SizeOf<WaveFormat>(waveFormat)) { throw new InvalidOperationException("Not enough memory assigned for a WaveFormat structure"); } Marshal.StructureToPtr<WaveFormat>(waveFormat, pbFormat, fDeleteOld: false); } } [StructLayout(LayoutKind.Sequential, Pack = 8)] public struct DmoOutputDataBuffer : IDisposable { [MarshalAs(UnmanagedType.Interface)] private IMediaBuffer pBuffer; private DmoOutputDataBufferFlags dwStatus; private long rtTimestamp; private long referenceTimeDuration; public IMediaBuffer MediaBuffer { get { return pBuffer; } internal set { pBuffer = value; } } public int Length => ((MediaBuffer)pBuffer).Length; public DmoOutputDataBufferFlags StatusFlags { get { return dwStatus; } internal set { dwStatus = value; } } public long Timestamp { get { return rtTimestamp; } internal set { rtTimestamp = value; } } public long Duration { get { return referenceTimeDuration; } internal set { referenceTimeDuration = value; } } public bool MoreDataAvailable => (StatusFlags & DmoOutputDataBufferFlags.Incomplete) == DmoOutputDataBufferFlags.Incomplete; public DmoOutputDataBuffer(int maxBufferSize) { pBuffer = new MediaBuffer(maxBufferSize); dwStatus = DmoOutputDataBufferFlags.None; rtTimestamp = 0L; referenceTimeDuration = 0L; } public void Dispose() { if (pBuffer != null) { ((MediaBuffer)pBuffer).Dispose(); pBuffer = null; GC.SuppressFinalize(this); } } public void RetrieveData(byte[] data, int offset) { ((MediaBuffer)pBuffer).RetrieveData(data, offset); } } [Flags] public enum DmoOutputDataBufferFlags { None = 0, SyncPoint = 1, Time = 2, TimeLength = 4, Incomplete = 0x1000000 } internal struct DmoPartialMediaType { private Guid type; private Guid subtype; public Guid Type { get { return type; } internal set { type = value; } } public Guid Subtype { get { return subtype; } internal set { subtype = value; } } } [Flags] public enum DmoProcessOutputFlags { None = 0, DiscardWhenNoBuffer = 1 } [Flags] internal enum DmoSetTypeFlags { None = 0, DMO_SET_TYPEF_TEST_ONLY = 1, DMO_SET_TYPEF_CLEAR = 2 } [ComImport] [Guid("2c3cd98a-2bfa-4a53-9c27-5249ba64ba0f")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IEnumDmo { int Next(int itemsToFetch, out Guid clsid, out IntPtr name, out int itemsFetched); int Skip(int itemsToSkip); int Reset(); int Clone(out IEnumDmo enumPointer); } [ComImport] [SuppressUnmanagedCodeSecurity] [Guid("59eff8b9-938c-4a26-82f2-95cb84cdc837")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMediaBuffer { [PreserveSig] int SetLength(int length); [PreserveSig] int GetMaxLength(out int maxLength); [PreserveSig] int GetBufferAndLength(IntPtr bufferPointerPointer, IntPtr validDataLengthPointer); } [ComImport] [SuppressUnmanagedCodeSecurity] [Guid("d8ad0f58-5494-4102-97c5-ec798e59bcf4")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IMediaObject { [PreserveSig] int GetStreamCount(out int inputStreams, out int outputStreams); [PreserveSig] int GetInputStreamInfo(int inputStreamIndex, out InputStreamInfoFlags flags); [PreserveSig] int GetOutputStreamInfo(int outputStreamIndex, out OutputStreamInfoFlags flags); [PreserveSig] int GetInputType(int inputStreamIndex, int typeIndex, out DmoMediaType mediaType); [PreserveSig] int GetOutputType(int outputStreamIndex, int typeIndex, out DmoMediaType mediaType); [PreserveSig] int SetInputType(int inputStreamIndex, [In] ref DmoMediaType mediaType, DmoSetTypeFlags flags); [PreserveSig] int SetOutputType(int outputStreamIndex, [In] ref DmoMediaType mediaType, DmoSetTypeFlags flags); [PreserveSig] int GetInputCurrentType(int inputStreamIndex, out DmoMediaType mediaType); [PreserveSig] int GetOutputCurrentType(int outputStreamIndex, out DmoMediaType mediaType); [PreserveSig] int GetInputSizeInfo(int inputStreamIndex, out int size, out int maxLookahead, out int alignment); [PreserveSig] int GetOutputSizeInfo(int outputStreamIndex, out int size, out int alignment); [PreserveSig] int GetInputMaxLatency(int inputStreamIndex, out long referenceTimeMaxLatency); [PreserveSig] int SetInputMaxLatency(int inputStreamIndex, long referenceTimeMaxLatency); [PreserveSig] int Flush(); [PreserveSig] int Discontinuity(int inputStreamIndex); [PreserveSig] int AllocateStreamingResources(); [PreserveSig] int FreeStreamingResources(); [PreserveSig] int GetInputStatus(int inputStreamIndex, out DmoInputStatusFlags flags); [PreserveSig] int ProcessInput(int inputStreamIndex, [In] IMediaBuffer mediaBuffer, DmoInputDataBufferFlags flags, long referenceTimeTimestamp, long referenceTimeDuration); [PreserveSig] int ProcessOutput(DmoProcessOutputFlags flags, int outputBufferCount, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] DmoOutputDataBuffer[] outputBuffers, out int statusReserved); [PreserveSig] int Lock(bool acquireLock); } [ComImport] [SuppressUnmanagedCodeSecurity] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("651B9AD0-0FC7-4AA9-9538-D89931010741")] internal interface IMediaObjectInPlace { [PreserveSig] int Process([In] int size, [In] IntPtr data, [In] long refTimeStart, [In] DmoInPlaceProcessFlags dwFlags); [PreserveSig] int Clone([MarshalAs(UnmanagedType.Interface)] out IMediaObjectInPlace mediaObjectInPlace); [PreserveSig] int GetLatency(out long latencyTime); } [ComImport] [SuppressUnmanagedCodeSecurity] [Guid("6d6cbb60-a223-44aa-842f-a2f06750be6d")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IMediaParamInfo { [PreserveSig] int GetParamCount(out int paramCount); [PreserveSig] int GetParamInfo(int paramIndex, ref MediaParamInfo paramInfo); [PreserveSig] int GetParamText(int paramIndex, out IntPtr paramText); [PreserveSig] int GetNumTimeFormats(out int numTimeFormats); [PreserveSig] int GetSupportedTimeFormat(int formatIndex, out Guid guidTimeFormat); [PreserveSig] int GetCurrentTimeFormat(out Guid guidTimeFormat, out int mediaTimeData); } [Flags] internal enum InputStreamInfoFlags { None = 0, DMO_INPUT_STREAMF_WHOLE_SAMPLES = 1, DMO_INPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER = 2, DMO_INPUT_STREAMF_FIXED_SAMPLE_SIZE = 4, DMO_INPUT_STREAMF_HOLDS_BUFFERS = 8 } [ComImport] [Guid("E7E9984F-F09F-4da4-903F-6E2E0EFE56B5")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IWMResamplerProps { int SetHalfFilterLength(int outputQuality); int SetUserChannelMtx([In] float[] channelConversionMatrix); } public class MediaBuffer : IMediaBuffer, IDisposable { private IntPtr buffer; private int length; private readonly int maxLength; public int Length { get { return length; } set { if (length > maxLength) { throw new ArgumentException("Cannot be greater than maximum buffer size"); } length = value; } } public MediaBuffer(int maxLength) { buffer = Marshal.AllocCoTaskMem(maxLength); this.maxLength = maxLength; } public void Dispose() { if (buffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(buffer); buffer = IntPtr.Zero; GC.SuppressFinalize(this); } } ~MediaBuffer() { Dispose(); } int IMediaBuffer.SetLength(int length) { if (length > maxLength) { return -2147483645; } this.length = length; return 0; } int IMediaBuffer.GetMaxLength(out int maxLength) { maxLength = this.maxLength; return 0; } int IMediaBuffer.GetBufferAndLength(IntPtr bufferPointerPointer, IntPtr validDataLengthPointer) { if (bufferPointerPointer != IntPtr.Zero) { Marshal.WriteIntPtr(bufferPointerPointer, buffer); } if (validDataLengthPointer != IntPtr.Zero) { Marshal.WriteInt32(validDataLengthPointer, length); } return 0; } public void LoadData(byte[] data, int bytes) { Length = bytes; Marshal.Copy(data, 0, buffer, bytes); } public void RetrieveData(byte[] data, int offset) { Marshal.Copy(buffer, data, offset, Length); } } public class MediaObject : IDisposable { private IMediaObject mediaObject; private readonly int inputStreams; private readonly int outputStreams; public int InputStreamCount => inputStreams; public int OutputStreamCount => outputStreams; internal MediaObject(IMediaObject mediaObject) { this.mediaObject = mediaObject; mediaObject.GetStreamCount(out inputStreams, out outputStreams); } public DmoMediaType? GetInputType(int inputStream, int inputTypeIndex) { try { if (mediaObject.GetInputType(inputStream, inputTypeIndex, out var mediaType) == 0) { DmoInterop.MoFreeMediaType(ref mediaType); return mediaType; } } catch (COMException ex) { if (HResult.GetHResult(ex) != -2147220986) { throw; } } return null; } public DmoMediaType? GetOutputType(int outputStream, int outputTypeIndex) { try { if (mediaObject.GetOutputType(outputStream, outputTypeIndex, out var mediaType) == 0) { DmoInterop.MoFreeMediaType(ref mediaType); return mediaType; } } catch (COMException ex) { if (HResult.GetHResult(ex) != -2147220986) { throw; } } return null; } public DmoMediaType GetOutputCurrentType(int outputStreamIndex) { DmoMediaType mediaType; int outputCurrentType = mediaObject.GetOutputCurrentType(outputStreamIndex, out mediaType); switch (outputCurrentType) { case 0: DmoInterop.MoFreeMediaType(ref mediaType); return mediaType; case -2147220989: throw new InvalidOperationException("Media type was not set."); default: throw Marshal.GetExceptionForHR(outputCurrentType); } } public IEnumerable<DmoMediaType> GetInputTypes(int inputStreamIndex) { int typeIndex = 0; while (true) { DmoMediaType? inputType; DmoMediaType? dmoMediaType = (inputType = GetInputType(inputStreamIndex, typeIndex)); if (dmoMediaType.HasValue) { yield return inputType.Value; typeIndex++; continue; } break; } } public IEnumerable<DmoMediaType> GetOutputTypes(int outputStreamIndex) { int typeIndex = 0; while (true) { DmoMediaType? outputType; DmoMediaType? dmoMediaType = (outputType = GetOutputType(outputStreamIndex, typeIndex)); if (dmoMediaType.HasValue) { yield return outputType.Value; typeIndex++; continue; } break; } } public bool SupportsInputType(int inputStreamIndex, DmoMediaType mediaType) { return SetInputType(inputStreamIndex, mediaType, DmoSetTypeFlags.DMO_SET_TYPEF_TEST_ONLY); } private bool SetInputType(int inputStreamIndex, DmoMediaType mediaType, DmoSetTypeFlags flags) { switch (mediaObject.SetInputType(inputStreamIndex, ref mediaType, flags)) { case -2147220991: throw new ArgumentException("Invalid stream index"); default: _ = -2147220987; return false; case 0: return true; } } public void SetInputType(int inputStreamIndex, DmoMediaType mediaType) { if (!SetInputType(inputStreamIndex, mediaType, DmoSetTypeFlags.None)) { throw new ArgumentException("Media Type not supported"); } } public void SetInputWaveFormat(int inputStreamIndex, WaveFormat waveFormat) { DmoMediaType mediaType = CreateDmoMediaTypeForWaveFormat(waveFormat); bool num = SetInputType(inputStreamIndex, mediaType, DmoSetTypeFlags.None); DmoInterop.MoFreeMediaType(ref mediaType); if (!num) { throw new ArgumentException("Media Type not supported"); } } public bool SupportsInputWaveFormat(int inputStreamIndex, WaveFormat waveFormat) { DmoMediaType mediaType = CreateDmoMediaTypeForWaveFormat(waveFormat); bool result = SetInputType(inputStreamIndex, mediaType, DmoSetTypeFlags.DMO_SET_TYPEF_TEST_ONLY); DmoInterop.MoFreeMediaType(ref mediaType); return result; } private DmoMediaType CreateDmoMediaTypeForWaveFormat(WaveFormat
deps/NAudio.WinForms.dll
Decompiled a day agousing System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Windows.Forms; using NAudio.Mixer; using NAudio.Wave; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("Mark Heath")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Mark Heath 2023")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("NAudio.WinForms")] [assembly: AssemblyTitle("NAudio.WinForms")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")] [assembly: AssemblyVersion("2.2.1.0")] namespace NAudio.Wave { public class WaveCallbackInfo { private WaveWindow waveOutWindow; private WaveWindowNative waveOutWindowNative; public WaveCallbackStrategy Strategy { get; private set; } public IntPtr Handle { get; private set; } public static WaveCallbackInfo FunctionCallback() { return new WaveCallbackInfo((WaveCallbackStrategy)0, IntPtr.Zero); } public static WaveCallbackInfo NewWindow() { return new WaveCallbackInfo((WaveCallbackStrategy)1, IntPtr.Zero); } public static WaveCallbackInfo ExistingWindow(IntPtr handle) { if (handle == IntPtr.Zero) { throw new ArgumentException("Handle cannot be zero"); } return new WaveCallbackInfo((WaveCallbackStrategy)2, handle); } private WaveCallbackInfo(WaveCallbackStrategy strategy, IntPtr handle) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Strategy = strategy; Handle = handle; } internal void Connect(WaveCallback callback) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 if ((int)Strategy == 1) { waveOutWindow = new WaveWindow(callback); ((Control)waveOutWindow).CreateControl(); Handle = ((Control)waveOutWindow).Handle; } else if ((int)Strategy == 2) { waveOutWindowNative = new WaveWindowNative(callback); ((NativeWindow)waveOutWindowNative).AssignHandle(Handle); } } internal MmResult WaveOutOpen(out IntPtr waveOutHandle, int deviceNumber, WaveFormat waveFormat, WaveCallback callback) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) if ((int)Strategy == 0) { return WaveInterop.waveOutOpen(ref waveOutHandle, (IntPtr)deviceNumber, waveFormat, callback, IntPtr.Zero, (WaveInOutOpenFlags)196608); } return WaveInterop.waveOutOpenWindow(ref waveOutHandle, (IntPtr)deviceNumber, waveFormat, Handle, IntPtr.Zero, (WaveInOutOpenFlags)65536); } internal MmResult WaveInOpen(out IntPtr waveInHandle, int deviceNumber, WaveFormat waveFormat, WaveCallback callback) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) if ((int)Strategy == 0) { return WaveInterop.waveInOpen(ref waveInHandle, (IntPtr)deviceNumber, waveFormat, callback, IntPtr.Zero, (WaveInOutOpenFlags)196608); } return WaveInterop.waveInOpenWindow(ref waveInHandle, (IntPtr)deviceNumber, waveFormat, Handle, IntPtr.Zero, (WaveInOutOpenFlags)65536); } internal void Disconnect() { if (waveOutWindow != null) { ((Form)waveOutWindow).Close(); waveOutWindow = null; } if (waveOutWindowNative != null) { ((NativeWindow)waveOutWindowNative).ReleaseHandle(); waveOutWindowNative = null; } } } public class WaveIn : IWaveIn, IDisposable { private IntPtr waveInHandle; private volatile bool recording; private WaveInBuffer[] buffers; private readonly WaveCallback callback; private WaveCallbackInfo callbackInfo; private readonly SynchronizationContext syncContext; private int lastReturnedBufferIndex; public static int DeviceCount => WaveInterop.waveInGetNumDevs(); public int BufferMilliseconds { get; set; } public int NumberOfBuffers { get; set; } public int DeviceNumber { get; set; } public WaveFormat WaveFormat { get; set; } public event EventHandler<WaveInEventArgs> DataAvailable; public event EventHandler<StoppedEventArgs> RecordingStopped; public WaveIn() : this(WaveCallbackInfo.NewWindow()) { } public WaveIn(IntPtr windowHandle) : this(WaveCallbackInfo.ExistingWindow(windowHandle)) { } public WaveIn(WaveCallbackInfo callbackInfo) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown syncContext = SynchronizationContext.Current; if (((int)callbackInfo.Strategy == 1 || (int)callbackInfo.Strategy == 2) && syncContext == null) { throw new InvalidOperationException("Use WaveInEvent to record on a background thread"); } DeviceNumber = 0; WaveFormat = new WaveFormat(8000, 16, 1); BufferMilliseconds = 100; NumberOfBuffers = 3; callback = new WaveCallback(Callback); this.callbackInfo = callbackInfo; callbackInfo.Connect(callback); } public static WaveInCapabilities GetCapabilities(int devNumber) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) WaveInCapabilities val = default(WaveInCapabilities); int num = Marshal.SizeOf<WaveInCapabilities>(val); MmException.Try(WaveInterop.waveInGetDevCaps((IntPtr)devNumber, ref val, num), "waveInGetDevCaps"); return val; } private void CreateBuffers() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown int num = BufferMilliseconds * WaveFormat.AverageBytesPerSecond / 1000; if (num % WaveFormat.BlockAlign != 0) { num -= num % WaveFormat.BlockAlign; } buffers = (WaveInBuffer[])(object)new WaveInBuffer[NumberOfBuffers]; for (int i = 0; i < buffers.Length; i++) { buffers[i] = new WaveInBuffer(waveInHandle, num); } } private void Callback(IntPtr waveInHandle, WaveMessage message, IntPtr userData, WaveHeader waveHeader, IntPtr reserved) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown if ((int)message != 960 || !recording) { return; } WaveInBuffer val = (WaveInBuffer)((GCHandle)waveHeader.userData).Target; if (val != null) { lastReturnedBufferIndex = Array.IndexOf(buffers, val); RaiseDataAvailable(val); try { val.Reuse(); } catch (Exception e) { recording = false; RaiseRecordingStopped(e); } } } private void RaiseDataAvailable(WaveInBuffer buffer) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown this.DataAvailable?.Invoke(this, new WaveInEventArgs(buffer.Data, buffer.BytesRecorded)); } private void RaiseRecordingStopped(Exception e) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown EventHandler<StoppedEventArgs> handler = this.RecordingStopped; if (handler == null) { return; } if (syncContext == null) { handler(this, new StoppedEventArgs(e)); return; } syncContext.Post(delegate { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown handler(this, new StoppedEventArgs(e)); }, null); } private void OpenWaveInDevice() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) CloseWaveInDevice(); MmException.Try(callbackInfo.WaveInOpen(out waveInHandle, DeviceNumber, WaveFormat, callback), "waveInOpen"); CreateBuffers(); } public void StartRecording() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (recording) { throw new InvalidOperationException("Already recording"); } OpenWaveInDevice(); EnqueueBuffers(); MmException.Try(WaveInterop.waveInStart(waveInHandle), "waveInStart"); recording = true; } private void EnqueueBuffers() { WaveInBuffer[] array = buffers; foreach (WaveInBuffer val in array) { if (!val.InQueue) { val.Reuse(); } } } public void StopRecording() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!recording) { return; } recording = false; MmException.Try(WaveInterop.waveInStop(waveInHandle), "waveInStop"); for (int i = 0; i < buffers.Length; i++) { int num = (i + lastReturnedBufferIndex + 1) % buffers.Length; WaveInBuffer val = buffers[num]; if (val.Done) { RaiseDataAvailable(val); } } RaiseRecordingStopped(null); } public long GetPosition() { //IL_0002: 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_001e: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) MmTime val = default(MmTime); val.wType = 4u; MmException.Try(WaveInterop.waveInGetPosition(waveInHandle, ref val, Marshal.SizeOf<MmTime>(val)), "waveInGetPosition"); if (val.wType != 4) { throw new Exception($"waveInGetPosition: wType -> Expected {4}, Received {val.wType}"); } return val.cb; } protected virtual void Dispose(bool disposing) { if (disposing) { if (recording) { StopRecording(); } CloseWaveInDevice(); if (callbackInfo != null) { callbackInfo.Disconnect(); callbackInfo = null; } } } private void CloseWaveInDevice() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (waveInHandle == IntPtr.Zero) { return; } WaveInterop.waveInReset(waveInHandle); if (buffers != null) { for (int i = 0; i < buffers.Length; i++) { buffers[i].Dispose(); } buffers = null; } WaveInterop.waveInClose(waveInHandle); waveInHandle = IntPtr.Zero; } public MixerLine GetMixerLine() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown if (waveInHandle != IntPtr.Zero) { return new MixerLine(waveInHandle, 0, (MixerFlags)(-1610612736)); } return new MixerLine((IntPtr)DeviceNumber, 0, (MixerFlags)536870912); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public class WaveOut : IWavePlayer, IDisposable, IWavePosition { private IntPtr hWaveOut; private WaveOutBuffer[] buffers; private IWaveProvider waveStream; private volatile PlaybackState playbackState; private readonly WaveCallback callback; private readonly WaveCallbackInfo callbackInfo; private readonly object waveOutLock; private int queuedBuffers; private readonly SynchronizationContext syncContext; public static int DeviceCount => WaveInterop.waveOutGetNumDevs(); public int DesiredLatency { get; set; } public int NumberOfBuffers { get; set; } public int DeviceNumber { get; set; } = -1; public WaveFormat OutputWaveFormat => waveStream.WaveFormat; public PlaybackState PlaybackState => playbackState; public float Volume { get { return WaveOutUtils.GetWaveOutVolume(hWaveOut, waveOutLock); } set { WaveOutUtils.SetWaveOutVolume(value, hWaveOut, waveOutLock); } } public event EventHandler<StoppedEventArgs> PlaybackStopped; public static WaveOutCapabilities GetCapabilities(int devNumber) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) WaveOutCapabilities val = default(WaveOutCapabilities); int num = Marshal.SizeOf<WaveOutCapabilities>(val); MmException.Try(WaveInterop.waveOutGetDevCaps((IntPtr)devNumber, ref val, num), "waveOutGetDevCaps"); return val; } public WaveOut() : this((SynchronizationContext.Current == null) ? WaveCallbackInfo.FunctionCallback() : WaveCallbackInfo.NewWindow()) { } public WaveOut(IntPtr windowHandle) : this(WaveCallbackInfo.ExistingWindow(windowHandle)) { } public WaveOut(WaveCallbackInfo callbackInfo) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown syncContext = SynchronizationContext.Current; DesiredLatency = 300; NumberOfBuffers = 2; callback = new WaveCallback(Callback); waveOutLock = new object(); this.callbackInfo = callbackInfo; callbackInfo.Connect(callback); } public void Init(IWaveProvider waveProvider) { //IL_005d: 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_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Expected O, but got Unknown waveStream = waveProvider; int num = waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1) / NumberOfBuffers); MmResult val; lock (waveOutLock) { val = callbackInfo.WaveOutOpen(out hWaveOut, DeviceNumber, waveStream.WaveFormat, callback); } MmException.Try(val, "waveOutOpen"); buffers = (WaveOutBuffer[])(object)new WaveOutBuffer[NumberOfBuffers]; playbackState = (PlaybackState)0; for (int i = 0; i < NumberOfBuffers; i++) { buffers[i] = new WaveOutBuffer(hWaveOut, num, waveStream, waveOutLock); } } public void Play() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 //IL_000c: 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) if ((int)playbackState == 0) { playbackState = (PlaybackState)1; EnqueueBuffers(); } else if ((int)playbackState == 2) { EnqueueBuffers(); Resume(); playbackState = (PlaybackState)1; } } private void EnqueueBuffers() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < NumberOfBuffers; i++) { if (!buffers[i].InQueue) { if (!buffers[i].OnDone()) { playbackState = (PlaybackState)0; break; } Interlocked.Increment(ref queuedBuffers); } } } public void Pause() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000d: 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_0030: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if ((int)playbackState == 1) { playbackState = (PlaybackState)2; MmResult val; lock (waveOutLock) { val = WaveInterop.waveOutPause(hWaveOut); } if ((int)val != 0) { throw new MmException(val, "waveOutPause"); } } } public void Resume() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_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) if ((int)playbackState == 2) { MmResult val; lock (waveOutLock) { val = WaveInterop.waveOutRestart(hWaveOut); } if ((int)val != 0) { throw new MmException(val, "waveOutRestart"); } playbackState = (PlaybackState)1; } } public void Stop() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if ((int)playbackState != 0) { playbackState = (PlaybackState)0; MmResult val; lock (waveOutLock) { val = WaveInterop.waveOutReset(hWaveOut); } if ((int)val != 0) { throw new MmException(val, "waveOutReset"); } if ((int)callbackInfo.Strategy == 0) { RaisePlaybackStoppedEvent(null); } } } public long GetPosition() { return WaveOutUtils.GetPositionBytes(hWaveOut, waveOutLock); } public void Dispose() { GC.SuppressFinalize(this); Dispose(disposing: true); } protected void Dispose(bool disposing) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) Stop(); if (disposing && buffers != null) { for (int i = 0; i < buffers.Length; i++) { if (buffers[i] != null) { buffers[i].Dispose(); } } buffers = null; } lock (waveOutLock) { WaveInterop.waveOutClose(hWaveOut); } if (disposing) { callbackInfo.Disconnect(); } } ~WaveOut() { Dispose(disposing: false); } private void Callback(IntPtr hWaveOut, WaveMessage uMsg, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Invalid comparison between Unknown and I4 //IL_0080: 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_0088: Unknown result type (might be due to invalid IL or missing references) if ((int)uMsg != 957) { return; } WaveOutBuffer val = (WaveOutBuffer)((GCHandle)wavhdr.userData).Target; Interlocked.Decrement(ref queuedBuffers); Exception e = null; if ((int)PlaybackState == 1) { lock (waveOutLock) { try { if (val.OnDone()) { Interlocked.Increment(ref queuedBuffers); } } catch (Exception ex) { e = ex; } } } if (queuedBuffers == 0 && ((int)callbackInfo.Strategy != 0 || (int)playbackState != 0)) { playbackState = (PlaybackState)0; RaisePlaybackStoppedEvent(e); } } private void RaisePlaybackStoppedEvent(Exception e) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown EventHandler<StoppedEventArgs> handler = this.PlaybackStopped; if (handler == null) { return; } if (syncContext == null) { handler(this, new StoppedEventArgs(e)); return; } syncContext.Post(delegate { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown handler(this, new StoppedEventArgs(e)); }, null); } } internal class WaveWindowNative : NativeWindow { private WaveCallback waveCallback; public WaveWindowNative(WaveCallback waveCallback) { this.waveCallback = waveCallback; } protected override void WndProc(ref Message m) { //IL_0006: 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_000d: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected I4, but got Unknown //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) WaveMessage val = (WaveMessage)((Message)(ref m)).Msg; switch (val - 955) { case 2: case 5: { IntPtr wParam = ((Message)(ref m)).WParam; WaveHeader val2 = new WaveHeader(); Marshal.PtrToStructure<WaveHeader>(((Message)(ref m)).LParam, val2); waveCallback.Invoke(wParam, val, IntPtr.Zero, val2, IntPtr.Zero); break; } case 0: case 1: case 3: case 4: waveCallback.Invoke(((Message)(ref m)).WParam, val, IntPtr.Zero, (WaveHeader)null, IntPtr.Zero); break; default: ((NativeWindow)this).WndProc(ref m); break; } } } internal class WaveWindow : Form { private WaveCallback waveCallback; public WaveWindow(WaveCallback waveCallback) { this.waveCallback = waveCallback; } protected override void WndProc(ref Message m) { //IL_0006: 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_000d: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected I4, but got Unknown //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) WaveMessage val = (WaveMessage)((Message)(ref m)).Msg; switch (val - 955) { case 2: case 5: { IntPtr wParam = ((Message)(ref m)).WParam; WaveHeader val2 = new WaveHeader(); Marshal.PtrToStructure<WaveHeader>(((Message)(ref m)).LParam, val2); waveCallback.Invoke(wParam, val, IntPtr.Zero, val2, IntPtr.Zero); break; } case 0: case 1: case 3: case 4: waveCallback.Invoke(((Message)(ref m)).WParam, val, IntPtr.Zero, (WaveHeader)null, IntPtr.Zero); break; default: ((Form)this).WndProc(ref m); break; } } } } namespace NAudio.Utils { public class ProgressLog : UserControl { private delegate void LogMessageDelegate(Color color, string message); private delegate void ClearLogDelegate(); private IContainer components; private RichTextBox richTextBoxLog; public string Text => ((Control)richTextBoxLog).Text; public ProgressLog() { InitializeComponent(); } public void LogMessage(Color color, string message) { if (((Control)richTextBoxLog).InvokeRequired) { ((Control)this).Invoke((Delegate)new LogMessageDelegate(LogMessage), new object[2] { color, message }); } else { ((TextBoxBase)richTextBoxLog).SelectionStart = ((TextBoxBase)richTextBoxLog).TextLength; richTextBoxLog.SelectionColor = color; ((TextBoxBase)richTextBoxLog).AppendText(message); ((TextBoxBase)richTextBoxLog).AppendText(Environment.NewLine); } } public void ClearLog() { if (((Control)richTextBoxLog).InvokeRequired) { ((Control)this).Invoke((Delegate)new ClearLogDelegate(ClearLog), new object[0]); } else { ((TextBoxBase)richTextBoxLog).Clear(); } } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } ((ContainerControl)this).Dispose(disposing); } private void InitializeComponent() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_00d2: Unknown result type (might be due to invalid IL or missing references) richTextBoxLog = new RichTextBox(); ((Control)this).SuspendLayout(); ((TextBoxBase)richTextBoxLog).BorderStyle = (BorderStyle)0; ((Control)richTextBoxLog).Dock = (DockStyle)5; ((Control)richTextBoxLog).Location = new Point(1, 1); ((Control)richTextBoxLog).Name = "richTextBoxLog"; ((TextBoxBase)richTextBoxLog).ReadOnly = true; ((Control)richTextBoxLog).Size = new Size(311, 129); ((Control)richTextBoxLog).TabIndex = 0; ((Control)richTextBoxLog).Text = ""; ((ContainerControl)this).AutoScaleDimensions = new SizeF(6f, 13f); ((ContainerControl)this).AutoScaleMode = (AutoScaleMode)1; ((Control)this).BackColor = SystemColors.ControlDarkDark; ((Control)this).Controls.Add((Control)(object)richTextBoxLog); ((Control)this).Name = "ProgressLog"; ((Control)this).Padding = new Padding(1); ((Control)this).Size = new Size(313, 131); ((Control)this).ResumeLayout(false); } } } namespace NAudio.WinForms.Gui { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Fader { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { resourceMan = new ResourceManager("NAudio.WinForms.Gui.Fader", typeof(Fader).Assembly); } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal Fader() { } } [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class PanSlider { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { resourceMan = new ResourceManager("NAudio.WinForms.Gui.PanSlider", typeof(PanSlider).Assembly); } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal PanSlider() { } } [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class VolumeSlider { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { resourceMan = new ResourceManager("NAudio.WinForms.Gui.VolumeSlider", typeof(VolumeSlider).Assembly); } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal VolumeSlider() { } } [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class WaveViewer { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { resourceMan = new ResourceManager("NAudio.WinForms.Gui.WaveViewer", typeof(WaveViewer).Assembly); } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal WaveViewer() { } } } namespace NAudio.Gui { public class Fader : Control { private int minimum; private int maximum; private float percent; private Orientation orientation; private Container components; private readonly int SliderHeight = 30; private readonly int SliderWidth = 15; private Rectangle sliderRectangle; private bool dragging; private int dragY; public int Minimum { get { return minimum; } set { minimum = value; } } public int Maximum { get { return maximum; } set { maximum = value; } } public int Value { get { return (int)(percent * (float)(maximum - minimum)) + minimum; } set { percent = (float)(value - minimum) / (float)(maximum - minimum); } } public Orientation Orientation { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return orientation; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) orientation = value; } } public Fader() { InitializeComponent(); ((Control)this).SetStyle((ControlStyles)73730, true); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } ((Control)this).Dispose(disposing); } private void DrawSlider(Graphics g) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown Brush val = (Brush)new SolidBrush(Color.White); Pen val2 = new Pen(Color.Black); sliderRectangle.X = (((Control)this).Width - SliderWidth) / 2; sliderRectangle.Width = SliderWidth; sliderRectangle.Y = (int)((float)(((Control)this).Height - SliderHeight) * percent); sliderRectangle.Height = SliderHeight; g.FillRectangle(val, sliderRectangle); g.DrawLine(val2, sliderRectangle.Left, sliderRectangle.Top + sliderRectangle.Height / 2, sliderRectangle.Right, sliderRectangle.Top + sliderRectangle.Height / 2); val.Dispose(); val2.Dispose(); } protected override void OnPaint(PaintEventArgs e) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown Graphics graphics = e.Graphics; if ((int)Orientation == 1) { Brush val = (Brush)new SolidBrush(Color.Black); graphics.FillRectangle(val, ((Control)this).Width / 2, SliderHeight / 2, 2, ((Control)this).Height - SliderHeight); val.Dispose(); DrawSlider(graphics); } ((Control)this).OnPaint(e); } protected override void OnMouseDown(MouseEventArgs e) { if (sliderRectangle.Contains(e.X, e.Y)) { dragging = true; dragY = e.Y - sliderRectangle.Y; } ((Control)this).OnMouseDown(e); } protected override void OnMouseMove(MouseEventArgs e) { if (dragging) { int num = e.Y - dragY; if (num < 0) { percent = 0f; } else if (num > ((Control)this).Height - SliderHeight) { percent = 1f; } else { percent = (float)num / (float)(((Control)this).Height - SliderHeight); } ((Control)this).Invalidate(); } ((Control)this).OnMouseMove(e); } protected override void OnMouseUp(MouseEventArgs e) { dragging = false; ((Control)this).OnMouseUp(e); } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); } } public class PanSlider : UserControl { private Container components; private float pan; public float Pan { get { return pan; } set { if (value < -1f) { value = -1f; } if (value > 1f) { value = 1f; } if (value != pan) { pan = value; if (this.PanChanged != null) { this.PanChanged(this, EventArgs.Empty); } ((Control)this).Invalidate(); } } } public event EventHandler PanChanged; public PanSlider() { InitializeComponent(); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } ((ContainerControl)this).Dispose(disposing); } private void InitializeComponent() { ((Control)this).Name = "PanSlider"; ((Control)this).Size = new Size(104, 16); } protected override void OnPaint(PaintEventArgs pe) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown StringFormat val = new StringFormat(); val.LineAlignment = (StringAlignment)1; val.Alignment = (StringAlignment)1; string text; if ((double)pan == 0.0) { pe.Graphics.FillRectangle(Brushes.Orange, ((Control)this).Width / 2 - 1, 1, 3, ((Control)this).Height - 2); text = "C"; } else if (pan > 0f) { pe.Graphics.FillRectangle(Brushes.Orange, ((Control)this).Width / 2, 1, (int)((float)(((Control)this).Width / 2) * pan), ((Control)this).Height - 2); text = $"{pan * 100f:F0}%R"; } else { pe.Graphics.FillRectangle(Brushes.Orange, (int)((float)(((Control)this).Width / 2) * (pan + 1f)), 1, (int)((float)(((Control)this).Width / 2) * (0f - pan)), ((Control)this).Height - 2); text = $"{pan * -100f:F0}%L"; } pe.Graphics.DrawRectangle(Pens.Black, 0, 0, ((Control)this).Width - 1, ((Control)this).Height - 1); pe.Graphics.DrawString(text, ((Control)this).Font, Brushes.Black, (RectangleF)((Control)this).ClientRectangle, val); } protected override void OnMouseMove(MouseEventArgs e) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 if ((int)e.Button == 1048576) { SetPanFromMouse(e.X); } ((Control)this).OnMouseMove(e); } protected override void OnMouseDown(MouseEventArgs e) { SetPanFromMouse(e.X); ((UserControl)this).OnMouseDown(e); } private void SetPanFromMouse(int x) { Pan = (float)x / (float)((Control)this).Width * 2f - 1f; } } public class Pot : UserControl { private double minimum; private double maximum = 1.0; private double value = 0.5; private int beginDragY; private double beginDragValue; private bool dragging; private IContainer components; public double Minimum { get { return minimum; } set { if (value >= maximum) { throw new ArgumentOutOfRangeException("Minimum must be less than maximum"); } minimum = value; if (Value < minimum) { Value = minimum; } } } public double Maximum { get { return maximum; } set { if (value <= minimum) { throw new ArgumentOutOfRangeException("Maximum must be greater than minimum"); } maximum = value; if (Value > maximum) { Value = maximum; } } } public double Value { get { return value; } set { SetValue(value, raiseEvents: false); } } public event EventHandler ValueChanged; public Pot() { ((Control)this).SetStyle((ControlStyles)73730, true); InitializeComponent(); } private void SetValue(double newValue, bool raiseEvents) { if (value != newValue) { value = newValue; if (raiseEvents && this.ValueChanged != null) { this.ValueChanged(this, EventArgs.Empty); } ((Control)this).Invalidate(); } } protected override void OnPaint(PaintEventArgs e) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown int num = Math.Min(((Control)this).Width - 4, ((Control)this).Height - 4); Pen val = new Pen(((Control)this).ForeColor, 3f); val.LineJoin = (LineJoin)2; GraphicsState val2 = e.Graphics.Save(); e.Graphics.TranslateTransform((float)(((Control)this).Width / 2), (float)(((Control)this).Height / 2)); e.Graphics.SmoothingMode = (SmoothingMode)4; e.Graphics.DrawArc(val, new Rectangle(num / -2, num / -2, num, num), 135f, 270f); double num2 = (value - minimum) / (maximum - minimum); double num3 = 135.0 + num2 * 270.0; double num4 = (double)num / 2.0 * Math.Cos(Math.PI * num3 / 180.0); double num5 = (double)num / 2.0 * Math.Sin(Math.PI * num3 / 180.0); e.Graphics.DrawLine(val, 0f, 0f, (float)num4, (float)num5); e.Graphics.Restore(val2); ((Control)this).OnPaint(e); } protected override void OnMouseDown(MouseEventArgs e) { dragging = true; beginDragY = e.Y; beginDragValue = value; ((UserControl)this).OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { dragging = false; ((Control)this).OnMouseUp(e); } protected override void OnMouseMove(MouseEventArgs e) { if (dragging) { int num = beginDragY - e.Y; double num2 = (maximum - minimum) * ((double)num / 150.0); double num3 = beginDragValue + num2; if (num3 < minimum) { num3 = minimum; } if (num3 > maximum) { num3 = maximum; } SetValue(num3, raiseEvents: true); } ((Control)this).OnMouseMove(e); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } ((ContainerControl)this).Dispose(disposing); } private void InitializeComponent() { ((Control)this).SuspendLayout(); ((ContainerControl)this).AutoScaleDimensions = new SizeF(6f, 13f); ((ContainerControl)this).AutoScaleMode = (AutoScaleMode)1; ((Control)this).Name = "Pot"; ((Control)this).Size = new Size(32, 32); ((Control)this).ResumeLayout(false); } } public class VolumeMeter : Control { private Brush foregroundBrush; private float amplitude; private IContainer components; [DefaultValue(-3.0)] public float Amplitude { get { return amplitude; } set { amplitude = value; ((Control)this).Invalidate(); } } [DefaultValue(-60.0)] public float MinDb { get; set; } [DefaultValue(18.0)] public float MaxDb { get; set; } [DefaultValue(/*Could not decode attribute arguments.*/)] public Orientation Orientation { get; set; } public VolumeMeter() { ((Control)this).SetStyle((ControlStyles)139266, true); MinDb = -60f; MaxDb = 18f; Amplitude = 0f; Orientation = (Orientation)1; InitializeComponent(); ((Control)this).OnForeColorChanged(EventArgs.Empty); } protected override void OnForeColorChanged(EventArgs e) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown foregroundBrush = (Brush)new SolidBrush(((Control)this).ForeColor); ((Control)this).OnForeColorChanged(e); } protected override void OnPaint(PaintEventArgs pe) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) pe.Graphics.DrawRectangle(Pens.Black, 0, 0, ((Control)this).Width - 1, ((Control)this).Height - 1); double num = 20.0 * Math.Log10(Amplitude); if (num < (double)MinDb) { num = MinDb; } if (num > (double)MaxDb) { num = MaxDb; } double num2 = (num - (double)MinDb) / (double)(MaxDb - MinDb); int num3 = ((Control)this).Width - 2; int num4 = ((Control)this).Height - 2; if ((int)Orientation == 0) { num3 = (int)((double)num3 * num2); pe.Graphics.FillRectangle(foregroundBrush, 1, 1, num3, num4); } else { num4 = (int)((double)num4 * num2); pe.Graphics.FillRectangle(foregroundBrush, 1, ((Control)this).Height - 1 - num4, num3, num4); } } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } ((Control)this).Dispose(disposing); } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); } } public class VolumeSlider : UserControl { private Container components; private float volume = 1f; private float MinDb = -48f; [DefaultValue(1f)] public float Volume { get { return volume; } set { if (value < 0f) { value = 0f; } if (value > 1f) { value = 1f; } if (volume != value) { volume = value; if (this.VolumeChanged != null) { this.VolumeChanged(this, EventArgs.Empty); } ((Control)this).Invalidate(); } } } public event EventHandler VolumeChanged; public VolumeSlider() { InitializeComponent(); } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } ((ContainerControl)this).Dispose(disposing); } private void InitializeComponent() { ((Control)this).Name = "VolumeSlider"; ((Control)this).Size = new Size(96, 16); } protected override void OnPaint(PaintEventArgs pe) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown StringFormat val = new StringFormat(); val.LineAlignment = (StringAlignment)1; val.Alignment = (StringAlignment)1; pe.Graphics.DrawRectangle(Pens.Black, 0, 0, ((Control)this).Width - 1, ((Control)this).Height - 1); float num = 20f * (float)Math.Log10(Volume); float num2 = 1f - num / MinDb; pe.Graphics.FillRectangle(Brushes.LightGreen, 1, 1, (int)((float)(((Control)this).Width - 2) * num2), ((Control)this).Height - 2); string text = $"{num:F2} dB"; pe.Graphics.DrawString(text, ((Control)this).Font, Brushes.Black, (RectangleF)((Control)this).ClientRectangle, val); } protected override void OnMouseMove(MouseEventArgs e) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 if ((int)e.Button == 1048576) { SetVolumeFromMouse(e.X); } ((Control)this).OnMouseMove(e); } protected override void OnMouseDown(MouseEventArgs e) { SetVolumeFromMouse(e.X); ((UserControl)this).OnMouseDown(e); } private void SetVolumeFromMouse(int x) { float num = (1f - (float)x / (float)((Control)this).Width) * MinDb; if (x <= 0) { Volume = 0f; } else { Volume = (float)Math.Pow(10.0, num / 20f); } } } public class WaveformPainter : Control { private Pen foregroundPen; private List<float> samples = new List<float>(1000); private int maxSamples; private int insertPos; private IContainer components; public WaveformPainter() { ((Control)this).SetStyle((ControlStyles)139266, true); InitializeComponent(); ((Control)this).OnForeColorChanged(EventArgs.Empty); ((Control)this).OnResize(EventArgs.Empty); } protected override void OnResize(EventArgs e) { maxSamples = ((Control)this).Width; ((Control)this).OnResize(e); } protected override void OnForeColorChanged(EventArgs e) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown foregroundPen = new Pen(((Control)this).ForeColor); ((Control)this).OnForeColorChanged(e); } public void AddMax(float maxSample) { if (maxSamples != 0) { if (samples.Count <= maxSamples) { samples.Add(maxSample); } else if (insertPos < maxSamples) { samples[insertPos] = maxSample; } insertPos++; insertPos %= maxSamples; ((Control)this).Invalidate(); } } protected override void OnPaint(PaintEventArgs pe) { ((Control)this).OnPaint(pe); for (int i = 0; i < ((Control)this).Width; i++) { float num = (float)((Control)this).Height * GetSample(i - ((Control)this).Width + insertPos); float num2 = ((float)((Control)this).Height - num) / 2f; pe.Graphics.DrawLine(foregroundPen, (float)i, num2, (float)i, num2 + num); } } private float GetSample(int index) { if (index < 0) { index += maxSamples; } if ((index >= 0) & (index < samples.Count)) { return samples[index]; } return 0f; } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } ((Control)this).Dispose(disposing); } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); } } public class WaveViewer : UserControl { private Container components; private WaveStream waveStream; private int samplesPerPixel = 128; private long startPosition; private int bytesPerSample; public WaveStream WaveStream { get { return waveStream; } set { waveStream = value; if (waveStream != null) { bytesPerSample = waveStream.WaveFormat.BitsPerSample / 8 * waveStream.WaveFormat.Channels; } ((Control)this).Invalidate(); } } public int SamplesPerPixel { get { return samplesPerPixel; } set { samplesPerPixel = value; ((Control)this).Invalidate(); } } public long StartPosition { get { return startPosition; } set { startPosition = value; } } public WaveViewer() { InitializeComponent(); ((Control)this).DoubleBuffered = true; } protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } ((ContainerControl)this).Dispose(disposing); } protected override void OnPaint(PaintEventArgs e) { if (waveStream != null) { ((Stream)(object)waveStream).Position = 0L; byte[] array = new byte[samplesPerPixel * bytesPerSample]; ((Stream)(object)waveStream).Position = startPosition + e.ClipRectangle.Left * bytesPerSample * samplesPerPixel; for (float num = e.ClipRectangle.X; num < (float)e.ClipRectangle.Right; num += 1f) { short num2 = 0; short num3 = 0; int num4 = ((Stream)(object)waveStream).Read(array, 0, samplesPerPixel * bytesPerSample); if (num4 == 0) { break; } for (int i = 0; i < num4; i += 2) { short num5 = BitConverter.ToInt16(array, i); if (num5 < num2) { num2 = num5; } if (num5 > num3) { num3 = num5; } } float num6 = ((float)num2 - -32768f) / 65535f; float num7 = ((float)num3 - -32768f) / 65535f; e.Graphics.DrawLine(Pens.Black, num, (float)((Control)this).Height * num6, num, (float)((Control)this).Height * num7); } } ((Control)this).OnPaint(e); } private void InitializeComponent() { components = new Container(); } } }
deps/NAudio.WinMM.dll
Decompiled a day agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using Microsoft.Win32; using NAudio.CoreAudioApi; using NAudio.Mixer; using NAudio.Utils; using NAudio.Wave.Compression; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("NAudio.WinMM")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Mark Heath 2023")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("NAudio.WinMM")] [assembly: AssemblyTitle("NAudio.WinMM")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")] [assembly: AssemblyVersion("2.2.1.0")] namespace NAudio.Mixer { public class BooleanMixerControl : MixerControl { private MixerInterop.MIXERCONTROLDETAILS_BOOLEAN boolDetails; public bool Value { get { GetControlDetails(); return boolDetails.fValue == 1; } set { //IL_0055: Unknown result type (might be due to invalid IL or missing references) boolDetails.fValue = (value ? 1 : 0); mixerControlDetails.paDetails = Marshal.AllocHGlobal(Marshal.SizeOf(boolDetails)); Marshal.StructureToPtr(boolDetails, mixerControlDetails.paDetails, fDeleteOld: false); MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails"); Marshal.FreeHGlobal(mixerControlDetails.paDetails); } } internal BooleanMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels) { base.mixerControl = mixerControl; base.mixerHandle = mixerHandle; base.mixerHandleType = mixerHandleType; base.nChannels = nChannels; mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS); GetControlDetails(); } protected override void GetDetails(IntPtr pDetails) { boolDetails = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_BOOLEAN>(pDetails); } } public class CustomMixerControl : MixerControl { internal CustomMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels) { base.mixerControl = mixerControl; base.mixerHandle = mixerHandle; base.mixerHandleType = mixerHandleType; base.nChannels = nChannels; mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS); GetControlDetails(); } protected override void GetDetails(IntPtr pDetails) { } } public class ListTextMixerControl : MixerControl { internal ListTextMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels) { base.mixerControl = mixerControl; base.mixerHandle = mixerHandle; base.mixerHandleType = mixerHandleType; base.nChannels = nChannels; mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS); GetControlDetails(); } protected override void GetDetails(IntPtr pDetails) { } } public class Mixer { private MixerInterop.MIXERCAPS caps; private IntPtr mixerHandle; private MixerFlags mixerHandleType; public static int NumberOfDevices => MixerInterop.mixerGetNumDevs(); public int DestinationCount => (int)caps.cDestinations; public string Name => caps.szPname; public Manufacturers Manufacturer => (Manufacturers)caps.wMid; public int ProductID => caps.wPid; public IEnumerable<MixerLine> Destinations { get { for (int destination = 0; destination < DestinationCount; destination++) { yield return GetDestination(destination); } } } public static IEnumerable<Mixer> Mixers { get { for (int device = 0; device < NumberOfDevices; device++) { yield return new Mixer(device); } } } public Mixer(int mixerIndex) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (mixerIndex < 0 || mixerIndex >= NumberOfDevices) { throw new ArgumentOutOfRangeException("mixerID"); } caps = default(MixerInterop.MIXERCAPS); MmException.Try(MixerInterop.mixerGetDevCaps((IntPtr)mixerIndex, ref caps, Marshal.SizeOf(caps)), "mixerGetDevCaps"); mixerHandle = (IntPtr)mixerIndex; mixerHandleType = MixerFlags.Mixer; } public MixerLine GetDestination(int destinationIndex) { if (destinationIndex < 0 || destinationIndex >= DestinationCount) { throw new ArgumentOutOfRangeException("destinationIndex"); } return new MixerLine(mixerHandle, destinationIndex, mixerHandleType); } } public abstract class MixerControl { internal MixerInterop.MIXERCONTROL mixerControl; internal MixerInterop.MIXERCONTROLDETAILS mixerControlDetails; protected IntPtr mixerHandle; protected int nChannels; protected MixerFlags mixerHandleType; public string Name => mixerControl.szName; public MixerControlType ControlType => mixerControl.dwControlType; public bool IsBoolean => IsControlBoolean(mixerControl.dwControlType); public bool IsListText => IsControlListText(mixerControl.dwControlType); public bool IsSigned => IsControlSigned(mixerControl.dwControlType); public bool IsUnsigned => IsControlUnsigned(mixerControl.dwControlType); public bool IsCustom => IsControlCustom(mixerControl.dwControlType); public static IList<MixerControl> GetMixerControls(IntPtr mixerHandle, MixerLine mixerLine, MixerFlags mixerHandleType) { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007a: 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) List<MixerControl> list = new List<MixerControl>(); if (mixerLine.ControlsCount > 0) { int num = Marshal.SizeOf<MixerInterop.MIXERCONTROL>(); MixerInterop.MIXERLINECONTROLS mixerLineControls = default(MixerInterop.MIXERLINECONTROLS); IntPtr intPtr = Marshal.AllocHGlobal(num * mixerLine.ControlsCount); mixerLineControls.cbStruct = Marshal.SizeOf(mixerLineControls); mixerLineControls.dwLineID = mixerLine.LineId; mixerLineControls.cControls = mixerLine.ControlsCount; mixerLineControls.pamxctrl = intPtr; mixerLineControls.cbmxctrl = Marshal.SizeOf<MixerInterop.MIXERCONTROL>(); try { MmResult val = MixerInterop.mixerGetLineControls(mixerHandle, ref mixerLineControls, MixerFlags.Mixer | mixerHandleType); if ((int)val != 0) { throw new MmException(val, "mixerGetLineControls"); } for (int i = 0; i < mixerLineControls.cControls; i++) { MixerInterop.MIXERCONTROL mIXERCONTROL = Marshal.PtrToStructure<MixerInterop.MIXERCONTROL>((IntPtr)(intPtr.ToInt64() + num * i)); MixerControl item = GetMixerControl(mixerHandle, mixerLine.LineId, mIXERCONTROL.dwControlID, mixerLine.Channels, mixerHandleType); list.Add(item); } } finally { Marshal.FreeHGlobal(intPtr); } } return list; } public static MixerControl GetMixerControl(IntPtr mixerHandle, int nLineId, int controlId, int nChannels, MixerFlags mixerFlags) { //IL_005d: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) MixerInterop.MIXERLINECONTROLS mixerLineControls = default(MixerInterop.MIXERLINECONTROLS); MixerInterop.MIXERCONTROL structure = default(MixerInterop.MIXERCONTROL); IntPtr intPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(structure)); mixerLineControls.cbStruct = Marshal.SizeOf(mixerLineControls); mixerLineControls.cControls = 1; mixerLineControls.dwControlID = controlId; mixerLineControls.cbmxctrl = Marshal.SizeOf(structure); mixerLineControls.pamxctrl = intPtr; mixerLineControls.dwLineID = nLineId; MmResult val = MixerInterop.mixerGetLineControls(mixerHandle, ref mixerLineControls, MixerFlags.ListText | mixerFlags); if ((int)val != 0) { Marshal.FreeCoTaskMem(intPtr); throw new MmException(val, "mixerGetLineControls"); } structure = Marshal.PtrToStructure<MixerInterop.MIXERCONTROL>(mixerLineControls.pamxctrl); Marshal.FreeCoTaskMem(intPtr); if (IsControlBoolean(structure.dwControlType)) { return new BooleanMixerControl(structure, mixerHandle, mixerFlags, nChannels); } if (IsControlSigned(structure.dwControlType)) { return new SignedMixerControl(structure, mixerHandle, mixerFlags, nChannels); } if (IsControlUnsigned(structure.dwControlType)) { return new UnsignedMixerControl(structure, mixerHandle, mixerFlags, nChannels); } if (IsControlListText(structure.dwControlType)) { return new ListTextMixerControl(structure, mixerHandle, mixerFlags, nChannels); } if (IsControlCustom(structure.dwControlType)) { return new CustomMixerControl(structure, mixerHandle, mixerFlags, nChannels); } throw new InvalidOperationException($"Unknown mixer control type {structure.dwControlType}"); } protected void GetControlDetails() { //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) mixerControlDetails.cbStruct = Marshal.SizeOf(mixerControlDetails); mixerControlDetails.dwControlID = mixerControl.dwControlID; if (IsCustom) { mixerControlDetails.cChannels = 0; } else if ((mixerControl.fdwControl & (true ? 1u : 0u)) != 0) { mixerControlDetails.cChannels = 1; } else { mixerControlDetails.cChannels = nChannels; } if ((mixerControl.fdwControl & 2u) != 0) { mixerControlDetails.hwndOwner = (IntPtr)mixerControl.cMultipleItems; } else if (IsCustom) { mixerControlDetails.hwndOwner = IntPtr.Zero; } else { mixerControlDetails.hwndOwner = IntPtr.Zero; } if (IsBoolean) { mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_BOOLEAN>(); } else if (IsListText) { mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_LISTTEXT>(); } else if (IsSigned) { mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_SIGNED>(); } else if (IsUnsigned) { mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_UNSIGNED>(); } else { mixerControlDetails.cbDetails = mixerControl.Metrics.customData; } int num = mixerControlDetails.cbDetails * mixerControlDetails.cChannels; if ((mixerControl.fdwControl & 2u) != 0) { num *= (int)mixerControl.cMultipleItems; } IntPtr intPtr = Marshal.AllocCoTaskMem(num); mixerControlDetails.paDetails = intPtr; MmResult val = MixerInterop.mixerGetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType); if ((int)val == 0) { GetDetails(mixerControlDetails.paDetails); } Marshal.FreeCoTaskMem(intPtr); if ((int)val != 0) { throw new MmException(val, "mixerGetControlDetails"); } } protected abstract void GetDetails(IntPtr pDetails); private static bool IsControlBoolean(MixerControlType controlType) { switch (controlType) { case MixerControlType.BooleanMeter: case MixerControlType.Boolean: case MixerControlType.OnOff: case MixerControlType.Mute: case MixerControlType.Mono: case MixerControlType.Loudness: case MixerControlType.StereoEnhance: case MixerControlType.Button: case MixerControlType.SingleSelect: case MixerControlType.Mux: case MixerControlType.MultipleSelect: case MixerControlType.Mixer: return true; default: return false; } } private static bool IsControlListText(MixerControlType controlType) { if (controlType == MixerControlType.Equalizer || (uint)(controlType - 1879113728) <= 1u || (uint)(controlType - 1895890944) <= 1u) { return true; } return false; } private static bool IsControlSigned(MixerControlType controlType) { switch (controlType) { case MixerControlType.SignedMeter: case MixerControlType.PeakMeter: case MixerControlType.Signed: case MixerControlType.Decibels: case MixerControlType.Slider: case MixerControlType.Pan: case MixerControlType.QSoundPan: return true; default: return false; } } private static bool IsControlUnsigned(MixerControlType controlType) { switch (controlType) { case MixerControlType.UnsignedMeter: case MixerControlType.Unsigned: case MixerControlType.Percent: case MixerControlType.Fader: case MixerControlType.Volume: case MixerControlType.Bass: case MixerControlType.Treble: case MixerControlType.Equalizer: case MixerControlType.MicroTime: case MixerControlType.MilliTime: return true; default: return false; } } private static bool IsControlCustom(MixerControlType controlType) { return controlType == MixerControlType.Custom; } public override string ToString() { return $"{Name} {ControlType}"; } } [Flags] internal enum MixerControlClass { Custom = 0, Meter = 0x10000000, Switch = 0x20000000, Number = 0x30000000, Slider = 0x40000000, Fader = 0x50000000, Time = 0x60000000, List = 0x70000000, Mask = 0x70000000 } [Flags] internal enum MixerControlSubclass { SwitchBoolean = 0, SwitchButton = 0x1000000, MeterPolled = 0, TimeMicrosecs = 0, TimeMillisecs = 0x1000000, ListSingle = 0, ListMultiple = 0x1000000, Mask = 0xF000000 } [Flags] internal enum MixerControlUnits { Custom = 0, Boolean = 0x10000, Signed = 0x20000, Unsigned = 0x30000, Decibels = 0x40000, Percent = 0x50000, Mask = 0xFF0000 } public enum MixerControlType { Custom = 0, BooleanMeter = 268500992, SignedMeter = 268566528, PeakMeter = 268566529, UnsignedMeter = 268632064, Boolean = 536936448, OnOff = 536936449, Mute = 536936450, Mono = 536936451, Loudness = 536936452, StereoEnhance = 536936453, Button = 553713664, Decibels = 805568512, Signed = 805437440, Unsigned = 805502976, Percent = 805634048, Slider = 1073872896, Pan = 1073872897, QSoundPan = 1073872898, Fader = 1342373888, Volume = 1342373889, Bass = 1342373890, Treble = 1342373891, Equalizer = 1342373892, SingleSelect = 1879113728, Mux = 1879113729, MultipleSelect = 1895890944, Mixer = 1895890945, MicroTime = 1610809344, MilliTime = 1627586560 } [Flags] public enum MixerFlags { Handle = int.MinValue, Mixer = 0, MixerHandle = int.MinValue, WaveOut = 0x10000000, WaveOutHandle = -1879048192, WaveIn = 0x20000000, WaveInHandle = -1610612736, MidiOut = 0x30000000, MidiOutHandle = -1342177280, MidiIn = 0x40000000, MidiInHandle = -1073741824, Aux = 0x50000000, Value = 0, ListText = 1, QueryMask = 0xF, All = 0, OneById = 1, OneByType = 2, GetLineInfoOfDestination = 0, GetLineInfoOfSource = 1, GetLineInfoOfLineId = 2, GetLineInfoOfComponentType = 3, GetLineInfoOfTargetType = 4, GetLineInfoOfQueryMask = 0xF } internal class MixerInterop { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)] public struct MIXERCONTROLDETAILS { public int cbStruct; public int dwControlID; public int cChannels; public IntPtr hwndOwner; public int cbDetails; public IntPtr paDetails; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct MIXERCAPS { public ushort wMid; public ushort wPid; public uint vDriverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szPname; public uint fdwSupport; public uint cDestinations; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct MIXERLINECONTROLS { public int cbStruct; public int dwLineID; public int dwControlID; public int cControls; public int cbmxctrl; public IntPtr pamxctrl; } [Flags] public enum MIXERLINE_LINEF { MIXERLINE_LINEF_ACTIVE = 1, MIXERLINE_LINEF_DISCONNECTED = 0x8000, MIXERLINE_LINEF_SOURCE = int.MinValue } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct MIXERLINE { public int cbStruct; public int dwDestination; public int dwSource; public int dwLineID; public MIXERLINE_LINEF fdwLine; public IntPtr dwUser; public MixerLineComponentType dwComponentType; public int cChannels; public int cConnections; public int cControls; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string szShortName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string szName; public uint dwType; public uint dwDeviceID; public ushort wMid; public ushort wPid; public uint vDriverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szPname; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct Bounds { public int minimum; public int maximum; public int reserved2; public int reserved3; public int reserved4; public int reserved5; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct Metrics { public int step; public int customData; public int reserved2; public int reserved3; public int reserved4; public int reserved5; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct MIXERCONTROL { public uint cbStruct; public int dwControlID; public MixerControlType dwControlType; public uint fdwControl; public uint cMultipleItems; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] public string szShortName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string szName; public Bounds Bounds; public Metrics Metrics; } public struct MIXERCONTROLDETAILS_BOOLEAN { public int fValue; } public struct MIXERCONTROLDETAILS_SIGNED { public int lValue; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct MIXERCONTROLDETAILS_LISTTEXT { public uint dwParam1; public uint dwParam2; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string szName; } public struct MIXERCONTROLDETAILS_UNSIGNED { public uint dwValue; } public const uint MIXERCONTROL_CONTROLF_UNIFORM = 1u; public const uint MIXERCONTROL_CONTROLF_MULTIPLE = 2u; public const uint MIXERCONTROL_CONTROLF_DISABLED = 2147483648u; public const int MAXPNAMELEN = 32; public const int MIXER_SHORT_NAME_CHARS = 16; public const int MIXER_LONG_NAME_CHARS = 64; [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern int mixerGetNumDevs(); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerOpen(out IntPtr hMixer, int uMxId, IntPtr dwCallback, IntPtr dwInstance, MixerFlags dwOpenFlags); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerClose(IntPtr hMixer); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerGetControlDetails(IntPtr hMixer, ref MIXERCONTROLDETAILS mixerControlDetails, MixerFlags dwDetailsFlags); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerGetDevCaps(IntPtr nMixerID, ref MIXERCAPS mixerCaps, int mixerCapsSize); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerGetID(IntPtr hMixer, out int mixerID, MixerFlags dwMixerIDFlags); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerGetLineControls(IntPtr hMixer, ref MIXERLINECONTROLS mixerLineControls, MixerFlags dwControlFlags); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerGetLineInfo(IntPtr hMixer, ref MIXERLINE mixerLine, MixerFlags dwInfoFlags); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerMessage(IntPtr hMixer, uint nMessage, IntPtr dwParam1, IntPtr dwParam2); [DllImport("winmm.dll", CharSet = CharSet.Ansi)] public static extern MmResult mixerSetControlDetails(IntPtr hMixer, ref MIXERCONTROLDETAILS mixerControlDetails, MixerFlags dwDetailsFlags); } public class MixerLine { private MixerInterop.MIXERLINE mixerLine; private IntPtr mixerHandle; private MixerFlags mixerHandleType; public string Name => mixerLine.szName; public string ShortName => mixerLine.szShortName; public int LineId => mixerLine.dwLineID; public MixerLineComponentType ComponentType => mixerLine.dwComponentType; public string TypeDescription => mixerLine.dwComponentType switch { MixerLineComponentType.DestinationUndefined => "Undefined Destination", MixerLineComponentType.DestinationDigital => "Digital Destination", MixerLineComponentType.DestinationLine => "Line Level Destination", MixerLineComponentType.DestinationMonitor => "Monitor Destination", MixerLineComponentType.DestinationSpeakers => "Speakers Destination", MixerLineComponentType.DestinationHeadphones => "Headphones Destination", MixerLineComponentType.DestinationTelephone => "Telephone Destination", MixerLineComponentType.DestinationWaveIn => "Wave Input Destination", MixerLineComponentType.DestinationVoiceIn => "Voice Recognition Destination", MixerLineComponentType.SourceUndefined => "Undefined Source", MixerLineComponentType.SourceDigital => "Digital Source", MixerLineComponentType.SourceLine => "Line Level Source", MixerLineComponentType.SourceMicrophone => "Microphone Source", MixerLineComponentType.SourceSynthesizer => "Synthesizer Source", MixerLineComponentType.SourceCompactDisc => "Compact Disk Source", MixerLineComponentType.SourceTelephone => "Telephone Source", MixerLineComponentType.SourcePcSpeaker => "PC Speaker Source", MixerLineComponentType.SourceWaveOut => "Wave Out Source", MixerLineComponentType.SourceAuxiliary => "Auxiliary Source", MixerLineComponentType.SourceAnalog => "Analog Source", _ => "Invalid Component Type", }; public int Channels => mixerLine.cChannels; public int SourceCount => mixerLine.cConnections; public int ControlsCount => mixerLine.cControls; public bool IsActive => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_ACTIVE) != 0; public bool IsDisconnected => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_DISCONNECTED) != 0; public bool IsSource => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_SOURCE) != 0; public IEnumerable<MixerControl> Controls => MixerControl.GetMixerControls(mixerHandle, this, mixerHandleType); public IEnumerable<MixerLine> Sources { get { for (int source = 0; source < SourceCount; source++) { yield return GetSource(source); } } } public string TargetName => mixerLine.szPname; public MixerLine(IntPtr mixerHandle, int destinationIndex, MixerFlags mixerHandleType) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) this.mixerHandle = mixerHandle; this.mixerHandleType = mixerHandleType; mixerLine = default(MixerInterop.MIXERLINE); mixerLine.cbStruct = Marshal.SizeOf(mixerLine); mixerLine.dwDestination = destinationIndex; MmException.Try(MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.Mixer), "mixerGetLineInfo"); } public MixerLine(IntPtr mixerHandle, int destinationIndex, int sourceIndex, MixerFlags mixerHandleType) { //IL_005a: Unknown result type (might be due to invalid IL or missing references) this.mixerHandle = mixerHandle; this.mixerHandleType = mixerHandleType; mixerLine = default(MixerInterop.MIXERLINE); mixerLine.cbStruct = Marshal.SizeOf(mixerLine); mixerLine.dwDestination = destinationIndex; mixerLine.dwSource = sourceIndex; MmException.Try(MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.ListText), "mixerGetLineInfo"); } public static int GetMixerIdForWaveIn(int waveInDevice) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) int mixerID = -1; MmException.Try(MixerInterop.mixerGetID((IntPtr)waveInDevice, out mixerID, MixerFlags.WaveIn), "mixerGetID"); return mixerID; } public MixerLine GetSource(int sourceIndex) { if (sourceIndex < 0 || sourceIndex >= SourceCount) { throw new ArgumentOutOfRangeException("sourceIndex"); } return new MixerLine(mixerHandle, mixerLine.dwDestination, sourceIndex, mixerHandleType); } public override string ToString() { return $"{Name} {TypeDescription} ({ControlsCount} controls, ID={mixerLine.dwLineID})"; } } public enum MixerLineComponentType { DestinationUndefined = 0, DestinationDigital = 1, DestinationLine = 2, DestinationMonitor = 3, DestinationSpeakers = 4, DestinationHeadphones = 5, DestinationTelephone = 6, DestinationWaveIn = 7, DestinationVoiceIn = 8, SourceUndefined = 4096, SourceDigital = 4097, SourceLine = 4098, SourceMicrophone = 4099, SourceSynthesizer = 4100, SourceCompactDisc = 4101, SourceTelephone = 4102, SourcePcSpeaker = 4103, SourceWaveOut = 4104, SourceAuxiliary = 4105, SourceAnalog = 4106 } public class SignedMixerControl : MixerControl { private MixerInterop.MIXERCONTROLDETAILS_SIGNED signedDetails; public int Value { get { GetControlDetails(); return signedDetails.lValue; } set { //IL_0052: Unknown result type (might be due to invalid IL or missing references) signedDetails.lValue = value; mixerControlDetails.paDetails = Marshal.AllocHGlobal(Marshal.SizeOf(signedDetails)); Marshal.StructureToPtr(signedDetails, mixerControlDetails.paDetails, fDeleteOld: false); MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails"); Marshal.FreeHGlobal(mixerControlDetails.paDetails); } } public int MinValue => mixerControl.Bounds.minimum; public int MaxValue => mixerControl.Bounds.maximum; public double Percent { get { return 100.0 * (double)(Value - MinValue) / (double)(MaxValue - MinValue); } set { Value = (int)((double)MinValue + value / 100.0 * (double)(MaxValue - MinValue)); } } internal SignedMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels) { base.mixerControl = mixerControl; base.mixerHandle = mixerHandle; base.mixerHandleType = mixerHandleType; base.nChannels = nChannels; mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS); GetControlDetails(); } protected override void GetDetails(IntPtr pDetails) { signedDetails = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_SIGNED>(mixerControlDetails.paDetails); } public override string ToString() { return $"{base.ToString()} {Percent}%"; } } public class UnsignedMixerControl : MixerControl { private MixerInterop.MIXERCONTROLDETAILS_UNSIGNED[] unsignedDetails; public uint Value { get { GetControlDetails(); return unsignedDetails[0].dwValue; } set { //IL_008f: Unknown result type (might be due to invalid IL or missing references) int num = Marshal.SizeOf(unsignedDetails[0]); mixerControlDetails.paDetails = Marshal.AllocHGlobal(num * nChannels); for (int i = 0; i < nChannels; i++) { unsignedDetails[i].dwValue = value; long num2 = mixerControlDetails.paDetails.ToInt64() + num * i; Marshal.StructureToPtr(unsignedDetails[i], (IntPtr)num2, fDeleteOld: false); } MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails"); Marshal.FreeHGlobal(mixerControlDetails.paDetails); } } public uint MinValue => (uint)mixerControl.Bounds.minimum; public uint MaxValue => (uint)mixerControl.Bounds.maximum; public double Percent { get { return 100.0 * (double)(Value - MinValue) / (double)(MaxValue - MinValue); } set { Value = (uint)((double)MinValue + value / 100.0 * (double)(MaxValue - MinValue)); } } internal UnsignedMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels) { base.mixerControl = mixerControl; base.mixerHandle = mixerHandle; base.mixerHandleType = mixerHandleType; base.nChannels = nChannels; mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS); GetControlDetails(); } protected override void GetDetails(IntPtr pDetails) { unsignedDetails = new MixerInterop.MIXERCONTROLDETAILS_UNSIGNED[nChannels]; for (int i = 0; i < nChannels; i++) { unsignedDetails[i] = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_UNSIGNED>(mixerControlDetails.paDetails); } } public override string ToString() { return $"{base.ToString()} {Percent}%"; } } } namespace NAudio.Wave { internal enum AcmMetrics { CountDrivers = 1, CountCodecs = 2, CountConverters = 3, CountFilters = 4, CountDisabled = 5, CountHardware = 6, CountLocalDrivers = 20, CountLocalCodecs = 21, CountLocalConverters = 22, CountLocalFilters = 23, CountLocalDisabled = 24, HardwareWaveInput = 30, HardwareWaveOutput = 31, MaxSizeFormat = 50, MaxSizeFilter = 51, DriverSupport = 100, DriverPriority = 101 } [Flags] internal enum AcmStreamConvertFlags { BlockAlign = 4, Start = 0x10, End = 0x20 } [StructLayout(LayoutKind.Explicit)] public struct MmTime { public const int TIME_MS = 1; public const int TIME_SAMPLES = 2; public const int TIME_BYTES = 4; [FieldOffset(0)] public uint wType; [FieldOffset(4)] public uint ms; [FieldOffset(4)] public uint sample; [FieldOffset(4)] public uint cb; [FieldOffset(4)] public uint ticks; [FieldOffset(4)] public byte smpteHour; [FieldOffset(5)] public byte smpteMin; [FieldOffset(6)] public byte smpteSec; [FieldOffset(7)] public byte smpteFrame; [FieldOffset(8)] public byte smpteFps; [FieldOffset(9)] public byte smpteDummy; [FieldOffset(10)] public byte smptePad0; [FieldOffset(11)] public byte smptePad1; [FieldOffset(4)] public uint midiSongPtrPos; } public enum WaveCallbackStrategy { FunctionCallback, NewWindow, ExistingWindow, Event } [StructLayout(LayoutKind.Sequential)] public sealed class WaveHeader { public IntPtr dataBuffer; public int bufferLength; public int bytesRecorded; public IntPtr userData; public WaveHeaderFlags flags; public int loops; public IntPtr next; public IntPtr reserved; } [Flags] public enum WaveHeaderFlags { BeginLoop = 4, Done = 1, EndLoop = 8, InQueue = 0x10, Prepared = 2 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct WaveInCapabilities { private short manufacturerId; private short productId; private int driverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] private string productName; private SupportedWaveFormat supportedFormats; private short channels; private short reserved; private Guid manufacturerGuid; private Guid productGuid; private Guid nameGuid; private const int MaxProductNameLength = 32; public int Channels => channels; public string ProductName => productName; public Guid NameGuid => nameGuid; public Guid ProductGuid => productGuid; public Guid ManufacturerGuid => manufacturerGuid; public bool SupportsWaveFormat(SupportedWaveFormat waveFormat) { return (supportedFormats & waveFormat) == waveFormat; } } public static class WaveCapabilitiesHelpers { public static readonly Guid MicrosoftDefaultManufacturerId = new Guid("d5a47fa8-6d98-11d1-a21a-00a0c9223196"); public static readonly Guid DefaultWaveOutGuid = new Guid("E36DC310-6D9A-11D1-A21A-00A0C9223196"); public static readonly Guid DefaultWaveInGuid = new Guid("E36DC311-6D9A-11D1-A21A-00A0C9223196"); public static string GetNameFromGuid(Guid guid) { string result = null; using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\MediaCategories")) { using RegistryKey registryKey2 = registryKey.OpenSubKey(guid.ToString("B")); if (registryKey2 != null) { result = registryKey2.GetValue("Name") as string; } } return result; } } public class WaveInterop { [Flags] public enum WaveInOutOpenFlags { CallbackNull = 0, CallbackFunction = 0x30000, CallbackEvent = 0x50000, CallbackWindow = 0x10000, CallbackThread = 0x20000 } public enum WaveMessage { WaveInOpen = 958, WaveInClose = 959, WaveInData = 960, WaveOutClose = 956, WaveOutDone = 957, WaveOutOpen = 955 } public delegate void WaveCallback(IntPtr hWaveOut, WaveMessage message, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved); [DllImport("winmm.dll")] public static extern int mmioStringToFOURCC([MarshalAs(UnmanagedType.LPStr)] string s, int flags); [DllImport("winmm.dll")] public static extern int waveOutGetNumDevs(); [DllImport("winmm.dll")] public static extern MmResult waveOutPrepareHeader(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult waveOutUnprepareHeader(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult waveOutWrite(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult waveOutOpen(out IntPtr hWaveOut, IntPtr uDeviceID, WaveFormat lpFormat, WaveCallback dwCallback, IntPtr dwInstance, WaveInOutOpenFlags dwFlags); [DllImport("winmm.dll", EntryPoint = "waveOutOpen")] public static extern MmResult waveOutOpenWindow(out IntPtr hWaveOut, IntPtr uDeviceID, WaveFormat lpFormat, IntPtr callbackWindowHandle, IntPtr dwInstance, WaveInOutOpenFlags dwFlags); [DllImport("winmm.dll")] public static extern MmResult waveOutReset(IntPtr hWaveOut); [DllImport("winmm.dll")] public static extern MmResult waveOutClose(IntPtr hWaveOut); [DllImport("winmm.dll")] public static extern MmResult waveOutPause(IntPtr hWaveOut); [DllImport("winmm.dll")] public static extern MmResult waveOutRestart(IntPtr hWaveOut); [DllImport("winmm.dll")] public static extern MmResult waveOutGetPosition(IntPtr hWaveOut, ref MmTime mmTime, int uSize); [DllImport("winmm.dll")] public static extern MmResult waveOutSetVolume(IntPtr hWaveOut, int dwVolume); [DllImport("winmm.dll")] public static extern MmResult waveOutGetVolume(IntPtr hWaveOut, out int dwVolume); [DllImport("winmm.dll", CharSet = CharSet.Auto)] public static extern MmResult waveOutGetDevCaps(IntPtr deviceID, out WaveOutCapabilities waveOutCaps, int waveOutCapsSize); [DllImport("winmm.dll")] public static extern int waveInGetNumDevs(); [DllImport("winmm.dll", CharSet = CharSet.Auto)] public static extern MmResult waveInGetDevCaps(IntPtr deviceID, out WaveInCapabilities waveInCaps, int waveInCapsSize); [DllImport("winmm.dll")] public static extern MmResult waveInAddBuffer(IntPtr hWaveIn, WaveHeader pwh, int cbwh); [DllImport("winmm.dll")] public static extern MmResult waveInClose(IntPtr hWaveIn); [DllImport("winmm.dll")] public static extern MmResult waveInOpen(out IntPtr hWaveIn, IntPtr uDeviceID, WaveFormat lpFormat, WaveCallback dwCallback, IntPtr dwInstance, WaveInOutOpenFlags dwFlags); [DllImport("winmm.dll", EntryPoint = "waveInOpen")] public static extern MmResult waveInOpenWindow(out IntPtr hWaveIn, IntPtr uDeviceID, WaveFormat lpFormat, IntPtr callbackWindowHandle, IntPtr dwInstance, WaveInOutOpenFlags dwFlags); [DllImport("winmm.dll")] public static extern MmResult waveInPrepareHeader(IntPtr hWaveIn, WaveHeader lpWaveInHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult waveInUnprepareHeader(IntPtr hWaveIn, WaveHeader lpWaveInHdr, int uSize); [DllImport("winmm.dll")] public static extern MmResult waveInReset(IntPtr hWaveIn); [DllImport("winmm.dll")] public static extern MmResult waveInStart(IntPtr hWaveIn); [DllImport("winmm.dll")] public static extern MmResult waveInStop(IntPtr hWaveIn); [DllImport("winmm.dll")] public static extern MmResult waveInGetPosition(IntPtr hWaveIn, out MmTime mmTime, int uSize); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct WaveOutCapabilities { private short manufacturerId; private short productId; private int driverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] private string productName; private SupportedWaveFormat supportedFormats; private short channels; private short reserved; private WaveOutSupport support; private Guid manufacturerGuid; private Guid productGuid; private Guid nameGuid; private const int MaxProductNameLength = 32; public int Channels => channels; public bool SupportsPlaybackRateControl => (support & WaveOutSupport.PlaybackRate) == WaveOutSupport.PlaybackRate; public string ProductName => productName; public Guid NameGuid => nameGuid; public Guid ProductGuid => productGuid; public Guid ManufacturerGuid => manufacturerGuid; public bool SupportsWaveFormat(SupportedWaveFormat waveFormat) { return (supportedFormats & waveFormat) == waveFormat; } } [Flags] public enum SupportedWaveFormat { WAVE_FORMAT_1M08 = 1, WAVE_FORMAT_1S08 = 2, WAVE_FORMAT_1M16 = 4, WAVE_FORMAT_1S16 = 8, WAVE_FORMAT_2M08 = 0x10, WAVE_FORMAT_2S08 = 0x20, WAVE_FORMAT_2M16 = 0x40, WAVE_FORMAT_2S16 = 0x80, WAVE_FORMAT_4M08 = 0x100, WAVE_FORMAT_4S08 = 0x200, WAVE_FORMAT_4M16 = 0x400, WAVE_FORMAT_4S16 = 0x800, WAVE_FORMAT_44M08 = 0x100, WAVE_FORMAT_44S08 = 0x200, WAVE_FORMAT_44M16 = 0x400, WAVE_FORMAT_44S16 = 0x800, WAVE_FORMAT_48M08 = 0x1000, WAVE_FORMAT_48S08 = 0x2000, WAVE_FORMAT_48M16 = 0x4000, WAVE_FORMAT_48S16 = 0x8000, WAVE_FORMAT_96M08 = 0x10000, WAVE_FORMAT_96S08 = 0x20000, WAVE_FORMAT_96M16 = 0x40000, WAVE_FORMAT_96S16 = 0x80000 } [Flags] internal enum WaveOutSupport { Pitch = 1, PlaybackRate = 2, Volume = 4, LRVolume = 8, Sync = 0x10, SampleAccurate = 0x20 } public class AcmMp3FrameDecompressor : IMp3FrameDecompressor, IDisposable { private readonly AcmStream conversionStream; private readonly WaveFormat pcmFormat; private bool disposed; public WaveFormat OutputFormat => pcmFormat; public AcmMp3FrameDecompressor(WaveFormat sourceFormat) { pcmFormat = AcmStream.SuggestPcmFormat(sourceFormat); try { conversionStream = new AcmStream(sourceFormat, pcmFormat); } catch (Exception) { disposed = true; GC.SuppressFinalize(this); throw; } } public int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset) { if (frame == null) { throw new ArgumentNullException("frame", "You must provide a non-null Mp3Frame to decompress"); } Array.Copy(frame.RawData, conversionStream.SourceBuffer, frame.FrameLength); int sourceBytesConverted; int num = conversionStream.Convert(frame.FrameLength, out sourceBytesConverted); if (sourceBytesConverted != frame.FrameLength) { throw new InvalidOperationException($"Couldn't convert the whole MP3 frame (converted {sourceBytesConverted}/{frame.FrameLength})"); } Array.Copy(conversionStream.DestBuffer, 0, dest, destOffset, num); return num; } public void Reset() { conversionStream.Reposition(); } public void Dispose() { if (!disposed) { disposed = true; if (conversionStream != null) { conversionStream.Dispose(); } GC.SuppressFinalize(this); } } ~AcmMp3FrameDecompressor() { Dispose(); } } public class WaveFormatConversionProvider : IWaveProvider, IDisposable { private readonly AcmStream conversionStream; private readonly IWaveProvider sourceProvider; private readonly int preferredSourceReadSize; private int leftoverDestBytes; private int leftoverDestOffset; private int leftoverSourceBytes; private bool isDisposed; public WaveFormat WaveFormat { get; } public WaveFormatConversionProvider(WaveFormat targetFormat, IWaveProvider sourceProvider) { this.sourceProvider = sourceProvider; WaveFormat = targetFormat; conversionStream = new AcmStream(sourceProvider.WaveFormat, targetFormat); preferredSourceReadSize = Math.Min(sourceProvider.WaveFormat.AverageBytesPerSecond, conversionStream.SourceBuffer.Length); preferredSourceReadSize -= preferredSourceReadSize % sourceProvider.WaveFormat.BlockAlign; } public void Reposition() { leftoverDestBytes = 0; leftoverDestOffset = 0; leftoverSourceBytes = 0; conversionStream.Reposition(); } public int Read(byte[] buffer, int offset, int count) { int i = 0; if (count % WaveFormat.BlockAlign != 0) { count -= count % WaveFormat.BlockAlign; } int num5; for (; i < count; i += num5) { int num = Math.Min(count - i, leftoverDestBytes); if (num > 0) { Array.Copy(conversionStream.DestBuffer, leftoverDestOffset, buffer, offset + i, num); leftoverDestOffset += num; leftoverDestBytes -= num; i += num; } if (i >= count) { break; } int num2 = Math.Min(preferredSourceReadSize, conversionStream.SourceBuffer.Length - leftoverSourceBytes); int num3 = sourceProvider.Read(conversionStream.SourceBuffer, leftoverSourceBytes, num2) + leftoverSourceBytes; if (num3 == 0) { break; } int sourceBytesConverted; int num4 = conversionStream.Convert(num3, out sourceBytesConverted); if (sourceBytesConverted == 0) { break; } leftoverSourceBytes = num3 - sourceBytesConverted; if (leftoverSourceBytes > 0) { Buffer.BlockCopy(conversionStream.SourceBuffer, sourceBytesConverted, conversionStream.SourceBuffer, 0, leftoverSourceBytes); } if (num4 <= 0) { break; } int val = count - i; num5 = Math.Min(num4, val); if (num5 < num4) { leftoverDestBytes = num4 - num5; leftoverDestOffset = num5; } Array.Copy(conversionStream.DestBuffer, 0, buffer, i + offset, num5); } return i; } protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; conversionStream?.Dispose(); } } public void Dispose() { GC.SuppressFinalize(this); Dispose(disposing: true); } ~WaveFormatConversionProvider() { Dispose(disposing: false); } } public class WaveFormatConversionStream : WaveStream { private readonly WaveFormatConversionProvider conversionProvider; private readonly WaveFormat targetFormat; private readonly long length; private long position; private readonly WaveStream sourceStream; private bool isDisposed; public override long Position { get { return position; } set { value -= value % ((WaveStream)this).BlockAlign; long num = EstimateDestToSource(value); ((Stream)(object)sourceStream).Position = num; position = EstimateSourceToDest(((Stream)(object)sourceStream).Position); conversionProvider.Reposition(); } } public override long Length => length; public override WaveFormat WaveFormat => targetFormat; public WaveFormatConversionStream(WaveFormat targetFormat, WaveStream sourceStream) { this.sourceStream = sourceStream; this.targetFormat = targetFormat; conversionProvider = new WaveFormatConversionProvider(targetFormat, (IWaveProvider)(object)sourceStream); length = EstimateSourceToDest((int)((Stream)(object)sourceStream).Length); position = 0L; } public static WaveStream CreatePcmStream(WaveStream sourceStream) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown if ((int)sourceStream.WaveFormat.Encoding == 1) { return sourceStream; } WaveFormat val = AcmStream.SuggestPcmFormat(sourceStream.WaveFormat); if (val.SampleRate < 8000) { if ((int)sourceStream.WaveFormat.Encoding != 163) { throw new InvalidOperationException("Invalid suggested output format, please explicitly provide a target format"); } val = new WaveFormat(8000, 16, 1); } return (WaveStream)(object)new WaveFormatConversionStream(val, sourceStream); } [Obsolete("can be unreliable, use of this method not encouraged")] public int SourceToDest(int source) { return (int)EstimateSourceToDest(source); } private long EstimateSourceToDest(long source) { long num = source * targetFormat.AverageBytesPerSecond / sourceStream.WaveFormat.AverageBytesPerSecond; return num - num % targetFormat.BlockAlign; } private long EstimateDestToSource(long dest) { long num = dest * sourceStream.WaveFormat.AverageBytesPerSecond / targetFormat.AverageBytesPerSecond; return (int)(num - num % sourceStream.WaveFormat.BlockAlign); } [Obsolete("can be unreliable, use of this method not encouraged")] public int DestToSource(int dest) { return (int)EstimateDestToSource(dest); } public override int Read(byte[] buffer, int offset, int count) { int num = conversionProvider.Read(buffer, offset, count); position += num; return num; } protected override void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; if (disposing) { ((Stream)(object)sourceStream).Dispose(); conversionProvider.Dispose(); } } ((Stream)this).Dispose(disposing); } } public class WaveInBuffer : IDisposable { private readonly WaveHeader header; private readonly int bufferSize; private readonly byte[] buffer; private GCHandle hBuffer; private IntPtr waveInHandle; private GCHandle hHeader; private GCHandle hThis; public byte[] Data => buffer; public bool Done => (header.flags & WaveHeaderFlags.Done) == WaveHeaderFlags.Done; public bool InQueue => (header.flags & WaveHeaderFlags.InQueue) == WaveHeaderFlags.InQueue; public int BytesRecorded => header.bytesRecorded; public int BufferSize => bufferSize; public WaveInBuffer(IntPtr waveInHandle, int bufferSize) { //IL_00b1: Unknown result type (might be due to invalid IL or missing references) this.bufferSize = bufferSize; buffer = new byte[bufferSize]; hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); this.waveInHandle = waveInHandle; header = new WaveHeader(); hHeader = GCHandle.Alloc(header, GCHandleType.Pinned); header.dataBuffer = hBuffer.AddrOfPinnedObject(); header.bufferLength = bufferSize; header.loops = 1; hThis = GCHandle.Alloc(this); header.userData = (IntPtr)hThis; MmException.Try(WaveInterop.waveInPrepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveInPrepareHeader"); } public void Reuse() { //IL_0017: 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_0063: Unknown result type (might be due to invalid IL or missing references) MmException.Try(WaveInterop.waveInUnprepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveUnprepareHeader"); MmException.Try(WaveInterop.waveInPrepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveInPrepareHeader"); MmException.Try(WaveInterop.waveInAddBuffer(waveInHandle, header, Marshal.SizeOf(header)), "waveInAddBuffer"); } ~WaveInBuffer() { Dispose(disposing: false); } public void Dispose() { GC.SuppressFinalize(this); Dispose(disposing: true); } protected void Dispose(bool disposing) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (waveInHandle != IntPtr.Zero) { WaveInterop.waveInUnprepareHeader(waveInHandle, header, Marshal.SizeOf(header)); waveInHandle = IntPtr.Zero; } if (hHeader.IsAllocated) { hHeader.Free(); } if (hBuffer.IsAllocated) { hBuffer.Free(); } if (hThis.IsAllocated) { hThis.Free(); } } } public class WaveInEvent : IWaveIn, IDisposable { private readonly AutoResetEvent callbackEvent; private readonly SynchronizationContext syncContext; private IntPtr waveInHandle; private volatile CaptureState captureState; private WaveInBuffer[] buffers; public static int DeviceCount => WaveInterop.waveInGetNumDevs(); public int BufferMilliseconds { get; set; } public int NumberOfBuffers { get; set; } public int DeviceNumber { get; set; } public WaveFormat WaveFormat { get; set; } public event EventHandler<WaveInEventArgs> DataAvailable; public event EventHandler<StoppedEventArgs> RecordingStopped; public WaveInEvent() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown //IL_0048: Unknown result type (might be due to invalid IL or missing references) callbackEvent = new AutoResetEvent(initialState: false); syncContext = SynchronizationContext.Current; DeviceNumber = 0; WaveFormat = new WaveFormat(8000, 16, 1); BufferMilliseconds = 100; NumberOfBuffers = 3; captureState = (CaptureState)0; } public static WaveInCapabilities GetCapabilities(int devNumber) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) WaveInCapabilities waveInCaps = default(WaveInCapabilities); int waveInCapsSize = Marshal.SizeOf(waveInCaps); MmException.Try(WaveInterop.waveInGetDevCaps((IntPtr)devNumber, out waveInCaps, waveInCapsSize), "waveInGetDevCaps"); return waveInCaps; } private void CreateBuffers() { int num = BufferMilliseconds * WaveFormat.AverageBytesPerSecond / 1000; if (num % WaveFormat.BlockAlign != 0) { num -= num % WaveFormat.BlockAlign; } buffers = new WaveInBuffer[NumberOfBuffers]; for (int i = 0; i < buffers.Length; i++) { buffers[i] = new WaveInBuffer(waveInHandle, num); } } private void OpenWaveInDevice() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) CloseWaveInDevice(); MmException.Try(WaveInterop.waveInOpenWindow(out waveInHandle, (IntPtr)DeviceNumber, WaveFormat, callbackEvent.SafeWaitHandle.DangerousGetHandle(), IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackEvent), "waveInOpen"); CreateBuffers(); } public void StartRecording() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) if ((int)captureState != 0) { throw new InvalidOperationException("Already recording"); } OpenWaveInDevice(); MmException.Try(WaveInterop.waveInStart(waveInHandle), "waveInStart"); captureState = (CaptureState)1; ThreadPool.QueueUserWorkItem(delegate { RecordThread(); }, null); } private void RecordThread() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) Exception e = null; try { DoRecording(); } catch (Exception ex) { e = ex; } finally { captureState = (CaptureState)0; RaiseRecordingStoppedEvent(e); } } private void DoRecording() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Invalid comparison between Unknown and I4 //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Invalid comparison between Unknown and I4 //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown captureState = (CaptureState)2; WaveInBuffer[] array = buffers; foreach (WaveInBuffer waveInBuffer in array) { if (!waveInBuffer.InQueue) { waveInBuffer.Reuse(); } } while ((int)captureState == 2) { if (!callbackEvent.WaitOne()) { continue; } array = buffers; foreach (WaveInBuffer waveInBuffer2 in array) { if (waveInBuffer2.Done) { if (waveInBuffer2.BytesRecorded > 0) { this.DataAvailable?.Invoke(this, new WaveInEventArgs(waveInBuffer2.Data, waveInBuffer2.BytesRecorded)); } if ((int)captureState == 2) { waveInBuffer2.Reuse(); } } } } } private void RaiseRecordingStoppedEvent(Exception e) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown EventHandler<StoppedEventArgs> handler = this.RecordingStopped; if (handler == null) { return; } if (syncContext == null) { handler(this, new StoppedEventArgs(e)); return; } syncContext.Post(delegate { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown handler(this, new StoppedEventArgs(e)); }, null); } public void StopRecording() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if ((int)captureState != 0) { captureState = (CaptureState)3; MmException.Try(WaveInterop.waveInStop(waveInHandle), "waveInStop"); MmException.Try(WaveInterop.waveInReset(waveInHandle), "waveInReset"); callbackEvent.Set(); } } public long GetPosition() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) MmTime mmTime = default(MmTime); mmTime.wType = 4u; MmException.Try(WaveInterop.waveInGetPosition(waveInHandle, out mmTime, Marshal.SizeOf(mmTime)), "waveInGetPosition"); if (mmTime.wType != 4) { throw new Exception($"waveInGetPosition: wType -> Expected {4}, Received {mmTime.wType}"); } return mmTime.cb; } protected virtual void Dispose(bool disposing) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) if (disposing) { if ((int)captureState != 0) { StopRecording(); } CloseWaveInDevice(); } } private void CloseWaveInDevice() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) WaveInterop.waveInReset(waveInHandle); if (buffers != null) { for (int i = 0; i < buffers.Length; i++) { buffers[i].Dispose(); } buffers = null; } WaveInterop.waveInClose(waveInHandle); waveInHandle = IntPtr.Zero; } public MixerLine GetMixerLine() { if (waveInHandle != IntPtr.Zero) { return new MixerLine(waveInHandle, 0, MixerFlags.WaveInHandle); } return new MixerLine((IntPtr)DeviceNumber, 0, MixerFlags.WaveIn); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public class WaveOutBuffer : IDisposable { private readonly WaveHeader header; private readonly int bufferSize; private readonly byte[] buffer; private readonly IWaveProvider waveStream; private readonly object waveOutLock; private GCHandle hBuffer; private IntPtr hWaveOut; private GCHandle hHeader; private GCHandle hThis; public bool InQueue => (header.flags & WaveHeaderFlags.InQueue) == WaveHeaderFlags.InQueue; public int BufferSize => bufferSize; public WaveOutBuffer(IntPtr hWaveOut, int bufferSize, IWaveProvider bufferFillStream, object waveOutLock) { //IL_00cd: Unknown result type (might be due to invalid IL or missing references) this.bufferSize = bufferSize; buffer = new byte[bufferSize]; hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); this.hWaveOut = hWaveOut; waveStream = bufferFillStream; this.waveOutLock = waveOutLock; header = new WaveHeader(); hHeader = GCHandle.Alloc(header, GCHandleType.Pinned); header.dataBuffer = hBuffer.AddrOfPinnedObject(); header.bufferLength = bufferSize; header.loops = 1; hThis = GCHandle.Alloc(this); header.userData = (IntPtr)hThis; lock (waveOutLock) { MmException.Try(WaveInterop.waveOutPrepareHeader(hWaveOut, header, Marshal.SizeOf(header)), "waveOutPrepareHeader"); } } ~WaveOutBuffer() { Dispose(disposing: false); } public void Dispose() { GC.SuppressFinalize(this); Dispose(disposing: true); } protected void Dispose(bool disposing) { //IL_0084: Unknown result type (might be due to invalid IL or missing references) if (hHeader.IsAllocated) { hHeader.Free(); } if (hBuffer.IsAllocated) { hBuffer.Free(); } if (hThis.IsAllocated) { hThis.Free(); } if (hWaveOut != IntPtr.Zero) { lock (waveOutLock) { WaveInterop.waveOutUnprepareHeader(hWaveOut, header, Marshal.SizeOf(header)); } hWaveOut = IntPtr.Zero; } } public bool OnDone() { int num; lock (waveStream) { num = waveStream.Read(buffer, 0, buffer.Length); } if (num == 0) { return false; } for (int i = num; i < buffer.Length; i++) { buffer[i] = 0; } WriteToWaveOut(); return true; } private void WriteToWaveOut() { //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_003a: 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_0043: Unknown result type (might be due to invalid IL or missing references) MmResult val; lock (waveOutLock) { val = WaveInterop.waveOutWrite(hWaveOut, header, Marshal.SizeOf(header)); } if ((int)val != 0) { throw new MmException(val, "waveOutWrite"); } GC.KeepAlive(this); } } public class WaveOutEvent : IWavePlayer, IDisposable, IWavePosition { private readonly object waveOutLock; private readonly SynchronizationContext syncContext; private IntPtr hWaveOut; private WaveOutBuffer[] buffers; private IWaveProvider waveStream; private volatile PlaybackState playbackState; private AutoResetEvent callbackEvent; public int DesiredLatency { get; set; } public int NumberOfBuffers { get; set; } public int DeviceNumber { get; set; } = -1; public WaveFormat OutputWaveFormat => waveStream.WaveFormat; public PlaybackState PlaybackState => playbackState; public float Volume { get { return WaveOutUtils.GetWaveOutVolume(hWaveOut, waveOutLock); } set { WaveOutUtils.SetWaveOutVolume(value, hWaveOut, waveOutLock); } } public event EventHandler<StoppedEventArgs> PlaybackStopped; public WaveOutEvent() { syncContext = SynchronizationContext.Current; if (syncContext != null && (syncContext.GetType().Name == "LegacyAspNetSynchronizationContext" || syncContext.GetType().Name == "AspNetSynchronizationContext")) { syncContext = null; } DesiredLatency = 300; NumberOfBuffers = 2; waveOutLock = new object(); } public void Init(IWaveProvider waveProvider) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) if ((int)playbackState != 0) { throw new InvalidOperationException("Can't re-initialize during playback"); } if (hWaveOut != IntPtr.Zero) { DisposeBuffers(); CloseWaveOut(); } callbackEvent = new AutoResetEvent(initialState: false); waveStream = waveProvider; int bufferSize = waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1) / NumberOfBuffers); MmResult val; lock (waveOutLock) { val = WaveInterop.waveOutOpenWindow(out hWaveOut, (IntPtr)DeviceNumber, waveStream.WaveFormat, callbackEvent.SafeWaitHandle.DangerousGetHandle(), IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackEvent); } MmException.Try(val, "waveOutOpen"); buffers = new WaveOutBuffer[NumberOfBuffers]; playbackState = (PlaybackState)0; for (int i = 0; i < NumberOfBuffers; i++) { buffers[i] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock); } } public void Play() { //IL_001c: 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_0057: Invalid comparison between Unknown and I4 //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (buffers == null || waveStream == null) { throw new InvalidOperationException("Must call Init first"); } if ((int)playbackState == 0) { playbackState = (PlaybackState)1; callbackEvent.Set(); ThreadPool.QueueUserWorkItem(delegate { PlaybackThread(); }, null); } else if ((int)playbackState == 2) { Resume(); callbackEvent.Set(); } } private void PlaybackThread() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) Exception e = null; try { DoPlayback(); } catch (Exception ex) { e = ex; } finally { playbackState = (PlaybackState)0; RaisePlaybackStoppedEvent(e); } } private void DoPlayback() { //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) while ((int)playbackState != 0) { if (!callbackEvent.WaitOne(DesiredLatency)) { _ = playbackState; _ = 1; } if ((int)playbackState != 1) { continue; } int num = 0; WaveOutBuffer[] array = buffers; foreach (WaveOutBuffer waveOutBuffer in array) { if (waveOutBuffer.InQueue || waveOutBuffer.OnDone()) { num++; } } if (num == 0) { playbackState = (PlaybackState)0; callbackEvent.Set(); } } } public void Pause() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000d: 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_0030: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if ((int)playbackState == 1) { playbackState = (PlaybackState)2; MmResult val; lock (waveOutLock) { val = WaveInterop.waveOutPause(hWaveOut); } if ((int)val != 0) { throw new MmException(val, "waveOutPause"); } } } private void Resume() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_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) if ((int)playbackState == 2) { MmResult val; lock (waveOutLock) { val = WaveInterop.waveOutRestart(hWaveOut); } if ((int)val != 0) { throw new MmException(val, "waveOutRestart"); } playbackState = (PlaybackState)1; } } public void Stop() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if ((int)playbackState != 0) { playbackState = (PlaybackState)0; MmResult val; lock (waveOutLock) { val = WaveInterop.waveOutReset(hWaveOut); } if ((int)val != 0) { throw new MmException(val, "waveOutReset"); } callbackEvent.Set(); } } public long GetPosition() { return WaveOutUtils.GetPositionBytes(hWaveOut, waveOutLock); } public void Dispose() { GC.SuppressFinalize(this); Dispose(disposing: true); } protected void Dispose(bool disposing) { Stop(); if (disposing) { DisposeBuffers(); } CloseWaveOut(); } private void CloseWaveOut() { //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (callbackEvent != null) { callbackEvent.Close(); callbackEvent = null; } lock (waveOutLock) { if (hWaveOut != IntPtr.Zero) { WaveInterop.waveOutClose(hWaveOut); hWaveOut = IntPtr.Zero; } } } private void DisposeBuffers() { if (buffers != null) { WaveOutBuffer[] array = buffers; for (int i = 0; i < array.Length; i++) { array[i].Dispose(); } buffers = null; } } ~WaveOutEvent() { Dispose(disposing: false); } private void RaisePlaybackStoppedEvent(Exception e) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown EventHandler<StoppedEventArgs> handler = this.PlaybackStopped; if (handler == null) { return; } if (syncContext == null) { handler(this, new StoppedEventArgs(e)); return; } syncContext.Post(delegate { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown handler(this, new StoppedEventArgs(e)); }, null); } } public static class WaveOutUtils { public static float GetWaveOutVolume(IntPtr hWaveOut, object lockObject) { //IL_000f: 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_0021: Unknown result type (might be due to invalid IL or missing references) MmResult val; int dwVolume; lock (lockObject) { val = WaveInterop.waveOutGetVolume(hWaveOut, out dwVolume); } MmException.Try(val, "waveOutGetVolume"); return (float)(dwVolume & 0xFFFF) / 65535f; } public static void SetWaveOutVolume(float value, IntPtr hWaveOut, object lockObject) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) if (value < 0f) { throw new ArgumentOutOfRangeException("value", "Volume must be between 0.0 and 1.0"); } if (value > 1f) { throw new ArgumentOutOfRangeException("value", "Volume must be between 0.0 and 1.0"); } int dwVolume = (int)(value * 65535f) + ((int)(value * 65535f) << 16); MmResult val; lock (lockObject) { val = WaveInterop.waveOutSetVolume(hWaveOut, dwVolume); } MmException.Try(val, "waveOutSetVolume"); } public static long GetPositionBytes(IntPtr hWaveOut, object lockObject) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) lock (lockObject) { MmTime mmTime = default(MmTime); mmTime.wType = 4u; MmException.Try(WaveInterop.waveOutGetPosition(hWaveOut, ref mmTime, Marshal.SizeOf(mmTime)), "waveOutGetPosition"); if (mmTime.wType != 4) { throw new Exception($"waveOutGetPosition: wType -> Expected {4}, Received {mmTime.wType}"); } return mmTime.cb; } } } } namespace NAudio.Wave.Compression { public class AcmDriver : IDisposable { private static List<AcmDriver> drivers; private AcmDriverDetails details; private IntPtr driverId; private IntPtr driverHandle; private List<AcmFormatTag> formatTags; private List<AcmFormat> tempFormatsList; private IntPtr localDllHandle; public int MaxFormatSize { get { //IL_000a: Unknown result type (might be due to invalid IL or missing references) MmException.Try(AcmInterop.acmMetrics(driverHandle, AcmMetrics.MaxSizeFormat, out var output), "acmMetrics"); return output; } } public string ShortName => details.shortName; public string LongName => details.longName; public IntPtr DriverId => driverId; public IEnumerable<AcmFormatTag> FormatTags { get { //IL_005f: Unknown result type (might be due to invalid IL or missing references) if (formatTags == null) { if (driverHandle == IntPtr.Zero) { throw new InvalidOperationException("Driver must be opened first"); } formatTags = new List<AcmFormatTag>(); AcmFormatTagDetails formatTagDetails = default(AcmFormatTagDetails); formatTagDetails.structureSize = Marshal.SizeOf(formatTagDetails); MmException.Try(AcmInterop.acmFormatTagEnum(driverHandle, ref formatTagDetails, AcmFormatTagEnumCallback, IntPtr.Zero, 0), "acmFormatTagEnum"); } return formatTags; } } public static bool IsCodecInstalled(string shortName) { foreach (AcmDriver item in EnumerateAcmDrivers()) { if (item.ShortName == shortName) { return true; } } return false; } public static AcmDriver AddLocalDriver(string driverFile) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) IntPtr intPtr = NativeMethods.LoadLibrary(driverFile); if (intPtr == IntPtr.Zero) { throw new ArgumentException("Failed to load driver file"); } IntPtr procAddress = NativeMethods.GetProcAddress(intPtr, "DriverProc"); if (procAddress == IntPtr.Zero) { NativeMethods.FreeLibrary(intPtr); throw new ArgumentException("Failed to discover DriverProc"); } IntPtr hAcmDriver; MmResult val = AcmInterop.acmDriverAdd(out hAcmDriver, intPtr, procAddress, 0, AcmDriverAddFlags.Function); if ((int)val != 0) { NativeMethods.FreeLibrary(intPtr); throw new MmException(val, "acmDriverAdd"); } AcmDriver acmDriver = new AcmDriver(hAcmDriver); if (string.IsNullOrEmpty(acmDriver.details.longName)) { acmDriver.details.longName = "Local driver: " + Path.GetFileName(driverFile); acmDriver.localDllHandle = intPtr; } return acmDriver; } public static void RemoveLocalDriver(AcmDriver localDriver) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (localDriver.localDllHandle == IntPtr.Zero) { throw new ArgumentException("Please pass in the AcmDriver returned by the AddLocalDriver method"); } MmResult val = AcmInterop.acmDriverRemove(localDriver.driverId, 0); NativeMethods.FreeLibrary(localDriver.localDllHandle); MmException.Try(val, "acmDriverRemove"); } public static bool ShowFormatChooseDialog(IntPtr ownerWindowHandle, string windowTitle, AcmFormatEnumFlags enumFlags, WaveFormat enumFormat, out WaveFormat selectedFormat, out string selectedFormatDescription, out string selectedFormatTagDescription) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Invalid comparison between Unknown and I4 //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Invalid comparison between Unknown and I4 //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) AcmFormatChoose formatChoose = default(AcmFormatChoose); formatChoose.structureSize = Marshal.SizeOf(formatChoose); formatChoose.styleFlags = AcmFormatChooseStyleFlags.None; formatChoose.ownerWindowHandle = ownerWindowHandle; int num = 200; formatChoose.selectedWaveFormatPointer = Marshal.AllocHGlobal(num); formatChoose.selectedWaveFormatByteSize = num; formatChoose.title = windowTitle; formatChoose.name = null; formatChoose.formatEnumFlags = enumFlags; formatChoose.waveFormatEnumPointer = IntPtr.Zero; if (enumFormat != null) { IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf<WaveFormat>(enumFormat)); Marshal.StructureToPtr<WaveFormat>(enumFormat, intPtr, fDeleteOld: false); formatChoose.waveFormatEnumPointer = intPtr; } formatChoose.instanceHandle = IntPtr.Zero; formatChoose.templateName = null; MmResult val = AcmInterop.acmFormatChoose(ref formatChoose); selectedFormat = null; selectedFormatDescription = null; selectedFormatTagDescription = null; if ((int)val == 0) { selectedFormat = WaveFormat.MarshalFromPtr(formatChoose.selectedWaveFormatPointer); selectedFormatDescription = formatChoose.formatDescription; selectedFormatTagDescription = formatChoose.formatTagDescription; } Marshal.FreeHGlobal(formatChoose.waveFormatEnumPointer); Marshal.FreeHGlobal(formatChoose.selectedWaveFormatPointer); if ((int)val != 515 && (int)val != 0) { throw new MmException(val, "acmFormatChoose"); } return (int)val == 0; } public static AcmDriver FindByShortName(string shortName) { foreach (AcmDriver item in EnumerateAcmDrivers()) { if (item.ShortName == shortName) { return item; } } return null; } public static IEnumerable<AcmDriver> EnumerateAcmDrivers() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) drivers = new List<AcmDriver>(); MmException.Try(AcmInterop.acmDriverEnum(DriverEnumCallback, IntPtr.Zero, (AcmDriverEnumFlags)0), "acmDriverEnum"); return drivers; } private static bool DriverEnumCallback(IntPtr hAcmDriver, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { drivers.Add(new AcmDriver(hAcmDriver)); return true; } private AcmDriver(IntPtr hAcmDriver) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) driverId = hAcmDriver; details = default(AcmDriverDetails); details.structureSize = Marshal.SizeOf(details); MmException.Try(AcmInterop.acmDriverDetails(hAcmDriver, ref details, 0), "acmDriverDetails"); } public override string ToString() { return LongName; } public IEnumerable<AcmFormat> GetFormats(AcmFormatTag formatTag) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected I4, but got Unknown //IL_0082: Unknown result type (might be due to invalid IL or missing references) if (driverHandle == IntPtr.Zero) { throw new InvalidOperationException("Driver must be opened first"); } tempFormatsList = new List<AcmFormat>(); AcmFormatDetails formatDetails = default(AcmFormatDetails); formatDetails.structSize = Marshal.SizeOf(formatDetails); formatDetails.waveFormatByteSize = 1024; formatDetails.waveFormatPointer = Marshal.AllocHGlobal(formatDetails.waveFormatByteSize); formatDetails.formatTag = (int)formatTag.FormatTag; MmResult val = AcmInterop.acmFormatEnum(driverHandle, ref formatDetails, AcmFormatEnumCallback, IntPtr.Zero, AcmFormatEnumFlags.None); Marshal.FreeHGlobal(formatDetails.waveFormatPointer); MmException.Try(val, "acmFormatEnum"); return tempFormatsList; } public void Open() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (driverHandle == IntPtr.Zero) { MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, DriverId, 0), "acmDriverOpen"); } } public void Close() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (driverHandle != IntPtr.Zero) { MmException.Try(AcmInterop.acmDriverClose(driverHandle, 0), "acmDriverClose"); driverHandle = IntPtr.Zero; } } private bool AcmFormatTagEnumCallback(IntPtr hAcmDriverId, ref AcmFormatTagDetails formatTagDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { formatTags.Add(new AcmFormatTag(formatTagDetails)); return true; } private bool AcmFormatEnumCallback(IntPtr hAcmDriverId, ref AcmFormatDetails formatDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { tempFormatsList.Add(new AcmFormat(formatDetails)); return true; } public void Dispose() { if (driverHandle != IntPtr.Zero) { Close(); GC.SuppressFinalize(this); } } } internal enum AcmDriverAddFlags { Local = 0, Global = 8, Function = 3, NotifyWindowHandle = 4 } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal struct AcmDriverDetails { public int structureSize; public uint fccType; public uint fccComp; public ushort manufacturerId; public ushort productId; public uint acmVersion; public uint driverVersion; public AcmDriverDetailsSupportFlags supportFlags; public int formatTagsCount; public int filterTagsCount; public IntPtr hicon; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string shortName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string longName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string copyright; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string licensing; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)] public string features; private const int ShortNameChars = 32; private const int LongNameChars = 128; private const int CopyrightChars = 80; private const int LicensingChars = 128; private const int FeaturesChars = 512; } [Flags] public enum AcmDriverDetailsSupportFlags { Codec = 1, Converter = 2, Filter = 4, Hardware = 8, Async = 0x10, Local = 0x40000000, Disabled = int.MinValue } [Flags] internal enum AcmDriverEnumFlags { NoLocal = 0x40000000, Disabled = int.MinValue } public class AcmFormat { private readonly AcmFormatDetails formatDetails; public int FormatIndex => formatDetails.formatIndex; public WaveFormatEncoding FormatTag => (WaveFormatEncoding)(ushort)formatDetails.formatTag; public AcmDriverDetailsSupportFlags SupportFlags => formatDetails.supportFlags; public WaveFormat WaveFormat { get; private set; } public int WaveFormatByteSize => formatDetails.waveFormatByteSize; public string FormatDescription => formatDetails.formatDescription; internal AcmFormat(AcmFormatDetails formatDetails) { this.formatDetails = formatDetails; WaveFormat = WaveFormat.MarshalFromPtr(formatDetails.waveFormatPointer); } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)] internal struct AcmFormatChoose { public int structureSize; public AcmFormatChooseStyleFlags styleFlags; public IntPtr ownerWindowHandle; public IntPtr selectedWaveFormatPointer; public int selectedWaveFormatByteSize; [MarshalAs(UnmanagedType.LPTStr)] public string title; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)] public string formatTagDescription; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string formatDescription; [MarshalAs(UnmanagedType.LPTStr)] public string name; public int nameByteSize; public AcmFormatEnumFlags formatEnumFlags; public IntPtr waveFormatEnumPointer; public IntPtr instanceHandle; [MarshalAs(UnmanagedType.LPTStr)] public string templateName; public IntPtr customData; public AcmInterop.AcmFormatChooseHookProc windowCallbackFunction; } [Flags] internal enum AcmFormatChooseStyleFlags { None = 0, ShowHelp = 4, EnableHook = 8, EnableTemplate = 0x10, EnableTemplateHandle = 0x20, InitToWfxStruct = 0x40, ContextHelp = 0x80 } [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct AcmFormatDetails { public int structSize; public int formatIndex; public int formatTag; public AcmDriverDetailsSupportFlags supportFlags; public IntPtr waveFormatPointer; public int waveFormatByteSize; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string formatDescription; public const int FormatDescriptionChars = 128; } [Flags] public enum AcmFormatEnumFlags { None = 0, Convert = 0x100000, Hardware = 0x400000, Input = 0x800000, Channels = 0x20000, SamplesPerSecond = 0x40000, Output = 0x1000000, Suggest = 0x200000, BitsPerSample = 0x80000, FormatTag = 0x10000 } [Flags] internal enum AcmFormatSuggestFlags { FormatTag = 0x10000, Channels = 0x20000, SamplesPerSecond = 0x40000, BitsPerSample = 0x80000, TypeMask = 0xFF0000 } public class AcmFormatTag { private AcmFormatTagDetails formatTagDetails; public int FormatTagIndex => formatTagDetails.formatTagIndex; public WaveFormatEncoding FormatTag => (WaveFormatEncoding)(ushort)formatTagDetails.formatTag; public int FormatSize => formatTagDetails.formatSize; public AcmDriverDetailsSupportFlags SupportFlags => formatTagDetails.supportFlags; public int StandardFormatsCount => formatTagDetails.standardFormatsCount; public string FormatDescription => formatTagDetails.formatDescription; internal AcmFormatTag(AcmFormatTagDetails formatTagDetails) { this.formatTagDetails = formatTagDetails; } } internal struct AcmFormatTagDetails { public int structureSize; public int formatTagIndex; public int formatTag; public int formatSize; public AcmDriverDetailsSupportFlags supportFlags; public int standardFormatsCount; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)] public string formatDescription; public const int FormatTagDescriptionChars = 48; } internal class AcmInterop { public delegate bool AcmDriverEnumCallback(IntPtr hAcmDriverId, IntPtr instance, AcmDriverDetailsSupportFlags flags); public delegate bool AcmFormatEnumCallback(IntPtr hAcmDriverId, ref AcmFormatDetails formatDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags); public delegate bool AcmFormatTagEnumCallback(IntPtr hAcmDriverId, ref AcmFormatTagDetails formatTagDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags); public delegate bool AcmFormatChooseHookProc(IntPtr windowHandle, int message, IntPtr wParam, IntPtr lParam); [DllImport("msacm32.dll")] public static extern MmResult acmDriverAdd(out IntPtr driverHandle, IntPtr driverModule, IntPtr driverFunctionAddress, int priority, AcmDriverAddFlags flags); [DllImport("msacm32.dll")] public static extern MmResult acmDriverRemove(IntPtr driverHandle, int removeFlags); [DllImport("Msacm32.dll")] public static extern MmResult acmDriverClose(IntPtr hAcmDriver, int closeFlags); [DllImport("Msacm32.dll")] public static extern MmResult acmDriverEnum(AcmDriverEnumCallback fnCallback, IntPtr dwInstance, AcmDriverEnumFlags flags); [DllImport("Msacm32.dll")] public static extern MmResult acmDriverDetails(IntPtr hAcmDriver, ref AcmDriverDetails driverDetails, int reserved); [DllImport("Msacm32.dll")] public static extern MmResult acmDriverOpen(out IntPtr pAcmDriver, IntPtr hAcmDriverId, int openFlags); [DllImport("Msacm32.dll", EntryPoint = "acmFormatChooseW")] public static extern MmResult acmFormatChoose(ref AcmFormatChoose formatChoose); [DllImport("Msacm32.dll")] public static extern MmResult acmFormatEnum(IntPtr hAcmDriver, ref AcmFormatDetails formatDetails, AcmFormatEnumCallback callback, IntPtr instance, AcmFormatEnumFlags flags); [DllImport("Msacm32.dll", EntryPoint = "acmFormatSuggest")] public static extern MmResult acmFormatSuggest2(IntPtr hAcmDriver, IntPtr sourceFormatPointer, IntPtr destFormatPointer, int sizeDestFormat, AcmFormatSuggestFlags suggestFlags); [DllImport("Msacm32.dll")] public static extern MmResult acmFormatTagEnum(IntPtr hAcmDriver, ref AcmFormatTagDetails formatTagDetails, AcmFormatTagEnumCallback callback, IntPtr instance, int reserved); [DllImport("Msacm32.dll")] public static extern MmResult acmMetrics(IntPtr hAcmObject, AcmMetrics metric, out int output); [DllImport("Msacm32.dll", EntryPoint = "acmStreamOpen")] public static extern MmResult acmStreamOpen2(out IntPtr hAcmStream, IntPtr hAcmDriver, IntPtr sourceFormatPointer, IntPtr destFormatPointer, [In] WaveFilter waveFilter, IntPtr callback, IntPtr instance, AcmStreamOpenFlags openFlags); [DllImport("Msacm32.dll")] public static extern MmResult acmStreamClose(IntPtr hAcmStream, int closeFlags); [DllImport("Msacm32.dll")] public static extern MmResult acmStreamConvert(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, AcmStreamConvertFlags streamConvertFlags); [DllImport("Msacm32.dll")] public static extern MmResult acmStreamPrepareHeader(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, int prepareFlags); [DllImport("Msacm32.dll")] public static extern MmResult acmStreamReset(IntPtr hAcmStream, int resetFlags); [DllImport("Msacm32.dll")] public static extern MmResult acmStreamSize(IntPtr hAcmStream, int inputBufferSize, out int outputBufferSize, AcmStreamSizeFlags flags); [DllImport("Msacm32.dll")] public static extern MmResult acmStreamUnprepareHeader(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, int flags); } public class AcmStream : IDisposable { private IntPtr streamHandle; private IntPtr driverHandle; private AcmStreamHeader streamHeader; private readonly WaveFormat sourceFormat; public byte[] SourceBuffer => streamHeader.SourceBuffer; public byte[] DestBuffer => streamHeader.DestBuffer; public AcmStream(WaveFormat sourceFormat, WaveFormat destFormat) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) try { streamHandle = IntPtr.Zero; this.sourceFormat = sourceFormat; int num = Math.Max(65536, sourceFormat.AverageBytesPerSecond); num -= num % sourceFormat.BlockAlign; IntPtr intPtr = WaveFormat.MarshalToPtr(sourceFormat); IntPtr intPtr2 = WaveFormat.MarshalToPtr(destFormat); try { MmException.Try(AcmInterop.acmStreamOpen2(out streamHandle, IntPtr.Zero, intPtr, intPtr2, null, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen"); } finally { Marshal.FreeHGlobal(intPtr); Marshal.FreeHGlobal(intPtr2); } int destBufferLength = SourceToDest(num); streamHeader = new AcmStreamHeader(streamHandle, num, destBufferLength); driverHandle = IntPtr.Zero; } catch { Dispose(); throw; } } public AcmStream(IntPtr driverId, WaveFormat sourceFormat, WaveFilter waveFilter) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) int num = Math.Max(16384, sourceFormat.AverageBytesPerSecond); this.sourceFormat = sourceFormat; num -= num % sourceFormat.BlockAlign; MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, driverId, 0), "acmDriverOpen"); IntPtr intPtr = WaveFormat.MarshalToPtr(sourceFormat); try { MmException.Try(AcmInterop.acmStreamOpen2(out streamHandle, driverHandle, intPtr, intPtr, waveFilter, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen"); } finally { Marshal.FreeHGlobal(intPtr); } streamHeader = new AcmStreamHeader(streamHandle, num, SourceToDest(num)); } public int SourceToDest(int source) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (source == 0) { return 0; } MmException.Try(AcmInterop.acmStreamSize(streamHandle, source, out var outputBufferSize, AcmStreamSizeFlags.Source), "acmStreamSize"); return outputBufferSize; } public int DestToSource(int dest) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (dest == 0) { return 0; } MmException.Try(AcmInterop.acmStreamSize(streamHandle, dest, out var outputBufferSize, AcmStreamSizeFlags.Destination), "acmStreamSize"); return outputBufferSize; } public static WaveFormat SuggestPcmFormat(WaveFormat compressedFormat) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) WaveFormat val = new WaveFormat(compressedFormat.SampleRate, 16, compressedFormat.Channels); IntPtr intPtr = WaveFormat.MarshalToPtr(val); IntPtr intPtr2 = WaveFormat.MarshalToPtr(compressedFormat); try { MmResult val2 = AcmInterop.acmFormatSuggest2(IntPtr.Zero, intPtr2, intPtr, Marshal.SizeOf<WaveFormat>(val), AcmFormatSuggestFlags.FormatTag); val = WaveFormat.MarshalFromPtr(intPtr); MmException.Try(val2, "acmFormatSuggest"); return val; } finally { Marshal.FreeHGlobal(intPtr); Marshal.FreeHGlobal(intPtr2); } } public void Reposition() { streamHeader.Reposition(); } public int Convert(int bytesToConvert, out int sourceBytesConverted) { if (bytesToConvert % sourceFormat.BlockAlign != 0) { bytesToConvert -= bytesToConvert % sourceFormat.BlockAlign; } return streamHeader.Convert(bytesToConvert, out sourceBytesConverted); } [Obsolete("Call the version returning sourceBytesConverted instead")] public int Convert(int bytesToConvert) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) int sourceBytesConverted; int result = Convert(bytesToConvert, out sourceBytesConverted); if (sourceBytesConverted != bytesToConvert) { throw new MmException((MmResult)8, "AcmStreamHeader.Convert didn't convert everything"); } return result; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { //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) //IL_0047: 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_004a: 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) if (disposing && streamHeader != null) { streamHeader.Dispose(); streamHeader = null; } if (streamHandle != IntPtr.Zero) { MmResult val = AcmInterop.acmStreamClose(streamHandle, 0); streamHandle = IntPtr.Zero; if ((int)val != 0) { throw new MmException(val, "acmStreamClose"); } } if (driverHandle != IntPtr.Zero) { AcmInterop.acmDriverClose(driverHandle, 0); driverHandle = IntPtr.Zero; } } ~AcmStream() { Dispose(disposing: false); } } internal class AcmStreamHeader : IDisposable { private AcmStreamHeaderStruct streamHeader; private GCHandle hSourceBuffer; private GCHandle hDestBuffer; private IntPtr streamHandle; private bool firstTime; private bool disposed; public byte[] SourceBuffer { get; private set; } public byte[] DestBuffer { get; private set; } public AcmStreamHeader(IntPtr streamHandle, int sourceBufferLength, int destBufferLength) { streamHeader = new AcmStreamHeaderStruct(); SourceBuffer = new byte[sourceBufferLength]; hSourceBuffer = GCHandle.Alloc(SourceBuffer, GCHandleType.Pinned); DestBuffer = new byte[destBufferLength]; hDestBuffer = GCHandle.Alloc(DestBuffer, GCHandleType.Pinned); this.streamHandle = streamHandle; firstTime = true; } private void Prepare() { //IL_0075: Unknown result type (might be due to invalid IL or missing references) streamHeader.cbStruct = Marshal.SizeOf(streamHeader); streamHeader.sourceBufferLength = SourceBuffer.Length; streamHeader.sourceBufferPointer = hSourceBuffer.AddrOfPinnedObject(); streamHeader.destBufferLength = DestBuffer.Length; streamHeader.destBufferPointer = hDestBuffer.AddrOfPinnedObject(); MmException.Try(AcmInterop.acmStreamPrepareHeader(streamHandle, streamHeader, 0), "acmStreamPrepareHeader"); } private void Unprepare() { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) streamHeader.sourceBufferLength = SourceBuffer.Length; streamHeader.sourceBufferPointer = hSourceBuffer.AddrOfPinnedObject(); streamHeader.destBufferLength = DestBuffer.Length; streamHeader.destBufferPointer = hDestBuffer.AddrOfPinnedObject(); MmResult val = AcmInterop.acmStreamUnprepareHeader(streamHandle, streamHeader, 0); if ((int)val != 0) { throw new MmException(val, "acmStreamUnprepareHeader"); } } public void Reposition() { firstTime = true; } public int Convert(int bytesToConvert, out int sourceBytesConverted) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) Prepare(); try { streamHeader.sourceBufferLength = bytesToConvert; streamHeader.sourceBufferLengthUsed = bytesToConvert; AcmStreamConvertFlags streamConvertFlags = (firstTime ? (AcmStreamConvertFlags.BlockAlign | AcmStreamConvertFlags.Start) : AcmStreamConvertFlags.BlockAlign); MmException.Try(AcmInterop.acmStreamConvert(streamHandle, streamHeader, streamConvertFlags), "acmStreamConvert"); firstTime = false; sourceBytesConverted = streamHeader.sourceBufferLengthUsed; } finally { Unprepare(); } return streamHeader.destBufferLengthUsed; } public void Dispose() { GC.SuppressFinalize(this); Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { if (!disposed) { SourceBuffer = null; DestBuffer = null; hSourceBuffer.Free(); hDestBuffer.Free(); } disposed = true; } ~AcmStreamHeader() { Dispose(disposing: false); } } [Flags] internal enum AcmStreamHeaderStatusFlags { Done = 0x10000, Prepared = 0x20000, InQueue = 0x100000 } [StructLayout(LayoutKind.Sequential, Size = 128)] internal class AcmStreamHeaderStruct { public int cbStruct; public AcmStreamHeaderStatusFlags fdwStatus; public IntPtr userData; public IntPtr sourceBufferPointer; public int sourceBufferLength; public int sourceBufferLengthUsed; public IntPtr sourceUserData; public IntPtr destBufferPointer; public int destBufferLength; public int destBufferLengthUsed; public IntPtr destUserData; } [Flags] internal enum AcmStreamOpenFlags { Query = 1, Async = 2, NonRealTime = 4, CallbackTypeMask = 0x70000, CallbackNull = 0, CallbackWindow = 0x10000, CallbackTask = 0x20000, CallbackFunction = 0x30000, CallbackThread = 0x20000, CallbackEvent = 0x50000 } internal enum AcmStreamSizeFlags { Source, Destination } [StructLayout(LayoutKind.Sequential)] public class WaveFilter { public int StructureSize = Marshal.SizeOf(typeof(WaveFilter)); public int FilterTag; public int Filter; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public int[] Reserved; } }
deps/netstandard.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Configuration.Assemblies; using System.Data; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Diagnostics.SymbolStore; using System.Diagnostics.Tracing; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.IO.Compression; using System.IO.Enumeration; using System.IO.IsolatedStorage; using System.IO.MemoryMappedFiles; using System.IO.Pipes; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Cache; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mail; using System.Net.Mime; using System.Net.NetworkInformation; using System.Net.Security; using System.Net.Sockets; using System.Net.WebSockets; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using System.Security; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using System.Timers; using System.Transactions; using System.Web; using System.Windows.Input; using System.Xml; using System.Xml.Linq; using System.Xml.Resolvers; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.XPath; using System.Xml.Xsl; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("netstandard")] [assembly: AssemblyDescription("netstandard")] [assembly: AssemblyDefaultAlias("netstandard")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyInformationalVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: TypeForwardedTo(typeof(CriticalHandleMinusOneIsInvalid))] [assembly: TypeForwardedTo(typeof(CriticalHandleZeroOrMinusOneIsInvalid))] [assembly: TypeForwardedTo(typeof(SafeFileHandle))] [assembly: TypeForwardedTo(typeof(SafeHandleMinusOneIsInvalid))] [assembly: TypeForwardedTo(typeof(SafeHandleZeroOrMinusOneIsInvalid))] [assembly: TypeForwardedTo(typeof(SafeMemoryMappedFileHandle))] [assembly: TypeForwardedTo(typeof(SafeMemoryMappedViewHandle))] [assembly: TypeForwardedTo(typeof(SafePipeHandle))] [assembly: TypeForwardedTo(typeof(SafeProcessHandle))] [assembly: TypeForwardedTo(typeof(SafeWaitHandle))] [assembly: TypeForwardedTo(typeof(SafeX509ChainHandle))] [assembly: TypeForwardedTo(typeof(AccessViolationException))] [assembly: TypeForwardedTo(typeof(Action))] [assembly: TypeForwardedTo(typeof(Action<>))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, >))] [assembly: TypeForwardedTo(typeof(Action<, , >))] [assembly: TypeForwardedTo(typeof(Action<, , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Activator))] [assembly: TypeForwardedTo(typeof(AggregateException))] [assembly: TypeForwardedTo(typeof(AppContext))] [assembly: TypeForwardedTo(typeof(AppDomain))] [assembly: TypeForwardedTo(typeof(AppDomainUnloadedException))] [assembly: TypeForwardedTo(typeof(ApplicationException))] [assembly: TypeForwardedTo(typeof(ApplicationId))] [assembly: TypeForwardedTo(typeof(ArgumentException))] [assembly: TypeForwardedTo(typeof(ArgumentNullException))] [assembly: TypeForwardedTo(typeof(ArgumentOutOfRangeException))] [assembly: TypeForwardedTo(typeof(ArithmeticException))] [assembly: TypeForwardedTo(typeof(Array))] [assembly: TypeForwardedTo(typeof(ArraySegment<>))] [assembly: TypeForwardedTo(typeof(ArrayTypeMismatchException))] [assembly: TypeForwardedTo(typeof(AssemblyLoadEventArgs))] [assembly: TypeForwardedTo(typeof(AssemblyLoadEventHandler))] [assembly: TypeForwardedTo(typeof(AsyncCallback))] [assembly: TypeForwardedTo(typeof(Attribute))] [assembly: TypeForwardedTo(typeof(AttributeTargets))] [assembly: TypeForwardedTo(typeof(AttributeUsageAttribute))] [assembly: TypeForwardedTo(typeof(BadImageFormatException))] [assembly: TypeForwardedTo(typeof(Base64FormattingOptions))] [assembly: TypeForwardedTo(typeof(BitConverter))] [assembly: TypeForwardedTo(typeof(bool))] [assembly: TypeForwardedTo(typeof(Buffer))] [assembly: TypeForwardedTo(typeof(ArrayBufferWriter<>))] [assembly: TypeForwardedTo(typeof(ArrayPool<>))] [assembly: TypeForwardedTo(typeof(BinaryPrimitives))] [assembly: TypeForwardedTo(typeof(BuffersExtensions))] [assembly: TypeForwardedTo(typeof(IBufferWriter<>))] [assembly: TypeForwardedTo(typeof(IMemoryOwner<>))] [assembly: TypeForwardedTo(typeof(IPinnable))] [assembly: TypeForwardedTo(typeof(MemoryHandle))] [assembly: TypeForwardedTo(typeof(MemoryManager<>))] [assembly: TypeForwardedTo(typeof(MemoryPool<>))] [assembly: TypeForwardedTo(typeof(OperationStatus))] [assembly: TypeForwardedTo(typeof(ReadOnlySequence<>))] [assembly: TypeForwardedTo(typeof(ReadOnlySequenceSegment<>))] [assembly: TypeForwardedTo(typeof(ReadOnlySpanAction<, >))] [assembly: TypeForwardedTo(typeof(SequenceReader<>))] [assembly: TypeForwardedTo(typeof(SequenceReaderExtensions))] [assembly: TypeForwardedTo(typeof(SpanAction<, >))] [assembly: TypeForwardedTo(typeof(StandardFormat))] [assembly: TypeForwardedTo(typeof(Base64))] [assembly: TypeForwardedTo(typeof(Utf8Formatter))] [assembly: TypeForwardedTo(typeof(Utf8Parser))] [assembly: TypeForwardedTo(typeof(byte))] [assembly: TypeForwardedTo(typeof(CannotUnloadAppDomainException))] [assembly: TypeForwardedTo(typeof(char))] [assembly: TypeForwardedTo(typeof(CharEnumerator))] [assembly: TypeForwardedTo(typeof(CLSCompliantAttribute))] [assembly: TypeForwardedTo(typeof(GeneratedCodeAttribute))] [assembly: TypeForwardedTo(typeof(IndentedTextWriter))] [assembly: TypeForwardedTo(typeof(ArrayList))] [assembly: TypeForwardedTo(typeof(BitArray))] [assembly: TypeForwardedTo(typeof(CaseInsensitiveComparer))] [assembly: TypeForwardedTo(typeof(CaseInsensitiveHashCodeProvider))] [assembly: TypeForwardedTo(typeof(CollectionBase))] [assembly: TypeForwardedTo(typeof(Comparer))] [assembly: TypeForwardedTo(typeof(BlockingCollection<>))] [assembly: TypeForwardedTo(typeof(ConcurrentBag<>))] [assembly: TypeForwardedTo(typeof(ConcurrentDictionary<, >))] [assembly: TypeForwardedTo(typeof(ConcurrentQueue<>))] [assembly: TypeForwardedTo(typeof(ConcurrentStack<>))] [assembly: TypeForwardedTo(typeof(EnumerablePartitionerOptions))] [assembly: TypeForwardedTo(typeof(IProducerConsumerCollection<>))] [assembly: TypeForwardedTo(typeof(OrderablePartitioner<>))] [assembly: TypeForwardedTo(typeof(Partitioner))] [assembly: TypeForwardedTo(typeof(Partitioner<>))] [assembly: TypeForwardedTo(typeof(DictionaryBase))] [assembly: TypeForwardedTo(typeof(DictionaryEntry))] [assembly: TypeForwardedTo(typeof(CollectionExtensions))] [assembly: TypeForwardedTo(typeof(Comparer<>))] [assembly: TypeForwardedTo(typeof(Dictionary<, >))] [assembly: TypeForwardedTo(typeof(EqualityComparer<>))] [assembly: TypeForwardedTo(typeof(HashSet<>))] [assembly: TypeForwardedTo(typeof(IAsyncEnumerable<>))] [assembly: TypeForwardedTo(typeof(IAsyncEnumerator<>))] [assembly: TypeForwardedTo(typeof(ICollection<>))] [assembly: TypeForwardedTo(typeof(IComparer<>))] [assembly: TypeForwardedTo(typeof(IDictionary<, >))] [assembly: TypeForwardedTo(typeof(IEnumerable<>))] [assembly: TypeForwardedTo(typeof(IEnumerator<>))] [assembly: TypeForwardedTo(typeof(IEqualityComparer<>))] [assembly: TypeForwardedTo(typeof(IList<>))] [assembly: TypeForwardedTo(typeof(IReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(IReadOnlyDictionary<, >))] [assembly: TypeForwardedTo(typeof(IReadOnlyList<>))] [assembly: TypeForwardedTo(typeof(ISet<>))] [assembly: TypeForwardedTo(typeof(KeyNotFoundException))] [assembly: TypeForwardedTo(typeof(KeyValuePair))] [assembly: TypeForwardedTo(typeof(KeyValuePair<, >))] [assembly: TypeForwardedTo(typeof(LinkedList<>))] [assembly: TypeForwardedTo(typeof(LinkedListNode<>))] [assembly: TypeForwardedTo(typeof(List<>))] [assembly: TypeForwardedTo(typeof(Queue<>))] [assembly: TypeForwardedTo(typeof(SortedDictionary<, >))] [assembly: TypeForwardedTo(typeof(SortedList<, >))] [assembly: TypeForwardedTo(typeof(SortedSet<>))] [assembly: TypeForwardedTo(typeof(Stack<>))] [assembly: TypeForwardedTo(typeof(Hashtable))] [assembly: TypeForwardedTo(typeof(ICollection))] [assembly: TypeForwardedTo(typeof(IComparer))] [assembly: TypeForwardedTo(typeof(IDictionary))] [assembly: TypeForwardedTo(typeof(IDictionaryEnumerator))] [assembly: TypeForwardedTo(typeof(IEnumerable))] [assembly: TypeForwardedTo(typeof(IEnumerator))] [assembly: TypeForwardedTo(typeof(IEqualityComparer))] [assembly: TypeForwardedTo(typeof(IHashCodeProvider))] [assembly: TypeForwardedTo(typeof(IList))] [assembly: TypeForwardedTo(typeof(IStructuralComparable))] [assembly: TypeForwardedTo(typeof(IStructuralEquatable))] [assembly: TypeForwardedTo(typeof(Collection<>))] [assembly: TypeForwardedTo(typeof(KeyedCollection<, >))] [assembly: TypeForwardedTo(typeof(ObservableCollection<>))] [assembly: TypeForwardedTo(typeof(ReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(ReadOnlyDictionary<, >))] [assembly: TypeForwardedTo(typeof(ReadOnlyObservableCollection<>))] [assembly: TypeForwardedTo(typeof(Queue))] [assembly: TypeForwardedTo(typeof(ReadOnlyCollectionBase))] [assembly: TypeForwardedTo(typeof(SortedList))] [assembly: TypeForwardedTo(typeof(BitVector32))] [assembly: TypeForwardedTo(typeof(CollectionsUtil))] [assembly: TypeForwardedTo(typeof(HybridDictionary))] [assembly: TypeForwardedTo(typeof(INotifyCollectionChanged))] [assembly: TypeForwardedTo(typeof(IOrderedDictionary))] [assembly: TypeForwardedTo(typeof(ListDictionary))] [assembly: TypeForwardedTo(typeof(NameObjectCollectionBase))] [assembly: TypeForwardedTo(typeof(NameValueCollection))] [assembly: TypeForwardedTo(typeof(NotifyCollectionChangedAction))] [assembly: TypeForwardedTo(typeof(NotifyCollectionChangedEventArgs))] [assembly: TypeForwardedTo(typeof(NotifyCollectionChangedEventHandler))] [assembly: TypeForwardedTo(typeof(OrderedDictionary))] [assembly: TypeForwardedTo(typeof(StringCollection))] [assembly: TypeForwardedTo(typeof(StringDictionary))] [assembly: TypeForwardedTo(typeof(StringEnumerator))] [assembly: TypeForwardedTo(typeof(Stack))] [assembly: TypeForwardedTo(typeof(StructuralComparisons))] [assembly: TypeForwardedTo(typeof(Comparison<>))] [assembly: TypeForwardedTo(typeof(AddingNewEventArgs))] [assembly: TypeForwardedTo(typeof(AddingNewEventHandler))] [assembly: TypeForwardedTo(typeof(AmbientValueAttribute))] [assembly: TypeForwardedTo(typeof(ArrayConverter))] [assembly: TypeForwardedTo(typeof(AsyncCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(AsyncCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(AsyncOperation))] [assembly: TypeForwardedTo(typeof(AsyncOperationManager))] [assembly: TypeForwardedTo(typeof(AttributeCollection))] [assembly: TypeForwardedTo(typeof(AttributeProviderAttribute))] [assembly: TypeForwardedTo(typeof(BackgroundWorker))] [assembly: TypeForwardedTo(typeof(BaseNumberConverter))] [assembly: TypeForwardedTo(typeof(BindableAttribute))] [assembly: TypeForwardedTo(typeof(BindableSupport))] [assembly: TypeForwardedTo(typeof(BindingDirection))] [assembly: TypeForwardedTo(typeof(BindingList<>))] [assembly: TypeForwardedTo(typeof(BooleanConverter))] [assembly: TypeForwardedTo(typeof(BrowsableAttribute))] [assembly: TypeForwardedTo(typeof(ByteConverter))] [assembly: TypeForwardedTo(typeof(CancelEventArgs))] [assembly: TypeForwardedTo(typeof(CancelEventHandler))] [assembly: TypeForwardedTo(typeof(CategoryAttribute))] [assembly: TypeForwardedTo(typeof(CharConverter))] [assembly: TypeForwardedTo(typeof(CollectionChangeAction))] [assembly: TypeForwardedTo(typeof(CollectionChangeEventArgs))] [assembly: TypeForwardedTo(typeof(CollectionChangeEventHandler))] [assembly: TypeForwardedTo(typeof(CollectionConverter))] [assembly: TypeForwardedTo(typeof(ComplexBindingPropertiesAttribute))] [assembly: TypeForwardedTo(typeof(Component))] [assembly: TypeForwardedTo(typeof(ComponentCollection))] [assembly: TypeForwardedTo(typeof(ComponentConverter))] [assembly: TypeForwardedTo(typeof(ComponentEditor))] [assembly: TypeForwardedTo(typeof(ComponentResourceManager))] [assembly: TypeForwardedTo(typeof(Container))] [assembly: TypeForwardedTo(typeof(ContainerFilterService))] [assembly: TypeForwardedTo(typeof(CultureInfoConverter))] [assembly: TypeForwardedTo(typeof(CustomTypeDescriptor))] [assembly: TypeForwardedTo(typeof(DataErrorsChangedEventArgs))] [assembly: TypeForwardedTo(typeof(DataObjectAttribute))] [assembly: TypeForwardedTo(typeof(DataObjectFieldAttribute))] [assembly: TypeForwardedTo(typeof(DataObjectMethodAttribute))] [assembly: TypeForwardedTo(typeof(DataObjectMethodType))] [assembly: TypeForwardedTo(typeof(DateTimeConverter))] [assembly: TypeForwardedTo(typeof(DateTimeOffsetConverter))] [assembly: TypeForwardedTo(typeof(DecimalConverter))] [assembly: TypeForwardedTo(typeof(DefaultBindingPropertyAttribute))] [assembly: TypeForwardedTo(typeof(DefaultEventAttribute))] [assembly: TypeForwardedTo(typeof(DefaultPropertyAttribute))] [assembly: TypeForwardedTo(typeof(DefaultValueAttribute))] [assembly: TypeForwardedTo(typeof(DescriptionAttribute))] [assembly: TypeForwardedTo(typeof(ActiveDesignerEventArgs))] [assembly: TypeForwardedTo(typeof(ActiveDesignerEventHandler))] [assembly: TypeForwardedTo(typeof(CheckoutException))] [assembly: TypeForwardedTo(typeof(CommandID))] [assembly: TypeForwardedTo(typeof(ComponentChangedEventArgs))] [assembly: TypeForwardedTo(typeof(ComponentChangedEventHandler))] [assembly: TypeForwardedTo(typeof(ComponentChangingEventArgs))] [assembly: TypeForwardedTo(typeof(ComponentChangingEventHandler))] [assembly: TypeForwardedTo(typeof(ComponentEventArgs))] [assembly: TypeForwardedTo(typeof(ComponentEventHandler))] [assembly: TypeForwardedTo(typeof(ComponentRenameEventArgs))] [assembly: TypeForwardedTo(typeof(ComponentRenameEventHandler))] [assembly: TypeForwardedTo(typeof(DesignerCollection))] [assembly: TypeForwardedTo(typeof(DesignerEventArgs))] [assembly: TypeForwardedTo(typeof(DesignerEventHandler))] [assembly: TypeForwardedTo(typeof(DesignerOptionService))] [assembly: TypeForwardedTo(typeof(DesignerTransaction))] [assembly: TypeForwardedTo(typeof(DesignerTransactionCloseEventArgs))] [assembly: TypeForwardedTo(typeof(DesignerTransactionCloseEventHandler))] [assembly: TypeForwardedTo(typeof(DesignerVerb))] [assembly: TypeForwardedTo(typeof(DesignerVerbCollection))] [assembly: TypeForwardedTo(typeof(DesigntimeLicenseContext))] [assembly: TypeForwardedTo(typeof(DesigntimeLicenseContextSerializer))] [assembly: TypeForwardedTo(typeof(HelpContextType))] [assembly: TypeForwardedTo(typeof(HelpKeywordAttribute))] [assembly: TypeForwardedTo(typeof(HelpKeywordType))] [assembly: TypeForwardedTo(typeof(IComponentChangeService))] [assembly: TypeForwardedTo(typeof(IComponentDiscoveryService))] [assembly: TypeForwardedTo(typeof(IComponentInitializer))] [assembly: TypeForwardedTo(typeof(IDesigner))] [assembly: TypeForwardedTo(typeof(IDesignerEventService))] [assembly: TypeForwardedTo(typeof(IDesignerFilter))] [assembly: TypeForwardedTo(typeof(IDesignerHost))] [assembly: TypeForwardedTo(typeof(IDesignerHostTransactionState))] [assembly: TypeForwardedTo(typeof(IDesignerOptionService))] [assembly: TypeForwardedTo(typeof(IDictionaryService))] [assembly: TypeForwardedTo(typeof(IEventBindingService))] [assembly: TypeForwardedTo(typeof(IExtenderListService))] [assembly: TypeForwardedTo(typeof(IExtenderProviderService))] [assembly: TypeForwardedTo(typeof(IHelpService))] [assembly: TypeForwardedTo(typeof(IInheritanceService))] [assembly: TypeForwardedTo(typeof(IMenuCommandService))] [assembly: TypeForwardedTo(typeof(IReferenceService))] [assembly: TypeForwardedTo(typeof(IResourceService))] [assembly: TypeForwardedTo(typeof(IRootDesigner))] [assembly: TypeForwardedTo(typeof(ISelectionService))] [assembly: TypeForwardedTo(typeof(IServiceContainer))] [assembly: TypeForwardedTo(typeof(ITreeDesigner))] [assembly: TypeForwardedTo(typeof(ITypeDescriptorFilterService))] [assembly: TypeForwardedTo(typeof(ITypeDiscoveryService))] [assembly: TypeForwardedTo(typeof(ITypeResolutionService))] [assembly: TypeForwardedTo(typeof(MenuCommand))] [assembly: TypeForwardedTo(typeof(SelectionTypes))] [assembly: TypeForwardedTo(typeof(ComponentSerializationService))] [assembly: TypeForwardedTo(typeof(ContextStack))] [assembly: TypeForwardedTo(typeof(DefaultSerializationProviderAttribute))] [assembly: TypeForwardedTo(typeof(DesignerLoader))] [assembly: TypeForwardedTo(typeof(DesignerSerializerAttribute))] [assembly: TypeForwardedTo(typeof(IDesignerLoaderHost))] [assembly: TypeForwardedTo(typeof(IDesignerLoaderHost2))] [assembly: TypeForwardedTo(typeof(IDesignerLoaderService))] [assembly: TypeForwardedTo(typeof(IDesignerSerializationManager))] [assembly: TypeForwardedTo(typeof(IDesignerSerializationProvider))] [assembly: TypeForwardedTo(typeof(IDesignerSerializationService))] [assembly: TypeForwardedTo(typeof(INameCreationService))] [assembly: TypeForwardedTo(typeof(InstanceDescriptor))] [assembly: TypeForwardedTo(typeof(MemberRelationship))] [assembly: TypeForwardedTo(typeof(MemberRelationshipService))] [assembly: TypeForwardedTo(typeof(ResolveNameEventArgs))] [assembly: TypeForwardedTo(typeof(ResolveNameEventHandler))] [assembly: TypeForwardedTo(typeof(RootDesignerSerializerAttribute))] [assembly: TypeForwardedTo(typeof(SerializationStore))] [assembly: TypeForwardedTo(typeof(ServiceContainer))] [assembly: TypeForwardedTo(typeof(ServiceCreatorCallback))] [assembly: TypeForwardedTo(typeof(StandardCommands))] [assembly: TypeForwardedTo(typeof(StandardToolWindows))] [assembly: TypeForwardedTo(typeof(TypeDescriptionProviderService))] [assembly: TypeForwardedTo(typeof(ViewTechnology))] [assembly: TypeForwardedTo(typeof(DesignerAttribute))] [assembly: TypeForwardedTo(typeof(DesignerCategoryAttribute))] [assembly: TypeForwardedTo(typeof(DesignerSerializationVisibility))] [assembly: TypeForwardedTo(typeof(DesignerSerializationVisibilityAttribute))] [assembly: TypeForwardedTo(typeof(DesignOnlyAttribute))] [assembly: TypeForwardedTo(typeof(DesignTimeVisibleAttribute))] [assembly: TypeForwardedTo(typeof(DisplayNameAttribute))] [assembly: TypeForwardedTo(typeof(DoubleConverter))] [assembly: TypeForwardedTo(typeof(DoWorkEventArgs))] [assembly: TypeForwardedTo(typeof(DoWorkEventHandler))] [assembly: TypeForwardedTo(typeof(EditorAttribute))] [assembly: TypeForwardedTo(typeof(EditorBrowsableAttribute))] [assembly: TypeForwardedTo(typeof(EditorBrowsableState))] [assembly: TypeForwardedTo(typeof(EnumConverter))] [assembly: TypeForwardedTo(typeof(EventDescriptor))] [assembly: TypeForwardedTo(typeof(EventDescriptorCollection))] [assembly: TypeForwardedTo(typeof(EventHandlerList))] [assembly: TypeForwardedTo(typeof(ExpandableObjectConverter))] [assembly: TypeForwardedTo(typeof(ExtenderProvidedPropertyAttribute))] [assembly: TypeForwardedTo(typeof(GuidConverter))] [assembly: TypeForwardedTo(typeof(HandledEventArgs))] [assembly: TypeForwardedTo(typeof(HandledEventHandler))] [assembly: TypeForwardedTo(typeof(IBindingList))] [assembly: TypeForwardedTo(typeof(IBindingListView))] [assembly: TypeForwardedTo(typeof(ICancelAddNew))] [assembly: TypeForwardedTo(typeof(IChangeTracking))] [assembly: TypeForwardedTo(typeof(IComNativeDescriptorHandler))] [assembly: TypeForwardedTo(typeof(IComponent))] [assembly: TypeForwardedTo(typeof(IContainer))] [assembly: TypeForwardedTo(typeof(ICustomTypeDescriptor))] [assembly: TypeForwardedTo(typeof(IDataErrorInfo))] [assembly: TypeForwardedTo(typeof(IEditableObject))] [assembly: TypeForwardedTo(typeof(IExtenderProvider))] [assembly: TypeForwardedTo(typeof(IIntellisenseBuilder))] [assembly: TypeForwardedTo(typeof(IListSource))] [assembly: TypeForwardedTo(typeof(ImmutableObjectAttribute))] [assembly: TypeForwardedTo(typeof(INestedContainer))] [assembly: TypeForwardedTo(typeof(INestedSite))] [assembly: TypeForwardedTo(typeof(InheritanceAttribute))] [assembly: TypeForwardedTo(typeof(InheritanceLevel))] [assembly: TypeForwardedTo(typeof(InitializationEventAttribute))] [assembly: TypeForwardedTo(typeof(INotifyDataErrorInfo))] [assembly: TypeForwardedTo(typeof(INotifyPropertyChanged))] [assembly: TypeForwardedTo(typeof(INotifyPropertyChanging))] [assembly: TypeForwardedTo(typeof(InstallerTypeAttribute))] [assembly: TypeForwardedTo(typeof(InstanceCreationEditor))] [assembly: TypeForwardedTo(typeof(Int16Converter))] [assembly: TypeForwardedTo(typeof(Int32Converter))] [assembly: TypeForwardedTo(typeof(Int64Converter))] [assembly: TypeForwardedTo(typeof(InvalidAsynchronousStateException))] [assembly: TypeForwardedTo(typeof(InvalidEnumArgumentException))] [assembly: TypeForwardedTo(typeof(IRaiseItemChangedEvents))] [assembly: TypeForwardedTo(typeof(IRevertibleChangeTracking))] [assembly: TypeForwardedTo(typeof(ISite))] [assembly: TypeForwardedTo(typeof(ISupportInitialize))] [assembly: TypeForwardedTo(typeof(ISupportInitializeNotification))] [assembly: TypeForwardedTo(typeof(ISynchronizeInvoke))] [assembly: TypeForwardedTo(typeof(ITypeDescriptorContext))] [assembly: TypeForwardedTo(typeof(ITypedList))] [assembly: TypeForwardedTo(typeof(License))] [assembly: TypeForwardedTo(typeof(LicenseContext))] [assembly: TypeForwardedTo(typeof(LicenseException))] [assembly: TypeForwardedTo(typeof(LicenseManager))] [assembly: TypeForwardedTo(typeof(LicenseProvider))] [assembly: TypeForwardedTo(typeof(LicenseProviderAttribute))] [assembly: TypeForwardedTo(typeof(LicenseUsageMode))] [assembly: TypeForwardedTo(typeof(LicFileLicenseProvider))] [assembly: TypeForwardedTo(typeof(ListBindableAttribute))] [assembly: TypeForwardedTo(typeof(ListChangedEventArgs))] [assembly: TypeForwardedTo(typeof(ListChangedEventHandler))] [assembly: TypeForwardedTo(typeof(ListChangedType))] [assembly: TypeForwardedTo(typeof(ListSortDescription))] [assembly: TypeForwardedTo(typeof(ListSortDescriptionCollection))] [assembly: TypeForwardedTo(typeof(ListSortDirection))] [assembly: TypeForwardedTo(typeof(LocalizableAttribute))] [assembly: TypeForwardedTo(typeof(LookupBindingPropertiesAttribute))] [assembly: TypeForwardedTo(typeof(MarshalByValueComponent))] [assembly: TypeForwardedTo(typeof(MaskedTextProvider))] [assembly: TypeForwardedTo(typeof(MaskedTextResultHint))] [assembly: TypeForwardedTo(typeof(MemberDescriptor))] [assembly: TypeForwardedTo(typeof(MergablePropertyAttribute))] [assembly: TypeForwardedTo(typeof(MultilineStringConverter))] [assembly: TypeForwardedTo(typeof(NestedContainer))] [assembly: TypeForwardedTo(typeof(NotifyParentPropertyAttribute))] [assembly: TypeForwardedTo(typeof(NullableConverter))] [assembly: TypeForwardedTo(typeof(ParenthesizePropertyNameAttribute))] [assembly: TypeForwardedTo(typeof(PasswordPropertyTextAttribute))] [assembly: TypeForwardedTo(typeof(ProgressChangedEventArgs))] [assembly: TypeForwardedTo(typeof(ProgressChangedEventHandler))] [assembly: TypeForwardedTo(typeof(PropertyChangedEventArgs))] [assembly: TypeForwardedTo(typeof(PropertyChangedEventHandler))] [assembly: TypeForwardedTo(typeof(PropertyChangingEventArgs))] [assembly: TypeForwardedTo(typeof(PropertyChangingEventHandler))] [assembly: TypeForwardedTo(typeof(PropertyDescriptor))] [assembly: TypeForwardedTo(typeof(PropertyDescriptorCollection))] [assembly: TypeForwardedTo(typeof(PropertyTabAttribute))] [assembly: TypeForwardedTo(typeof(PropertyTabScope))] [assembly: TypeForwardedTo(typeof(ProvidePropertyAttribute))] [assembly: TypeForwardedTo(typeof(ReadOnlyAttribute))] [assembly: TypeForwardedTo(typeof(RecommendedAsConfigurableAttribute))] [assembly: TypeForwardedTo(typeof(ReferenceConverter))] [assembly: TypeForwardedTo(typeof(RefreshEventArgs))] [assembly: TypeForwardedTo(typeof(RefreshEventHandler))] [assembly: TypeForwardedTo(typeof(RefreshProperties))] [assembly: TypeForwardedTo(typeof(RefreshPropertiesAttribute))] [assembly: TypeForwardedTo(typeof(RunInstallerAttribute))] [assembly: TypeForwardedTo(typeof(RunWorkerCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(RunWorkerCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(SByteConverter))] [assembly: TypeForwardedTo(typeof(SettingsBindableAttribute))] [assembly: TypeForwardedTo(typeof(SingleConverter))] [assembly: TypeForwardedTo(typeof(StringConverter))] [assembly: TypeForwardedTo(typeof(SyntaxCheck))] [assembly: TypeForwardedTo(typeof(TimeSpanConverter))] [assembly: TypeForwardedTo(typeof(ToolboxItemAttribute))] [assembly: TypeForwardedTo(typeof(ToolboxItemFilterAttribute))] [assembly: TypeForwardedTo(typeof(ToolboxItemFilterType))] [assembly: TypeForwardedTo(typeof(TypeConverter))] [assembly: TypeForwardedTo(typeof(TypeConverterAttribute))] [assembly: TypeForwardedTo(typeof(TypeDescriptionProvider))] [assembly: TypeForwardedTo(typeof(TypeDescriptionProviderAttribute))] [assembly: TypeForwardedTo(typeof(TypeDescriptor))] [assembly: TypeForwardedTo(typeof(TypeListConverter))] [assembly: TypeForwardedTo(typeof(UInt16Converter))] [assembly: TypeForwardedTo(typeof(UInt32Converter))] [assembly: TypeForwardedTo(typeof(UInt64Converter))] [assembly: TypeForwardedTo(typeof(WarningException))] [assembly: TypeForwardedTo(typeof(Win32Exception))] [assembly: TypeForwardedTo(typeof(AssemblyHashAlgorithm))] [assembly: TypeForwardedTo(typeof(AssemblyVersionCompatibility))] [assembly: TypeForwardedTo(typeof(Console))] [assembly: TypeForwardedTo(typeof(ConsoleCancelEventArgs))] [assembly: TypeForwardedTo(typeof(ConsoleCancelEventHandler))] [assembly: TypeForwardedTo(typeof(ConsoleColor))] [assembly: TypeForwardedTo(typeof(ConsoleKey))] [assembly: TypeForwardedTo(typeof(ConsoleKeyInfo))] [assembly: TypeForwardedTo(typeof(ConsoleModifiers))] [assembly: TypeForwardedTo(typeof(ConsoleSpecialKey))] [assembly: TypeForwardedTo(typeof(ContextBoundObject))] [assembly: TypeForwardedTo(typeof(ContextMarshalException))] [assembly: TypeForwardedTo(typeof(ContextStaticAttribute))] [assembly: TypeForwardedTo(typeof(Convert))] [assembly: TypeForwardedTo(typeof(Converter<, >))] [assembly: TypeForwardedTo(typeof(AcceptRejectRule))] [assembly: TypeForwardedTo(typeof(CommandBehavior))] [assembly: TypeForwardedTo(typeof(CommandType))] [assembly: TypeForwardedTo(typeof(CatalogLocation))] [assembly: TypeForwardedTo(typeof(DataAdapter))] [assembly: TypeForwardedTo(typeof(DataColumnMapping))] [assembly: TypeForwardedTo(typeof(DataColumnMappingCollection))] [assembly: TypeForwardedTo(typeof(DataTableMapping))] [assembly: TypeForwardedTo(typeof(DataTableMappingCollection))] [assembly: TypeForwardedTo(typeof(DbColumn))] [assembly: TypeForwardedTo(typeof(DbCommand))] [assembly: TypeForwardedTo(typeof(DbCommandBuilder))] [assembly: TypeForwardedTo(typeof(DbConnection))] [assembly: TypeForwardedTo(typeof(DbConnectionStringBuilder))] [assembly: TypeForwardedTo(typeof(DbDataAdapter))] [assembly: TypeForwardedTo(typeof(DbDataReader))] [assembly: TypeForwardedTo(typeof(DbDataReaderExtensions))] [assembly: TypeForwardedTo(typeof(DbDataRecord))] [assembly: TypeForwardedTo(typeof(DbDataSourceEnumerator))] [assembly: TypeForwardedTo(typeof(DbEnumerator))] [assembly: TypeForwardedTo(typeof(DbException))] [assembly: TypeForwardedTo(typeof(DbMetaDataCollectionNames))] [assembly: TypeForwardedTo(typeof(DbMetaDataColumnNames))] [assembly: TypeForwardedTo(typeof(DbParameter))] [assembly: TypeForwardedTo(typeof(DbParameterCollection))] [assembly: TypeForwardedTo(typeof(DbProviderFactories))] [assembly: TypeForwardedTo(typeof(DbProviderFactory))] [assembly: TypeForwardedTo(typeof(DbProviderSpecificTypePropertyAttribute))] [assembly: TypeForwardedTo(typeof(DbTransaction))] [assembly: TypeForwardedTo(typeof(GroupByBehavior))] [assembly: TypeForwardedTo(typeof(IDbColumnSchemaGenerator))] [assembly: TypeForwardedTo(typeof(IdentifierCase))] [assembly: TypeForwardedTo(typeof(RowUpdatedEventArgs))] [assembly: TypeForwardedTo(typeof(RowUpdatingEventArgs))] [assembly: TypeForwardedTo(typeof(SchemaTableColumn))] [assembly: TypeForwardedTo(typeof(SchemaTableOptionalColumn))] [assembly: TypeForwardedTo(typeof(SupportedJoinOperators))] [assembly: TypeForwardedTo(typeof(ConflictOption))] [assembly: TypeForwardedTo(typeof(ConnectionState))] [assembly: TypeForwardedTo(typeof(Constraint))] [assembly: TypeForwardedTo(typeof(ConstraintCollection))] [assembly: TypeForwardedTo(typeof(ConstraintException))] [assembly: TypeForwardedTo(typeof(DataColumn))] [assembly: TypeForwardedTo(typeof(DataColumnChangeEventArgs))] [assembly: TypeForwardedTo(typeof(DataColumnChangeEventHandler))] [assembly: TypeForwardedTo(typeof(DataColumnCollection))] [assembly: TypeForwardedTo(typeof(DataException))] [assembly: TypeForwardedTo(typeof(DataReaderExtensions))] [assembly: TypeForwardedTo(typeof(DataRelation))] [assembly: TypeForwardedTo(typeof(DataRelationCollection))] [assembly: TypeForwardedTo(typeof(DataRow))] [assembly: TypeForwardedTo(typeof(DataRowAction))] [assembly: TypeForwardedTo(typeof(DataRowBuilder))] [assembly: TypeForwardedTo(typeof(DataRowChangeEventArgs))] [assembly: TypeForwardedTo(typeof(DataRowChangeEventHandler))] [assembly: TypeForwardedTo(typeof(DataRowCollection))] [assembly: TypeForwardedTo(typeof(DataRowComparer))] [assembly: TypeForwardedTo(typeof(DataRowComparer<>))] [assembly: TypeForwardedTo(typeof(DataRowExtensions))] [assembly: TypeForwardedTo(typeof(DataRowState))] [assembly: TypeForwardedTo(typeof(DataRowVersion))] [assembly: TypeForwardedTo(typeof(DataRowView))] [assembly: TypeForwardedTo(typeof(DataSet))] [assembly: TypeForwardedTo(typeof(DataSetDateTime))] [assembly: TypeForwardedTo(typeof(DataSysDescriptionAttribute))] [assembly: TypeForwardedTo(typeof(DataTable))] [assembly: TypeForwardedTo(typeof(DataTableClearEventArgs))] [assembly: TypeForwardedTo(typeof(DataTableClearEventHandler))] [assembly: TypeForwardedTo(typeof(DataTableCollection))] [assembly: TypeForwardedTo(typeof(DataTableExtensions))] [assembly: TypeForwardedTo(typeof(DataTableNewRowEventArgs))] [assembly: TypeForwardedTo(typeof(DataTableNewRowEventHandler))] [assembly: TypeForwardedTo(typeof(DataTableReader))] [assembly: TypeForwardedTo(typeof(DataView))] [assembly: TypeForwardedTo(typeof(DataViewManager))] [assembly: TypeForwardedTo(typeof(DataViewRowState))] [assembly: TypeForwardedTo(typeof(DataViewSetting))] [assembly: TypeForwardedTo(typeof(DataViewSettingCollection))] [assembly: TypeForwardedTo(typeof(DBConcurrencyException))] [assembly: TypeForwardedTo(typeof(DbType))] [assembly: TypeForwardedTo(typeof(DeletedRowInaccessibleException))] [assembly: TypeForwardedTo(typeof(DuplicateNameException))] [assembly: TypeForwardedTo(typeof(EnumerableRowCollection))] [assembly: TypeForwardedTo(typeof(EnumerableRowCollection<>))] [assembly: TypeForwardedTo(typeof(EnumerableRowCollectionExtensions))] [assembly: TypeForwardedTo(typeof(EvaluateException))] [assembly: TypeForwardedTo(typeof(FillErrorEventArgs))] [assembly: TypeForwardedTo(typeof(FillErrorEventHandler))] [assembly: TypeForwardedTo(typeof(ForeignKeyConstraint))] [assembly: TypeForwardedTo(typeof(IColumnMapping))] [assembly: TypeForwardedTo(typeof(IColumnMappingCollection))] [assembly: TypeForwardedTo(typeof(IDataAdapter))] [assembly: TypeForwardedTo(typeof(IDataParameter))] [assembly: TypeForwardedTo(typeof(IDataParameterCollection))] [assembly: TypeForwardedTo(typeof(IDataReader))] [assembly: TypeForwardedTo(typeof(IDataRecord))] [assembly: TypeForwardedTo(typeof(IDbCommand))] [assembly: TypeForwardedTo(typeof(IDbConnection))] [assembly: TypeForwardedTo(typeof(IDbDataAdapter))] [assembly: TypeForwardedTo(typeof(IDbDataParameter))] [assembly: TypeForwardedTo(typeof(IDbTransaction))] [assembly: TypeForwardedTo(typeof(InRowChangingEventException))] [assembly: TypeForwardedTo(typeof(InternalDataCollectionBase))] [assembly: TypeForwardedTo(typeof(InvalidConstraintException))] [assembly: TypeForwardedTo(typeof(InvalidExpressionException))] [assembly: TypeForwardedTo(typeof(System.Data.IsolationLevel))] [assembly: TypeForwardedTo(typeof(ITableMapping))] [assembly: TypeForwardedTo(typeof(ITableMappingCollection))] [assembly: TypeForwardedTo(typeof(KeyRestrictionBehavior))] [assembly: TypeForwardedTo(typeof(LoadOption))] [assembly: TypeForwardedTo(typeof(MappingType))] [assembly: TypeForwardedTo(typeof(MergeFailedEventArgs))] [assembly: TypeForwardedTo(typeof(MergeFailedEventHandler))] [assembly: TypeForwardedTo(typeof(MissingMappingAction))] [assembly: TypeForwardedTo(typeof(MissingPrimaryKeyException))] [assembly: TypeForwardedTo(typeof(MissingSchemaAction))] [assembly: TypeForwardedTo(typeof(NoNullAllowedException))] [assembly: TypeForwardedTo(typeof(OrderedEnumerableRowCollection<>))] [assembly: TypeForwardedTo(typeof(ParameterDirection))] [assembly: TypeForwardedTo(typeof(PropertyCollection))] [assembly: TypeForwardedTo(typeof(ReadOnlyException))] [assembly: TypeForwardedTo(typeof(RowNotInTableException))] [assembly: TypeForwardedTo(typeof(Rule))] [assembly: TypeForwardedTo(typeof(SchemaSerializationMode))] [assembly: TypeForwardedTo(typeof(SchemaType))] [assembly: TypeForwardedTo(typeof(SerializationFormat))] [assembly: TypeForwardedTo(typeof(SqlDbType))] [assembly: TypeForwardedTo(typeof(INullable))] [assembly: TypeForwardedTo(typeof(SqlAlreadyFilledException))] [assembly: TypeForwardedTo(typeof(SqlBinary))] [assembly: TypeForwardedTo(typeof(SqlBoolean))] [assembly: TypeForwardedTo(typeof(SqlByte))] [assembly: TypeForwardedTo(typeof(SqlBytes))] [assembly: TypeForwardedTo(typeof(SqlChars))] [assembly: TypeForwardedTo(typeof(SqlCompareOptions))] [assembly: TypeForwardedTo(typeof(SqlDateTime))] [assembly: TypeForwardedTo(typeof(SqlDecimal))] [assembly: TypeForwardedTo(typeof(SqlDouble))] [assembly: TypeForwardedTo(typeof(SqlGuid))] [assembly: TypeForwardedTo(typeof(SqlInt16))] [assembly: TypeForwardedTo(typeof(SqlInt32))] [assembly: TypeForwardedTo(typeof(SqlInt64))] [assembly: TypeForwardedTo(typeof(SqlMoney))] [assembly: TypeForwardedTo(typeof(SqlNotFilledException))] [assembly: TypeForwardedTo(typeof(SqlNullValueException))] [assembly: TypeForwardedTo(typeof(SqlSingle))] [assembly: TypeForwardedTo(typeof(SqlString))] [assembly: TypeForwardedTo(typeof(SqlTruncateException))] [assembly: TypeForwardedTo(typeof(SqlTypeException))] [assembly: TypeForwardedTo(typeof(SqlXml))] [assembly: TypeForwardedTo(typeof(StorageState))] [assembly: TypeForwardedTo(typeof(StateChangeEventArgs))] [assembly: TypeForwardedTo(typeof(StateChangeEventHandler))] [assembly: TypeForwardedTo(typeof(StatementCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(StatementCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(StatementType))] [assembly: TypeForwardedTo(typeof(StrongTypingException))] [assembly: TypeForwardedTo(typeof(SyntaxErrorException))] [assembly: TypeForwardedTo(typeof(TypedTableBase<>))] [assembly: TypeForwardedTo(typeof(TypedTableBaseExtensions))] [assembly: TypeForwardedTo(typeof(UniqueConstraint))] [assembly: TypeForwardedTo(typeof(UpdateRowSource))] [assembly: TypeForwardedTo(typeof(UpdateStatus))] [assembly: TypeForwardedTo(typeof(VersionNotFoundException))] [assembly: TypeForwardedTo(typeof(XmlReadMode))] [assembly: TypeForwardedTo(typeof(XmlWriteMode))] [assembly: TypeForwardedTo(typeof(DataMisalignedException))] [assembly: TypeForwardedTo(typeof(DateTime))] [assembly: TypeForwardedTo(typeof(DateTimeKind))] [assembly: TypeForwardedTo(typeof(DateTimeOffset))] [assembly: TypeForwardedTo(typeof(DayOfWeek))] [assembly: TypeForwardedTo(typeof(DBNull))] [assembly: TypeForwardedTo(typeof(decimal))] [assembly: TypeForwardedTo(typeof(Delegate))] [assembly: TypeForwardedTo(typeof(BooleanSwitch))] [assembly: TypeForwardedTo(typeof(AllowNullAttribute))] [assembly: TypeForwardedTo(typeof(DisallowNullAttribute))] [assembly: TypeForwardedTo(typeof(DoesNotReturnAttribute))] [assembly: TypeForwardedTo(typeof(DoesNotReturnIfAttribute))] [assembly: TypeForwardedTo(typeof(ExcludeFromCodeCoverageAttribute))] [assembly: TypeForwardedTo(typeof(MaybeNullAttribute))] [assembly: TypeForwardedTo(typeof(MaybeNullWhenAttribute))] [assembly: TypeForwardedTo(typeof(NotNullAttribute))] [assembly: TypeForwardedTo(typeof(NotNullIfNotNullAttribute))] [assembly: TypeForwardedTo(typeof(NotNullWhenAttribute))] [assembly: TypeForwardedTo(typeof(SuppressMessageAttribute))] [assembly: TypeForwardedTo(typeof(ConditionalAttribute))] [assembly: TypeForwardedTo(typeof(Contract))] [assembly: TypeForwardedTo(typeof(ContractAbbreviatorAttribute))] [assembly: TypeForwardedTo(typeof(ContractArgumentValidatorAttribute))] [assembly: TypeForwardedTo(typeof(ContractClassAttribute))] [assembly: TypeForwardedTo(typeof(ContractClassForAttribute))] [assembly: TypeForwardedTo(typeof(ContractFailedEventArgs))] [assembly: TypeForwardedTo(typeof(ContractFailureKind))] [assembly: TypeForwardedTo(typeof(ContractInvariantMethodAttribute))] [assembly: TypeForwardedTo(typeof(ContractOptionAttribute))] [assembly: TypeForwardedTo(typeof(ContractPublicPropertyNameAttribute))] [assembly: TypeForwardedTo(typeof(ContractReferenceAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(ContractRuntimeIgnoredAttribute))] [assembly: TypeForwardedTo(typeof(ContractVerificationAttribute))] [assembly: TypeForwardedTo(typeof(PureAttribute))] [assembly: TypeForwardedTo(typeof(CorrelationManager))] [assembly: TypeForwardedTo(typeof(DataReceivedEventArgs))] [assembly: TypeForwardedTo(typeof(DataReceivedEventHandler))] [assembly: TypeForwardedTo(typeof(Debug))] [assembly: TypeForwardedTo(typeof(DebuggableAttribute))] [assembly: TypeForwardedTo(typeof(Debugger))] [assembly: TypeForwardedTo(typeof(DebuggerBrowsableAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerBrowsableState))] [assembly: TypeForwardedTo(typeof(DebuggerDisplayAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerHiddenAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerNonUserCodeAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerStepperBoundaryAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerStepThroughAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerTypeProxyAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerVisualizerAttribute))] [assembly: TypeForwardedTo(typeof(DefaultTraceListener))] [assembly: TypeForwardedTo(typeof(DelimitedListTraceListener))] [assembly: TypeForwardedTo(typeof(EventTypeFilter))] [assembly: TypeForwardedTo(typeof(FileVersionInfo))] [assembly: TypeForwardedTo(typeof(MonitoringDescriptionAttribute))] [assembly: TypeForwardedTo(typeof(Process))] [assembly: TypeForwardedTo(typeof(ProcessModule))] [assembly: TypeForwardedTo(typeof(ProcessModuleCollection))] [assembly: TypeForwardedTo(typeof(ProcessPriorityClass))] [assembly: TypeForwardedTo(typeof(ProcessStartInfo))] [assembly: TypeForwardedTo(typeof(ProcessThread))] [assembly: TypeForwardedTo(typeof(ProcessThreadCollection))] [assembly: TypeForwardedTo(typeof(ProcessWindowStyle))] [assembly: TypeForwardedTo(typeof(SourceFilter))] [assembly: TypeForwardedTo(typeof(SourceLevels))] [assembly: TypeForwardedTo(typeof(SourceSwitch))] [assembly: TypeForwardedTo(typeof(StackFrame))] [assembly: TypeForwardedTo(typeof(StackFrameExtensions))] [assembly: TypeForwardedTo(typeof(StackTrace))] [assembly: TypeForwardedTo(typeof(Stopwatch))] [assembly: TypeForwardedTo(typeof(Switch))] [assembly: TypeForwardedTo(typeof(SwitchAttribute))] [assembly: TypeForwardedTo(typeof(SwitchLevelAttribute))] [assembly: TypeForwardedTo(typeof(ISymbolBinder))] [assembly: TypeForwardedTo(typeof(ISymbolBinder1))] [assembly: TypeForwardedTo(typeof(ISymbolDocument))] [assembly: TypeForwardedTo(typeof(ISymbolDocumentWriter))] [assembly: TypeForwardedTo(typeof(ISymbolMethod))] [assembly: TypeForwardedTo(typeof(ISymbolNamespace))] [assembly: TypeForwardedTo(typeof(ISymbolReader))] [assembly: TypeForwardedTo(typeof(ISymbolScope))] [assembly: TypeForwardedTo(typeof(ISymbolVariable))] [assembly: TypeForwardedTo(typeof(ISymbolWriter))] [assembly: TypeForwardedTo(typeof(SymAddressKind))] [assembly: TypeForwardedTo(typeof(SymbolToken))] [assembly: TypeForwardedTo(typeof(SymDocumentType))] [assembly: TypeForwardedTo(typeof(SymLanguageType))] [assembly: TypeForwardedTo(typeof(SymLanguageVendor))] [assembly: TypeForwardedTo(typeof(TextWriterTraceListener))] [assembly: TypeForwardedTo(typeof(ThreadPriorityLevel))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.ThreadState))] [assembly: TypeForwardedTo(typeof(ThreadWaitReason))] [assembly: TypeForwardedTo(typeof(Trace))] [assembly: TypeForwardedTo(typeof(TraceEventCache))] [assembly: TypeForwardedTo(typeof(TraceEventType))] [assembly: TypeForwardedTo(typeof(TraceFilter))] [assembly: TypeForwardedTo(typeof(TraceLevel))] [assembly: TypeForwardedTo(typeof(TraceListener))] [assembly: TypeForwardedTo(typeof(TraceListenerCollection))] [assembly: TypeForwardedTo(typeof(TraceOptions))] [assembly: TypeForwardedTo(typeof(TraceSource))] [assembly: TypeForwardedTo(typeof(TraceSwitch))] [assembly: TypeForwardedTo(typeof(DiagnosticCounter))] [assembly: TypeForwardedTo(typeof(EventActivityOptions))] [assembly: TypeForwardedTo(typeof(EventAttribute))] [assembly: TypeForwardedTo(typeof(EventChannel))] [assembly: TypeForwardedTo(typeof(EventCommand))] [assembly: TypeForwardedTo(typeof(EventCommandEventArgs))] [assembly: TypeForwardedTo(typeof(EventCounter))] [assembly: TypeForwardedTo(typeof(EventDataAttribute))] [assembly: TypeForwardedTo(typeof(EventFieldAttribute))] [assembly: TypeForwardedTo(typeof(EventFieldFormat))] [assembly: TypeForwardedTo(typeof(EventFieldTags))] [assembly: TypeForwardedTo(typeof(EventIgnoreAttribute))] [assembly: TypeForwardedTo(typeof(EventKeywords))] [assembly: TypeForwardedTo(typeof(EventLevel))] [assembly: TypeForwardedTo(typeof(EventListener))] [assembly: TypeForwardedTo(typeof(EventManifestOptions))] [assembly: TypeForwardedTo(typeof(EventOpcode))] [assembly: TypeForwardedTo(typeof(EventSource))] [assembly: TypeForwardedTo(typeof(EventSourceAttribute))] [assembly: TypeForwardedTo(typeof(EventSourceCreatedEventArgs))] [assembly: TypeForwardedTo(typeof(EventSourceException))] [assembly: TypeForwardedTo(typeof(EventSourceOptions))] [assembly: TypeForwardedTo(typeof(EventSourceSettings))] [assembly: TypeForwardedTo(typeof(EventTags))] [assembly: TypeForwardedTo(typeof(EventTask))] [assembly: TypeForwardedTo(typeof(EventWrittenEventArgs))] [assembly: TypeForwardedTo(typeof(IncrementingEventCounter))] [assembly: TypeForwardedTo(typeof(IncrementingPollingCounter))] [assembly: TypeForwardedTo(typeof(NonEventAttribute))] [assembly: TypeForwardedTo(typeof(PollingCounter))] [assembly: TypeForwardedTo(typeof(DivideByZeroException))] [assembly: TypeForwardedTo(typeof(DllNotFoundException))] [assembly: TypeForwardedTo(typeof(double))] [assembly: TypeForwardedTo(typeof(Color))] [assembly: TypeForwardedTo(typeof(ColorConverter))] [assembly: TypeForwardedTo(typeof(KnownColor))] [assembly: TypeForwardedTo(typeof(Point))] [assembly: TypeForwardedTo(typeof(PointConverter))] [assembly: TypeForwardedTo(typeof(PointF))] [assembly: TypeForwardedTo(typeof(Rectangle))] [assembly: TypeForwardedTo(typeof(RectangleConverter))] [assembly: TypeForwardedTo(typeof(RectangleF))] [assembly: TypeForwardedTo(typeof(Size))] [assembly: TypeForwardedTo(typeof(SizeConverter))] [assembly: TypeForwardedTo(typeof(SizeF))] [assembly: TypeForwardedTo(typeof(SizeFConverter))] [assembly: TypeForwardedTo(typeof(DuplicateWaitObjectException))] [assembly: TypeForwardedTo(typeof(BinaryOperationBinder))] [assembly: TypeForwardedTo(typeof(BindingRestrictions))] [assembly: TypeForwardedTo(typeof(CallInfo))] [assembly: TypeForwardedTo(typeof(ConvertBinder))] [assembly: TypeForwardedTo(typeof(CreateInstanceBinder))] [assembly: TypeForwardedTo(typeof(DeleteIndexBinder))] [assembly: TypeForwardedTo(typeof(DeleteMemberBinder))] [assembly: TypeForwardedTo(typeof(DynamicMetaObject))] [assembly: TypeForwardedTo(typeof(DynamicMetaObjectBinder))] [assembly: TypeForwardedTo(typeof(DynamicObject))] [assembly: TypeForwardedTo(typeof(ExpandoObject))] [assembly: TypeForwardedTo(typeof(GetIndexBinder))] [assembly: TypeForwardedTo(typeof(GetMemberBinder))] [assembly: TypeForwardedTo(typeof(IDynamicMetaObjectProvider))] [assembly: TypeForwardedTo(typeof(IInvokeOnGetBinder))] [assembly: TypeForwardedTo(typeof(InvokeBinder))] [assembly: TypeForwardedTo(typeof(InvokeMemberBinder))] [assembly: TypeForwardedTo(typeof(SetIndexBinder))] [assembly: TypeForwardedTo(typeof(SetMemberBinder))] [assembly: TypeForwardedTo(typeof(UnaryOperationBinder))] [assembly: TypeForwardedTo(typeof(EntryPointNotFoundException))] [assembly: TypeForwardedTo(typeof(Enum))] [assembly: TypeForwardedTo(typeof(Environment))] [assembly: TypeForwardedTo(typeof(EnvironmentVariableTarget))] [assembly: TypeForwardedTo(typeof(EventArgs))] [assembly: TypeForwardedTo(typeof(EventHandler))] [assembly: TypeForwardedTo(typeof(EventHandler<>))] [assembly: TypeForwardedTo(typeof(Exception))] [assembly: TypeForwardedTo(typeof(ExecutionEngineException))] [assembly: TypeForwardedTo(typeof(FieldAccessException))] [assembly: TypeForwardedTo(typeof(FileStyleUriParser))] [assembly: TypeForwardedTo(typeof(FlagsAttribute))] [assembly: TypeForwardedTo(typeof(FormatException))] [assembly: TypeForwardedTo(typeof(FormattableString))] [assembly: TypeForwardedTo(typeof(FtpStyleUriParser))] [assembly: TypeForwardedTo(typeof(Func<>))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, >))] [assembly: TypeForwardedTo(typeof(Func<, , >))] [assembly: TypeForwardedTo(typeof(Func<, , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , >))] [assembly: TypeForwardedTo(typeof(GC))] [assembly: TypeForwardedTo(typeof(GCCollectionMode))] [assembly: TypeForwardedTo(typeof(GCNotificationStatus))] [assembly: TypeForwardedTo(typeof(GenericUriParser))] [assembly: TypeForwardedTo(typeof(GenericUriParserOptions))] [assembly: TypeForwardedTo(typeof(Calendar))] [assembly: TypeForwardedTo(typeof(CalendarAlgorithmType))] [assembly: TypeForwardedTo(typeof(CalendarWeekRule))] [assembly: TypeForwardedTo(typeof(CharUnicodeInfo))] [assembly: TypeForwardedTo(typeof(ChineseLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(CompareInfo))] [assembly: TypeForwardedTo(typeof(CompareOptions))] [assembly: TypeForwardedTo(typeof(CultureInfo))] [assembly: TypeForwardedTo(typeof(CultureNotFoundException))] [assembly: TypeForwardedTo(typeof(CultureTypes))] [assembly: TypeForwardedTo(typeof(DateTimeFormatInfo))] [assembly: TypeForwardedTo(typeof(DateTimeStyles))] [assembly: TypeForwardedTo(typeof(DaylightTime))] [assembly: TypeForwardedTo(typeof(DigitShapes))] [assembly: TypeForwardedTo(typeof(EastAsianLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(GlobalizationExtensions))] [assembly: TypeForwardedTo(typeof(GregorianCalendar))] [assembly: TypeForwardedTo(typeof(GregorianCalendarTypes))] [assembly: TypeForwardedTo(typeof(HebrewCalendar))] [assembly: TypeForwardedTo(typeof(HijriCalendar))] [assembly: TypeForwardedTo(typeof(IdnMapping))] [assembly: TypeForwardedTo(typeof(ISOWeek))] [assembly: TypeForwardedTo(typeof(JapaneseCalendar))] [assembly: TypeForwardedTo(typeof(JapaneseLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(JulianCalendar))] [assembly: TypeForwardedTo(typeof(KoreanCalendar))] [assembly: TypeForwardedTo(typeof(KoreanLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(NumberFormatInfo))] [assembly: TypeForwardedTo(typeof(NumberStyles))] [assembly: TypeForwardedTo(typeof(PersianCalendar))] [assembly: TypeForwardedTo(typeof(RegionInfo))] [assembly: TypeForwardedTo(typeof(SortKey))] [assembly: TypeForwardedTo(typeof(SortVersion))] [assembly: TypeForwardedTo(typeof(StringInfo))] [assembly: TypeForwardedTo(typeof(TaiwanCalendar))] [assembly: TypeForwardedTo(typeof(TaiwanLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(TextElementEnumerator))] [assembly: TypeForwardedTo(typeof(TextInfo))] [assembly: TypeForwardedTo(typeof(ThaiBuddhistCalendar))] [assembly: TypeForwardedTo(typeof(TimeSpanStyles))] [assembly: TypeForwardedTo(typeof(UmAlQuraCalendar))] [assembly: TypeForwardedTo(typeof(UnicodeCategory))] [assembly: TypeForwardedTo(typeof(GopherStyleUriParser))] [assembly: TypeForwardedTo(typeof(Guid))] [assembly: TypeForwardedTo(typeof(HashCode))] [assembly: TypeForwardedTo(typeof(HttpStyleUriParser))] [assembly: TypeForwardedTo(typeof(IAsyncDisposable))] [assembly: TypeForwardedTo(typeof(IAsyncResult))] [assembly: TypeForwardedTo(typeof(ICloneable))] [assembly: TypeForwardedTo(typeof(IComparable))] [assembly: TypeForwardedTo(typeof(IComparable<>))] [assembly: TypeForwardedTo(typeof(IConvertible))] [assembly: TypeForwardedTo(typeof(ICustomFormatter))] [assembly: TypeForwardedTo(typeof(IDisposable))] [assembly: TypeForwardedTo(typeof(IEquatable<>))] [assembly: TypeForwardedTo(typeof(IFormatProvider))] [assembly: TypeForwardedTo(typeof(IFormattable))] [assembly: TypeForwardedTo(typeof(Index))] [assembly: TypeForwardedTo(typeof(IndexOutOfRangeException))] [assembly: TypeForwardedTo(typeof(InsufficientExecutionStackException))] [assembly: TypeForwardedTo(typeof(InsufficientMemoryException))] [assembly: TypeForwardedTo(typeof(short))] [assembly: TypeForwardedTo(typeof(int))] [assembly: TypeForwardedTo(typeof(long))] [assembly: TypeForwardedTo(typeof(IntPtr))] [assembly: TypeForwardedTo(typeof(InvalidCastException))] [assembly: TypeForwardedTo(typeof(InvalidOperationException))] [assembly: TypeForwardedTo(typeof(InvalidProgramException))] [assembly: TypeForwardedTo(typeof(InvalidTimeZoneException))] [assembly: TypeForwardedTo(typeof(BinaryReader))] [assembly: TypeForwardedTo(typeof(BinaryWriter))] [assembly: TypeForwardedTo(typeof(BufferedStream))] [assembly: TypeForwardedTo(typeof(BrotliDecoder))] [assembly: TypeForwardedTo(typeof(BrotliEncoder))] [assembly: TypeForwardedTo(typeof(BrotliStream))] [assembly: TypeForwardedTo(typeof(CompressionLevel))] [assembly: TypeForwardedTo(typeof(CompressionMode))] [assembly: TypeForwardedTo(typeof(DeflateStream))] [assembly: TypeForwardedTo(typeof(GZipStream))] [assembly: TypeForwardedTo(typeof(ZipArchive))] [assembly: TypeForwardedTo(typeof(ZipArchiveEntry))] [assembly: TypeForwardedTo(typeof(ZipArchiveMode))] [assembly: TypeForwardedTo(typeof(ZipFile))] [assembly: TypeForwardedTo(typeof(ZipFileExtensions))] [assembly: TypeForwardedTo(typeof(Directory))] [assembly: TypeForwardedTo(typeof(DirectoryInfo))] [assembly: TypeForwardedTo(typeof(DirectoryNotFoundException))] [assembly: TypeForwardedTo(typeof(DriveInfo))] [assembly: TypeForwardedTo(typeof(DriveNotFoundException))] [assembly: TypeForwardedTo(typeof(DriveType))] [assembly: TypeForwardedTo(typeof(EndOfStreamException))] [assembly: TypeForwardedTo(typeof(FileSystemEntry))] [assembly: TypeForwardedTo(typeof(FileSystemEnumerable<>))] [assembly: TypeForwardedTo(typeof(FileSystemEnumerator<>))] [assembly: TypeForwardedTo(typeof(FileSystemName))] [assembly: TypeForwardedTo(typeof(EnumerationOptions))] [assembly: TypeForwardedTo(typeof(ErrorEventArgs))] [assembly: TypeForwardedTo(typeof(ErrorEventHandler))] [assembly: TypeForwardedTo(typeof(File))] [assembly: TypeForwardedTo(typeof(FileAccess))] [assembly: TypeForwardedTo(typeof(FileAttributes))] [assembly: TypeForwardedTo(typeof(FileInfo))] [assembly: TypeForwardedTo(typeof(FileLoadException))] [assembly: TypeForwardedTo(typeof(FileMode))] [assembly: TypeForwardedTo(typeof(FileNotFoundException))] [assembly: TypeForwardedTo(typeof(FileOptions))] [assembly: TypeForwardedTo(typeof(FileShare))] [assembly: TypeForwardedTo(typeof(FileStream))] [assembly: TypeForwardedTo(typeof(FileSystemEventArgs))] [assembly: TypeForwardedTo(typeof(FileSystemEventHandler))] [assembly: TypeForwardedTo(typeof(FileSystemInfo))] [assembly: TypeForwardedTo(typeof(FileSystemWatcher))] [assembly: TypeForwardedTo(typeof(HandleInheritability))] [assembly: TypeForwardedTo(typeof(InternalBufferOverflowException))] [assembly: TypeForwardedTo(typeof(InvalidDataException))] [assembly: TypeForwardedTo(typeof(IOException))] [assembly: TypeForwardedTo(typeof(INormalizeForIsolatedStorage))] [assembly: TypeForwardedTo(typeof(IsolatedStorage))] [assembly: TypeForwardedTo(typeof(IsolatedStorageException))] [assembly: TypeForwardedTo(typeof(IsolatedStorageFile))] [assembly: TypeForwardedTo(typeof(IsolatedStorageFileStream))] [assembly: TypeForwardedTo(typeof(IsolatedStorageScope))] [assembly: TypeForwardedTo(typeof(MatchCasing))] [assembly: TypeForwardedTo(typeof(MatchType))] [assembly: TypeForwardedTo(typeof(MemoryMappedFile))] [assembly: TypeForwardedTo(typeof(MemoryMappedFileAccess))] [assembly: TypeForwardedTo(typeof(MemoryMappedFileOptions))] [assembly: TypeForwardedTo(typeof(MemoryMappedFileRights))] [assembly: TypeForwardedTo(typeof(MemoryMappedViewAccessor))] [assembly: TypeForwardedTo(typeof(MemoryMappedViewStream))] [assembly: TypeForwardedTo(typeof(MemoryStream))] [assembly: TypeForwardedTo(typeof(NotifyFilters))] [assembly: TypeForwardedTo(typeof(Path))] [assembly: TypeForwardedTo(typeof(PathTooLongException))] [assembly: TypeForwardedTo(typeof(AnonymousPipeClientStream))] [assembly: TypeForwardedTo(typeof(AnonymousPipeServerStream))] [assembly: TypeForwardedTo(typeof(NamedPipeClientStream))] [assembly: TypeForwardedTo(typeof(NamedPipeServerStream))] [assembly: TypeForwardedTo(typeof(PipeDirection))] [assembly: TypeForwardedTo(typeof(PipeOptions))] [assembly: TypeForwardedTo(typeof(PipeStream))] [assembly: TypeForwardedTo(typeof(PipeStreamImpersonationWorker))] [assembly: TypeForwardedTo(typeof(PipeTransmissionMode))] [assembly: TypeForwardedTo(typeof(RenamedEventArgs))] [assembly: TypeForwardedTo(typeof(RenamedEventHandler))] [assembly: TypeForwardedTo(typeof(SearchOption))] [assembly: TypeForwardedTo(typeof(SeekOrigin))] [assembly: TypeForwardedTo(typeof(Stream))] [assembly: TypeForwardedTo(typeof(StreamReader))] [assembly: TypeForwardedTo(typeof(StreamWriter))] [assembly: TypeForwardedTo(typeof(StringReader))] [assembly: TypeForwardedTo(typeof(StringWriter))] [assembly: TypeForwardedTo(typeof(TextReader))] [assembly: TypeForwardedTo(typeof(TextWriter))] [assembly: TypeForwardedTo(typeof(UnmanagedMemoryAccessor))] [assembly: TypeForwardedTo(typeof(UnmanagedMemoryStream))] [assembly: TypeForwardedTo(typeof(WaitForChangedResult))] [assembly: TypeForwardedTo(typeof(WatcherChangeTypes))] [assembly: TypeForwardedTo(typeof(IObservable<>))] [assembly: TypeForwardedTo(typeof(IObserver<>))] [assembly: TypeForwardedTo(typeof(IProgress<>))] [assembly: TypeForwardedTo(typeof(IServiceProvider))] [assembly: TypeForwardedTo(typeof(Lazy<>))] [assembly: TypeForwardedTo(typeof(Lazy<, >))] [assembly: TypeForwardedTo(typeof(LdapStyleUriParser))] [assembly: TypeForwardedTo(typeof(Enumerable))] [assembly: TypeForwardedTo(typeof(EnumerableExecutor))] [assembly: TypeForwardedTo(typeof(EnumerableExecutor<>))] [assembly: TypeForwardedTo(typeof(EnumerableQuery))] [assembly: TypeForwardedTo(typeof(EnumerableQuery<>))] [assembly: TypeForwardedTo(typeof(BinaryExpression))] [assembly: TypeForwardedTo(typeof(BlockExpression))] [assembly: TypeForwardedTo(typeof(CatchBlock))] [assembly: TypeForwardedTo(typeof(ConditionalExpression))] [assembly: TypeForwardedTo(typeof(ConstantExpression))] [assembly: TypeForwardedTo(typeof(DebugInfoExpression))] [assembly: TypeForwardedTo(typeof(DefaultExpression))] [assembly: TypeForwardedTo(typeof(DynamicExpression))] [assembly: TypeForwardedTo(typeof(DynamicExpressionVisitor))] [assembly: TypeForwardedTo(typeof(ElementInit))] [assembly: TypeForwardedTo(typeof(Expression))] [assembly: TypeForwardedTo(typeof(Expression<>))] [assembly: TypeForwardedTo(typeof(ExpressionType))] [assembly: TypeForwardedTo(typeof(ExpressionVisitor))] [assembly: TypeForwardedTo(typeof(GotoExpression))] [assembly: TypeForwardedTo(typeof(GotoExpressionKind))] [assembly: TypeForwardedTo(typeof(IArgumentProvider))] [assembly: TypeForwardedTo(typeof(IDynamicExpression))] [assembly: TypeForwardedTo(typeof(IndexExpression))] [assembly: TypeForwardedTo(typeof(InvocationExpression))] [assembly: TypeForwardedTo(typeof(LabelExpression))] [assembly: TypeForwardedTo(typeof(LabelTarget))] [assembly: TypeForwardedTo(typeof(LambdaExpression))] [assembly: TypeForwardedTo(typeof(ListInitExpression))] [assembly: TypeForwardedTo(typeof(LoopExpression))] [assembly: TypeForwardedTo(typeof(MemberAssignment))] [assembly: TypeForwardedTo(typeof(MemberBinding))] [assembly: TypeForwardedTo(typeof(MemberBindingType))] [assembly: TypeForwardedTo(typeof(MemberExpression))] [assembly: TypeForwardedTo(typeof(MemberInitExpression))] [assembly: TypeForwardedTo(typeof(MemberListBinding))] [assembly: TypeForwardedTo(typeof(MemberMemberBinding))] [assembly: TypeForwardedTo(typeof(MethodCallExpression))] [assembly: TypeForwardedTo(typeof(NewArrayExpression))] [assembly: TypeForwardedTo(typeof(NewExpression))] [assembly: TypeForwardedTo(typeof(ParameterExpression))] [assembly: TypeForwardedTo(typeof(RuntimeVariablesExpression))] [assembly: TypeForwardedTo(typeof(SwitchCase))] [assembly: TypeForwardedTo(typeof(SwitchExpression))] [assembly: TypeForwardedTo(typeof(SymbolDocumentInfo))] [assembly: TypeForwardedTo(typeof(TryExpression))] [assembly: TypeForwardedTo(typeof(TypeBinaryExpression))] [assembly: TypeForwardedTo(typeof(UnaryExpression))] [assembly: TypeForwardedTo(typeof(IGrouping<, >))] [assembly: TypeForwardedTo(typeof(ILookup<, >))] [assembly: TypeForwardedTo(typeof(IOrderedEnumerable<>))] [assembly: TypeForwardedTo(typeof(IOrderedQueryable))] [assembly: TypeForwardedTo(typeof(IOrderedQueryable<>))] [assembly: TypeForwardedTo(typeof(IQueryable))] [assembly: TypeForwardedTo(typeof(IQueryable<>))] [assembly: TypeForwardedTo(typeof(IQueryProvider))] [assembly: TypeForwardedTo(typeof(Lookup<, >))] [assembly: TypeForwardedTo(typeof(OrderedParallelQuery<>))] [assembly: TypeForwardedTo(typeof(ParallelEnumerable))] [assembly: TypeForwardedTo(typeof(ParallelExecutionMode))] [assembly: TypeForwardedTo(typeof(ParallelMergeOptions))] [assembly: TypeForwardedTo(typeof(ParallelQuery))] [assembly: TypeForwardedTo(typeof(ParallelQuery<>))] [assembly: TypeForwardedTo(typeof(Queryable))] [assembly: TypeForwardedTo(typeof(LoaderOptimization))] [assembly: TypeForwardedTo(typeof(LoaderOptimizationAttribute))] [assembly: TypeForwardedTo(typeof(LocalDataStoreSlot))] [assembly: TypeForwardedTo(typeof(MarshalByRefObject))] [assembly: TypeForwardedTo(typeof(Math))] [assembly: TypeForwardedTo(typeof(MathF))] [assembly: TypeForwardedTo(typeof(MemberAccessException))] [assembly: TypeForwardedTo(typeof(Memory<>))] [assembly: TypeForwardedTo(typeof(MemoryExtensions))] [assembly: TypeForwardedTo(typeof(MethodAccessException))] [assembly: TypeForwardedTo(typeof(MidpointRounding))] [assembly: TypeForwardedTo(typeof(MissingFieldException))] [assembly: TypeForwardedTo(typeof(MissingMemberException))] [assembly: TypeForwardedTo(typeof(MissingMethodException))] [assembly: TypeForwardedTo(typeof(ModuleHandle))] [assembly: TypeForwardedTo(typeof(MTAThreadAttribute))] [assembly: TypeForwardedTo(typeof(MulticastDelegate))] [assembly: TypeForwardedTo(typeof(MulticastNotSupportedException))] [assembly: TypeForwardedTo(typeof(AuthenticationManager))] [assembly: TypeForwardedTo(typeof(AuthenticationSchemes))] [assembly: TypeForwardedTo(typeof(AuthenticationSchemeSelector))] [assembly: TypeForwardedTo(typeof(Authorization))] [assembly: TypeForwardedTo(typeof(BindIPEndPoint))] [assembly: TypeForwardedTo(typeof(HttpCacheAgeControl))] [assembly: TypeForwardedTo(typeof(HttpRequestCacheLevel))] [assembly: TypeForwardedTo(typeof(HttpRequestCachePolicy))] [assembly: TypeForwardedTo(typeof(RequestCacheLevel))] [assembly: TypeForwardedTo(typeof(RequestCachePolicy))] [assembly: TypeForwardedTo(typeof(Cookie))] [assembly: TypeForwardedTo(typeof(CookieCollection))] [assembly: TypeForwardedTo(typeof(CookieContainer))] [assembly: TypeForwardedTo(typeof(CookieException))] [assembly: TypeForwardedTo(typeof(CredentialCache))] [assembly: TypeForwardedTo(typeof(DecompressionMethods))] [assembly: TypeForwardedTo(typeof(Dns))] [assembly: TypeForwardedTo(typeof(DnsEndPoint))] [assembly: TypeForwardedTo(typeof(DownloadDataCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(DownloadDataCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(DownloadProgressChangedEventArgs))] [assembly: TypeForwardedTo(typeof(DownloadProgressChangedEventHandler))] [assembly: TypeForwardedTo(typeof(DownloadStringCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(DownloadStringCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(EndPoint))] [assembly: TypeForwardedTo(typeof(FileWebRequest))] [assembly: TypeForwardedTo(typeof(FileWebResponse))] [assembly: TypeForwardedTo(typeof(FtpStatusCode))] [assembly: TypeForwardedTo(typeof(FtpWebRequest))] [assembly: TypeForwardedTo(typeof(FtpWebResponse))] [assembly: TypeForwardedTo(typeof(GlobalProxySelection))] [assembly: TypeForwardedTo(typeof(ByteArrayContent))] [assembly: TypeForwardedTo(typeof(ClientCertificateOption))] [assembly: TypeForwardedTo(typeof(DelegatingHandler))] [assembly: TypeForwardedTo(typeof(FormUrlEncodedContent))] [assembly: TypeForwardedTo(typeof(AuthenticationHeaderValue))] [assembly: TypeForwardedTo(typeof(CacheControlHeaderValue))] [assembly: TypeForwardedTo(typeof(ContentDispositionHeaderValue))] [assembly: TypeForwardedTo(typeof(ContentRangeHeaderValue))] [assembly: TypeForwardedTo(typeof(EntityTagHeaderValue))] [assembly: TypeForwardedTo(typeof(HttpContentHeaders))] [assembly: TypeForwardedTo(typeof(HttpHeaders))] [assembly: TypeForwardedTo(typeof(HttpHeaderValueCollection<>))] [assembly: TypeForwardedTo(typeof(HttpRequestHeaders))] [assembly: TypeForwardedTo(typeof(HttpResponseHeaders))] [assembly: TypeForwardedTo(typeof(MediaTypeHeaderValue))] [assembly: TypeForwardedTo(typeof(MediaTypeWithQualityHeaderValue))] [assembly: TypeForwardedTo(typeof(NameValueHeaderValue))] [assembly: TypeForwardedTo(typeof(NameValueWithParametersHeaderValue))] [assembly: TypeForwardedTo(typeof(ProductHeaderValue))] [assembly: TypeForwardedTo(typeof(ProductInfoHeaderValue))] [assembly: TypeForwardedTo(typeof(RangeConditionHeaderValue))] [assembly: TypeForwardedTo(typeof(RangeHeaderValue))] [assembly: TypeForwardedTo(typeof(RangeItemHeaderValue))] [assembly: TypeForwardedTo(typeof(RetryConditionHeaderValue))] [assembly: TypeForwardedTo(typeof(StringWithQualityHeaderValue))] [assembly: TypeForwardedTo(typeof(TransferCodingHeaderValue))] [assembly: TypeForwardedTo(typeof(TransferCodingWithQualityHeaderValue))] [assembly: TypeForwardedTo(typeof(ViaHeaderValue))] [assembly: TypeForwardedTo(typeof(WarningHeaderValue))] [assembly: TypeForwardedTo(typeof(HttpClient))] [assembly: TypeForwardedTo(typeof(HttpClientHandler))] [assembly: TypeForwardedTo(typeof(HttpCompletionOption))] [assembly: TypeForwardedTo(typeof(HttpContent))] [assembly: TypeForwardedTo(typeof(HttpMessageHandler))] [assembly: TypeForwardedTo(typeof(HttpMessageInvoker))] [assembly: TypeForwardedTo(typeof(HttpMethod))] [assembly: TypeForwardedTo(typeof(HttpRequestException))] [assembly: TypeForwardedTo(typeof(HttpRequestMessage))] [assembly: TypeForwardedTo(typeof(HttpResponseMessage))] [assembly: TypeForwardedTo(typeof(MessageProcessingHandler))] [assembly: TypeForwardedTo(typeof(MultipartContent))] [assembly: TypeForwardedTo(typeof(MultipartFormDataContent))] [assembly: TypeForwardedTo(typeof(ReadOnlyMemoryContent))] [assembly: TypeForwardedTo(typeof(StreamContent))] [assembly: TypeForwardedTo(typeof(StringContent))] [assembly: TypeForwardedTo(typeof(HttpContinueDelegate))] [assembly: TypeForwardedTo(typeof(HttpListener))] [assembly: TypeForwardedTo(typeof(HttpListenerBasicIdentity))] [assembly: TypeForwardedTo(typeof(HttpListenerContext))] [assembly: TypeForwardedTo(typeof(HttpListenerException))] [assembly: TypeForwardedTo(typeof(HttpListenerPrefixCollection))] [assembly: TypeForwardedTo(typeof(HttpListenerRequest))] [assembly: TypeForwardedTo(typeof(HttpListenerResponse))] [assembly: TypeForwardedTo(typeof(HttpListenerTimeoutManager))] [assembly: TypeForwardedTo(typeof(HttpRequestHeader))] [assembly: TypeForwardedTo(typeof(HttpResponseHeader))] [assembly: TypeForwardedTo(typeof(HttpStatusCode))] [assembly: TypeForwardedTo(typeof(HttpVersion))] [assembly: TypeForwardedTo(typeof(HttpWebRequest))] [assembly: TypeForwardedTo(typeof(HttpWebResponse))] [assembly: TypeForwardedTo(typeof(IAuthenticationModule))] [assembly: TypeForwardedTo(typeof(ICredentialPolicy))] [assembly: TypeForwardedTo(typeof(ICredentials))] [assembly: TypeForwardedTo(typeof(ICredentialsByHost))] [assembly: TypeForwardedTo(typeof(IPAddress))] [assembly: TypeForwardedTo(typeof(IPEndPoint))] [assembly: TypeForwardedTo(typeof(IPHostEntry))] [assembly: TypeForwardedTo(typeof(IWebProxy))] [assembly: TypeForwardedTo(typeof(IWebProxyScript))] [assembly: TypeForwardedTo(typeof(IWebRequestCreate))] [assembly: TypeForwardedTo(typeof(AlternateView))] [assembly: TypeForwardedTo(typeof(AlternateViewCollection))] [assembly: TypeForwardedTo(typeof(Attachment))] [assembly: TypeForwardedTo(typeof(AttachmentBase))] [assembly: TypeForwardedTo(typeof(AttachmentCollection))] [assembly: TypeForwardedTo(typeof(DeliveryNotificationOptions))] [assembly: TypeForwardedTo(typeof(LinkedResource))] [assembly: TypeForwardedTo(typeof(LinkedResourceCollection))] [assembly: TypeForwardedTo(typeof(MailAddress))] [assembly: TypeForwardedTo(typeof(MailAddressCollection))] [assembly: TypeForwardedTo(typeof(MailMessage))] [assembly: TypeForwardedTo(typeof(MailPriority))] [assembly: TypeForwardedTo(typeof(SendCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(SmtpClient))] [assembly: TypeForwardedTo(typeof(SmtpDeliveryFormat))] [assembly: TypeForwardedTo(typeof(SmtpDeliveryMethod))] [assembly: TypeForwardedTo(typeof(SmtpException))] [assembly: TypeForwardedTo(typeof(SmtpFailedRecipientException))] [assembly: TypeForwardedTo(typeof(SmtpFailedRecipientsException))] [assembly: TypeForwardedTo(typeof(SmtpStatusCode))] [assembly: TypeForwardedTo(typeof(ContentDisposition))] [assembly: TypeForwardedTo(typeof(ContentType))] [assembly: TypeForwardedTo(typeof(DispositionTypeNames))] [assembly: TypeForwardedTo(typeof(MediaTypeNames))] [assembly: TypeForwardedTo(typeof(TransferEncoding))] [assembly: TypeForwardedTo(typeof(NetworkCredential))] [assembly: TypeForwardedTo(typeof(DuplicateAddressDetectionState))] [assembly: TypeForwardedTo(typeof(GatewayIPAddressInformation))] [assembly: TypeForwardedTo(typeof(GatewayIPAddressInformationCollection))] [assembly: TypeForwardedTo(typeof(IcmpV4Statistics))] [assembly: TypeForwardedTo(typeof(IcmpV6Statistics))] [assembly: TypeForwardedTo(typeof(IPAddressCollection))] [assembly: TypeForwardedTo(typeof(IPAddressInformation))] [assembly: TypeForwardedTo(typeof(IPAddressInformationCollection))] [assembly: TypeForwardedTo(typeof(IPGlobalProperties))] [assembly: TypeForwardedTo(typeof(IPGlobalStatistics))] [assembly: TypeForwardedTo(typeof(IPInterfaceProperties))] [assembly: TypeForwardedTo(typeof(IPInterfaceStatistics))] [assembly: TypeForwardedTo(typeof(IPStatus))] [assembly: TypeForwardedTo(typeof(IPv4InterfaceProperties))] [assembly: TypeForwardedTo(typeof(IPv4InterfaceStatistics))] [assembly: TypeForwardedTo(typeof(IPv6InterfaceProperties))] [assembly: TypeForwardedTo(typeof(MulticastIPAddressInformation))] [assembly: TypeForwardedTo(typeof(MulticastIPAddressInformationCollection))] [assembly: TypeForwardedTo(typeof(NetBiosNodeType))] [assembly: TypeForwardedTo(typeof(NetworkAddressChangedEventHandler))] [assembly: TypeForwardedTo(typeof(NetworkAvailabilityChangedEventHandler))] [assembly: TypeForwardedTo(typeof(NetworkAvailabilityEventArgs))] [assembly: TypeForwardedTo(typeof(NetworkChange))] [assembly: TypeForwardedTo(typeof(NetworkInformationException))] [assembly: TypeForwardedTo(typeof(NetworkInterface))] [assembly: TypeForwardedTo(typeof(NetworkInterfaceComponent))] [assembly: TypeForwardedTo(typeof(NetworkInterfaceType))] [assembly: TypeForwardedTo(typeof(OperationalStatus))] [assembly: TypeForwardedTo(typeof(PhysicalAddress))] [assembly: TypeForwardedTo(typeof(Ping))] [assembly: TypeForwardedTo(typeof(PingCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(PingCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(PingException))] [assembly: TypeForwardedTo(typeof(PingOptions))] [assembly: TypeForwardedTo(typeof(PingReply))] [assembly: TypeForwardedTo(typeof(PrefixOrigin))] [assembly: TypeForwardedTo(typeof(ScopeLevel))] [assembly: TypeForwardedTo(typeof(SuffixOrigin))] [assembly: TypeForwardedTo(typeof(TcpConnectionInformation))] [assembly: TypeForwardedTo(typeof(TcpState))] [assembly: TypeForwardedTo(typeof(TcpStatistics))] [assembly: TypeForwardedTo(typeof(UdpStatistics))] [assembly: TypeForwardedTo(typeof(UnicastIPAddressInformation))] [assembly: TypeForwardedTo(typeof(UnicastIPAddressInformationCollection))] [assembly: TypeForwardedTo(typeof(OpenReadCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(OpenReadCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(OpenWriteCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(OpenWriteCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(ProtocolViolationException))] [assembly: TypeForwardedTo(typeof(AuthenticatedStream))] [assembly: TypeForwardedTo(typeof(AuthenticationLevel))] [assembly: TypeForwardedTo(typeof(EncryptionPolicy))] [assembly: TypeForwardedTo(typeof(LocalCertificateSelectionCallback))] [assembly: TypeForwardedTo(typeof(NegotiateStream))] [assembly: TypeForwardedTo(typeof(ProtectionLevel))] [assembly: TypeForwardedTo(typeof(RemoteCertificateValidationCallback))] [assembly: TypeForwardedTo(typeof(ServerCertificateSelectionCallback))] [assembly: TypeForwardedTo(typeof(SslApplicationProtocol))] [assembly: TypeForwardedTo(typeof(SslClientAuthenticationOptions))] [assembly: TypeForwardedTo(typeof(SslPolicyErrors))] [assembly: TypeForwardedTo(typeof(SslServerAuthenticationOptions))] [assembly: TypeForwardedTo(typeof(SslStream))] [assembly: TypeForwardedTo(typeof(SecurityProtocolType))] [assembly: TypeForwardedTo(typeof(ServicePoint))] [assembly: TypeForwardedTo(typeof(ServicePointManager))] [assembly: TypeForwardedTo(typeof(SocketAddress))] [assembly: TypeForwardedTo(typeof(AddressFamily))] [assembly: TypeForwardedTo(typeof(IOControlCode))] [assembly: TypeForwardedTo(typeof(IPPacketInformation))] [assembly: TypeForwardedTo(typeof(IPProtectionLevel))] [assembly: TypeForwardedTo(typeof(IPv6MulticastOption))] [assembly: TypeForwardedTo(typeof(LingerOption))] [assembly: TypeForwardedTo(typeof(MulticastOption))] [assembly: TypeForwardedTo(typeof(NetworkStream))] [assembly: TypeForwardedTo(typeof(ProtocolFamily))] [assembly: TypeForwardedTo(typeof(ProtocolType))] [assembly: TypeForwardedTo(typeof(SelectMode))] [assembly: TypeForwardedTo(typeof(SendPacketsElement))] [assembly: TypeForwardedTo(typeof(Socket))] [assembly: TypeForwardedTo(typeof(SocketAsyncEventArgs))] [assembly: TypeForwardedTo(typeof(SocketAsyncOperation))] [assembly: TypeForwardedTo(typeof(SocketError))] [assembly: TypeForwardedTo(typeof(SocketException))] [assembly: TypeForwardedTo(typeof(SocketFlags))] [assembly: TypeForwardedTo(typeof(SocketInformation))] [assembly: TypeForwardedTo(typeof(SocketInformationOptions))] [assembly: TypeForwardedTo(typeof(SocketOptionLevel))] [assembly: TypeForwardedTo(typeof(SocketOptionName))] [assembly: TypeForwardedTo(typeof(SocketReceiveFromResult))] [assembly: TypeForwardedTo(typeof(SocketReceiveMessageFromResult))] [assembly: TypeForwardedTo(typeof(SocketShutdown))] [assembly: TypeForwardedTo(typeof(SocketTaskExtensions))] [assembly: TypeForwardedTo(typeof(SocketType))] [assembly: TypeForwardedTo(typeof(TcpClient))] [assembly: TypeForwardedTo(typeof(TcpListener))] [assembly: TypeForwardedTo(typeof(TransmitFileOptions))] [assembly: TypeForwardedTo(typeof(UdpClient))] [assembly: TypeForwardedTo(typeof(UdpReceiveResult))] [assembly: TypeForwardedTo(typeof(UnixDomainSocketEndPoint))] [assembly: TypeForwardedTo(typeof(TransportContext))] [assembly: TypeForwardedTo(typeof(UploadDataCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadDataCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(UploadFileCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadFileCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(UploadProgressChangedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadProgressChangedEventHandler))] [assembly: TypeForwardedTo(typeof(UploadStringCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadStringCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(UploadValuesCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadValuesCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(WebClient))] [assembly: TypeForwardedTo(typeof(WebException))] [assembly: TypeForwardedTo(typeof(WebExceptionStatus))] [assembly: TypeForwardedTo(typeof(WebHeaderCollection))] [assembly: TypeForwardedTo(typeof(WebProxy))] [assembly: TypeForwardedTo(typeof(WebRequest))] [assembly: TypeForwardedTo(typeof(WebRequestMethods))] [assembly: TypeForwardedTo(typeof(WebResponse))] [assembly: TypeForwardedTo(typeof(ClientWebSocket))] [assembly: TypeForwardedTo(typeof(ClientWebSocketOptions))] [assembly: TypeForwardedTo(typeof(HttpListenerWebSocketContext))] [assembly: TypeForwardedTo(typeof(ValueWebSocketReceiveResult))] [assembly: TypeForwardedTo(typeof(WebSocket))] [assembly: TypeForwardedTo(typeof(WebSocketCloseStatus))] [assembly: TypeForwardedTo(typeof(WebSocketContext))] [assembly: TypeForwardedTo(typeof(WebSocketError))] [assembly: TypeForwardedTo(typeof(WebSocketException))] [assembly: TypeForwardedTo(typeof(WebSocketMessageType))] [assembly: TypeForwardedTo(typeof(WebSocketReceiveResult))] [assembly: TypeForwardedTo(typeof(WebSocketState))] [assembly: TypeForwardedTo(typeof(WebUtility))] [assembly: TypeForwardedTo(typeof(NetPipeStyleUriParser))] [assembly: TypeForwardedTo(typeof(NetTcpStyleUriParser))] [assembly: TypeForwardedTo(typeof(NewsStyleUriParser))] [assembly: TypeForwardedTo(typeof(NonSerializedAttribute))] [assembly: TypeForwardedTo(typeof(NotFiniteNumberException))] [assembly: TypeForwardedTo(typeof(NotImplementedException))] [assembly: TypeForwardedTo(typeof(NotSupportedException))] [assembly: TypeForwardedTo(typeof(Nullable))] [assembly: TypeForwardedTo(typeof(Nullable<>))] [assembly: TypeForwardedTo(typeof(NullReferenceException))] [assembly: TypeForwardedTo(typeof(BigInteger))] [assembly: TypeForwardedTo(typeof(Complex))] [assembly: TypeForwardedTo(typeof(Matrix3x2))] [assembly: TypeForwardedTo(typeof(Matrix4x4))] [assembly: TypeForwardedTo(typeof(Plane))] [assembly: TypeForwardedTo(typeof(Quaternion))] [assembly: TypeForwardedTo(typeof(Vector))] [assembly: TypeForwardedTo(typeof(Vector<>))] [assembly: TypeForwardedTo(typeof(Vector2))] [assembly: TypeForwardedTo(typeof(Vector3))] [assembly: TypeForwardedTo(typeof(Vector4))] [assembly: TypeForwardedTo(typeof(object))] [assembly: TypeForwardedTo(typeof(ObjectDisposedException))] [assembly: TypeForwardedTo(typeof(ObsoleteAttribute))] [assembly: TypeForwardedTo(typeof(OperatingSystem))] [assembly: TypeForwardedTo(typeof(OperationCanceledException))] [assembly: TypeForwardedTo(typeof(OutOfMemoryException))] [assembly: TypeForwardedTo(typeof(OverflowException))] [assembly: TypeForwardedTo(typeof(ParamArrayAttribute))] [assembly: TypeForwardedTo(typeof(PlatformID))] [assembly: TypeForwardedTo(typeof(PlatformNotSupportedException))] [assembly: TypeForwardedTo(typeof(Predicate<>))] [assembly: TypeForwardedTo(typeof(Progress<>))] [assembly: TypeForwardedTo(typeof(Random))] [assembly: TypeForwardedTo(typeof(Range))] [assembly: TypeForwardedTo(typeof(RankException))] [assembly: TypeForwardedTo(typeof(ReadOnlyMemory<>))] [assembly: TypeForwardedTo(typeof(ReadOnlySpan<>))] [assembly: TypeForwardedTo(typeof(AmbiguousMatchException))] [assembly: TypeForwardedTo(typeof(Assembly))] [assembly: TypeForwardedTo(typeof(AssemblyAlgorithmIdAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyCompanyAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyConfigurationAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyContentType))] [assembly: TypeForwardedTo(typeof(AssemblyCopyrightAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyCultureAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyDefaultAliasAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyDelaySignAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyDescriptionAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyFileVersionAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyFlagsAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyInformationalVersionAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyKeyFileAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyKeyNameAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyMetadataAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyName))] [assembly: TypeForwardedTo(typeof(AssemblyNameFlags))] [assembly: TypeForwardedTo(typeof(AssemblyNameProxy))] [assembly: TypeForwardedTo(typeof(AssemblyProductAttribute))] [assembly: TypeForwardedTo(typeof(AssemblySignatureKeyAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyTitleAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyTrademarkAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyVersionAttribute))] [assembly: TypeForwardedTo(typeof(Binder))] [assembly: TypeForwardedTo(typeof(BindingFlags))] [assembly: TypeForwardedTo(typeof(CallingConventions))] [assembly: TypeForwardedTo(typeof(ConstructorInfo))] [assembly: TypeForwardedTo(typeof(CustomAttributeData))] [assembly: TypeForwardedTo(typeof(CustomAttributeExtensions))] [assembly: TypeForwardedTo(typeof(CustomAttributeFormatException))] [assembly: TypeForwardedTo(typeof(CustomAttributeNamedArgument))] [assembly: TypeForwardedTo(typeof(CustomAttributeTypedArgument))] [assembly: TypeForwardedTo(typeof(DefaultMemberAttribute))] [assembly: TypeForwardedTo(typeof(DispatchProxy))] [assembly: TypeForwardedTo(typeof(AssemblyBuilder))] [assembly: TypeForwardedTo(typeof(AssemblyBuilderAccess))] [assembly: TypeForwardedTo(typeof(ConstructorBuilder))] [assembly: TypeForwardedTo(typeof(CustomAttributeBuilder))] [assembly: TypeForwardedTo(typeof(DynamicILInfo))] [assembly: TypeForwardedTo(typeof(DynamicMethod))] [assembly: TypeForwardedTo(typeof(EnumBuilder))] [assembly: TypeForwardedTo(typeof(EventBuilder))] [assembly: TypeForwardedTo(typeof(EventToken))] [assembly: TypeForwardedTo(typeof(ExceptionHandler))] [assembly: TypeForwardedTo(typeof(FieldBuilder))] [assembly: TypeForwardedTo(typeof(FieldToken))] [assembly: TypeForwardedTo(typeof(FlowControl))] [assembly: TypeForwardedTo(typeof(GenericTypeParameterBuilder))] [assembly: TypeForwardedTo(typeof(ILGenerator))] [assembly: TypeForwardedTo(typeof(Label))] [assembly: TypeForwardedTo(typeof(LocalBuilder))] [assembly: TypeForwardedTo(typeof(MethodBuilder))] [assembly: TypeForwardedTo(typeof(MethodToken))] [assembly: TypeForwardedTo(typeof(ModuleBuilder))] [assembly: TypeForwardedTo(typeof(OpCode))] [assembly: TypeForwardedTo(typeof(OpCodes))] [assembly: TypeForwardedTo(typeof(OpCodeType))] [assembly: TypeForwardedTo(typeof(OperandType))] [assembly: TypeForwardedTo(typeof(PackingSize))] [assembly: TypeForwardedTo(typeof(ParameterBuilder))] [assembly: TypeForwardedTo(typeof(ParameterToken))] [assembly: TypeForwardedTo(typeof(PropertyBuilder))] [assembly: TypeForwardedTo(typeof(PropertyToken))] [assembly: TypeForwardedTo(typeof(SignatureHelper))] [assembly: TypeForwardedTo(typeof(SignatureToken))] [assembly: TypeForwardedTo(typeof(StackBehaviour))] [assembly: TypeForwardedTo(typeof(StringToken))] [assembly: TypeForwardedTo(typeof(TypeBuilder))] [assembly: TypeForwardedTo(typeof(TypeToken))] [assembly: TypeForwardedTo(typeof(EventAttributes))] [assembly: TypeForwardedTo(typeof(EventInfo))] [assembly: TypeForwardedTo(typeof(ExceptionHandlingClause))] [assembly: TypeForwardedTo(typeof(ExceptionHandlingClauseOptions))] [assembly: TypeForwardedTo(typeof(FieldAttributes))] [assembly: TypeForwardedTo(typeof(FieldInfo))] [assembly: TypeForwardedTo(typeof(GenericParameterAttributes))] [assembly: TypeForwardedTo(typeof(ICustomAttributeProvider))] [assembly: TypeForwardedTo(typeof(ImageFileMachine))] [assembly: TypeForwardedTo(typeof(InterfaceMapping))] [assembly: TypeForwardedTo(typeof(IntrospectionExtensions))] [assembly: TypeForwardedTo(typeof(InvalidFilterCriteriaException))] [assembly: TypeForwardedTo(typeof(IReflect))] [assembly: TypeForwardedTo(typeof(IReflectableType))] [assembly: TypeForwardedTo(typeof(LocalVariableInfo))] [assembly: TypeForwardedTo(typeof(ManifestResourceInfo))] [assembly: TypeForwardedTo(typeof(MemberFilter))] [assembly: TypeForwardedTo(typeof(MemberInfo))] [assembly: TypeForwardedTo(typeof(MemberTypes))] [assembly: TypeForwardedTo(typeof(MethodAttributes))] [assembly: TypeForwardedTo(typeof(MethodBase))] [assembly: TypeForwardedTo(typeof(MethodBody))] [assembly: TypeForwardedTo(typeof(MethodImplAttributes))] [assembly: TypeForwardedTo(typeof(MethodInfo))] [assembly: TypeForwardedTo(typeof(Missing))] [assembly: TypeForwardedTo(typeof(Module))] [assembly: TypeForwardedTo(typeof(ModuleResolveEventHandler))] [assembly: TypeForwardedTo(typeof(ObfuscateAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(ObfuscationAttribute))] [assembly: TypeForwardedTo(typeof(ParameterAttributes))] [assembly: TypeForwardedTo(typeof(ParameterInfo))] [assembly: TypeForwardedTo(typeof(ParameterModifier))] [assembly: TypeForwardedTo(typeof(Pointer))] [assembly: TypeForwardedTo(typeof(PortableExecutableKinds))] [assembly: TypeForwardedTo(typeof(ProcessorArchitecture))] [assembly: TypeForwardedTo(typeof(PropertyAttributes))] [assembly: TypeForwardedTo(typeof(PropertyInfo))] [assembly: TypeForwardedTo(typeof(ReflectionContext))] [assembly: TypeForwardedTo(typeof(ReflectionTypeLoadException))] [assembly: TypeForwardedTo(typeof(ResourceAttributes))] [assembly: TypeForwardedTo(typeof(ResourceLocation))] [assembly: TypeForwardedTo(typeof(RuntimeReflectionExtensions))] [assembly: TypeForwardedTo(typeof(StrongNameKeyPair))] [assembly: TypeForwardedTo(typeof(TargetException))] [assembly: TypeForwardedTo(typeof(TargetInvocationException))] [assembly: TypeForwardedTo(typeof(TargetParameterCountException))] [assembly: TypeForwardedTo(typeof(TypeAttributes))] [assembly: TypeForwardedTo(typeof(TypeDelegator))] [assembly: TypeForwardedTo(typeof(TypeFilter))] [assembly: TypeForwardedTo(typeof(TypeInfo))] [assembly: TypeForwardedTo(typeof(ResolveEventArgs))] [assembly: TypeForwardedTo(typeof(ResolveEventHandler))] [assembly: TypeForwardedTo(typeof(IResourceReader))] [assembly: TypeForwardedTo(typeof(IResourceWriter))] [assembly: TypeForwardedTo(typeof(MissingManifestResourceException))] [assembly: TypeForwardedTo(typeof(MissingSatelliteAssemblyException))] [assembly: TypeForwardedTo(typeof(NeutralResourcesLanguageAttribute))] [assembly: TypeForwardedTo(typeof(ResourceManager))] [assembly: TypeForwardedTo(typeof(ResourceReader))] [assembly: TypeForwardedTo(typeof(ResourceSet))] [assembly: TypeForwardedTo(typeof(ResourceWriter))] [assembly: TypeForwardedTo(typeof(SatelliteContractVersionAttribute))] [assembly: TypeForwardedTo(typeof(UltimateResourceFallbackLocation))] [assembly: TypeForwardedTo(typeof(AmbiguousImplementationException))] [assembly: TypeForwardedTo(typeof(AssemblyTargetedPatchBandAttribute))] [assembly: TypeForwardedTo(typeof(AccessedThroughPropertyAttribute))] [assembly: TypeForwardedTo(typeof(AsyncIteratorMethodBuilder))] [assembly: TypeForwardedTo(typeof(AsyncIteratorStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(AsyncMethodBuilderAttribute))] [assembly: TypeForwardedTo(typeof(AsyncStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(AsyncTaskMethodBuilder))] [assembly: TypeForwardedTo(typeof(AsyncTaskMethodBuilder<>))] [assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder))] [assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder<>))] [assembly: TypeForwardedTo(typeof(AsyncVoidMethodBuilder))] [assembly: TypeForwardedTo(typeof(CallConvCdecl))] [assembly: TypeForwardedTo(typeof(CallConvFastcall))] [assembly: TypeForwardedTo(typeof(CallConvStdcall))] [assembly: TypeForwardedTo(typeof(CallConvThiscall))] [assembly: TypeForwardedTo(typeof(CallerFilePathAttribute))] [assembly: TypeForwardedTo(typeof(CallerLineNumberAttribute))] [assembly: TypeForwardedTo(typeof(CallerMemberNameAttribute))] [assembly: TypeForwardedTo(typeof(CallSite))] [assembly: TypeForwardedTo(typeof(CallSite<>))] [assembly: TypeForwardedTo(typeof(CallSiteBinder))] [assembly: TypeForwardedTo(typeof(CallSiteHelpers))] [assembly: TypeForwardedTo(typeof(CompilationRelaxations))] [assembly: TypeForwardedTo(typeof(CompilationRelaxationsAttribute))] [assembly: TypeForwardedTo(typeof(CompilerGeneratedAttribute))] [assembly: TypeForwardedTo(typeof(CompilerGlobalScopeAttribute))] [assembly: TypeForwardedTo(typeof(CompilerMarshalOverride))] [assembly: TypeForwardedTo(typeof(ConditionalWeakTable<, >))] [assembly: TypeForwardedTo(typeof(ConfiguredAsyncDisposable))] [assembly: TypeForwardedTo(typeof(ConfiguredCancelableAsyncEnumerable<>))] [assembly: TypeForwardedTo(typeof(ConfiguredTaskAwaitable))] [assembly: TypeForwardedTo(typeof(ConfiguredTaskAwaitable<>))] [assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable))] [assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable<>))] [assembly: TypeForwardedTo(typeof(ContractHelper))] [assembly: TypeForwardedTo(typeof(CustomConstantAttribute))] [assembly: TypeForwardedTo(typeof(DateTimeConstantAttribute))] [assembly: TypeForwardedTo(typeof(DebugInfoGenerator))] [assembly: TypeForwardedTo(typeof(DecimalConstantAttribute))] [assembly: TypeForwardedTo(typeof(DefaultDependencyAttribute))] [assembly: TypeForwardedTo(typeof(DependencyAttribute))] [assembly: TypeForwardedTo(typeof(DisablePrivateReflectionAttribute))] [assembly: TypeForwardedTo(typeof(DiscardableAttribute))] [assembly: TypeForwardedTo(typeof(DynamicAttribute))] [assembly: TypeForwardedTo(typeof(EnumeratorCancellationAttribute))] [assembly: TypeForwardedTo(typeof(ExtensionAttribute))] [assembly: TypeForwardedTo(typeof(FixedAddressValueTypeAttribute))] [assembly: TypeForwardedTo(typeof(FixedBufferAttribute))] [assembly: TypeForwardedTo(typeof(FormattableStringFactory))] [assembly: TypeForwardedTo(typeof(HasCopySemanticsAttribute))] [assembly: TypeForwardedTo(typeof(IAsyncStateMachine))] [assembly: TypeForwardedTo(typeof(ICriticalNotifyCompletion))] [assembly: TypeForwardedTo(typeof(IndexerNameAttribute))] [assembly: TypeForwardedTo(typeof(INotifyCompletion))] [assembly: TypeForwardedTo(typeof(InternalsVisibleToAttribute))] [assembly: TypeForwardedTo(typeof(IRuntimeVariables))] [assembly: TypeForwardedTo(typeof(IsBoxed))] [assembly: TypeForwardedTo(typeof(IsByRefLikeAttribute))] [assembly: TypeForwardedTo(typeof(IsByValue))] [assembly: TypeForwardedTo(typeof(IsConst))] [assembly: TypeForwardedTo(typeof(IsCopyConstructed))] [assembly: TypeForwardedTo(typeof(IsExplicitlyDereferenced))] [assembly: TypeForwardedTo(typeof(IsImplicitlyDereferenced))] [assembly: TypeForwardedTo(typeof(IsJitIntrinsic))] [assembly: TypeForwardedTo(typeof(IsLong))] [assembly: TypeForwardedTo(typeof(IsPinned))] [assembly: TypeForwardedTo(typeof(IsReadOnlyAttribute))] [assembly: TypeForwardedTo(typeof(IsSignUnspecifiedByte))] [assembly: TypeForwardedTo(typeof(IStrongBox))] [assembly: TypeForwardedTo(typeof(IsUdtReturn))] [assembly: TypeForwardedTo(typeof(IsVolatile))] [assembly: TypeForwardedTo(typeof(IteratorStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(ITuple))] [assembly: TypeForwardedTo(typeof(IUnknownConstantAttribute))] [assembly: TypeForwardedTo(typeof(LoadHint))] [assembly: TypeForwardedTo(typeof(MethodCodeType))] [assembly: TypeForwardedTo(typeof(MethodImplAttribute))] [assembly: TypeForwardedTo(typeof(MethodImplOptions))] [assembly: TypeForwardedTo(typeof(NativeCppClassAttribute))] [assembly: TypeForwardedTo(typeof(ReadOnlyCollectionBuilder<>))] [assembly: TypeForwardedTo(typeof(ReferenceAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(RequiredAttributeAttribute))] [assembly: TypeForwardedTo(typeof(RuleCache<>))] [assembly: TypeForwardedTo(typeof(RuntimeCompatibilityAttribute))] [assembly: TypeForwardedTo(typeof(RuntimeFeature))] [assembly: TypeForwardedTo(typeof(RuntimeHelpers))] [assembly: TypeForwardedTo(typeof(RuntimeWrappedException))] [assembly: TypeForwardedTo(typeof(ScopelessEnumAttribute))] [assembly: TypeForwardedTo(typeof(SpecialNameAttribute))] [assembly: TypeForwardedTo(typeof(StateMachineAttribute))] [assembly: TypeForwardedTo(typeof(StringFreezingAttribute))] [assembly: TypeForwardedTo(typeof(StrongBox<>))] [assembly: TypeForwardedTo(typeof(SuppressIldasmAttribute))] [assembly: TypeForwardedTo(typeof(SwitchExpressionException))] [assembly: TypeForwardedTo(typeof(TaskAwaiter))] [assembly: TypeForwardedTo(typeof(TaskAwaiter<>))] [assembly: TypeForwardedTo(typeof(TupleElementNamesAttribute))] [assembly: TypeForwardedTo(typeof(TypeForwardedFromAttribute))] [assembly: TypeForwardedTo(typeof(TypeForwardedToAttribute))] [assembly: TypeForwardedTo(typeof(UnsafeValueTypeAttribute))] [assembly: TypeForwardedTo(typeof(ValueTaskAwaiter))] [assembly: TypeForwardedTo(typeof(ValueTaskAwaiter<>))] [assembly: TypeForwardedTo(typeof(YieldAwaitable))] [assembly: TypeForwardedTo(typeof(Cer))] [assembly: TypeForwardedTo(typeof(Consistency))] [assembly: TypeForwardedTo(typeof(CriticalFinalizerObject))] [assembly: TypeForwardedTo(typeof(PrePrepareMethodAttribute))] [assembly: TypeForwardedTo(typeof(ReliabilityContractAttribute))] [assembly: TypeForwardedTo(typeof(ExceptionDispatchInfo))] [assembly: TypeForwardedTo(typeof(FirstChanceExceptionEventArgs))] [assembly: TypeForwardedTo(typeof(HandleProcessCorruptedStateExceptionsAttribute))] [assembly: TypeForwardedTo(typeof(GCLargeObjectHeapCompactionMode))] [assembly: TypeForwardedTo(typeof(GCLatencyMode))] [assembly: TypeForwardedTo(typeof(GCSettings))] [assembly: TypeForwardedTo(typeof(AllowReversePInvokeCallsAttribute))] [assembly: TypeForwardedTo(typeof(Architecture))] [assembly: TypeForwardedTo(typeof(ArrayWithOffset))] [assembly: TypeForwardedTo(typeof(AutomationProxyAttribute))] [assembly: TypeForwardedTo(typeof(BestFitMappingAttribute))] [assembly: TypeForwardedTo(typeof(BStrWrapper))] [assembly: TypeForwardedTo(typeof(CallingConvention))] [assembly: TypeForwardedTo(typeof(CharSet))] [assembly: TypeForwardedTo(typeof(ClassInterfaceAttribute))] [assembly: TypeForwardedTo(typeof(ClassInterfaceType))] [assembly: TypeForwardedTo(typeof(CoClassAttribute))] [assembly: TypeForwardedTo(typeof(ComAliasNameAttribute))] [assembly: TypeForwardedTo(typeof(ComAwareEventInfo))] [assembly: TypeForwardedTo(typeof(ComCompatibleVersionAttribute))] [assembly: TypeForwardedTo(typeof(ComConversionLossAttribute))] [assembly: TypeForwardedTo(typeof(ComDefaultInterfaceAttribute))] [assembly: TypeForwardedTo(typeof(ComEventInterfaceAttribute))] [assembly: TypeForwardedTo(typeof(ComEventsHelper))] [assembly: TypeForwardedTo(typeof(COMException))] [assembly: TypeForwardedTo(typeof(ComImportAttribute))] [assembly: TypeForwardedTo(typeof(ComInterfaceType))] [assembly: TypeForwardedTo(typeof(ComMemberType))] [assembly: TypeForwardedTo(typeof(ComRegisterFunctionAttribute))] [assembly: TypeForwardedTo(typeof(ComSourceInterfacesAttribute))] [assembly: TypeForwardedTo(typeof(ADVF))] [assembly: TypeForwardedTo(typeof(BIND_OPTS))] [assembly: TypeForwardedTo(typeof(BINDPTR))] [assembly: TypeForwardedTo(typeof(CALLCONV))] [assembly: TypeForwardedTo(typeof(CONNECTDATA))] [assembly: TypeForwardedTo(typeof(DATADIR))] [assembly: TypeForwardedTo(typeof(DESCKIND))] [assembly: TypeForwardedTo(typeof(DISPPARAMS))] [assembly: TypeForwardedTo(typeof(DVASPECT))] [assembly: TypeForwardedTo(typeof(ELEMDESC))] [assembly: TypeForwardedTo(typeof(EXCEPINFO))] [assembly: TypeForwardedTo(typeof(FILETIME))] [assembly: TypeForwardedTo(typeof(FORMATETC))] [assembly: TypeForwardedTo(typeof(FUNCDESC))] [assembly: TypeForwardedTo(typeof(FUNCFLAGS))] [assembly: TypeForwardedTo(typeof(FUNCKIND))] [assembly: TypeForwardedTo(typeof(IAdviseSink))] [assembly: TypeForwardedTo(typeof(IBindCtx))] [assembly: TypeForwardedTo(typeof(IConnectionPoint))] [assembly: TypeForwardedTo(typeof(IConnectionPointContainer))] [assembly: TypeForwardedTo(typeof(IDataObject))] [assembly: TypeForwardedTo(typeof(IDLDESC))] [assembly: TypeForwardedTo(typeof(IDLFLAG))] [assembly: TypeForwardedTo(typeof(IEnumConnectionPoints))] [assembly: TypeForwardedTo(typeof(IEnumConnections))] [assembly: TypeForwardedTo(typeof(IEnumFORMATETC))] [assembly: TypeForwardedTo(typeof(IEnumMoniker))] [assembly: TypeForwardedTo(typeof(IEnumSTATDATA))] [assembly: TypeForwardedTo(typeof(IEnumString))] [assembly: TypeForwardedTo(typeof(IEnumVARIANT))] [assembly: TypeForwardedTo(typeof(IMoniker))] [assembly: TypeForwardedTo(typeof(IMPLTYPEFLAGS))] [assembly: TypeForwardedTo(typeof(INVOKEKIND))] [assembly: TypeForwardedTo(typeof(IPersistFile))] [assembly: TypeForwardedTo(typeof(IRunningObjectTable))] [assembly: TypeForwardedTo(typeof(IStream))] [assembly: TypeForwardedTo(typeof(ITypeComp))] [assembly: TypeForwardedTo(typeof(ITypeInfo))] [assembly: TypeForwardedTo(typeof(ITypeInfo2))] [assembly: TypeForwardedTo(typeof(ITypeLib))] [assembly: TypeForwardedTo(typeof(ITypeLib2))] [assembly: TypeForwardedTo(typeof(LIBFLAGS))] [assembly: TypeForwardedTo(typeof(PARAMDESC))] [assembly: TypeForwardedTo(typeof(PARAMFLAG))] [assembly: TypeForwardedTo(typeof(STATDATA))] [assembly: TypeForwardedTo(typeof(STATSTG))] [assembly: TypeForwardedTo(typeof(STGMEDIUM))] [assembly: TypeForwardedTo(typeof(SYSKIND))] [assembly: TypeForwardedTo(typeof(TYMED))] [assembly: TypeForwardedTo(typeof(TYPEATTR))] [assembly: TypeForwardedTo(typeof(TYPEDESC))] [assembly: TypeForwardedTo(typeof(TYPEFLAGS))] [assembly: TypeForwardedTo(typeof(TYPEKIND))] [assembly: TypeForwardedTo(typeof(TYPELIBATTR))] [assembly: TypeForwardedTo(typeof(VARDESC))] [assembly: TypeForwardedTo(typeof(VARFLAGS))] [assembly: TypeForwardedTo(typeof(VARKIND))] [assembly: TypeForwardedTo(typeof(ComUnregisterFunctionAttribute))] [assembly: TypeForwardedTo(typeof(ComVisibleAttribute))] [assembly: TypeForwardedTo(typeof(CriticalHandle))] [assembly: TypeForwardedTo(typeof(CurrencyWrapper))] [assembly: TypeForwardedTo(typeof(CustomQueryInterfaceMode))] [assembly: TypeForwardedTo(typeof(CustomQueryInterfaceResult))] [assembly: TypeForwardedTo(typeof(DefaultCharSetAttribute))] [assembly: TypeForwardedTo(typeof(DefaultDllImportSearchPathsAttribute))] [assembly: TypeForwardedTo(typeof(DefaultParameterValueAttribute))] [assembly: TypeForwardedTo(typeof(DispatchWrapper))] [assembly: TypeForwardedTo(typeof(DispIdAttribute))] [assembly: TypeForwardedTo(typeof(DllImportAttribute))] [assembly: TypeForwardedTo(typeof(DllImportSearchPath))] [assembly: TypeForwardedTo(typeof(ErrorWrapper))] [assembly: TypeForwardedTo(typeof(ExternalException))] [assembly: TypeForwardedTo(typeof(FieldOffsetAttribute))] [assembly: TypeForwardedTo(typeof(GCHandle))] [assembly: TypeForwardedTo(typeof(GCHandleType))] [assembly: TypeForwardedTo(typeof(GuidAttribute))] [assembly: TypeForwardedTo(typeof(HandleCollector))] [assembly: TypeForwardedTo(typeof(HandleRef))] [assembly: TypeForwardedTo(typeof(ICustomAdapter))] [assembly: TypeForwardedTo(typeof(ICustomFactory))] [assembly: TypeForwardedTo(typeof(ICustomMarshaler))] [assembly: TypeForwardedTo(typeof(ICustomQueryInterface))] [assembly: TypeForwardedTo(typeof(ImportedFromTypeLibAttribute))] [assembly: TypeForwardedTo(typeof(InAttribute))] [assembly: TypeForwardedTo(typeof(InterfaceTypeAttribute))] [assembly: TypeForwardedTo(typeof(InvalidComObjectException))] [assembly: TypeForwardedTo(typeof(InvalidOleVariantTypeException))] [assembly: TypeForwardedTo(typeof(LayoutKind))] [assembly: TypeForwardedTo(typeof(LCIDConversionAttribute))] [assembly: TypeForwardedTo(typeof(ManagedToNativeComInteropStubAttribute))] [assembly: TypeForwardedTo(typeof(Marshal))] [assembly: TypeForwardedTo(typeof(MarshalAsAttribute))] [assembly: TypeForwardedTo(typeof(MarshalDirectiveException))] [assembly: TypeForwardedTo(typeof(MemoryMarshal))] [assembly: TypeForwardedTo(typeof(OptionalAttribute))] [assembly: TypeForwardedTo(typeof(OSPlatform))] [assembly: TypeForwardedTo(typeof(OutAttribute))] [assembly: TypeForwardedTo(typeof(PreserveSigAttribute))] [assembly: TypeForwardedTo(typeof(PrimaryInteropAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(ProgIdAttribute))] [assembly: TypeForwardedTo(typeof(RuntimeEnvironment))] [assembly: TypeForwardedTo(typeof(RuntimeInformation))] [assembly: TypeForwardedTo(typeof(SafeArrayRankMismatchException))] [assembly: TypeForwardedTo(typeof(SafeArrayTypeMismatchException))] [assembly: TypeForwardedTo(typeof(SafeBuffer))] [assembly: TypeForwardedTo(typeof(SafeHandle))] [assembly: TypeForwardedTo(typeof(SEHException))] [assembly: TypeForwardedTo(typeof(SequenceMarshal))] [assembly: TypeForwardedTo(typeof(StructLayoutAttribute))] [assembly: TypeForwardedTo(typeof(TypeIdentifierAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibFuncAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibFuncFlags))] [assembly: TypeForwardedTo(typeof(TypeLibImportClassAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibTypeAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibTypeFlags))] [assembly: TypeForwardedTo(typeof(TypeLibVarAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibVarFlags))] [assembly: TypeForwardedTo(typeof(TypeLibVersionAttribute))] [assembly: TypeForwardedTo(typeof(UnknownWrapper))] [assembly: TypeForwardedTo(typeof(UnmanagedFunctionPointerAttribute))] [assembly: TypeForwardedTo(typeof(UnmanagedType))] [assembly: TypeForwardedTo(typeof(VarEnum))] [assembly: TypeForwardedTo(typeof(VariantWrapper))] [assembly: TypeForwardedTo(typeof(MemoryFailPoint))] [assembly: TypeForwardedTo(typeof(CollectionDataContractAttribute))] [assembly: TypeForwardedTo(typeof(ContractNamespaceAttribute))] [assembly: TypeForwardedTo(typeof(DataContractAttribute))] [assembly: TypeForwardedTo(typeof(DataContractResolver))] [assembly: TypeForwardedTo(typeof(DataContractSerializer))] [assembly: TypeForwardedTo(typeof(DataContractSerializerExtensions))] [assembly: TypeForwardedTo(typeof(DataContractSerializerSettings))] [assembly: TypeForwardedTo(typeof(DataMemberAttribute))] [assembly: TypeForwardedTo(typeof(DateTimeFormat))] [assembly: TypeForwardedTo(typeof(EmitTypeInformation))] [assembly: TypeForwardedTo(typeof(EnumMemberAttribute))] [assembly: TypeForwardedTo(typeof(ExportOptions))] [assembly: TypeForwardedTo(typeof(ExtensionDataObject))] [assembly: TypeForwardedTo(typeof(Formatter))] [assembly: TypeForwardedTo(typeof(FormatterConverter))] [assembly: TypeForwardedTo(typeof(BinaryFormatter))] [assembly: TypeForwardedTo(typeof(FormatterAssemblyStyle))] [assembly: TypeForwardedTo(typeof(FormatterTypeStyle))] [assembly: TypeForwardedTo(typeof(IFieldInfo))] [assembly: TypeForwardedTo(typeof(TypeFilterLevel))] [assembly: TypeForwardedTo(typeof(FormatterServices))] [assembly: TypeForwardedTo(typeof(IDeserializationCallback))] [assembly: TypeForwardedTo(typeof(IExtensibleDataObject))] [assembly: TypeForwardedTo(typeof(IFormatter))] [assembly: TypeForwardedTo(typeof(IFormatterConverter))] [assembly: TypeForwardedTo(typeof(IgnoreDataMemberAttribute))] [assembly: TypeForwardedTo(typeof(InvalidDa
deps/Newtonsoft.Json.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.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.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(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [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 Standard 2.0")] [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) { 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; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling
deps/OllamaSharp.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Microsoft.CodeAnalysis; using Microsoft.Extensions.AI; using OllamaSharp.AsyncEnumerableExtensions; using OllamaSharp.MicrosoftAi; using OllamaSharp.Models; using OllamaSharp.Models.Chat; using OllamaSharp.Models.Chat.Converter; using OllamaSharp.Models.Exceptions; using OllamaSharp.Tools; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: InternalsVisibleTo("Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a171f1618f5d4caf94ac5e1323ed80e3e2b686509951a686b66491108cf673ec16a8507ae06e7a4cc81ac14b057659e84401f1d56e17023037c160f4e3e35f6de81c479a778c78a184d15b4ccce943d2202eeeaec0c63028e1061ef5ca236b7a7d7fc52eef66d1fc65ebb89560b8dffb2353dfd2394ef2b1ec41bc3accab7df0")] [assembly: AssemblyCompany("Andreas Wäscher, Milkey Tan, Jerrett Davis")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Andreas Wäscher")] [assembly: AssemblyDescription("The easiest way to use the Ollama API in .NET")] [assembly: AssemblyFileVersion("5.4.8.0")] [assembly: AssemblyInformationalVersion("5.4.8+58db507dcbf4de937b8c774fd59dd27b47cfb814")] [assembly: AssemblyProduct("OllamaSharp")] [assembly: AssemblyTitle("OllamaSharp")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/awaescher/OllamaSharp")] [assembly: AssemblyVersion("5.4.8.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } internal static class IsExternalInit { } } namespace OllamaSharp { public static class IAsyncEnumerableExtensions { public static Task<string> StreamToEndAsync(this IAsyncEnumerable<string> stream, Action<string>? itemCallback = null) { return stream.StreamToEndAsync(new StringAppender(), itemCallback); } public static Task<GenerateDoneResponseStream?> StreamToEndAsync(this IAsyncEnumerable<GenerateResponseStream?> stream, Action<GenerateResponseStream?>? itemCallback = null) { return stream.StreamToEndAsync<GenerateResponseStream, GenerateDoneResponseStream>(new GenerateResponseStreamAppender(), itemCallback); } public static Task<ChatDoneResponseStream?> StreamToEndAsync(this IAsyncEnumerable<ChatResponseStream?> stream, Action<ChatResponseStream?>? itemCallback = null) { return stream.StreamToEndAsync<ChatResponseStream, ChatDoneResponseStream>(new ChatResponseStreamAppender(), itemCallback); } internal static async Task<Tout> StreamToEndAsync<Tin, Tout>(this IAsyncEnumerable<Tin> stream, IAppender<Tin, Tout> appender, Action<Tin>? itemCallback = null) { await foreach (Tin item in stream.ConfigureAwait(continueOnCapturedContext: false)) { appender.Append(item); itemCallback?.Invoke(item); } return appender.Complete(); } public static Task<ChatResponseUpdate?> StreamToEndAsync(this IAsyncEnumerable<ChatResponseUpdate?> stream, Action<ChatResponseUpdate?>? itemCallback = null) { return stream.StreamToEndAsync<ChatResponseUpdate, ChatResponseUpdate>(new ChatResponseUpdateAppender(), itemCallback); } } internal static class ByteArrayExtensions { public static string ToBase64(this IEnumerable<byte> bytes) { return Convert.ToBase64String(bytes.ToArray()); } public static IEnumerable<string>? ToBase64(this IEnumerable<IEnumerable<byte>>? byteArrays) { return byteArrays?.Select((IEnumerable<byte> bytes) => bytes.ToBase64()); } } public class Chat { [CompilerGenerated] private sealed class <SendAsAsync>d__45 : IAsyncEnumerable<string>, IAsyncEnumerator<string>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private string <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; private object format; public object <>3__format; public Chat <>4__this; private ChatRole role; public ChatRole <>3__role; private string message; public string <>3__message; private IEnumerable<string> imagesAsBase64; public IEnumerable<string> <>3__imagesAsBase64; private IEnumerable<object> tools; public IEnumerable<object> <>3__tools; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private MessageBuilder <messageBuilder>5__2; private ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator <>7__wrap2; private object <>7__wrap3; private int <>7__wrap4; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2; private List<Message> <toolResultMessages>5__6; private IEnumerator<Message.ToolCall> <>7__wrap6; private Message.ToolCall <toolCall>5__8; private ConfiguredTaskAwaitable<ToolResult>.ConfiguredTaskAwaiter <>u__3; private ConfiguredCancelableAsyncEnumerable<string>.Enumerator <>7__wrap8; string IAsyncEnumerator<string>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <SendAsAsync>d__45(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; Chat chat = <>4__this; try { ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter; object obj; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); if (format is CancellationToken) { throw new NotSupportedException("Argument \"format\" cannot be of type CancellationToken. Make sure you use the correct method overload of ChatSendAsync() or ChatSendAsAsync()."); } chat.Messages.Add(new Message(role, this.message, imagesAsBase64?.ToArray())); ChatRequest request = new ChatRequest { Messages = chat.Messages, Model = chat.Model, Stream = true, Tools = tools, Format = format, Options = chat.Options, Think = chat.Think }; <messageBuilder>5__2 = new MessageBuilder(); <>7__wrap2 = chat.Client.ChatAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap3 = null; <>7__wrap4 = 0; goto case -4; } goto end_IL_000e; case -4: case 0: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2; if (num != -4) { if (num != 0) { goto IL_0211; } awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_027c; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_0211; } goto end_IL_0130; IL_0211: <>2__current = null; awaiter2 = <>7__wrap2.MoveNextAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; <SendAsAsync>d__45 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_027c; IL_027c: if (awaiter2.GetResult()) { ChatResponseStream current = <>7__wrap2.Current; if (current != null) { <messageBuilder>5__2.Append(current); ThinkValue? think = chat.Think; if (!(think.HasValue ? ((bool?)think.GetValueOrDefault()) : null).GetValueOrDefault() || string.IsNullOrEmpty(current.Message.Thinking)) { <>2__current = current.Message.Content ?? string.Empty; num = (<>1__state = -4); goto IL_083e; } chat.OnThink?.Invoke(chat, current.Message.Thinking); } goto IL_0211; } end_IL_0130:; } catch (object obj2) { <>7__wrap3 = obj2; } <>2__current = null; awaiter = <>7__wrap2.DisposeAsync().GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter; <SendAsAsync>d__45 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_0301; case 1: awaiter = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_0301; case 2: try { if (num != 2) { goto IL_04e3; } ConfiguredTaskAwaitable<ToolResult>.ConfiguredTaskAwaiter awaiter3 = <>u__3; <>u__3 = default(ConfiguredTaskAwaitable<ToolResult>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_0489; IL_04e3: if (<>7__wrap6.MoveNext()) { <toolCall>5__8 = <>7__wrap6.Current; chat.OnToolCall?.Invoke(chat, <toolCall>5__8); <>2__current = null; awaiter3 = chat.ToolInvoker.InvokeAsync(<toolCall>5__8, tools ?? Array.Empty<object>(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter3.IsCompleted) { num = (<>1__state = 2); <>u__3 = awaiter3; <SendAsAsync>d__45 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine); return; } goto IL_0489; } goto end_IL_03c8; IL_0489: ToolResult result = awaiter3.GetResult(); <toolResultMessages>5__6.Add(new Message(ChatRole.Tool, $"Tool: {StringifyToolCall(<toolCall>5__8)}:\nResult: {result.Result}")); chat.OnToolResult?.Invoke(chat, result); <toolCall>5__8 = null; goto IL_04e3; end_IL_03c8:; } finally { if (num == -1 && <>7__wrap6 != null) { <>7__wrap6.Dispose(); } } if (!<>w__disposeMode) { <>7__wrap6 = null; if (!<toolResultMessages>5__6.Any()) { break; } chat.Messages.AddRange(<toolResultMessages>5__6.Take(<toolResultMessages>5__6.Count - 1)); <>7__wrap8 = chat.SendAsAsync(ChatRole.Tool, <toolResultMessages>5__6.Last().Content ?? "", tools, null, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap3 = null; <>7__wrap4 = 0; goto case -5; } goto end_IL_000e; case -5: case 3: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2; if (num != -5) { if (num != 3) { goto IL_05f2; } awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_065d; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_05f2; } goto end_IL_05aa; IL_05f2: <>2__current = null; awaiter2 = <>7__wrap8.MoveNextAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 3); <>u__1 = awaiter2; <SendAsAsync>d__45 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_065d; IL_065d: if (awaiter2.GetResult()) { string current2 = <>7__wrap8.Current; <>2__current = current2; num = (<>1__state = -5); goto IL_083e; } end_IL_05aa:; } catch (object obj2) { <>7__wrap3 = obj2; } <>2__current = null; awaiter = <>7__wrap8.DisposeAsync().GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 4); <>u__2 = awaiter; <SendAsAsync>d__45 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_06e2; case 4: { awaiter = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_06e2; } IL_06e2: awaiter.GetResult(); obj = <>7__wrap3; if (obj != null) { ExceptionDispatchInfo.Capture((obj as Exception) ?? throw obj).Throw(); } _ = <>7__wrap4; if (!<>w__disposeMode) { <>7__wrap3 = null; <>7__wrap8 = default(ConfiguredCancelableAsyncEnumerable<string>.Enumerator); break; } goto end_IL_000e; IL_0301: awaiter.GetResult(); obj = <>7__wrap3; if (obj != null) { ExceptionDispatchInfo.Capture((obj as Exception) ?? throw obj).Throw(); } _ = <>7__wrap4; if (!<>w__disposeMode) { <>7__wrap3 = null; <>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); if (<messageBuilder>5__2.HasValue) { Message message = <messageBuilder>5__2.ToMessage(); chat.Messages.Add(message); if (chat.ToolInvoker != null) { IEnumerable<Message.ToolCall>? toolCalls = message.ToolCalls; if (toolCalls != null && toolCalls.Any() && chat.AllowRecursiveToolCalls) { <toolResultMessages>5__6 = new List<Message>(); <>7__wrap6 = message.ToolCalls.GetEnumerator(); goto case 2; } } } } goto end_IL_000e; } <toolResultMessages>5__6 = null; end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <messageBuilder>5__2 = null; <>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); <>7__wrap3 = null; <toolResultMessages>5__6 = null; <>7__wrap6 = null; <toolCall>5__8 = null; <>7__wrap8 = default(ConfiguredCancelableAsyncEnumerable<string>.Enumerator); if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetException(exception); return; } <>1__state = -2; <messageBuilder>5__2 = null; <>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); <>7__wrap3 = null; <toolResultMessages>5__6 = null; <>7__wrap6 = null; <toolCall>5__8 = null; <>7__wrap8 = default(ConfiguredCancelableAsyncEnumerable<string>.Enumerator); if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_083e: <>v__promiseOfValueOrEnd.SetResult(result: true); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } [DebuggerHidden] IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <SendAsAsync>d__45 <SendAsAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <SendAsAsync>d__ = this; } else { <SendAsAsync>d__ = new <SendAsAsync>d__45(-3) { <>4__this = <>4__this }; } <SendAsAsync>d__.role = <>3__role; <SendAsAsync>d__.message = <>3__message; <SendAsAsync>d__.tools = <>3__tools; <SendAsAsync>d__.imagesAsBase64 = <>3__imagesAsBase64; <SendAsAsync>d__.format = <>3__format; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <SendAsAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <SendAsAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <SendAsAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <SendAsAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<string>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <SendAsAsync>d__45 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); short version = <>v__promiseOfValueOrEnd.Version; if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded) { return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version)); } return new ValueTask<bool>(this, version); } [DebuggerHidden] bool IValueTaskSource<bool>.GetResult(short token) { return <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] void IValueTaskSource.GetResult(short token) { <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] ValueTask IAsyncDisposable.DisposeAsync() { if (<>1__state >= -1) { throw new NotSupportedException(); } if (<>1__state == -2) { return default(ValueTask); } <>w__disposeMode = true; <>v__promiseOfValueOrEnd.Reset(); <SendAsAsync>d__45 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } public List<Message> Messages { get; set; } = new List<Message>(); public IOllamaApiClient Client { get; } public string Model { get; set; } public RequestOptions? Options { get; set; } public IToolInvoker ToolInvoker { get; set; } = new DefaultToolInvoker(); public ThinkValue? Think { get; set; } public bool AllowRecursiveToolCalls { get; set; } = true; public event EventHandler<string>? OnThink; public event EventHandler<Message.ToolCall>? OnToolCall; public event EventHandler<ToolResult>? OnToolResult; public Chat(IOllamaApiClient client) { Client = client ?? throw new ArgumentNullException("client"); Model = Client.SelectedModel; } public Chat(IOllamaApiClient client, string systemPrompt) : this(client) { if (!string.IsNullOrWhiteSpace(systemPrompt)) { Messages.Add(new Message(ChatRole.System, systemPrompt)); } } public IAsyncEnumerable<string> SendAsync(string message, CancellationToken cancellationToken = default(CancellationToken)) { return SendAsync(message, null, null, null, cancellationToken); } public IAsyncEnumerable<string> SendAsync(string message, IEnumerable<IEnumerable<byte>>? imagesAsBytes, CancellationToken cancellationToken = default(CancellationToken)) { return SendAsync(message, imagesAsBytes?.ToBase64(), cancellationToken); } public IAsyncEnumerable<string> SendAsync(string message, IEnumerable<string>? imagesAsBase64, CancellationToken cancellationToken = default(CancellationToken)) { return SendAsync(message, null, imagesAsBase64, null, cancellationToken); } public IAsyncEnumerable<string> SendAsync(string message, IEnumerable<object>? tools, IEnumerable<string>? imagesAsBase64 = null, object? format = null, CancellationToken cancellationToken = default(CancellationToken)) { return SendAsAsync(ChatRole.User, message, tools, imagesAsBase64, format, cancellationToken); } public IAsyncEnumerable<string> SendAsAsync(ChatRole role, string message, CancellationToken cancellationToken = default(CancellationToken)) { return SendAsAsync(role, message, null, null, null, cancellationToken); } public IAsyncEnumerable<string> SendAsAsync(ChatRole role, string message, IEnumerable<IEnumerable<byte>>? imagesAsBytes, CancellationToken cancellationToken = default(CancellationToken)) { return SendAsAsync(role, message, imagesAsBytes?.ToBase64(), cancellationToken); } public IAsyncEnumerable<string> SendAsAsync(ChatRole role, string message, IEnumerable<string>? imagesAsBase64, CancellationToken cancellationToken = default(CancellationToken)) { return SendAsAsync(role, message, null, imagesAsBase64, null, cancellationToken); } [AsyncIteratorStateMachine(typeof(<SendAsAsync>d__45))] public IAsyncEnumerable<string> SendAsAsync(ChatRole role, string message, IEnumerable<object>? tools, IEnumerable<string>? imagesAsBase64 = null, object? format = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { return new <SendAsAsync>d__45(-2) { <>4__this = this, <>3__role = role, <>3__message = message, <>3__tools = tools, <>3__imagesAsBase64 = imagesAsBase64, <>3__format = format, <>3__cancellationToken = cancellationToken }; } private static string StringifyToolCall(Message.ToolCall toolCall) { return (toolCall.Function?.Name ?? "(unnamed tool)") + "(" + string.Join(", ", toolCall.Function?.Arguments?.Select((KeyValuePair<string, object> kvp) => $"{kvp.Key}: {kvp.Value}") ?? Array.Empty<string>()) + ")"; } } internal static class CollectionExtensions { public static void AddRangeIfNotNull<T>(this List<T> list, IEnumerable<T>? items) { if (items != null) { list.AddRange(items); } } public static void ForEachItem<T>(this IEnumerable<T> collection, Action<T> action) { foreach (T item in collection) { action(item); } } } internal static class HttpRequestMessageExtensions { public static void ApplyCustomHeaders(this HttpRequestMessage requestMessage, Dictionary<string, string> headers, OllamaRequest? ollamaRequest) { HttpRequestMessage requestMessage2 = requestMessage; headers.Concat(ollamaRequest?.CustomHeaders ?? new Dictionary<string, string>()).ForEachItem<KeyValuePair<string, string>>(delegate(KeyValuePair<string, string> header) { requestMessage2.Headers.AddOrUpdateHeaderValue(header.Key, header.Value); }); } private static void AddOrUpdateHeaderValue(this HttpRequestHeaders requestMessageHeaders, string headerKey, string headerValue) { requestMessageHeaders.Remove(headerKey); requestMessageHeaders.Add(headerKey, headerValue); } } public interface IOllamaApiClient { Uri Uri { get; } string SelectedModel { get; set; } IAsyncEnumerable<ChatResponseStream?> ChatAsync(ChatRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)); Task CopyModelAsync(CopyModelRequest request, CancellationToken cancellationToken = default(CancellationToken)); IAsyncEnumerable<CreateModelResponse?> CreateModelAsync(CreateModelRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)); Task DeleteModelAsync(DeleteModelRequest request, CancellationToken cancellationToken = default(CancellationToken)); Task<EmbedResponse> EmbedAsync(EmbedRequest request, CancellationToken cancellationToken = default(CancellationToken)); Task<IEnumerable<Model>> ListLocalModelsAsync(CancellationToken cancellationToken = default(CancellationToken)); Task<IEnumerable<RunningModel>> ListRunningModelsAsync(CancellationToken cancellationToken = default(CancellationToken)); IAsyncEnumerable<PullModelResponse?> PullModelAsync(PullModelRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)); IAsyncEnumerable<PushModelResponse?> PushModelAsync(PushModelRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)); Task<ShowModelResponse> ShowModelAsync(ShowModelRequest request, CancellationToken cancellationToken = default(CancellationToken)); IAsyncEnumerable<GenerateResponseStream?> GenerateAsync(GenerateRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)); Task<bool> IsRunningAsync(CancellationToken cancellationToken = default(CancellationToken)); Task<string> GetVersionAsync(CancellationToken cancellationToken = default(CancellationToken)); Task PushBlobAsync(string digest, byte[] bytes, CancellationToken cancellationToken = default(CancellationToken)); Task<bool> IsBlobExistsAsync(string digest, CancellationToken cancellationToken = default(CancellationToken)); } public static class ChatOptionsExtensions { public static ChatOptions AddOllamaOption(this ChatOptions chatOptions, OllamaOption option, object? value) { //IL_000b: 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: Expected O, but got Unknown //IL_0017: Expected O, but got Unknown if (chatOptions.AdditionalProperties == null) { AdditionalPropertiesDictionary val = new AdditionalPropertiesDictionary(); AdditionalPropertiesDictionary val2 = val; chatOptions.AdditionalProperties = val; } ((AdditionalPropertiesDictionary<object>)(object)chatOptions.AdditionalProperties)[option.Name] = value; return chatOptions; } } public class OllamaApiClient : IOllamaApiClient, IChatClient, IDisposable, IEmbeddingGenerator<string, Embedding<float>>, IEmbeddingGenerator { public class Configuration { public Uri Uri { get; set; } public string Model { get; set; } public JsonSerializerContext? JsonSerializerContext { get; set; } } [CompilerGenerated] private sealed class <ChatAsync>d__34 : IAsyncEnumerable<ChatResponseStream>, IAsyncEnumerator<ChatResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private ChatResponseStream <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; private ChatRequest request; public ChatRequest <>3__request; public OllamaApiClient <>4__this; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private HttpRequestMessage <requestMessage>5__2; private HttpResponseMessage <response>5__3; private ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter <>u__1; private ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator <>7__wrap3; private object <>7__wrap4; private int <>7__wrap5; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__2; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__3; ChatResponseStream IAsyncEnumerator<ChatResponseStream>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ChatAsync>d__34(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; OllamaApiClient ollamaApiClient = <>4__this; try { switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); if (string.IsNullOrEmpty(request.Model)) { request.Model = ollamaApiClient.SelectedModel; } <requestMessage>5__2 = new HttpRequestMessage(HttpMethod.Post, "api/chat"); break; } goto end_IL_000e; case -4: case 0: case 1: case 2: break; } try { ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter awaiter; HttpResponseMessage result; switch (num) { default: { <requestMessage>5__2.Content = new StringContent(JsonSerializer.Serialize(request, ollamaApiClient.OutgoingJsonSerializerOptions), Encoding.UTF8, "application/json"); HttpCompletionOption completionOption = (request.Stream ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead); <>2__current = null; awaiter = ollamaApiClient.SendToOllamaAsync(<requestMessage>5__2, request, completionOption, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; <ChatAsync>d__34 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_0163; } case 0: awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_0163; case -4: case 1: case 2: break; IL_0163: result = awaiter.GetResult(); <response>5__3 = result; break; } try { ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter2; if (num != -4 && num != 1) { if (num == 2) { awaiter2 = <>u__3; <>u__3 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_02f1; } <>7__wrap3 = ollamaApiClient.ProcessStreamedChatResponseAsync(<response>5__3, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap4 = null; <>7__wrap5 = 0; } try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter3; if (num != -4) { if (num != 1) { goto IL_0201; } awaiter3 = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_026c; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_0201; } goto end_IL_01b9; IL_0201: <>2__current = null; awaiter3 = <>7__wrap3.MoveNextAsync().GetAwaiter(); if (!awaiter3.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter3; <ChatAsync>d__34 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine); return; } goto IL_026c; IL_026c: if (!awaiter3.GetResult()) { goto end_IL_01b9; } ChatResponseStream current = <>7__wrap3.Current; <>2__current = current; num = (<>1__state = -4); goto end_IL_0173; end_IL_01b9:; } catch (object obj) { <>7__wrap4 = obj; } <>2__current = null; awaiter2 = <>7__wrap3.DisposeAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 2); <>u__3 = awaiter2; <ChatAsync>d__34 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_02f1; IL_02f1: awaiter2.GetResult(); object obj2 = <>7__wrap4; if (obj2 != null) { ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw(); } _ = <>7__wrap5; if (<>w__disposeMode) { goto IL_035c; } <>7__wrap4 = null; <>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); goto end_IL_000e; end_IL_0173:; } finally { if (num == -1 && <response>5__3 != null) { ((IDisposable)<response>5__3).Dispose(); } } goto end_IL_0082; IL_035c: _ = <>w__disposeMode; goto IL_037d; end_IL_0082:; } finally { if (num == -1 && <requestMessage>5__2 != null) { ((IDisposable)<requestMessage>5__2).Dispose(); } } goto IL_045f; IL_037d: if (!<>w__disposeMode) { <requestMessage>5__2 = null; <response>5__3 = null; } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <requestMessage>5__2 = null; <response>5__3 = null; <>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); <>7__wrap4 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetException(exception); return; } <>1__state = -2; <requestMessage>5__2 = null; <response>5__3 = null; <>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); <>7__wrap4 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_045f: <>v__promiseOfValueOrEnd.SetResult(result: true); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } [DebuggerHidden] IAsyncEnumerator<ChatResponseStream> IAsyncEnumerable<ChatResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <ChatAsync>d__34 <ChatAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <ChatAsync>d__ = this; } else { <ChatAsync>d__ = new <ChatAsync>d__34(-3) { <>4__this = <>4__this }; } <ChatAsync>d__.request = <>3__request; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <ChatAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <ChatAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <ChatAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <ChatAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<ChatResponseStream>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <ChatAsync>d__34 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); short version = <>v__promiseOfValueOrEnd.Version; if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded) { return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version)); } return new ValueTask<bool>(this, version); } [DebuggerHidden] bool IValueTaskSource<bool>.GetResult(short token) { return <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] void IValueTaskSource.GetResult(short token) { <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] ValueTask IAsyncDisposable.DisposeAsync() { if (<>1__state >= -1) { throw new NotSupportedException(); } if (<>1__state == -2) { return default(ValueTask); } <>w__disposeMode = true; <>v__promiseOfValueOrEnd.Reset(); <ChatAsync>d__34 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } [CompilerGenerated] private sealed class <CreateModelAsync>d__24 : IAsyncEnumerable<CreateModelResponse>, IAsyncEnumerator<CreateModelResponse>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private CreateModelResponse <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; public OllamaApiClient <>4__this; private CreateModelRequest request; public CreateModelRequest <>3__request; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private ConfiguredCancelableAsyncEnumerable<CreateModelResponse>.Enumerator <>7__wrap1; private object <>7__wrap2; private int <>7__wrap3; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2; CreateModelResponse IAsyncEnumerator<CreateModelResponse>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <CreateModelAsync>d__24(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; OllamaApiClient ollamaApiClient = <>4__this; try { ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); <>7__wrap1 = ollamaApiClient.StreamPostAsync<CreateModelRequest, CreateModelResponse>("api/create", request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap2 = null; <>7__wrap3 = 0; goto case -4; } goto end_IL_000e; case -4: case 0: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2; if (num != -4) { if (num != 0) { goto IL_00c4; } awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_012f; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_00c4; } goto end_IL_007f; IL_00c4: <>2__current = null; awaiter2 = <>7__wrap1.MoveNextAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; <CreateModelAsync>d__24 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_012f; IL_012f: if (awaiter2.GetResult()) { CreateModelResponse current = <>7__wrap1.Current; <>2__current = current; num = (<>1__state = -4); goto IL_02b0; } end_IL_007f:; } catch (object obj) { <>7__wrap2 = obj; } <>2__current = null; awaiter = <>7__wrap1.DisposeAsync().GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter; <CreateModelAsync>d__24 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } break; case 1: awaiter = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); break; } awaiter.GetResult(); object obj2 = <>7__wrap2; if (obj2 != null) { ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw(); } _ = <>7__wrap3; if (!<>w__disposeMode) { <>7__wrap2 = null; <>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<CreateModelResponse>.Enumerator); } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<CreateModelResponse>.Enumerator); <>7__wrap2 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetException(exception); return; } <>1__state = -2; <>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<CreateModelResponse>.Enumerator); <>7__wrap2 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_02b0: <>v__promiseOfValueOrEnd.SetResult(result: true); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } [DebuggerHidden] IAsyncEnumerator<CreateModelResponse> IAsyncEnumerable<CreateModelResponse>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <CreateModelAsync>d__24 <CreateModelAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <CreateModelAsync>d__ = this; } else { <CreateModelAsync>d__ = new <CreateModelAsync>d__24(-3) { <>4__this = <>4__this }; } <CreateModelAsync>d__.request = <>3__request; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <CreateModelAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <CreateModelAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <CreateModelAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <CreateModelAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<CreateModelResponse>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <CreateModelAsync>d__24 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); short version = <>v__promiseOfValueOrEnd.Version; if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded) { return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version)); } return new ValueTask<bool>(this, version); } [DebuggerHidden] bool IValueTaskSource<bool>.GetResult(short token) { return <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] void IValueTaskSource.GetResult(short token) { <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] ValueTask IAsyncDisposable.DisposeAsync() { if (<>1__state >= -1) { throw new NotSupportedException(); } if (<>1__state == -2) { return default(ValueTask); } <>w__disposeMode = true; <>v__promiseOfValueOrEnd.Reset(); <CreateModelAsync>d__24 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } [CompilerGenerated] private sealed class <GenerateAsync>d__33 : IAsyncEnumerable<GenerateResponseStream>, IAsyncEnumerator<GenerateResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private GenerateResponseStream <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; private GenerateRequest request; public GenerateRequest <>3__request; public OllamaApiClient <>4__this; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator <>7__wrap1; private object <>7__wrap2; private int <>7__wrap3; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2; GenerateResponseStream IAsyncEnumerator<GenerateResponseStream>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GenerateAsync>d__33(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; OllamaApiClient ollamaApiClient = <>4__this; try { ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); if (string.IsNullOrEmpty(request.Model)) { request.Model = ollamaApiClient.SelectedModel; } <>7__wrap1 = ollamaApiClient.GenerateCompletionAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap2 = null; <>7__wrap3 = 0; goto case -4; } goto end_IL_000e; case -4: case 0: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2; if (num != -4) { if (num != 0) { goto IL_00e2; } awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_014d; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_00e2; } goto end_IL_009d; IL_00e2: <>2__current = null; awaiter2 = <>7__wrap1.MoveNextAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; <GenerateAsync>d__33 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_014d; IL_014d: if (awaiter2.GetResult()) { GenerateResponseStream current = <>7__wrap1.Current; <>2__current = current; num = (<>1__state = -4); goto IL_02ce; } end_IL_009d:; } catch (object obj) { <>7__wrap2 = obj; } <>2__current = null; awaiter = <>7__wrap1.DisposeAsync().GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter; <GenerateAsync>d__33 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } break; case 1: awaiter = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); break; } awaiter.GetResult(); object obj2 = <>7__wrap2; if (obj2 != null) { ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw(); } _ = <>7__wrap3; if (!<>w__disposeMode) { <>7__wrap2 = null; <>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator); } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator); <>7__wrap2 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetException(exception); return; } <>1__state = -2; <>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator); <>7__wrap2 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_02ce: <>v__promiseOfValueOrEnd.SetResult(result: true); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } [DebuggerHidden] IAsyncEnumerator<GenerateResponseStream> IAsyncEnumerable<GenerateResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <GenerateAsync>d__33 <GenerateAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <GenerateAsync>d__ = this; } else { <GenerateAsync>d__ = new <GenerateAsync>d__33(-3) { <>4__this = <>4__this }; } <GenerateAsync>d__.request = <>3__request; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <GenerateAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <GenerateAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <GenerateAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <GenerateAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<GenerateResponseStream>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <GenerateAsync>d__33 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); short version = <>v__promiseOfValueOrEnd.Version; if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded) { return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version)); } return new ValueTask<bool>(this, version); } [DebuggerHidden] bool IValueTaskSource<bool>.GetResult(short token) { return <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] void IValueTaskSource.GetResult(short token) { <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] ValueTask IAsyncDisposable.DisposeAsync() { if (<>1__state >= -1) { throw new NotSupportedException(); } if (<>1__state == -2) { return default(ValueTask); } <>w__disposeMode = true; <>v__promiseOfValueOrEnd.Reset(); <GenerateAsync>d__33 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } [CompilerGenerated] private sealed class <GenerateCompletionAsync>d__39 : IAsyncEnumerable<GenerateResponseStream>, IAsyncEnumerator<GenerateResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private GenerateResponseStream <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; public OllamaApiClient <>4__this; private GenerateRequest generateRequest; public GenerateRequest <>3__generateRequest; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private HttpRequestMessage <requestMessage>5__2; private HttpResponseMessage <response>5__3; private ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter <>u__1; private ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator <>7__wrap3; private object <>7__wrap4; private int <>7__wrap5; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__2; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__3; GenerateResponseStream IAsyncEnumerator<GenerateResponseStream>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GenerateCompletionAsync>d__39(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; OllamaApiClient ollamaApiClient = <>4__this; try { switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); <requestMessage>5__2 = ollamaApiClient.CreateRequestMessage(HttpMethod.Post, "api/generate", generateRequest); break; } goto end_IL_000e; case -4: case 0: case 1: case 2: break; } try { ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter awaiter; HttpResponseMessage result; switch (num) { default: { HttpCompletionOption completionOption = (generateRequest.Stream ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead); <>2__current = null; awaiter = ollamaApiClient.SendToOllamaAsync(<requestMessage>5__2, generateRequest, completionOption, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; <GenerateCompletionAsync>d__39 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_011c; } case 0: awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_011c; case -4: case 1: case 2: break; IL_011c: result = awaiter.GetResult(); <response>5__3 = result; break; } try { ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter2; if (num != -4 && num != 1) { if (num == 2) { awaiter2 = <>u__3; <>u__3 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_02aa; } <>7__wrap3 = ollamaApiClient.ProcessStreamedCompletionResponseAsync(<response>5__3, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap4 = null; <>7__wrap5 = 0; } try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter3; if (num != -4) { if (num != 1) { goto IL_01ba; } awaiter3 = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_0225; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_01ba; } goto end_IL_0172; IL_01ba: <>2__current = null; awaiter3 = <>7__wrap3.MoveNextAsync().GetAwaiter(); if (!awaiter3.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter3; <GenerateCompletionAsync>d__39 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine); return; } goto IL_0225; IL_0225: if (!awaiter3.GetResult()) { goto end_IL_0172; } GenerateResponseStream current = <>7__wrap3.Current; <>2__current = current; num = (<>1__state = -4); goto end_IL_012c; end_IL_0172:; } catch (object obj) { <>7__wrap4 = obj; } <>2__current = null; awaiter2 = <>7__wrap3.DisposeAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 2); <>u__3 = awaiter2; <GenerateCompletionAsync>d__39 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_02aa; IL_02aa: awaiter2.GetResult(); object obj2 = <>7__wrap4; if (obj2 != null) { ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw(); } _ = <>7__wrap5; if (<>w__disposeMode) { goto IL_0315; } <>7__wrap4 = null; <>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator); goto end_IL_000e; end_IL_012c:; } finally { if (num == -1 && <response>5__3 != null) { ((IDisposable)<response>5__3).Dispose(); } } goto end_IL_0066; IL_0315: _ = <>w__disposeMode; goto IL_0336; end_IL_0066:; } finally { if (num == -1 && <requestMessage>5__2 != null) { ((IDisposable)<requestMessage>5__2).Dispose(); } } goto IL_0418; IL_0336: if (!<>w__disposeMode) { <requestMessage>5__2 = null; <response>5__3 = null; } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <requestMessage>5__2 = null; <response>5__3 = null; <>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator); <>7__wrap4 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetException(exception); return; } <>1__state = -2; <requestMessage>5__2 = null; <response>5__3 = null; <>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator); <>7__wrap4 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_0418: <>v__promiseOfValueOrEnd.SetResult(result: true); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } [DebuggerHidden] IAsyncEnumerator<GenerateResponseStream> IAsyncEnumerable<GenerateResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <GenerateCompletionAsync>d__39 <GenerateCompletionAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <GenerateCompletionAsync>d__ = this; } else { <GenerateCompletionAsync>d__ = new <GenerateCompletionAsync>d__39(-3) { <>4__this = <>4__this }; } <GenerateCompletionAsync>d__.generateRequest = <>3__generateRequest; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <GenerateCompletionAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <GenerateCompletionAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <GenerateCompletionAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <GenerateCompletionAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<GenerateResponseStream>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <GenerateCompletionAsync>d__39 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); short version = <>v__promiseOfValueOrEnd.Version; if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded) { return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version)); } return new ValueTask<bool>(this, version); } [DebuggerHidden] bool IValueTaskSource<bool>.GetResult(short token) { return <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] void IValueTaskSource.GetResult(short token) { <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] ValueTask IAsyncDisposable.DisposeAsync() { if (<>1__state >= -1) { throw new NotSupportedException(); } if (<>1__state == -2) { return default(ValueTask); } <>w__disposeMode = true; <>v__promiseOfValueOrEnd.Reset(); <GenerateCompletionAsync>d__39 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } [CompilerGenerated] private sealed class <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 : IAsyncEnumerable<ChatResponseUpdate>, IAsyncEnumerator<ChatResponseUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private ChatResponseUpdate <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; public OllamaApiClient <>4__this; private IEnumerable<ChatMessage> messages; public IEnumerable<ChatMessage> <>3__messages; private ChatOptions options; public ChatOptions <>3__options; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private string <responseId>5__2; private ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator <>7__wrap2; private object <>7__wrap3; private int <>7__wrap4; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2; ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; OllamaApiClient ollamaApiClient = <>4__this; try { ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); ChatRequest request = AbstractionMapper.ToOllamaSharpChatRequest((IChatClient?)(object)ollamaApiClient, messages, options, stream: true, ollamaApiClient.OutgoingJsonSerializerOptions); <responseId>5__2 = Guid.NewGuid().ToString("N"); <>7__wrap2 = ollamaApiClient.ChatAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap3 = null; <>7__wrap4 = 0; goto case -4; } goto end_IL_000e; case -4: case 0: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2; if (num != -4) { if (num != 0) { goto IL_00fa; } awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_0165; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_00fa; } goto end_IL_00a8; IL_00fa: <>2__current = null; awaiter2 = <>7__wrap2.MoveNextAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_0165; IL_0165: if (awaiter2.GetResult()) { ChatResponseStream current = <>7__wrap2.Current; <>2__current = AbstractionMapper.ToChatResponseUpdate(current, <responseId>5__2); num = (<>1__state = -4); goto IL_02f4; } end_IL_00a8:; } catch (object obj) { <>7__wrap3 = obj; } <>2__current = null; awaiter = <>7__wrap2.DisposeAsync().GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter; <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } break; case 1: awaiter = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); break; } awaiter.GetResult(); object obj2 = <>7__wrap3; if (obj2 != null) { ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw(); } _ = <>7__wrap4; if (!<>w__disposeMode) { <>7__wrap3 = null; <>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <responseId>5__2 = null; <>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); <>7__wrap3 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetException(exception); return; } <>1__state = -2; <responseId>5__2 = null; <>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator); <>7__wrap3 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_02f4: <>v__promiseOfValueOrEnd.SetResult(result: true); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } [DebuggerHidden] IAsyncEnumerator<ChatResponseUpdate> IAsyncEnumerable<ChatResponseUpdate>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__ = this; } else { <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__ = new <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55(-3) { <>4__this = <>4__this }; } <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.messages = <>3__messages; <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.options = <>3__options; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); short version = <>v__promiseOfValueOrEnd.Version; if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded) { return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version)); } return new ValueTask<bool>(this, version); } [DebuggerHidden] bool IValueTaskSource<bool>.GetResult(short token) { return <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] void IValueTaskSource.GetResult(short token) { <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] ValueTask IAsyncDisposable.DisposeAsync() { if (<>1__state >= -1) { throw new NotSupportedException(); } if (<>1__state == -2) { return default(ValueTask); } <>w__disposeMode = true; <>v__promiseOfValueOrEnd.Reset(); <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } [CompilerGenerated] private sealed class <ProcessStreamedChatResponseAsync>d__49 : IAsyncEnumerable<ChatResponseStream>, IAsyncEnumerator<ChatResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private ChatResponseStream <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; private HttpResponseMessage response; public HttpResponseMessage <>3__response; public OllamaApiClient <>4__this; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private Stream <stream>5__2; private StreamReader <reader>5__3; private ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter <>u__1; private ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter <>u__2; ChatResponseStream IAsyncEnumerator<ChatResponseStream>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ProcessStreamedChatResponseAsync>d__49(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; OllamaApiClient ollamaApiClient = <>4__this; try { ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter awaiter; Stream result; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); <>2__current = null; awaiter = response.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; <ProcessStreamedChatResponseAsync>d__49 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_00b8; } goto end_IL_000e; case 0: awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_00b8; case -4: case 1: break; IL_00b8: result = awaiter.GetResult(); <stream>5__2 = result; break; } try { if (num != -4 && num != 1) { <reader>5__3 = new StreamReader(<stream>5__2); } try { ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter awaiter2; if (num != -4) { if (num != 1) { goto IL_01ca; } awaiter2 = <>u__2; <>u__2 = default(ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_0165; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_01ca; } goto end_IL_00e3; IL_01ca: if (!<reader>5__3.EndOfStream && !cancellationToken.IsCancellationRequested) { <>2__current = null; awaiter2 = <reader>5__3.ReadLineAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter2; <ProcessStreamedChatResponseAsync>d__49 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_0165; } goto end_IL_00c8; IL_0165: string json = awaiter2.GetResult() ?? ""; ChatResponseStream chatResponseStream = JsonSerializer.Deserialize<ChatResponseStream>(json, ollamaApiClient.IncomingJsonSerializerOptions); <>2__current = ((chatResponseStream != null && chatResponseStream.Done) ? JsonSerializer.Deserialize<ChatDoneResponseStream>(json, ollamaApiClient.IncomingJsonSerializerOptions) : chatResponseStream); num = (<>1__state = -4); goto IL_02e3; end_IL_00e3:; } finally { if (num == -1 && <reader>5__3 != null) { ((IDisposable)<reader>5__3).Dispose(); } } _ = <>w__disposeMode; goto IL_0227; end_IL_00c8:; } finally { if (num == -1 && <stream>5__2 != null) { ((IDisposable)<stream>5__2).Dispose(); } } goto end_IL_000e; IL_0227: if (!<>w__disposeMode) { <stream>5__2 = null; <reader>5__3 = null; } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <stream>5__2 = null; <reader>5__3 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetException(exception); return; } <>1__state = -2; <stream>5__2 = null; <reader>5__3 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_02e3: <>v__promiseOfValueOrEnd.SetResult(result: true); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } [DebuggerHidden] IAsyncEnumerator<ChatResponseStream> IAsyncEnumerable<ChatResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <ProcessStreamedChatResponseAsync>d__49 <ProcessStreamedChatResponseAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <ProcessStreamedChatResponseAsync>d__ = this; } else { <ProcessStreamedChatResponseAsync>d__ = new <ProcessStreamedChatResponseAsync>d__49(-3) { <>4__this = <>4__this }; } <ProcessStreamedChatResponseAsync>d__.response = <>3__response; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <ProcessStreamedChatResponseAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <ProcessStreamedChatResponseAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <ProcessStreamedChatResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <ProcessStreamedChatResponseAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<ChatResponseStream>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <ProcessStreamedChatResponseAsync>d__49 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); short version = <>v__promiseOfValueOrEnd.Version; if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded) { return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version)); } return new ValueTask<bool>(this, version); } [DebuggerHidden] bool IValueTaskSource<bool>.GetResult(short token) { return <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] void IValueTaskSource.GetResult(short token) { <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] ValueTask IAsyncDisposable.DisposeAsync() { if (<>1__state >= -1) { throw new NotSupportedException(); } if (<>1__state == -2) { return default(ValueTask); } <>w__disposeMode = true; <>v__promiseOfValueOrEnd.Reset(); <ProcessStreamedChatResponseAsync>d__49 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } [CompilerGenerated] private sealed class <ProcessStreamedCompletionResponseAsync>d__48 : IAsyncEnumerable<GenerateResponseStream>, IAsyncEnumerator<GenerateResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private GenerateResponseStream <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; private HttpResponseMessage response; public HttpResponseMessage <>3__response; public OllamaApiClient <>4__this; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private Stream <stream>5__2; private StreamReader <reader>5__3; private ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter <>u__1; private ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter <>u__2; GenerateResponseStream IAsyncEnumerator<GenerateResponseStream>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ProcessStreamedCompletionResponseAsync>d__48(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; OllamaApiClient ollamaApiClient = <>4__this; try { ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter awaiter; Stream result; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); <>2__current = null; awaiter = response.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; <ProcessStreamedCompletionResponseAsync>d__48 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_00b8; } goto end_IL_000e; case 0: awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_00b8; case -4: case 1: break; IL_00b8: result = awaiter.GetResult(); <stream>5__2 = result; break; } try { if (num != -4 && num != 1) { <reader>5__3 = new StreamReader(<stream>5__2); } try { ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter awaiter2; if (num != -4) { if (num != 1) { goto IL_01ca; } awaiter2 = <>u__2; <>u__2 = default(ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_0165; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_01ca; } goto end_IL_00e3; IL_01ca: if (!<reader>5__3.EndOfStream && !cancellationToken.IsCancellationRequested) { <>2__current = null; awaiter2 = <reader>5__3.ReadLineAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter2; <ProcessStreamedCompletionResponseAsync>d__48 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_0165; } goto end_IL_00c8; IL_0165: string json = awaiter2.GetResult() ?? ""; GenerateResponseStream generateResponseStream = JsonSerializer.Deserialize<GenerateResponseStream>(json, ollamaApiClient.IncomingJsonSerializerOptions); <>2__current = ((generateResponseStream != null && generateResponseStream.Done) ? JsonSerializer.Deserialize<GenerateDoneResponseStream>(json, ollamaApiClient.IncomingJsonSerializerOptions) : generateResponseStream); num = (<>1__state = -4); goto IL_02e3; end_IL_00e3:; } finally { if (num == -1 && <reader>5__3 != null) { ((IDisposable)<reader>5__3).Dispose(); } } _ = <>w__disposeMode; goto IL_0227; end_IL_00c8:; } finally { if (num == -1 && <stream>5__2 != null) { ((IDisposable)<stream>5__2).Dispose(); } } goto end_IL_000e; IL_0227: if (!<>w__disposeMode) { <stream>5__2 = null; <reader>5__3 = null; } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <stream>5__2 = null; <reader>5__3 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetException(exception); return; } <>1__state = -2; <stream>5__2 = null; <reader>5__3 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_02e3: <>v__promiseOfValueOrEnd.SetResult(result: true); } void IAsyncStateMachine.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext this.MoveNext(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine this.SetStateMachine(stateMachine); } [DebuggerHidden] IAsyncEnumerator<GenerateResponseStream> IAsyncEnumerable<GenerateResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <ProcessStreamedCompletionResponseAsync>d__48 <ProcessStreamedCompletionResponseAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <ProcessStreamedCompletionResponseAsync>d__ = this; } else { <ProcessStreamedCompletionResponseAsync>d__ = new <ProcessStreamedCompletionResponseAsync>d__48(-3) { <>4__this = <>4__this }; } <ProcessStreamedCompletionResponseAsync>d__.response = <>3__response; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <ProcessStreamedCompletionResponseAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <ProcessStreamedCompletionResponseAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <ProcessStreamedCompletionResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <ProcessStreamedCompletionResponseAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<GenerateResponseStream>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <ProcessStreamedCompletionResponseAsync>d__48 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); short version = <>v__promiseOfValueOrEnd.Version; if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded) { return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version)); } return new ValueTask<bool>(this, version); } [DebuggerHidden] bool IValueTaskSource<bool>.GetResult(short token) { return <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] void IValueTaskSource.GetResult(short token) { <>v__promiseOfValueOrEnd.GetResult(token); } [DebuggerHidden] ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return <>v__promiseOfValueOrEnd.GetStatus(token); } [DebuggerHidden] void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { <>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags); } [DebuggerHidden] ValueTask IAsyncDisposable.DisposeAsync() { if (<>1__state >= -1) { throw new NotSupportedException(); } if (<>1__state == -2) { return default(ValueTask); } <>w__disposeMode = true; <>v__promiseOfValueOrEnd.Reset(); <ProcessStreamedCompletionResponseAsync>d__48 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } [CompilerGenerated] private sealed class <ProcessStreamedResponseAsync>d__47<TLine> : IAsyncEnumerable<TLine>, IAsyncEnumerator<TLine>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine where TLine : notnull { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private TLine <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; private HttpResponseMessage response; public HttpResponseMessage <>3__response; public OllamaApiClient <>4__this; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private StreamReader <reader>5__2; private ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter <>u__1; private ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter <>u__2; TLine IAsyncEnumerator<TLine>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ProcessStreamedResponseAsync>d__47(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; OllamaApiClient ollamaApiClient = <>4__this; try { ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter awaiter; Stream result; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); <>2__current = default(TLine); awaiter = response.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; <ProcessStreamedResponseAsync>d__47<TLine> stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_00bd; } goto end_IL_000e; case 0: awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_00bd; case -4: case 1: break; IL_00bd: result = awaiter.GetResult(); <reader>5__2 = new StreamReader(result); break;
deps/System.Buffers.dll
Decompiled a day agousing System.Buffers; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Buffers")] [assembly: AssemblyDescription("System.Buffers")] [assembly: AssemblyDefaultAlias("System.Buffers")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyInformationalVersion("4.0.99.0")] [assembly: AssemblyFileVersion("4.0.99.0")] [assembly: AssemblyVersion("4.0.99.0")] [assembly: TypeForwardedTo(typeof(ArrayPool<>))]
deps/System.ClientModel.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Text; using System.ClientModel.Internal; using System.ClientModel.Primitives; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Logging; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("System.ClientModel.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] [assembly: InternalsVisibleTo("System.ClientModel.Tests.Internal, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] [assembly: InternalsVisibleTo("System.ClientModel.Tests.Internal.Perf, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Contains building blocks for clients that call cloud services.")] [assembly: AssemblyFileVersion("1.700.25.47207")] [assembly: AssemblyInformationalVersion("1.7.0+5ed63e2e9a633d290bd8cc9578fe2fe3966dbc79")] [assembly: AssemblyProduct("Azure .NET SDK")] [assembly: AssemblyTitle("System.ClientModel")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Azure/azure-sdk-for-net")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("1.7.0.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] internal sealed class IsByRefLikeAttribute : 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; } } } [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] [EditorBrowsable(EditorBrowsableState.Never)] internal static class __LoggerMessageGenerator { public static string Enumerate(IEnumerable? enumerable) { if (enumerable == null) { return "(null)"; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); bool flag = true; foreach (object item in enumerable) { if (!flag) { stringBuilder.Append(", "); } if (item == null) { stringBuilder.Append("(null)"); } else if (item is IFormattable formattable) { stringBuilder.Append(formattable.ToString(null, CultureInfo.InvariantCulture)); } else { stringBuilder.Append(item); } flag = false; } stringBuilder.Append(']'); return stringBuilder.ToString(); } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class ExperimentalAttribute : Attribute { public string DiagnosticId { get; } public string? UrlFormat { get; set; } public ExperimentalAttribute(string diagnosticId) { DiagnosticId = diagnosticId; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed 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; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class DynamicDependencyAttribute : Attribute { public string? MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public Type? Type { get; } public string? TypeName { get; } public string? AssemblyName { get; } public string? Condition { get; set; } public DynamicDependencyAttribute(string memberSignature) { MemberSignature = memberSignature; } public DynamicDependencyAttribute(string memberSignature, Type type) { MemberSignature = memberSignature; Type = type; } public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) { MemberTypes = memberTypes; Type = type; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } } [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 } } namespace System.ClientModel { public abstract class AuthenticationTokenProvider { public abstract GetTokenOptions? CreateTokenOptions(IReadOnlyDictionary<string, object> properties); public abstract AuthenticationToken GetToken(GetTokenOptions options, CancellationToken cancellationToken); public abstract ValueTask<AuthenticationToken> GetTokenAsync(GetTokenOptions options, CancellationToken cancellationToken); } public class ApiKeyCredential { private string _key; public ApiKeyCredential(string key) { Update(key); } public void Deconstruct(out string key) { key = Volatile.Read(ref _key); } public void Update(string key) { Argument.AssertNotNullOrEmpty(key, "key"); Volatile.Write(ref _key, key); } } public abstract class AsyncCollectionResult<T> : AsyncCollectionResult, IAsyncEnumerable<T> { protected internal AsyncCollectionResult() { } public async IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { await foreach (ClientResult item in GetRawPagesAsync().ConfigureAwait(continueOnCapturedContext: false).WithCancellation(cancellationToken)) { await foreach (T item2 in GetValuesFromPageAsync(item).ConfigureAwait(continueOnCapturedContext: false).WithCancellation(cancellationToken)) { yield return item2; } } } protected abstract IAsyncEnumerable<T> GetValuesFromPageAsync(ClientResult page); } public class ClientResult { private readonly PipelineResponse _response; protected ClientResult(PipelineResponse response) { Argument.AssertNotNull(response, "response"); _response = response; } public PipelineResponse GetRawResponse() { return _response; } public static ClientResult FromResponse(PipelineResponse response) { Argument.AssertNotNull(response, "response"); return new ClientResult(response); } public static ClientResult<T> FromValue<T>(T value, PipelineResponse response) { Argument.AssertNotNull(response, "response"); if (value == null) { string message = "ClientResult<T> contract guarantees that ClientResult<T>.Value is non-null. If you need to return a ClientResult where the Value is null, please use ClientResult.FromOptionalValue instead."; throw new ArgumentNullException("value", message); } return new ClientResult<T>(value, response); } public static ClientResult<T?> FromOptionalValue<T>(T? value, PipelineResponse response) { Argument.AssertNotNull(response, "response"); return new ClientResult<T>(value, response); } } public class ClientResultException : Exception { private const string DefaultMessage = "Service request failed."; private readonly PipelineResponse? _response; private int _status; public int Status { get { return _status; } protected set { _status = value; } } public static async Task<ClientResultException> CreateAsync(PipelineResponse response, Exception? innerException = null) { Argument.AssertNotNull(response, "response"); return new ClientResultException(await CreateMessageAsync(response).ConfigureAwait(continueOnCapturedContext: false), response, innerException); } public ClientResultException(PipelineResponse response, Exception? innerException = null) : base(CreateMessage(response), innerException) { Argument.AssertNotNull(response, "response"); _response = response; _status = response.Status; } public ClientResultException(string message, PipelineResponse? response = null, Exception? innerException = null) : base(message, innerException) { Argument.AssertNotNull(message, "message"); _response = response; _status = response?.Status ?? 0; } public PipelineResponse? GetRawResponse() { return _response; } private static string CreateMessage(PipelineResponse response) { return CreateMessageSyncOrAsync(response, async: false).EnsureCompleted(); } private static async ValueTask<string> CreateMessageAsync(PipelineResponse response) { return await CreateMessageSyncOrAsync(response, async: true).ConfigureAwait(continueOnCapturedContext: false); } private static async ValueTask<string> CreateMessageSyncOrAsync(PipelineResponse response, bool async) { Argument.AssertNotNull(response, "response"); if (async) { await response.BufferContentAsync().ConfigureAwait(continueOnCapturedContext: false); } else { response.BufferContent(); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Service request failed.").Append("Status: ").Append(response.Status.ToString(CultureInfo.InvariantCulture)); if (!string.IsNullOrEmpty(response.ReasonPhrase)) { stringBuilder.Append(" (").Append(response.ReasonPhrase).AppendLine(")"); } else { stringBuilder.AppendLine(); } return stringBuilder.ToString(); } } public class ClientResult<T> : ClientResult { public virtual T Value { get; } protected internal ClientResult(T value, PipelineResponse response) : base(response) { Value = value; } public static implicit operator T(ClientResult<T> result) { if (result == null) { throw new ArgumentNullException("result", $"The implicit cast from ClientResult<{typeof(T)}> to {typeof(T)} failed because the ClientResult<{typeof(T)}> was null."); } return result.Value; } } public abstract class CollectionResult<T> : CollectionResult, IEnumerable<T>, IEnumerable { protected internal CollectionResult() { } public IEnumerator<T> GetEnumerator() { foreach (ClientResult rawPage in GetRawPages()) { foreach (T item in GetValuesFromPage(rawPage)) { yield return item; } } } protected abstract IEnumerable<T> GetValuesFromPage(ClientResult page); IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class ContinuationToken { private readonly BinaryData? _bytes; protected ContinuationToken() { } protected ContinuationToken(BinaryData bytes) { Argument.AssertNotNull<BinaryData>(bytes, "bytes"); _bytes = bytes; } public static ContinuationToken FromBytes(BinaryData bytes) { return new ContinuationToken(bytes); } public virtual BinaryData ToBytes() { return _bytes ?? throw new InvalidOperationException("Unable to write token as bytes."); } } public abstract class BinaryContent : IDisposable { private sealed class BinaryDataBinaryContent : BinaryContent { private readonly ReadOnlyMemory<byte> _bytes; public BinaryDataBinaryContent(ReadOnlyMemory<byte> bytes, string? mediaType = null) { _bytes = bytes; base.MediaType = mediaType; } public override bool TryComputeLength(out long length) { length = _bytes.Length; return true; } public override void WriteTo(Stream stream, CancellationToken cancellation) { Argument.AssertNotNull(stream, "stream"); byte[] array = _bytes.ToArray(); stream.Write(array, 0, array.Length); } public override async Task WriteToAsync(Stream stream, CancellationToken cancellation) { Argument.AssertNotNull(stream, "stream"); await StreamExtensions.WriteAsync(stream, _bytes, cancellation).ConfigureAwait(continueOnCapturedContext: false); } public override void Dispose() { } } private sealed class ModelBinaryContent<T> : BinaryContent where T : IPersistableModel<T> { private readonly T _model; private readonly ModelReaderWriterOptions _options; private UnsafeBufferSequence.Reader? _sequenceReader; private BinaryData? _data; private byte[]? _bytes; private UnsafeBufferSequence.Reader SequenceReader { get { if (!((object)_model is IJsonModel<T> model)) { throw new InvalidOperationException("Cannot use Writer with non-IJsonModel model type."); } if (_sequenceReader == null) { _sequenceReader = new ModelWriter<T>(model, _options).ExtractReader(); } return _sequenceReader; } } private BinaryData Data { get { if (ModelReaderWriter.ShouldWriteAsJson(_model, _options)) { throw new InvalidOperationException("Should use ModelWriter instead of _model.Write with IJsonModel."); } if (_data == null) { _data = _model.Write(_options); } return _data; } } private byte[] Bytes => _bytes ?? (_bytes = Data.ToArray()); public ModelBinaryContent(T model, ModelReaderWriterOptions options) { _model = model; _options = options; if (options.Format == "J" || (options.Format == "W" && model.GetFormatFromOptions(options) == "J")) { base.MediaType = "application/json"; } } public override bool TryComputeLength(out long length) { length = (ModelReaderWriter.ShouldWriteAsJson(_model, _options) ? SequenceReader.Length : Data.ToMemory().Length); return true; } public override void WriteTo(Stream stream, CancellationToken cancellation) { Argument.AssertNotNull(stream, "stream"); if (ModelReaderWriter.ShouldWriteAsJson(_model, _options)) { SequenceReader.CopyTo(stream, cancellation); } else { stream.Write(Bytes, 0, Bytes.Length); } } public override async Task WriteToAsync(Stream stream, CancellationToken cancellation) { Argument.AssertNotNull(stream, "stream"); if (ModelReaderWriter.ShouldWriteAsJson(_model, _options)) { await SequenceReader.CopyToAsync(stream, cancellation).ConfigureAwait(continueOnCapturedContext: false); } else { await StreamExtensions.WriteAsync(stream, Data.ToMemory(), cancellation).ConfigureAwait(continueOnCapturedContext: false); } } public override void Dispose() { UnsafeBufferSequence.Reader sequenceReader = _sequenceReader; if (sequenceReader != null) { _sequenceReader = null; sequenceReader.Dispose(); } } } private sealed class StreamBinaryContent : BinaryContent { private readonly Stream _stream; private readonly long _origin; public StreamBinaryContent(Stream stream) { if (!stream.CanSeek) { throw new ArgumentException("Stream must be seekable.", "stream"); } _stream = stream; _origin = stream.Position; } public override bool TryComputeLength(out long length) { length = _stream.Length - _origin; return true; } public override void WriteTo(Stream stream, CancellationToken cancellationToken) { Argument.AssertNotNull(stream, "stream"); _stream.Seek(_origin, SeekOrigin.Begin); _stream.CopyTo(stream, cancellationToken); _stream.Flush(); } public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken) { Argument.AssertNotNull(stream, "stream"); _stream.Seek(_origin, SeekOrigin.Begin); await StreamExtensions.CopyToAsync(_stream, stream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); await _stream.FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public override void Dispose() { _stream.Dispose(); } } private static readonly ModelReaderWriterOptions ModelWriteWireOptions = new ModelReaderWriterOptions("W"); private const string JsonSerializerRequiresDynamicCode = "JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation."; private const string JsonSerializerRequiresUnreferencedCode = "JSON serialization and deserialization might require types that cannot be statically analyzed."; public string? MediaType { get; protected set; } public static BinaryContent Create(BinaryData value) { Argument.AssertNotNull<BinaryData>(value, "value"); return new BinaryDataBinaryContent(value.ToMemory()); } public static BinaryContent Create<T>(T model, ModelReaderWriterOptions? options = null) where T : IPersistableModel<T> { Argument.AssertNotNull(model, "model"); return new ModelBinaryContent<T>(model, options ?? ModelWriteWireOptions); } public static BinaryContent Create(Stream stream) { Argument.AssertNotNull(stream, "stream"); return new StreamBinaryContent(stream); } [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.")] [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")] public static BinaryContent CreateJson<T>(T jsonSerializable, JsonSerializerOptions? options = null) { Argument.AssertNotNull(jsonSerializable, "jsonSerializable"); return new BinaryDataBinaryContent(BinaryData.FromObjectAsJson<T>(jsonSerializable, options).ToMemory(), "application/json"); } public static BinaryContent CreateJson<T>(T jsonSerializable, JsonTypeInfo<T> jsonTypeInfo) { Argument.AssertNotNull(jsonSerializable, "jsonSerializable"); Argument.AssertNotNull(jsonTypeInfo, "jsonTypeInfo"); return new BinaryDataBinaryContent(BinaryData.FromObjectAsJson<T>(jsonSerializable, jsonTypeInfo).ToMemory(), "application/json"); } public static BinaryContent CreateJson(string jsonString, bool validate = false) { Argument.AssertNotNull(jsonString, "jsonString"); if (validate) { ValidateJsonString(jsonString); } return new BinaryDataBinaryContent(BinaryData.FromString(jsonString).ToMemory(), "application/json"); } private static void ValidateJsonString(string jsonString) { try { Utf8JsonReader utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(jsonString)); while (utf8JsonReader.Read()) { } } catch (JsonException ex) { throw new ArgumentException("The provided string is not valid JSON: " + ex.Message, "jsonString", ex); } } public abstract bool TryComputeLength(out long length); public abstract Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)); public abstract void WriteTo(Stream stream, CancellationToken cancellationToken = default(CancellationToken)); public abstract void Dispose(); } } namespace System.ClientModel.Internal { internal class Argument { public static void AssertNotNull<T>(T value, string name) { if (value == null) { throw new ArgumentNullException(name); } } public static void AssertNotNullOrEmpty(string value, string name) { if (value == null) { throw new ArgumentNullException(name); } if (value.Length == 0) { throw new ArgumentException("Value cannot be an empty string.", name); } } public static void AssertInRange<T>(T value, T minimum, T maximum, string name) where T : notnull, IComparable<T> { if (minimum.CompareTo(value) > 0) { throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); } if (maximum.CompareTo(value) < 0) { throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); } } } internal struct ArrayBackedPropertyBag<TKey, TValue> where TKey : struct, IEquatable<TKey> { private (TKey Key, TValue? Value) _first; private (TKey Key, TValue? Value) _second; private (TKey Key, TValue? Value)[]? _rest; private int _count; private readonly object _lock; public int Count => _count; public bool IsEmpty => _count == 0; public ArrayBackedPropertyBag() { _first = default((TKey, TValue)); _second = default((TKey, TValue)); _rest = null; _count = 0; _lock = new object(); } public void GetAt(int index, out TKey key, out TValue? value) { (key, value) = index switch { 0 => _first, 1 => _second, _ => GetRest()[index - 2], }; } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue? value) { int index = GetIndex(key); if (index < 0) { value = default(TValue); return false; } value = GetAt(index); return true; } public bool TryAdd(TKey key, TValue value, out TValue? existingValue) { int index = GetIndex(key); if (index >= 0) { existingValue = GetAt(index); return false; } AddInternal(key, value); existingValue = default(TValue); return true; } public void Set(TKey key, TValue? value) { int index = GetIndex(key); if (index < 0) { AddInternal(key, value); } else { SetAt(index, (key, value)); } } public bool TryRemove(TKey key) { switch (_count) { case 0: return false; case 1: if (IsFirst(key)) { _first = default((TKey, TValue)); _count--; return true; } return false; case 2: if (IsFirst(key)) { _first = _second; _second = default((TKey, TValue)); _count--; return true; } if (IsSecond(key)) { _second = default((TKey, TValue)); _count--; return true; } return false; default: { (TKey, TValue)[] rest = GetRest(); if (IsFirst(key)) { _first = _second; _second = rest[0]; _count--; Array.Copy(rest, 1, rest, 0, _count - 2); rest[_count - 2] = default((TKey, TValue)); return true; } if (IsSecond(key)) { _second = rest[0]; _count--; Array.Copy(rest, 1, rest, 0, _count - 2); rest[_count - 2] = default((TKey, TValue)); return true; } for (int i = 0; i < _count - 2; i++) { if (rest[i].Item1.Equals(key)) { _count--; Array.Copy(rest, i + 1, rest, i, _count - 2 - i); rest[_count - 2] = default((TKey, TValue)); return true; } } return false; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsFirst(TKey key) { return _first.Key.Equals(key); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsSecond(TKey key) { return _second.Key.Equals(key); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AddInternal(TKey key, TValue? value) { switch (_count) { case 0: _first = (key, value); _count = 1; return; case 1: if (IsFirst(key)) { _first = (_first.Key, value); return; } _second = (key, value); _count = 2; return; } if (_rest == null) { _rest = ArrayPool<(TKey, TValue)>.Shared.Rent(8); _rest[_count++ - 2] = (key, value); return; } if (_rest.Length <= _count) { (TKey, TValue)[] array = ArrayPool<(TKey, TValue)>.Shared.Rent(_rest.Length << 1); _rest.CopyTo(array, 0); (TKey, TValue)[] rest = _rest; _rest = array; ArrayPool<(TKey, TValue)>.Shared.Return(rest, clearArray: true); } _rest[_count++ - 2] = (key, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetAt(int index, (TKey Key, TValue? Value) value) { switch (index) { case 0: _first = value; break; case 1: _second = value; break; default: GetRest()[index - 2] = value; break; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private TValue? GetAt(int index) { return index switch { 0 => _first.Value, 1 => _second.Value, _ => GetRest()[index - 2].Value, }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetIndex(TKey key) { if (_count == 0) { return -1; } if (_count > 0 && _first.Key.Equals(key)) { return 0; } if (_count > 1 && _second.Key.Equals(key)) { return 1; } if (_count <= 2) { return -1; } (TKey, TValue)[] rest = GetRest(); int num = _count - 2; for (int i = 0; i < num; i++) { if (rest[i].Item1.Equals(key)) { return i + 2; } } return -1; } public void Dispose() { _count = 0; _first = default((TKey, TValue)); _second = default((TKey, TValue)); lock (_lock) { if (_rest != null) { (TKey, TValue)[] rest = _rest; _rest = null; ArrayPool<(TKey, TValue)>.Shared.Return(rest, clearArray: true); } } } private (TKey Key, TValue? Value)[] GetRest() { return _rest ?? throw new InvalidOperationException(string.Format("{0} field is null while {1} == {2}", "_rest", "_count", _count)); } [Conditional("DEBUG")] private void CheckDisposed() { } } internal struct BitVector640 { private ulong _bits0; private ulong _bits1; private ulong _bits2; private ulong _bits3; private ulong _bits4; private ulong _bits5; private ulong _bits6; private ulong _bits7; private ulong _bits8; private ulong _bits9; public bool this[int i] { readonly get { int index = i >> 6; int num = i & 0x3F; ulong num2 = (ulong)(1L << num); return (Get(index) & num2) == num2; } set { int index = i >> 6; int num = i & 0x3F; ulong mask = (ulong)(1L << num); Set(index, mask, value); } } private readonly ulong Get(int index) { return index switch { 0 => _bits0, 1 => _bits1, 2 => _bits2, 3 => _bits3, 4 => _bits4, 5 => _bits5, 6 => _bits6, 7 => _bits7, 8 => _bits8, 9 => _bits9, _ => throw new InvalidOperationException(), }; } private void Set(int index, ulong mask, bool value) { if (value) { switch (index) { case 0: _bits0 |= mask; break; case 1: _bits1 |= mask; break; case 2: _bits2 |= mask; break; case 3: _bits3 |= mask; break; case 4: _bits4 |= mask; break; case 5: _bits5 |= mask; break; case 6: _bits6 |= mask; break; case 7: _bits7 |= mask; break; case 8: _bits8 |= mask; break; case 9: _bits9 |= mask; break; default: throw new InvalidOperationException(); } } else { switch (index) { case 0: _bits0 &= ~mask; break; case 1: _bits1 &= ~mask; break; case 2: _bits2 &= ~mask; break; case 3: _bits3 &= ~mask; break; case 4: _bits4 &= ~mask; break; case 5: _bits5 &= ~mask; break; case 6: _bits6 &= ~mask; break; case 7: _bits7 &= ~mask; break; case 8: _bits8 &= ~mask; break; case 9: _bits9 &= ~mask; break; default: throw new InvalidOperationException(); } } } } internal static class CancellationHelper { private static readonly string s_cancellationMessage = new OperationCanceledException().Message; internal static bool ShouldWrapInOperationCanceledException(Exception exception, CancellationToken cancellationToken) { if (!(exception is OperationCanceledException)) { return cancellationToken.IsCancellationRequested; } return false; } internal static Exception CreateOperationCanceledException(Exception? innerException, CancellationToken cancellationToken, string? message = null) { return new TaskCanceledException(message ?? s_cancellationMessage, innerException); } private static void ThrowOperationCanceledException(Exception? innerException, CancellationToken cancellationToken) { throw CreateOperationCanceledException(innerException, cancellationToken); } internal static void ThrowIfCancellationRequested(CancellationToken cancellationToken, Exception? innerException = null) { if (cancellationToken.IsCancellationRequested) { ThrowOperationCanceledException(innerException, cancellationToken); } } internal static void ThrowIfCancellationRequestedOrTimeout(CancellationToken messageToken, CancellationToken timeoutToken, Exception? innerException, TimeSpan timeout) { ThrowIfCancellationRequested(messageToken, innerException); if (timeoutToken.IsCancellationRequested) { throw CreateOperationCanceledException(innerException, timeoutToken, $"The operation was cancelled because it exceeded the configured timeout of {timeout:g}. " + "The default timeout can be adjusted by passing a custom ClientPipelineOptions.NetworkTimeout value to the client's constructor. See https://aka.ms/net/scm/configure/networktimeout for more information."); } } } internal class ChangeTrackingStringList : IList<string>, ICollection<string>, IEnumerable<string>, IEnumerable { private IList<string> _list; private bool _frozen; private bool _tracking = true; public bool HasChanged { get; private set; } public string this[int index] { get { return _list[index]; } set { AssertNotFrozen(); _list[index] = value; HasChanged |= _tracking; } } public int Count => _list.Count; public bool IsReadOnly => _list.IsReadOnly; public ChangeTrackingStringList() { _list = new List<string>(); } public ChangeTrackingStringList(IEnumerable<string> collection) { _list = new List<string>(collection); } public void Freeze() { _frozen = true; } public void AssertNotFrozen() { if (_frozen) { throw new InvalidOperationException("Cannot change any client pipeline options after the client pipeline has been created."); } } public void Add(string item) { AssertNotFrozen(); _list.Add(item); HasChanged |= _tracking; } public void Clear() { AssertNotFrozen(); int count = _list.Count; _list.Clear(); HasChanged |= _tracking && count != 0; } public bool Contains(string item) { return _list.Contains(item); } public void CopyTo(string[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public IEnumerator<string> GetEnumerator() { return _list.GetEnumerator(); } public int IndexOf(string item) { return _list.IndexOf(item); } public void Insert(int index, string item) { AssertNotFrozen(); _list.Insert(index, item); HasChanged |= _tracking; } public bool Remove(string item) { AssertNotFrozen(); bool flag = _list.Remove(item); HasChanged |= _tracking && flag; return flag; } public void RemoveAt(int index) { AssertNotFrozen(); _list.RemoveAt(index); HasChanged |= _tracking; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal class ContentTypeUtilities { public static bool TryGetTextEncoding(string contentType, out Encoding? encoding) { if (contentType == null) { encoding = null; return false; } int num = contentType.IndexOf("; charset=", StringComparison.OrdinalIgnoreCase); if (num != -1 && contentType.AsSpan().Slice(num + "; charset=".Length).StartsWith("utf-8".AsSpan(), StringComparison.OrdinalIgnoreCase)) { encoding = Encoding.UTF8; return true; } if (contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("json", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("xml", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-urlencoded", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { encoding = Encoding.UTF8; return true; } encoding = null; return false; } } [EventSource(Name = "System.ClientModel")] internal sealed class ClientModelEventSource : EventSource { public static ClientModelEventSource Log = new ClientModelEventSource("System.ClientModel"); private ClientModelEventSource(string eventSourceName, string[]? traits = null) : base(eventSourceName, EventSourceSettings.Default, traits) { } [NonEvent] public void Request(string requestId, PipelineRequest request, string? clientAssembly, PipelineMessageSanitizer sanitizer) { if (IsEnabled(EventLevel.Informational, EventKeywords.None)) { Request(requestId, request.Method, sanitizer.SanitizeUrl(request.Uri.AbsoluteUri), FormatHeaders(request.Headers, sanitizer), clientAssembly); } } [Event(1, Level = EventLevel.Informational, Message = "Request [{0}] {1} {2}\r\n{3}client assembly: {4}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")] private void Request(string? requestId, string method, string uri, string headers, string? clientAssembly) { WriteEvent(1, requestId, method, uri, headers, clientAssembly); } [NonEvent] public void RequestContent(string requestId, byte[] content, Encoding? textEncoding) { if (IsEnabled(EventLevel.Verbose, EventKeywords.None)) { if (textEncoding != null) { RequestContentText(requestId, textEncoding.GetString(content)); } else { RequestContent(requestId, content); } } } [Event(2, Level = EventLevel.Verbose, Message = "Request [{0}] content: {1}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")] private void RequestContent(string? requestId, byte[] content) { WriteEvent(2, requestId, content); } [Event(17, Level = EventLevel.Verbose, Message = "Request [{0}] content: {1}")] private void RequestContentText(string? requestId, string content) { WriteEvent(17, requestId, content); } [NonEvent] public void Response(string requestId, PipelineResponse response, double seconds, PipelineMessageSanitizer sanitizer) { if (IsEnabled(EventLevel.Informational, EventKeywords.None)) { Response(requestId, response.Status, response.ReasonPhrase, FormatHeaders(response.Headers, sanitizer), seconds); } } [Event(5, Level = EventLevel.Informational, Message = "Response [{0}] {1} {2} ({4:00.0}s)\r\n{3}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")] private void Response(string? requestId, int status, string reasonPhrase, string headers, double seconds) { WriteEvent(5, requestId, status, reasonPhrase, headers, seconds); } [NonEvent] public void ResponseContent(string requestId, byte[] content, Encoding? textEncoding) { if (IsEnabled(EventLevel.Verbose, EventKeywords.None)) { if (textEncoding != null) { ResponseContentText(requestId, textEncoding.GetString(content)); } else { ResponseContent(requestId, content); } } } [Event(6, Level = EventLevel.Verbose, Message = "Response [{0}] content: {1}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")] private void ResponseContent(string? requestId, byte[] content) { WriteEvent(6, requestId, content); } [Event(13, Level = EventLevel.Verbose, Message = "Response [{0}] content: {1}")] private void ResponseContentText(string? requestId, string content) { WriteEvent(13, requestId, content); } [NonEvent] public void ResponseContentBlock(string requestId, int blockNumber, byte[] content, Encoding? textEncoding) { if (IsEnabled(EventLevel.Verbose, EventKeywords.None)) { if (textEncoding != null) { ResponseContentTextBlock(requestId, blockNumber, textEncoding.GetString(content)); } else { ResponseContentBlock(requestId, blockNumber, content); } } } [Event(11, Level = EventLevel.Verbose, Message = "Response [{0}] content block {1}: {2}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")] private void ResponseContentBlock(string? requestId, int blockNumber, byte[] content) { WriteEvent(11, requestId, blockNumber, content); } [Event(15, Level = EventLevel.Verbose, Message = "Response [{0}] content block {1}: {2}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")] private void ResponseContentTextBlock(string? requestId, int blockNumber, string content) { WriteEvent(15, requestId, blockNumber, content); } [NonEvent] public void ErrorResponse(string requestId, PipelineResponse response, double elapsed, PipelineMessageSanitizer sanitizer) { if (IsEnabled(EventLevel.Warning, EventKeywords.None)) { ErrorResponse(requestId, response.Status, response.ReasonPhrase, FormatHeaders(response.Headers, sanitizer), elapsed); } } [Event(8, Level = EventLevel.Warning, Message = "Error response [{0}] {1} {2} ({4:00.0}s)\r\n{3}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")] private void ErrorResponse(string? requestId, int status, string reasonPhrase, string headers, double seconds) { WriteEvent(8, requestId, status, reasonPhrase, headers, seconds); } [NonEvent] public void ErrorResponseContent(string requestId, byte[] content, Encoding? textEncoding) { if (IsEnabled(EventLevel.Informational, EventKeywords.None)) { if (textEncoding != null) { ErrorResponseContentText(requestId, textEncoding.GetString(content)); } else { ErrorResponseContent(requestId, content); } } } [Event(9, Level = EventLevel.Informational, Message = "Error response [{0}] content: {1}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")] private void ErrorResponseContent(string? requestId, byte[] content) { WriteEvent(9, requestId, content); } [Event(14, Level = EventLevel.Informational, Message = "Error response [{0}] content: {1}")] private void ErrorResponseContentText(string? requestId, string content) { WriteEvent(14, requestId, content); } [NonEvent] public void ErrorResponseContentBlock(string requestId, int blockNumber, byte[] content, Encoding? textEncoding) { if (IsEnabled(EventLevel.Informational, EventKeywords.None)) { if (textEncoding != null) { ErrorResponseContentTextBlock(requestId, blockNumber, textEncoding.GetString(content)); } else { ErrorResponseContentBlock(requestId, blockNumber, content); } } } [Event(12, Level = EventLevel.Informational, Message = "Error response [{0}] content block {1}: {2}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")] private void ErrorResponseContentBlock(string? requestId, int blockNumber, byte[] content) { WriteEvent(12, requestId, blockNumber, content); } [Event(16, Level = EventLevel.Informational, Message = "Error response [{0}] content block {1}: {2}")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")] private void ErrorResponseContentTextBlock(string? requestId, int blockNumber, string content) { WriteEvent(16, requestId, blockNumber, content); } [Event(10, Level = EventLevel.Informational, Message = "Request [{0}] attempt number {1} took {2:00.0}s")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")] public void RequestRetrying(string? requestId, int retryNumber, double seconds) { if (IsEnabled(EventLevel.Informational, EventKeywords.None)) { WriteEvent(10, requestId, retryNumber, seconds); } } [Event(7, Level = EventLevel.Warning, Message = "Response [{0}] took {1:00.0}s")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")] public void ResponseDelay(string? requestId, double seconds) { if (IsEnabled(EventLevel.Warning, EventKeywords.None)) { WriteEvent(7, requestId, seconds); } } [Event(18, Level = EventLevel.Informational, Message = "Request [{0}] exception {1}")] public void ExceptionResponse(string? requestId, string exception) { if (IsEnabled(EventLevel.Informational, EventKeywords.None)) { WriteEvent(18, requestId, exception); } } [NonEvent] private string FormatHeaders(IEnumerable<KeyValuePair<string, string>> headers, PipelineMessageSanitizer sanitizer) { StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair<string, string> header in headers) { stringBuilder.Append(header.Key); stringBuilder.Append(':'); stringBuilder.Append(sanitizer.SanitizeHeader(header.Key, header.Value)); stringBuilder.Append(Environment.NewLine); } return stringBuilder.ToString(); } } internal class LoggingEventIds { public const int RequestEvent = 1; public const int RequestContentEvent = 2; public const int ResponseEvent = 5; public const int ResponseContentEvent = 6; public const int ResponseDelayEvent = 7; public const int ErrorResponseEvent = 8; public const int ErrorResponseContentEvent = 9; public const int RequestRetryingEvent = 10; public const int ResponseContentBlockEvent = 11; public const int ErrorResponseContentBlockEvent = 12; public const int ResponseContentTextEvent = 13; public const int ErrorResponseContentTextEvent = 14; public const int ResponseContentTextBlockEvent = 15; public const int ErrorResponseContentTextBlockEvent = 16; public const int RequestContentTextEvent = 17; public const int ExceptionResponseEvent = 18; } internal class PipelineMessageHeadersLogValue : IReadOnlyList<KeyValuePair<string, string>>, IEnumerable<KeyValuePair<string, string>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, string>> { private readonly PipelineRequestHeaders? _requestHeaders; private readonly PipelineResponseHeaders? _responseHeaders; private readonly PipelineMessageSanitizer _sanitizer; private List<KeyValuePair<string, string>>? _values; private string? _formatted; private List<KeyValuePair<string, string>> Values { get { if (_values == null) { List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(); if (_requestHeaders != null) { foreach (KeyValuePair<string, string> requestHeader in _requestHeaders) { list.Add(new KeyValuePair<string, string>(requestHeader.Key, _sanitizer.SanitizeHeader(requestHeader.Key, requestHeader.Value))); } } else if (_responseHeaders != null) { foreach (KeyValuePair<string, string> responseHeader in _responseHeaders) { list.Add(new KeyValuePair<string, string>(responseHeader.Key, _sanitizer.SanitizeHeader(responseHeader.Key, responseHeader.Value))); } } _values = list; } return _values; } } public KeyValuePair<string, string> this[int index] { get { if (index < 0 || index >= Count) { throw new IndexOutOfRangeException("index"); } return Values[index]; } } public int Count => Values.Count; public PipelineMessageHeadersLogValue(PipelineRequestHeaders headers, PipelineMessageSanitizer sanitizer) { _sanitizer = sanitizer; _requestHeaders = headers; } public PipelineMessageHeadersLogValue(PipelineResponseHeaders headers, PipelineMessageSanitizer sanitizer) { _sanitizer = sanitizer; _responseHeaders = headers; } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return Values.GetEnumerator(); } public override string ToString() { if (_formatted == null) { StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair<string, string> value in Values) { stringBuilder.Append(value.Key); stringBuilder.Append(':'); stringBuilder.Append(_sanitizer.SanitizeHeader(value.Key, value.Value)); stringBuilder.Append(Environment.NewLine); } _formatted = stringBuilder.ToString(); } return _formatted; } } internal class PipelineMessageLogger { [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] [EditorBrowsable(EditorBrowsableState.Never)] private readonly struct __ResponseStruct : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>> { private readonly string _requestId; private readonly int _status; private readonly string _reasonPhrase; private readonly PipelineMessageHeadersLogValue _headers; private readonly double _seconds; public static readonly Func<__ResponseStruct, Exception?, string> Format = (__ResponseStruct state, Exception? ex) => state.ToString(); public int Count => 6; public KeyValuePair<string, object?> this[int index] => index switch { 0 => new KeyValuePair<string, object>("requestId", _requestId), 1 => new KeyValuePair<string, object>("status", _status), 2 => new KeyValuePair<string, object>("reasonPhrase", _reasonPhrase), 3 => new KeyValuePair<string, object>("headers", _headers), 4 => new KeyValuePair<string, object>("seconds", _seconds), 5 => new KeyValuePair<string, object>("{OriginalFormat}", "Response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{headers}"), _ => throw new IndexOutOfRangeException("index"), }; public __ResponseStruct(string requestId, int status, string reasonPhrase, PipelineMessageHeadersLogValue headers, double seconds) { _requestId = requestId; _status = status; _reasonPhrase = reasonPhrase; _headers = headers; _seconds = seconds; } public override string ToString() { string requestId = _requestId; int status = _status; string reasonPhrase = _reasonPhrase; double seconds = _seconds; string text = __LoggerMessageGenerator.Enumerate(_headers); return $"Response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{text}"; } public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() { for (int i = 0; i < 6; i++) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] [EditorBrowsable(EditorBrowsableState.Never)] private readonly struct __ErrorResponseStruct : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>> { private readonly string _requestId; private readonly int _status; private readonly string _reasonPhrase; private readonly PipelineMessageHeadersLogValue _headers; private readonly double _seconds; public static readonly Func<__ErrorResponseStruct, Exception?, string> Format = (__ErrorResponseStruct state, Exception? ex) => state.ToString(); public int Count => 6; public KeyValuePair<string, object?> this[int index] => index switch { 0 => new KeyValuePair<string, object>("requestId", _requestId), 1 => new KeyValuePair<string, object>("status", _status), 2 => new KeyValuePair<string, object>("reasonPhrase", _reasonPhrase), 3 => new KeyValuePair<string, object>("headers", _headers), 4 => new KeyValuePair<string, object>("seconds", _seconds), 5 => new KeyValuePair<string, object>("{OriginalFormat}", "Error response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{headers}"), _ => throw new IndexOutOfRangeException("index"), }; public __ErrorResponseStruct(string requestId, int status, string reasonPhrase, PipelineMessageHeadersLogValue headers, double seconds) { _requestId = requestId; _status = status; _reasonPhrase = reasonPhrase; _headers = headers; _seconds = seconds; } public override string ToString() { string requestId = _requestId; int status = _status; string reasonPhrase = _reasonPhrase; double seconds = _seconds; string text = __LoggerMessageGenerator.Enumerate(_headers); return $"Error response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{text}"; } public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() { for (int i = 0; i < 6; i++) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly ILogger<MessageLoggingPolicy>? _logger; private readonly PipelineMessageSanitizer _sanitizer; [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, string, string, PipelineMessageHeadersLogValue, string?, Exception?> __RequestCallback = LoggerMessage.Define<string, string, string, PipelineMessageHeadersLogValue, string>(LogLevel.Information, new EventId(1, "Request"), "Request [{requestId}] {method} {uri}\r\n{headers}client assembly: {clientAssembly}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, byte[], Exception?> __RequestContentCallback = LoggerMessage.Define<string, byte[]>(LogLevel.Debug, new EventId(2, "RequestContent"), "Request [{requestId}] content: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, string, Exception?> __RequestContentTextCallback = LoggerMessage.Define<string, string>(LogLevel.Debug, new EventId(17, "RequestContentText"), "Request [{requestId}] content: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, byte[], Exception?> __ResponseContentCallback = LoggerMessage.Define<string, byte[]>(LogLevel.Debug, new EventId(6, "ResponseContent"), "Response [{requestId}] content: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, string, Exception?> __ResponseContentTextCallback = LoggerMessage.Define<string, string>(LogLevel.Debug, new EventId(13, "ResponseContentText"), "Response [{requestId}] content: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, int, byte[], Exception?> __ResponseContentBlockCallback = LoggerMessage.Define<string, int, byte[]>(LogLevel.Debug, new EventId(11, "ResponseContentBlock"), "Response [{requestId}] content block {blockNumber}: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, int, string, Exception?> __ResponseContentTextBlockCallback = LoggerMessage.Define<string, int, string>(LogLevel.Debug, new EventId(15, "ResponseContentTextBlock"), "Response [{requestId}] content block {blockNumber}: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, byte[], Exception?> __ErrorResponseContentCallback = LoggerMessage.Define<string, byte[]>(LogLevel.Information, new EventId(9, "ErrorResponseContent"), "Error response [{requestId}] content: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, string, Exception?> __ErrorResponseContentTextCallback = LoggerMessage.Define<string, string>(LogLevel.Information, new EventId(14, "ErrorResponseContentText"), "Error response [{requestId}] content: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, int, byte[], Exception?> __ErrorResponseContentBlockCallback = LoggerMessage.Define<string, int, byte[]>(LogLevel.Information, new EventId(12, "ErrorResponseContentBlock"), "Error response [{requestId}] content block {blockNumber}: {content}", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, int, string, Exception?> __ErrorResponseContentTextBlockCallback = LoggerMessage.Define<string, int, string>(LogLevel.Information, new EventId(16, "ErrorResponseContentTextBlock"), "Error response [{requestId}] content block {blockNumber}: {content}", new LogDefineOptions { SkipEnabledCheck = true }); public PipelineMessageLogger(PipelineMessageSanitizer sanitizer, ILoggerFactory? loggerFactory) { _sanitizer = sanitizer; _logger = loggerFactory?.CreateLogger<MessageLoggingPolicy>() ?? null; } public bool IsEnabled(LogLevel logLevel, EventLevel eventLevel) { if (_logger == null) { return ClientModelEventSource.Log.IsEnabled(eventLevel, EventKeywords.None); } return _logger.IsEnabled(logLevel); } public void LogRequest(string requestId, PipelineRequest request, string? clientAssembly) { if (_logger != null) { if (_logger.IsEnabled(LogLevel.Information)) { Request(_logger, requestId, request.Method, _sanitizer.SanitizeUrl(request.Uri.AbsoluteUri), new PipelineMessageHeadersLogValue(request.Headers, _sanitizer), clientAssembly); } } else { ClientModelEventSource.Log.Request(requestId, request, clientAssembly, _sanitizer); } } [LoggerMessage(1, LogLevel.Information, "Request [{requestId}] {method} {uri}\r\n{headers}client assembly: {clientAssembly}", SkipEnabledCheck = true, EventName = "Request")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void Request(ILogger logger, string requestId, string method, string uri, PipelineMessageHeadersLogValue headers, string? clientAssembly) { __RequestCallback(logger, requestId, method, uri, headers, clientAssembly, null); } public void LogRequestContent(string requestId, byte[] content, Encoding? textEncoding) { if (_logger != null) { if (_logger.IsEnabled(LogLevel.Debug)) { if (textEncoding != null) { RequestContentText(_logger, requestId, textEncoding.GetString(content)); } else { RequestContent(_logger, requestId, content); } } } else { ClientModelEventSource.Log.RequestContent(requestId, content, textEncoding); } } [LoggerMessage(2, LogLevel.Debug, "Request [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "RequestContent")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void RequestContent(ILogger logger, string requestId, byte[] content) { __RequestContentCallback(logger, requestId, content, null); } [LoggerMessage(17, LogLevel.Debug, "Request [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "RequestContentText")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void RequestContentText(ILogger logger, string requestId, string content) { __RequestContentTextCallback(logger, requestId, content, null); } public void LogResponse(string requestId, PipelineResponse response, double seconds) { if (_logger != null) { if (_logger.IsEnabled(LogLevel.Information)) { Response(_logger, requestId, response.Status, response.ReasonPhrase, new PipelineMessageHeadersLogValue(response.Headers, _sanitizer), seconds); } } else { ClientModelEventSource.Log.Response(requestId, response, seconds, _sanitizer); } } [LoggerMessage(5, LogLevel.Information, "Response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{headers}", SkipEnabledCheck = true, EventName = "Response")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void Response(ILogger logger, string requestId, int status, string reasonPhrase, PipelineMessageHeadersLogValue headers, double seconds) { logger.Log(LogLevel.Information, new EventId(5, "Response"), new __ResponseStruct(requestId, status, reasonPhrase, headers, seconds), null, __ResponseStruct.Format); } public void LogResponseContent(string requestId, byte[] content, Encoding? textEncoding) { if (_logger != null) { if (_logger.IsEnabled(LogLevel.Debug)) { if (textEncoding != null) { ResponseContentText(_logger, requestId, textEncoding.GetString(content)); } else { ResponseContent(_logger, requestId, content); } } } else { ClientModelEventSource.Log.ResponseContent(requestId, content, textEncoding); } } [LoggerMessage(6, LogLevel.Debug, "Response [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "ResponseContent")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ResponseContent(ILogger logger, string requestId, byte[] content) { __ResponseContentCallback(logger, requestId, content, null); } [LoggerMessage(13, LogLevel.Debug, "Response [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "ResponseContentText")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ResponseContentText(ILogger logger, string requestId, string content) { __ResponseContentTextCallback(logger, requestId, content, null); } public void LogResponseContentBlock(string requestId, int blockNumber, byte[] content, Encoding? textEncoding) { if (_logger != null) { if (_logger.IsEnabled(LogLevel.Debug)) { if (textEncoding != null) { ResponseContentTextBlock(_logger, requestId, blockNumber, textEncoding.GetString(content)); } else { ResponseContentBlock(_logger, requestId, blockNumber, content); } } } else { ClientModelEventSource.Log.ResponseContentBlock(requestId, blockNumber, content, textEncoding); } } [LoggerMessage(11, LogLevel.Debug, "Response [{requestId}] content block {blockNumber}: {content}", SkipEnabledCheck = true, EventName = "ResponseContentBlock")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ResponseContentBlock(ILogger logger, string requestId, int blockNumber, byte[] content) { __ResponseContentBlockCallback(logger, requestId, blockNumber, content, null); } [LoggerMessage(15, LogLevel.Debug, "Response [{requestId}] content block {blockNumber}: {content}", SkipEnabledCheck = true, EventName = "ResponseContentTextBlock")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ResponseContentTextBlock(ILogger logger, string requestId, int blockNumber, string content) { __ResponseContentTextBlockCallback(logger, requestId, blockNumber, content, null); } public void LogErrorResponse(string requestId, PipelineResponse response, double seconds) { if (_logger != null) { if (_logger.IsEnabled(LogLevel.Warning)) { ErrorResponse(_logger, requestId, response.Status, response.ReasonPhrase, new PipelineMessageHeadersLogValue(response.Headers, _sanitizer), seconds); } } else { ClientModelEventSource.Log.ErrorResponse(requestId, response, seconds, _sanitizer); } } [LoggerMessage(8, LogLevel.Warning, "Error response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{headers}", SkipEnabledCheck = true, EventName = "ErrorResponse")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ErrorResponse(ILogger logger, string requestId, int status, string reasonPhrase, PipelineMessageHeadersLogValue headers, double seconds) { logger.Log(LogLevel.Warning, new EventId(8, "ErrorResponse"), new __ErrorResponseStruct(requestId, status, reasonPhrase, headers, seconds), null, __ErrorResponseStruct.Format); } public void LogErrorResponseContent(string requestId, byte[] content, Encoding? textEncoding) { if (_logger != null) { if (_logger.IsEnabled(LogLevel.Information)) { if (textEncoding != null) { ErrorResponseContentText(_logger, requestId, textEncoding.GetString(content)); } else { ErrorResponseContent(_logger, requestId, content); } } } else { ClientModelEventSource.Log.ErrorResponseContent(requestId, content, textEncoding); } } [LoggerMessage(9, LogLevel.Information, "Error response [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "ErrorResponseContent")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ErrorResponseContent(ILogger logger, string requestId, byte[] content) { __ErrorResponseContentCallback(logger, requestId, content, null); } [LoggerMessage(14, LogLevel.Information, "Error response [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "ErrorResponseContentText")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ErrorResponseContentText(ILogger logger, string requestId, string content) { __ErrorResponseContentTextCallback(logger, requestId, content, null); } public void LogErrorResponseContentBlock(string requestId, int blockNumber, byte[] content, Encoding? textEncoding) { if (_logger != null) { if (_logger.IsEnabled(LogLevel.Information)) { if (textEncoding != null) { ErrorResponseContentTextBlock(_logger, requestId, blockNumber, textEncoding.GetString(content)); } else { ErrorResponseContentBlock(_logger, requestId, blockNumber, content); } } } else { ClientModelEventSource.Log.ErrorResponseContentBlock(requestId, blockNumber, content, textEncoding); } } [LoggerMessage(12, LogLevel.Information, "Error response [{requestId}] content block {blockNumber}: {content}", SkipEnabledCheck = true, EventName = "ErrorResponseContentBlock")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ErrorResponseContentBlock(ILogger logger, string requestId, int blockNumber, byte[] content) { __ErrorResponseContentBlockCallback(logger, requestId, blockNumber, content, null); } [LoggerMessage(16, LogLevel.Information, "Error response [{requestId}] content block {blockNumber}: {content}", SkipEnabledCheck = true, EventName = "ErrorResponseContentTextBlock")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ErrorResponseContentTextBlock(ILogger logger, string requestId, int blockNumber, string content) { __ErrorResponseContentTextBlockCallback(logger, requestId, blockNumber, content, null); } } internal class PipelineMessageSanitizer { private const string LogAllValue = "*"; private readonly bool _logAllHeaders; private readonly bool _logFullQueries; private readonly string _redactedPlaceholder; [ThreadStatic] private static StringBuilder? s_cachedStringBuilder; private const int MaxCachedStringBuilderCapacity = 1024; internal readonly HashSet<string> _allowedQueryParameters; internal readonly HashSet<string> _allowedHeaders; public PipelineMessageSanitizer(HashSet<string> allowedQueryParameters, HashSet<string> allowedHeaders, string redactedPlaceholder = "REDACTED") { _logAllHeaders = allowedHeaders.Contains("*"); _logFullQueries = allowedQueryParameters.Contains("*"); _allowedQueryParameters = allowedQueryParameters; _redactedPlaceholder = redactedPlaceholder; _allowedHeaders = allowedHeaders; } public string SanitizeHeader(string name, string value) { if (_logAllHeaders || _allowedHeaders.Contains(name)) { return value; } return _redactedPlaceholder; } public bool ShouldSanitizeHeaderValue(string name) { if (_logAllHeaders || _allowedHeaders.Contains(name)) { return false; } return true; } public string SanitizeUrl(string url) { if (_logFullQueries) { return url; } int num = url.IndexOf('?'); if (num == -1) { return url; } StringBuilder stringBuilder = null; int num2 = num + 1; ReadOnlySpan<char> span2 = url.AsSpan(num + 1); while (span2.Length > 0) { int num3 = span2.IndexOf('&'); int num4 = span2.IndexOf('='); bool flag = false; if ((num3 == -1 && num4 == -1) || (num3 != -1 && (num4 == -1 || num4 > num3))) { num4 = num3; flag = true; } if (num4 == -1) { num4 = span2.Length; } num3 = ((num3 != -1) ? (num3 + 1) : span2.Length); ReadOnlySpan<char> span3 = span2.Slice(0, num4); bool flag2 = false; foreach (string allowedQueryParameter in _allowedQueryParameters) { if (MemoryExtensions.Equals(span3, allowedQueryParameter.AsSpan(), StringComparison.OrdinalIgnoreCase)) { flag2 = true; break; } } int num5 = num3; int length = num4; if (flag2 || flag) { if (stringBuilder == null) { num2 += num5; } else { AppendReadOnlySpan(stringBuilder, span2.Slice(0, num5)); } } else { if (stringBuilder == null) { stringBuilder = RentStringBuilder(url.Length).Append(url, 0, num2); } AppendReadOnlySpan(stringBuilder, span2.Slice(0, length)).Append('=').Append(_redactedPlaceholder); if (span2[num3 - 1] == '&') { stringBuilder.Append('&'); } } span2 = span2.Slice(num5); } if (stringBuilder != null) { return ToStringAndReturnStringBuilder(stringBuilder); } return url; static StringBuilder AppendReadOnlySpan(StringBuilder builder, ReadOnlySpan<char> span) { ReadOnlySpan<char> readOnlySpan = span; for (int i = 0; i < readOnlySpan.Length; i++) { char value = readOnlySpan[i]; builder.Append(value); } return builder; } } private static StringBuilder RentStringBuilder(int capacity) { if (capacity <= 1024) { StringBuilder stringBuilder = s_cachedStringBuilder; if (stringBuilder != null && stringBuilder.Capacity >= capacity) { s_cachedStringBuilder = null; return stringBuilder; } } return new StringBuilder(capacity); } private static string ToStringAndReturnStringBuilder(StringBuilder builder) { string result = builder.ToString(); if (builder.Capacity <= 1024) { s_cachedStringBuilder = builder.Clear(); } return result; } } internal class PipelineRetryLogger { private readonly ILogger<ClientRetryPolicy>? _logger; [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string?, int, double, Exception?> __RequestRetryingCallback = LoggerMessage.Define<string, int, double>(LogLevel.Information, new EventId(10, "RequestRetrying"), "Request [{requestId}] attempt number {retryNumber} took {seconds:00.0}s", new LogDefineOptions { SkipEnabledCheck = true }); public PipelineRetryLogger(ILoggerFactory? loggerFactory) { _logger = loggerFactory?.CreateLogger<ClientRetryPolicy>() ?? null; } public void LogRequestRetrying(string? requestId, int retryNumber, double seconds) { if (_logger != null) { RequestRetrying(_logger, requestId, retryNumber, seconds); } else { ClientModelEventSource.Log.RequestRetrying(requestId, retryNumber, seconds); } } [LoggerMessage(10, LogLevel.Information, "Request [{requestId}] attempt number {retryNumber} took {seconds:00.0}s", EventName = "RequestRetrying")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void RequestRetrying(ILogger logger, string? requestId, int retryNumber, double seconds) { if (logger.IsEnabled(LogLevel.Information)) { __RequestRetryingCallback(logger, requestId, retryNumber, seconds, null); } } } internal class PipelineTransportLogger { private readonly ILogger<PipelineTransport>? _logger; [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, double, Exception?> __ResponseDelayCallback = LoggerMessage.Define<string, double>(LogLevel.Warning, new EventId(7, "ResponseDelay"), "Response [{requestId}] took {seconds:00.0}s", new LogDefineOptions { SkipEnabledCheck = true }); [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static readonly Action<ILogger, string, Exception?> __ExceptionResponseCallback = LoggerMessage.Define<string>(LogLevel.Information, new EventId(18, "ExceptionResponse"), "Request [{requestId}] exception occurred.", new LogDefineOptions { SkipEnabledCheck = true }); public PipelineTransportLogger(ILoggerFactory? loggerFactory) { _logger = loggerFactory?.CreateLogger<PipelineTransport>() ?? null; } public void LogResponseDelay(string requestId, double seconds) { if (_logger != null) { ResponseDelay(_logger, requestId, seconds); } else { ClientModelEventSource.Log.ResponseDelay(requestId, seconds); } } [LoggerMessage(7, LogLevel.Warning, "Response [{requestId}] took {seconds:00.0}s", EventName = "ResponseDelay")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ResponseDelay(ILogger logger, string requestId, double seconds) { if (logger.IsEnabled(LogLevel.Warning)) { __ResponseDelayCallback(logger, requestId, seconds, null); } } public void LogExceptionResponse(string requestId, Exception exception) { if (_logger != null) { ExceptionResponse(_logger, requestId, exception); } else if (ClientModelEventSource.Log.IsEnabled(EventLevel.Informational, EventKeywords.None)) { ClientModelEventSource.Log.ExceptionResponse(requestId, exception.ToString()); } } [LoggerMessage(18, LogLevel.Information, "Request [{requestId}] exception occurred.", EventName = "ExceptionResponse")] [GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")] private static void ExceptionResponse(ILogger logger, string requestId, Exception exception) { if (logger.IsEnabled(LogLevel.Information)) { __ExceptionResponseCallback(logger, requestId, exception); } } } internal sealed class PollingInterval { private static readonly TimeSpan DefaultDelay = TimeSpan.FromSeconds(1.0); private readonly TimeSpan _interval; public PollingInterval(TimeSpan? interval = null) { _interval = interval ?? DefaultDelay; } public async Task WaitAsync(PipelineResponse response, CancellationToken cancellationToken) { await Task.Delay(GetDelay(response), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public void Wait(PipelineResponse response, CancellationToken cancellationToken) { TimeSpan delay = GetDelay(response); if (!cancellationToken.CanBeCanceled) { Thread.Sleep(delay); } else if (cancellationToken.WaitHandle.WaitOne(delay)) { cancellationToken.ThrowIfCancellationRequested(); } } private TimeSpan GetDelay(PipelineResponse response) { if (!PipelineResponseHeaders.TryGetRetryAfter(response, out var value) || !(value > _interval)) { return _interval; } return value; } } internal class ReadTimeoutStream : Stream { private readonly Stream _stream; private TimeSpan _readTimeout; private CancellationTokenSource _cancellationTokenSource; public override bool CanRead => _stream.CanRead; public override bool CanSeek => _stream.CanSeek; public override bool CanWrite => false; public override long Length => _stream.Length; public override long Position { get { return _stream.Position; } set { _stream.Position = value; } } public override int ReadTimeout { get { return (int)_readTimeout.TotalMilliseconds; } set { _readTimeout = TimeSpan.FromMilliseconds(value); UpdateReadTimeout(); } } public ReadTimeoutStream(Stream stream, TimeSpan readTimeout) { _stream = stream; _readTimeout = readTimeout; UpdateReadTimeout(); InitializeTokenSource(); } public override void Close() { _stream.Close(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { bool dispose; CancellationTokenSource cancellationTokenSource = StartTimeout(default(CancellationToken), out dispose); try { return _stream.Read(buffer, offset, count); } catch (IOException innerException) { CancellationHelper.ThrowIfCancellationRequestedOrTimeout(default(CancellationToken), cancellationTokenSource.Token, innerException, _readTimeout); throw; } catch (ObjectDisposedException innerException2) { CancellationHelper.ThrowIfCancellationRequestedOrTimeout(default(CancellationToken), cancellationTokenSource.Token, innerException2, _readTimeout); throw; } catch (OperationCanceledException innerException3) { CancellationHelper.ThrowIfCancellationRequestedOrTimeout(default(CancellationToken), cancellationTokenSource.Token, innerException3, _readTimeout); throw; } finally { StopTimeout(cancellationTokenSource, dispose); } } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { bool dispose; CancellationTokenSource source = StartTimeout(cancellationToken, out dispose); try { return await _stream.ReadAsync(buffer, offset, count, source.Token).ConfigureAwait(continueOnCapturedContext: false); } catch (IOException innerException) { CancellationHelper.ThrowIfCancellationRequestedOrTimeout(cancellationToken, source.Token, innerException, _readTimeout); throw; } catch (ObjectDisposedException innerException2) { CancellationHelper.ThrowIfCancellationRequestedOrTimeout(cancellationToken, source.Token, innerException2, _readTimeout); throw; } catch (OperationCanceledException innerException3) { CancellationHelper.ThrowIfCancellationRequestedOrTimeout(cancellationToken, source.Token, innerException3, _readTimeout); throw; } finally { StopTimeout(source, dispose); } } public override long Seek(long offset, SeekOrigin origin) { return _stream.Seek(offset, origin); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } private CancellationTokenSource StartTimeout(CancellationToken additionalToken, out bool dispose) { if (_cancellationTokenSource.IsCancellationRequested) { InitializeTokenSource(); } CancellationTokenSource result; if (additionalToken.CanBeCanceled) { result = CancellationTokenSource.CreateLinkedTokenSource(additionalToken, _cancellationTokenSource.Token); dispose = true; } else { result = _cancellationTokenSource; dispose = false; } _cancellationTokenSource.CancelAfter(_readTimeout); return result; } private void InitializeTokenSource() { _cancellationTokenSource = new CancellationTokenSource(); _cancellationTokenSource.Token.Register(delegate(object state) { ((ReadTimeoutStream)state).DisposeStream(); }, this); } private void StopTimeout(CancellationTokenSource source, bool dispose) { _cancellationTokenSource.CancelAfter(Timeout.InfiniteTimeSpan); if (dispose) { source.Dispose(); } } private void UpdateReadTimeout() { try { if (_stream.CanTimeout) { _stream.ReadTimeout = (int)_readTimeout.TotalMilliseconds; } } catch { } } protected override void Dispose(bool disposing) { base.Dispose(disposing); _stream.Dispose(); _cancellationTokenSource.Dispose(); } private void DisposeStream() { _stream.Dispose(); } } internal class RuntimeInformationWrapper { public virtual string FrameworkDescription => RuntimeInformation.FrameworkDescription; public virtual string OSDescription => RuntimeInformation.OSDescription; public virtual Architecture OSArchitecture => RuntimeInformation.OSArchitecture; public virtual Architecture ProcessArchitecture => RuntimeInformation.ProcessArchitecture; public virtual bool IsOSPlatform(OSPlatform osPlatform) { return RuntimeInformation.IsOSPlatform(osPlatform); } } internal static class ServicePointHelpers { private const int RuntimeDefaultConnectionLimit = 2; private const int IncreasedConnectionLimit = 50; private const int IncreasedConnectionLeaseTimeout = 300000; private static TimeSpan DefaultConnectionLeaseTimeoutTimeSpan = Timeout.InfiniteTimeSpan; private static TimeSpan IncreasedConnectionLeaseTimeoutTimeSpan = TimeSpan.FromMilliseconds(300000.0); public static void SetLimits(HttpMessageHandler messageHandler) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER"))) { return; } try { if (messageHandler is HttpClientHandler httpClientHandler && httpClientHandler.MaxConnectionsPerServer == 2) { httpClientHandler.MaxConnectionsPerServer = 50; } } catch (NotSupportedException) { } catch (NotImplementedException) { } } } internal static class TaskExtensions { public readonly struct Enumerable<T> : IEnumerable<T>, IEnumerable { private readonly IAsyncEnumerable<T> _asyncEnumerable; public Enumerable(IAsyncEnumerable<T> asyncEnumerable) { _asyncEnumerable = asyncEnumerable; } public Enumerator<T> GetEnumerator() { return new Enumerator<T>(_asyncEnumerable.GetAsyncEnumerator()); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator<T>(_asyncEnumerable.GetAsyncEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public readonly struct Enumerator<T> : IEnumerator<T>, IEnumerator, IDisposable { private readonly IAsyncEnumerator<T> _asyncEnumerator; public T Current => _asyncEnumerator.Current; object? IEnumerator.Current => Current; public Enumerator(IAsyncEnumerator<T> asyncEnumerator) { _asyncEnumerator = asyncEnumerator; } public bool MoveNext() { return _asyncEnumerator.MoveNextAsync().EnsureCompleted(); } public void Reset() { throw new NotSupportedException($"{GetType()} is a synchronous wrapper for {_asyncEnumerator.GetType()} async enumerator, which can't be reset, so IEnumerable.Reset() calls aren't supported."); } public void Dispose() { _asyncEnumerator.DisposeAsync().EnsureCompleted(); } } public readonly struct WithCancellationTaskAwaitable { private readonly CancellationToken _cancellationToken; private readonly ConfiguredTaskAwaitable _awaitable; public WithCancellationTaskAwaitable(Task task, CancellationToken cancellationToken) { _awaitable = task.ConfigureAwait(continueOnCapturedContext: false); _cancellationToken = cancellationToken; } public WithCancellationTaskAwaiter GetAwaiter() { ConfiguredTaskAwaitable awaitable = _awaitable; return new WithCancellationTaskAwaiter(awaitable.GetAwaiter(), _cancellationToken); } } public readonly struct WithCancellationTaskAwaitable<T> { private readonly CancellationToken _cancellationToken; private readonly ConfiguredTaskAwaitable<T> _awaitable; public WithCancellationTaskAwaitable(Task<T> task, CancellationToken cancellationToken) { _awaitable = task.ConfigureAwait(continueOnCapturedContext: false); _cancellationToken = cancellationToken; } public WithCancellationTaskAwaiter<T> GetAwaiter() { ConfiguredTaskAwaitable<T> awaitable = _awaitable; return new WithCancellationTaskAwaiter<T>(awaitable.GetAwaiter(), _cancellationToken); } } public readonly struct WithCancellationValueTaskAwaitable<T> { private readonly CancellationToken _cancellationToken; private readonly ConfiguredValueTaskAwaitable<T> _awaitable; public WithCancellationValueTaskAwaitable(ValueTask<T> task, CancellationToken cancellationToken) { _awaitable = task.ConfigureAwait(continueOnCapturedContext: false); _cancellationToken = cancellationToken; } public WithCancellationValueTaskAwaiter<T> GetAwaiter() { return new WithCancellationValueTaskAwaiter<T>(_awaitable.GetAwaiter(), _cancellationToken); } } public readonly struct WithCancellationTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly CancellationToken _cancellationToken; private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter _taskAwaiter; public bool IsCompleted { get { ConfiguredTaskAwaitable.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter; if (!taskAwaiter.IsCompleted) { CancellationToken cancellationToken = _cancellationToken; return cancellationToken.IsCancellationRequested; } return true; } } public WithCancellationTaskAwaiter(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter, CancellationToken cancellationToken) { _taskAwaiter = awaiter; _cancellationToken = cancellationToken; } public void OnCompleted(Action continuation) { ConfiguredTaskAwaitable.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter; taskAwaiter.OnCompleted(WrapContinuation(in continuation)); } public void UnsafeOnCompleted(Action continuation) { ConfiguredTaskAwaitable.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter; taskAwaiter.UnsafeOnCompleted(WrapContinuation(in continuation)); } public void GetResult() { ConfiguredTaskAwaitable.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter; if (!taskAwaiter.IsCompleted) { CancellationToken cancellationToken = _cancellationToken; cancellationToken.ThrowIfCancellationRequested(); } taskAwaiter = _taskAwaiter; taskAwaiter.GetResult(); } private Action WrapContinuation(in Action originalContinuation) { CancellationToken cancellationToken = _cancellationToken; if (!cancellationToken.CanBeCanceled) { return originalContinuation; } return new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation; } } public readonly struct WithCancellationTaskAwaiter<T> : ICriticalNotifyCompletion, INotifyCompletion { private readonly CancellationToken _cancellationToken; private readonly ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter _taskAwaiter; public bool IsCompleted { get { ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter; if (!taskAwaiter.IsCompleted) { CancellationToken cancellationToken = _cancellationToken; return cancellationToken.IsCancellationRequested; } return true; } } public WithCancellationTaskAwaiter(ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter awaiter, CancellationToken cancellationToken) { _taskAwaiter = awaiter; _cancellationToken = cancellationToken; } public void OnCompleted(Action continuation) { ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter; taskAwaiter.OnCompleted(WrapContinuation(in continuation)); } public void UnsafeOnCompleted(Action continuation) { ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter; taskAwaiter.UnsafeOnCompleted(WrapContinuation(in continuation)); } public T GetResult() { ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter; if (!taskAwaiter.IsCompleted) { CancellationToken cancellationToken = _cancellationToken; cancellationToken.ThrowIfCancellationRequested(); } taskAwaiter = _taskAwaiter; return taskAwaiter.GetResult(); } private Action WrapContinuation(in Action originalContinuation) { CancellationToken cancellationToken = _cancellationToken; if (!cancellationToken.CanBeCanceled) { return originalContinuation; } return new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation; } } public readonly struct WithCancellationValueTaskAwaiter<T> : ICriticalNotifyCompletion, INotifyCompletion { private readonly CancellationToken _cancellationToken; private readonly ConfiguredValueTaskAwaitable<T>.ConfiguredValueTaskAwaiter _taskAwaiter; public bool IsCompleted { get { if (!_taskAwaiter.IsCompleted) { CancellationToken cancellationToken = _cancellationToken; return cancellationToken.IsCancellationRequested; } return true; } } public WithCancellationValueTaskAwaiter(ConfiguredValueTaskAwaitable<T>.ConfiguredValueTaskAwaiter awaiter, CancellationToken cancellationToken) { _taskAwaiter = awaiter; _cancellationToken = cancellationToken; } public void OnCompleted(Action continuation) { _taskAwaiter.OnCompleted(WrapContinuation(in continuation)); } public void UnsafeOnCompleted(Action continuation) { _taskAwaiter.UnsafeOnCompleted(WrapContinuation(in continuation)); } public T GetResult() { if (!_taskAwaiter.IsCompleted) { CancellationToken cancellationToken = _cancellationToken; cancellationToken.ThrowIfCancellationRequested(); } return _taskAwaiter.GetResult(); } private Action WrapContinuation(in Action originalContinuation) { CancellationToken cancellationToken = _cancellationToken; if (!cancellationToken.CanBeCanceled) { return originalContinuation; } return new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation; } } private class WithCancellationContinuationWrapper { private Action? _originalContinuation; private readonly CancellationTokenRegistration _registration; public Action Continuation { get; } public WithCancellationContinuationWrapper(Action originalContinuation, CancellationToken cancellationToken) { Action callback = ContinuationImplementation; _originalContinuation = originalContinuation; _registration = cancellationToken.Register(callback); Continuation = callback; } private void ContinuationImplementation() { Action action = Interlocked.Exchange(ref _originalContinuation, null); if (action != null) { CancellationTokenRegistration registration = _registration; registration.Dispose(); action(); } } } public static WithCancellationTaskAwaitable AwaitWithCancellation(this Task task, CancellationToken cancellationToken) { return new WithCancellationTaskAwaitable(task, cancellationToken); } public static WithCancellationTaskAwaitable<T> AwaitWithCancellation<T>(this Task<T> task, CancellationToken cancellationToken) { return new WithCancellationTaskAwaitable<T>(task, cancellationToken); } public static WithCancellationValueTaskAwaitable<T> AwaitWithCancellation<T>(this ValueTask<T> task, CancellationToken cancellationToken) { return new WithCancellationValueTaskAwaitable<T>(task, cancellationToken); } public static T EnsureCompleted<T>(this Task<T> task) { return task.GetAwaiter().GetResult(); } public static void EnsureCompleted(this Task task) { task.GetAwaiter().GetResult(); } public static T EnsureCompleted<T>(this ValueTask<T> task) { return task.GetAwaiter().GetResult(); } public static void EnsureCompleted(this ValueTask task) { task.GetAwaiter().GetResult(); } public static Enumerable<T> EnsureSyncEnumerable<T>(this IAsyncEnumerable<T> asyncEnumerable) { return new Enumerable<T>(asyncEnumerable); } public static ConfiguredValueTaskAwaitable<T> EnsureCompleted<T>(this ConfiguredValueTaskAwaitable<T> awaitable, bool async) { return awaitable; } public static ConfiguredValueTaskAwaitable EnsureCompleted(this ConfiguredValueTaskAwaitable awaitable, bool async) { return awaitable; } [Conditional("DEBUG")] private static void VerifyTaskCompleted(bool isCompleted) { if (!isCompleted) { if (Debugger.IsAttached) { Debugger.Break(); } throw new InvalidOperationException("Task is not completed"); } } } internal static class TypeExtensions { public static string ToFriendlyName(this Type type) { if (type == null) { return string.Empty; } if (type.IsGenericType) { string obj = type.GetGenericTypeDefinition().Name.Split(new char[1] { '`' })[0]; Type[] genericArguments = type.GetGenericArguments(); string text = string.Join(", ", Array.ConvertAll(genericArguments, (Type t) => t.ToFriendlyName())); return obj + "<" + text + ">"; } if (type.IsArray) { if (type.GetArrayRank() > 1) { return type.GetElementType().ToFriendlyName() + "[" + new string(',', type.GetArrayRank() - 1) + "]"; } return type.GetElementType().ToFriendlyName() + "[]"; } Type underlyingType = Nullable.GetUnderlyingType(type); if ((object)underlyingType != null) { return underlyingType.ToFriendlyName(); } return type.Name; } } internal class ModelWriter : ModelWriter<object> { public ModelWriter(IJsonModel<object> model, ModelReaderWriterOptions options) : base(model, options) { } } internal class ModelWriter<T> { private readonly IJsonModel<T> _model; private readonly ModelReaderWriterOptions _options; public ModelWriter(IJsonModel<T> model, ModelReaderWriterOptions options) { _model = model; _options = options; } public UnsafeBufferSequence.Reader ExtractReader() { using UnsafeBufferSequence unsafeBufferSequence = new UnsafeBufferSequence(); using Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(unsafeBufferSequence, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); _model.Write(utf8JsonWriter, _options); utf8JsonWriter.Flush(); return unsafeBufferSequence.ExtractReader(); } } internal struct UnsafeBufferSegment { public byte[] Array; public int Written; } internal sealed class UnsafeBufferSequence : IBufferWriter<byte>, IDisposable { private class ReaderInstance : Reader { public ReaderInstance(UnsafeBufferSegment[] buffers, int count) : base(buffers, count) { } } internal class Reader : IDisposable { private UnsafeBufferSegment[] _buffers; private int _count; private bool _isDisposed; private static readonly object _disposeLock = new object(); public long Length { get { if (_isDisposed) { throw new ObjectDisposedException("Reader"); } long num = 0L; for (int i = 0; i < _count; i++) { num += _buffers[i].Written; } return num; } } private protected Reader(UnsafeBufferSegment[] buffers, int count) { _buffers = buffers; _count = count; } public void CopyTo(Stream stream, CancellationToken cancellation) { if (_isDisposed) { throw new ObjectDisposedException("Reader"); } for (int i = 0; i < _count; i++) { cancellation.ThrowIfCancellationRequested(); UnsafeBufferSegment unsafeBufferSegment = _buffers[i]; stream.Write(unsafeBufferSegment.Array, 0, unsafeBufferSegment.Written); } } public async Task CopyToAsync(Stream stream, CancellationToken cancellation) { if (_isDisposed) { throw new ObjectDisposedException("Reader"); } for (int i = 0; i < _count; i++) { cancellation.ThrowIfCancellationRequested(); UnsafeBufferSegment unsafeBufferSegment = _buffers[i]; await stream.WriteAsync(unsafeBufferSegment.Array, 0, unsafeBufferSegment.Written, cancellation).ConfigureAwait(continueOnCapturedContext: false); } } public BinaryData ToBinaryData() { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Expected O, but got Unknown if (_isDisposed) { throw new ObjectDisposedException("Reader"); } long length = Length; if (length > int.MaxValue) { throw new InvalidOperationException($"Length of serialized model is too long. Value was {length} max is {int.MaxValue}"); } if (_count == 1) { byte[] array = new byte[_buffers[0].Written]; Buffer.BlockCopy(_buffers[0].Array, 0, array, 0, _buffers[0].Written); return new BinaryData(array); } using MemoryStream memoryStream = new MemoryStream((int)length); CopyTo(memoryStream, default(CancellationToken)); return new BinaryData((ReadOnlyMemory<byte>)memoryStream.GetBuffer().AsMemory(0, (int)memoryStream.Position)); } public void Dispose() { if (_isDisposed) { return; } lock (_disposeLock) { if (!_isDisposed) { int count = _count; UnsafeBufferSegment[] buffers = _buffers; _count = 0; _buffers = Array.Empty<UnsafeBufferSegment>(); for (int i = 0; i < count; i++) { ArrayPool<byte>.Shared.Return(buffers[i].Array); } _isDisposed = true; } } } } private volatile UnsafeBufferSegment[] _buff
deps/System.Collections.Immutable.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Collections.Immutable; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("System.Collections.Immutable.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Collections.Immutable")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("This package provides collections that are thread safe and guaranteed to never change their contents, also known as immutable collections. Like strings, any methods that perform modifications will not change the existing instance but instead return a new instance. For efficiency reasons, the implementation uses a sharing mechanism to ensure that newly created instances share as much data as possible with the previous instance while ensuring that operations have a predictable time complexity.\r\n\r\nThe System.Collections.Immutable library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] [assembly: AssemblyFileVersion("9.0.24.52809")] [assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Collections.Immutable")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("9.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] 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] internal sealed class ParamCollectionAttribute : 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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [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 FxResources.System.Collections.Immutable { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue(); private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey"); internal static string ArrayInitializedStateNotEqual => GetResourceString("ArrayInitializedStateNotEqual"); internal static string ArrayLengthsNotEqual => GetResourceString("ArrayLengthsNotEqual"); internal static string CannotFindOldValue => GetResourceString("CannotFindOldValue"); internal static string CapacityMustBeGreaterThanOrEqualToCount => GetResourceString("CapacityMustBeGreaterThanOrEqualToCount"); internal static string CapacityMustEqualCountOnMove => GetResourceString("CapacityMustEqualCountOnMove"); internal static string CollectionModifiedDuringEnumeration => GetResourceString("CollectionModifiedDuringEnumeration"); internal static string DuplicateKey => GetResourceString("DuplicateKey"); internal static string InvalidEmptyOperation => GetResourceString("InvalidEmptyOperation"); internal static string InvalidOperationOnDefaultArray => GetResourceString("InvalidOperationOnDefaultArray"); internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow"); internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported"); internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound"); internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall"); internal static string Argument_IncompatibleArrayType => GetResourceString("Argument_IncompatibleArrayType"); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); internal static string InvalidOperation_IncompatibleComparer => GetResourceString("InvalidOperation_IncompatibleComparer"); private static bool GetUsingResourceKeysSwitchValue() { if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled)) { return false; } return isEnabled; } internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Linq { public static class ImmutableArrayExtensions { public static IEnumerable<TResult> Select<T, TResult>(this ImmutableArray<T> immutableArray, Func<T, TResult> selector) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.Select(selector); } public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this ImmutableArray<TSource> immutableArray, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { immutableArray.ThrowNullRefIfNotInitialized(); if (collectionSelector == null || resultSelector == null) { return Enumerable.SelectMany(immutableArray, collectionSelector, resultSelector); } if (immutableArray.Length != 0) { return immutableArray.SelectManyIterator(collectionSelector, resultSelector); } return Enumerable.Empty<TResult>(); } public static IEnumerable<T> Where<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.Where(predicate); } public static bool Any<T>(this ImmutableArray<T> immutableArray) { return immutableArray.Length > 0; } public static bool Any<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); Requires.NotNull(predicate, "predicate"); T[] array = immutableArray.array; foreach (T arg in array) { if (predicate(arg)) { return true; } } return false; } public static bool All<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); Requires.NotNull(predicate, "predicate"); T[] array = immutableArray.array; foreach (T arg in array) { if (!predicate(arg)) { return false; } } return true; } public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, IEqualityComparer<TBase>? comparer = null) where TDerived : TBase { immutableArray.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); if (immutableArray.array == items.array) { return true; } if (immutableArray.Length != items.Length) { return false; } if (comparer == null) { comparer = EqualityComparer<TBase>.Default; } for (int i = 0; i < immutableArray.Length; i++) { if (!comparer.Equals(immutableArray.array[i], (TBase)(object)items.array[i])) { return false; } } return true; } public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, IEnumerable<TDerived> items, IEqualityComparer<TBase>? comparer = null) where TDerived : TBase { Requires.NotNull(items, "items"); if (comparer == null) { comparer = EqualityComparer<TBase>.Default; } int num = 0; int length = immutableArray.Length; foreach (TDerived item in items) { if (num == length) { return false; } if (!comparer.Equals(immutableArray[num], (TBase)(object)item)) { return false; } num++; } return num == length; } public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, Func<TBase, TBase, bool> predicate) where TDerived : TBase { Requires.NotNull(predicate, "predicate"); immutableArray.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); if (immutableArray.array == items.array) { return true; } if (immutableArray.Length != items.Length) { return false; } int i = 0; for (int length = immutableArray.Length; i < length; i++) { if (!predicate(immutableArray[i], (TBase)(object)items[i])) { return false; } } return true; } public static T? Aggregate<T>(this ImmutableArray<T> immutableArray, Func<T, T, T> func) { Requires.NotNull(func, "func"); if (immutableArray.Length == 0) { return default(T); } T val = immutableArray[0]; int i = 1; for (int length = immutableArray.Length; i < length; i++) { val = func(val, immutableArray[i]); } return val; } public static TAccumulate Aggregate<TAccumulate, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func) { Requires.NotNull(func, "func"); TAccumulate val = seed; T[] array = immutableArray.array; foreach (T arg in array) { val = func(val, arg); } return val; } public static TResult Aggregate<TAccumulate, TResult, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func, Func<TAccumulate, TResult> resultSelector) { Requires.NotNull(resultSelector, "resultSelector"); return resultSelector(immutableArray.Aggregate(seed, func)); } public static T ElementAt<T>(this ImmutableArray<T> immutableArray, int index) { return immutableArray[index]; } public static T? ElementAtOrDefault<T>(this ImmutableArray<T> immutableArray, int index) { if (index < 0 || index >= immutableArray.Length) { return default(T); } return immutableArray[index]; } public static T First<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); T[] array = immutableArray.array; foreach (T val in array) { if (predicate(val)) { return val; } } return Enumerable.Empty<T>().First(); } public static T First<T>(this ImmutableArray<T> immutableArray) { if (immutableArray.Length <= 0) { return immutableArray.array.First(); } return immutableArray[0]; } public static T? FirstOrDefault<T>(this ImmutableArray<T> immutableArray) { if (immutableArray.array.Length == 0) { return default(T); } return immutableArray.array[0]; } public static T? FirstOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); T[] array = immutableArray.array; foreach (T val in array) { if (predicate(val)) { return val; } } return default(T); } public static T Last<T>(this ImmutableArray<T> immutableArray) { if (immutableArray.Length <= 0) { return immutableArray.array.Last(); } return immutableArray[immutableArray.Length - 1]; } public static T Last<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); for (int num = immutableArray.Length - 1; num >= 0; num--) { if (predicate(immutableArray[num])) { return immutableArray[num]; } } return Enumerable.Empty<T>().Last(); } public static T? LastOrDefault<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.LastOrDefault(); } public static T? LastOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); for (int num = immutableArray.Length - 1; num >= 0; num--) { if (predicate(immutableArray[num])) { return immutableArray[num]; } } return default(T); } public static T Single<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.Single(); } public static T Single<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); bool flag = true; T result = default(T); T[] array = immutableArray.array; foreach (T val in array) { if (predicate(val)) { if (!flag) { ImmutableArray.TwoElementArray.Single(); } flag = false; result = val; } } if (flag) { Enumerable.Empty<T>().Single(); } return result; } public static T? SingleOrDefault<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.SingleOrDefault(); } public static T? SingleOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); bool flag = true; T result = default(T); T[] array = immutableArray.array; foreach (T val in array) { if (predicate(val)) { if (!flag) { ImmutableArray.TwoElementArray.Single(); } flag = false; result = val; } } return result; } public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector) where TKey : notnull { return immutableArray.ToDictionary(keySelector, EqualityComparer<TKey>.Default); } public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector) where TKey : notnull { return immutableArray.ToDictionary(keySelector, elementSelector, EqualityComparer<TKey>.Default); } public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) where TKey : notnull { Requires.NotNull(keySelector, "keySelector"); Dictionary<TKey, T> dictionary = new Dictionary<TKey, T>(immutableArray.Length, comparer); ImmutableArray<T>.Enumerator enumerator = immutableArray.GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; dictionary.Add(keySelector(current), current); } return dictionary; } public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector, IEqualityComparer<TKey>? comparer) where TKey : notnull { Requires.NotNull(keySelector, "keySelector"); Requires.NotNull(elementSelector, "elementSelector"); Dictionary<TKey, TElement> dictionary = new Dictionary<TKey, TElement>(immutableArray.Length, comparer); T[] array = immutableArray.array; foreach (T arg in array) { dictionary.Add(keySelector(arg), elementSelector(arg)); } return dictionary; } public static T[] ToArray<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); if (immutableArray.array.Length == 0) { return ImmutableArray<T>.Empty.array; } return (T[])immutableArray.array.Clone(); } public static T First<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { throw new InvalidOperationException(); } return builder[0]; } public static T? FirstOrDefault<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { return default(T); } return builder[0]; } public static T Last<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { throw new InvalidOperationException(); } return builder[builder.Count - 1]; } public static T? LastOrDefault<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { return default(T); } return builder[builder.Count - 1]; } public static bool Any<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); return builder.Count > 0; } private static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>(this ImmutableArray<TSource> immutableArray, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { TSource[] array = immutableArray.array; foreach (TSource item in array) { foreach (TCollection item2 in collectionSelector(item)) { yield return resultSelector(item, item2); } } } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.InteropServices { public static class ImmutableCollectionsMarshal { public static ImmutableArray<T> AsImmutableArray<T>(T[]? array) { return new ImmutableArray<T>(array); } public static T[]? AsArray<T>(ImmutableArray<T> array) { return array.array; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] internal sealed class CollectionBuilderAttribute : Attribute { public Type BuilderType { get; } public string MethodName { get; } public CollectionBuilderAttribute(Type builderType, string methodName) { BuilderType = builderType; MethodName = methodName; } } } namespace System.Numerics { internal static class BitOperations { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint RotateLeft(uint value, int offset) { return (value << offset) | (value >> 32 - offset); } } } namespace System.Collections { internal static class ThrowHelper { public static void ThrowIfNull(object arg, [CallerArgumentExpression("arg")] string? paramName = null) { if (arg == null) { ThrowArgumentNullException(paramName); } } [DoesNotReturn] public static void ThrowIfDestinationTooSmall() { throw new ArgumentException(System.SR.CapacityMustBeGreaterThanOrEqualToCount, "destination"); } [DoesNotReturn] public static void ThrowArgumentNullException(string? paramName) { throw new ArgumentNullException(paramName); } [DoesNotReturn] public static void ThrowKeyNotFoundException() { throw new KeyNotFoundException(); } [DoesNotReturn] public static void ThrowKeyNotFoundException<TKey>(TKey key) { throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key)); } [DoesNotReturn] public static void ThrowInvalidOperationException() { throw new InvalidOperationException(); } [DoesNotReturn] internal static void ThrowIncompatibleComparer() { throw new InvalidOperationException(System.SR.InvalidOperation_IncompatibleComparer); } } internal static class HashHelpers { public const uint HashCollisionThreshold = 100u; public const int MaxPrimeArrayLength = 2147483587; public const int HashPrime = 101; internal static ReadOnlySpan<int> Primes { get { object obj = global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6; if (obj == null) { obj = new int[72] { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6 = (int[])obj; } return new ReadOnlySpan<int>((int[]?)obj); } } public static bool IsPrime(int candidate) { if (((uint)candidate & (true ? 1u : 0u)) != 0) { int num = (int)Math.Sqrt(candidate); for (int i = 3; i <= num; i += 2) { if (candidate % i == 0) { return false; } } return true; } return candidate == 2; } public static int GetPrime(int min) { if (min < 0) { throw new ArgumentException(System.SR.Arg_HTCapacityOverflow); } ReadOnlySpan<int> primes = Primes; for (int i = 0; i < primes.Length; i++) { int num = primes[i]; if (num >= min) { return num; } } for (int j = min | 1; j < int.MaxValue; j += 2) { if (IsPrime(j) && (j - 1) % 101 != 0) { return j; } } return min; } public static int ExpandPrime(int oldSize) { int num = 2 * oldSize; if ((uint)num > 2147483587u && 2147483587 > oldSize) { return 2147483587; } return GetPrime(num); } public static ulong GetFastModMultiplier(uint divisor) { return ulong.MaxValue / (ulong)divisor + 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint FastMod(uint value, uint divisor, ulong multiplier) { return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32); } } } namespace System.Collections.Immutable { internal static class AllocFreeConcurrentStack<T> { private const int MaxSize = 35; private static readonly Type s_typeOfT = typeof(T); private static Stack<RefAsValueType<T>> ThreadLocalStack { get { Dictionary<Type, object> dictionary = AllocFreeConcurrentStack.t_stacks ?? (AllocFreeConcurrentStack.t_stacks = new Dictionary<Type, object>()); if (!dictionary.TryGetValue(s_typeOfT, out var value)) { value = new Stack<RefAsValueType<T>>(35); dictionary.Add(s_typeOfT, value); } return (Stack<RefAsValueType<T>>)value; } } public static void TryAdd(T item) { Stack<RefAsValueType<T>> threadLocalStack = ThreadLocalStack; if (threadLocalStack.Count < 35) { threadLocalStack.Push(new RefAsValueType<T>(item)); } } public static bool TryTake([MaybeNullWhen(false)] out T item) { Stack<RefAsValueType<T>> threadLocalStack = ThreadLocalStack; if (threadLocalStack != null && threadLocalStack.Count > 0) { item = threadLocalStack.Pop().Value; return true; } item = default(T); return false; } } internal static class AllocFreeConcurrentStack { [ThreadStatic] internal static Dictionary<Type, object>? t_stacks; } internal sealed class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator, IEnumerator where TKey : notnull { private readonly IEnumerator<KeyValuePair<TKey, TValue>> _inner; public DictionaryEntry Entry => new DictionaryEntry(_inner.Current.Key, _inner.Current.Value); public object Key => _inner.Current.Key; public object? Value => _inner.Current.Value; public object Current => Entry; internal DictionaryEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> inner) { Requires.NotNull(inner, "inner"); _inner = inner; } public bool MoveNext() { return _inner.MoveNext(); } public void Reset() { _inner.Reset(); } } internal struct DisposableEnumeratorAdapter<T, TEnumerator> : IDisposable where TEnumerator : struct, IEnumerator<T> { private readonly IEnumerator<T> _enumeratorObject; private TEnumerator _enumeratorStruct; public T Current { get { if (_enumeratorObject == null) { return _enumeratorStruct.Current; } return _enumeratorObject.Current; } } internal DisposableEnumeratorAdapter(TEnumerator enumerator) { _enumeratorStruct = enumerator; _enumeratorObject = null; } internal DisposableEnumeratorAdapter(IEnumerator<T> enumerator) { _enumeratorStruct = default(TEnumerator); _enumeratorObject = enumerator; } public bool MoveNext() { if (_enumeratorObject == null) { return _enumeratorStruct.MoveNext(); } return _enumeratorObject.MoveNext(); } public void Dispose() { if (_enumeratorObject != null) { _enumeratorObject.Dispose(); } else { _enumeratorStruct.Dispose(); } } public DisposableEnumeratorAdapter<T, TEnumerator> GetEnumerator() { return this; } } internal interface IBinaryTree { int Height { get; } bool IsEmpty { get; } int Count { get; } IBinaryTree? Left { get; } IBinaryTree? Right { get; } } internal interface IBinaryTree<out T> : IBinaryTree { T Value { get; } new IBinaryTree<T>? Left { get; } new IBinaryTree<T>? Right { get; } } internal interface IImmutableArray { Array? Array { get; } } public interface IImmutableDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IReadOnlyCollection<KeyValuePair<TKey, TValue>> { IImmutableDictionary<TKey, TValue> Clear(); IImmutableDictionary<TKey, TValue> Add(TKey key, TValue value); IImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs); IImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value); IImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items); IImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys); IImmutableDictionary<TKey, TValue> Remove(TKey key); bool Contains(KeyValuePair<TKey, TValue> pair); bool TryGetKey(TKey equalKey, out TKey actualKey); } internal interface IImmutableDictionaryInternal<TKey, TValue> { bool ContainsValue(TValue value); } [CollectionBuilder(typeof(ImmutableList), "Create")] public interface IImmutableList<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T> { IImmutableList<T> Clear(); int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer); int LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer); IImmutableList<T> Add(T value); IImmutableList<T> AddRange(IEnumerable<T> items); IImmutableList<T> Insert(int index, T element); IImmutableList<T> InsertRange(int index, IEnumerable<T> items); IImmutableList<T> Remove(T value, IEqualityComparer<T>? equalityComparer); IImmutableList<T> RemoveAll(Predicate<T> match); IImmutableList<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer); IImmutableList<T> RemoveRange(int index, int count); IImmutableList<T> RemoveAt(int index); IImmutableList<T> SetItem(int index, T value); IImmutableList<T> Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer); } internal interface IImmutableListQueries<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T> { ImmutableList<TOutput> ConvertAll<TOutput>(Func<T, TOutput> converter); void ForEach(Action<T> action); ImmutableList<T> GetRange(int index, int count); void CopyTo(T[] array); void CopyTo(T[] array, int arrayIndex); void CopyTo(int index, T[] array, int arrayIndex, int count); bool Exists(Predicate<T> match); T? Find(Predicate<T> match); ImmutableList<T> FindAll(Predicate<T> match); int FindIndex(Predicate<T> match); int FindIndex(int startIndex, Predicate<T> match); int FindIndex(int startIndex, int count, Predicate<T> match); T? FindLast(Predicate<T> match); int FindLastIndex(Predicate<T> match); int FindLastIndex(int startIndex, Predicate<T> match); int FindLastIndex(int startIndex, int count, Predicate<T> match); bool TrueForAll(Predicate<T> match); int BinarySearch(T item); int BinarySearch(T item, IComparer<T>? comparer); int BinarySearch(int index, int count, T item, IComparer<T>? comparer); } [CollectionBuilder(typeof(ImmutableQueue), "Create")] public interface IImmutableQueue<T> : IEnumerable<T>, IEnumerable { bool IsEmpty { get; } IImmutableQueue<T> Clear(); T Peek(); IImmutableQueue<T> Enqueue(T value); IImmutableQueue<T> Dequeue(); } [CollectionBuilder(typeof(ImmutableHashSet), "Create")] public interface IImmutableSet<T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable { IImmutableSet<T> Clear(); bool Contains(T value); IImmutableSet<T> Add(T value); IImmutableSet<T> Remove(T value); bool TryGetValue(T equalValue, out T actualValue); IImmutableSet<T> Intersect(IEnumerable<T> other); IImmutableSet<T> Except(IEnumerable<T> other); IImmutableSet<T> SymmetricExcept(IEnumerable<T> other); IImmutableSet<T> Union(IEnumerable<T> other); bool SetEquals(IEnumerable<T> other); bool IsProperSubsetOf(IEnumerable<T> other); bool IsProperSupersetOf(IEnumerable<T> other); bool IsSubsetOf(IEnumerable<T> other); bool IsSupersetOf(IEnumerable<T> other); bool Overlaps(IEnumerable<T> other); } [CollectionBuilder(typeof(ImmutableStack), "Create")] public interface IImmutableStack<T> : IEnumerable<T>, IEnumerable { bool IsEmpty { get; } IImmutableStack<T> Clear(); IImmutableStack<T> Push(T value); IImmutableStack<T> Pop(); T Peek(); } [CollectionBuilder(typeof(ImmutableHashSet), "Create")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] public sealed class ImmutableHashSet<T> : IImmutableSet<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, IHashKeyCollection<T>, ICollection<T>, ISet<T>, ICollection, IStrongEnumerable<T, ImmutableHashSet<T>.Enumerator> { private sealed class HashBucketByValueEqualityComparer : IEqualityComparer<HashBucket> { private static readonly IEqualityComparer<HashBucket> s_defaultInstance = new HashBucketByValueEqualityComparer(EqualityComparer<T>.Default); private readonly IEqualityComparer<T> _valueComparer; internal static IEqualityComparer<HashBucket> DefaultInstance => s_defaultInstance; internal HashBucketByValueEqualityComparer(IEqualityComparer<T> valueComparer) { Requires.NotNull(valueComparer, "valueComparer"); _valueComparer = valueComparer; } public bool Equals(HashBucket x, HashBucket y) { return x.EqualsByValue(y, _valueComparer); } public int GetHashCode(HashBucket obj) { throw new NotSupportedException(); } } private sealed class HashBucketByRefEqualityComparer : IEqualityComparer<HashBucket> { private static readonly IEqualityComparer<HashBucket> s_defaultInstance = new HashBucketByRefEqualityComparer(); internal static IEqualityComparer<HashBucket> DefaultInstance => s_defaultInstance; private HashBucketByRefEqualityComparer() { } public bool Equals(HashBucket x, HashBucket y) { return x.EqualsByRef(y); } public int GetHashCode(HashBucket obj) { throw new NotSupportedException(); } } [DebuggerDisplay("Count = {Count}")] public sealed class Builder : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, ISet<T>, ICollection<T> { private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode; private IEqualityComparer<T> _equalityComparer; private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer; private int _count; private ImmutableHashSet<T> _immutable; private int _version; public int Count => _count; bool ICollection<T>.IsReadOnly => false; public IEqualityComparer<T> KeyComparer { get { return _equalityComparer; } set { Requires.NotNull(value, "value"); if (value != _equalityComparer) { MutationResult mutationResult = ImmutableHashSet<T>.Union((IEnumerable<T>)this, new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, value, _hashBucketEqualityComparer, 0)); _immutable = null; _equalityComparer = value; Root = mutationResult.Root; _count = mutationResult.Count; } } } internal int Version => _version; private MutationInput Origin => new MutationInput(Root, _equalityComparer, _hashBucketEqualityComparer, _count); private SortedInt32KeyNode<HashBucket> Root { get { return _root; } set { _version++; if (_root != value) { _root = value; _immutable = null; } } } internal Builder(ImmutableHashSet<T> set) { Requires.NotNull(set, "set"); _root = set._root; _count = set._count; _equalityComparer = set._equalityComparer; _hashBucketEqualityComparer = set._hashBucketEqualityComparer; _immutable = set; } public Enumerator GetEnumerator() { return new Enumerator(_root, this); } public ImmutableHashSet<T> ToImmutable() { return _immutable ?? (_immutable = ImmutableHashSet<T>.Wrap(_root, _equalityComparer, _count)); } public bool TryGetValue(T equalValue, out T actualValue) { int key = ((equalValue != null) ? _equalityComparer.GetHashCode(equalValue) : 0); if (_root.TryGetValue(key, out var value)) { return value.TryExchange(equalValue, _equalityComparer, out actualValue); } actualValue = equalValue; return false; } public bool Add(T item) { MutationResult result = ImmutableHashSet<T>.Add(item, Origin); Apply(result); return result.Count != 0; } public bool Remove(T item) { MutationResult result = ImmutableHashSet<T>.Remove(item, Origin); Apply(result); return result.Count != 0; } public bool Contains(T item) { return ImmutableHashSet<T>.Contains(item, Origin); } public void Clear() { _count = 0; Root = SortedInt32KeyNode<HashBucket>.EmptyNode; } public void ExceptWith(IEnumerable<T> other) { MutationResult result = ImmutableHashSet<T>.Except(other, _equalityComparer, _hashBucketEqualityComparer, _root); Apply(result); } public void IntersectWith(IEnumerable<T> other) { MutationResult result = ImmutableHashSet<T>.Intersect(other, Origin); Apply(result); } public bool IsProperSubsetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsProperSubsetOf(other, Origin); } public bool IsProperSupersetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsProperSupersetOf(other, Origin); } public bool IsSubsetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsSubsetOf(other, Origin); } public bool IsSupersetOf(IEnumerable<T> other) { return ImmutableHashSet<T>.IsSupersetOf(other, Origin); } public bool Overlaps(IEnumerable<T> other) { return ImmutableHashSet<T>.Overlaps(other, Origin); } public bool SetEquals(IEnumerable<T> other) { if (this == other) { return true; } return ImmutableHashSet<T>.SetEquals(other, Origin); } public void SymmetricExceptWith(IEnumerable<T> other) { MutationResult result = ImmutableHashSet<T>.SymmetricExcept(other, Origin); Apply(result); } public void UnionWith(IEnumerable<T> other) { MutationResult result = ImmutableHashSet<T>.Union(other, Origin); Apply(result); } void ICollection<T>.Add(T item) { Add(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); using Enumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; array[arrayIndex++] = current; } } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private void Apply(MutationResult result) { Root = result.Root; if (result.CountType == CountType.Adjustment) { _count += result.Count; } else { _count = result.Count; } } } public struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable, IStrongEnumerator<T> { private readonly Builder _builder; private SortedInt32KeyNode<HashBucket>.Enumerator _mapEnumerator; private HashBucket.Enumerator _bucketEnumerator; private int _enumeratingBuilderVersion; public T Current { get { _mapEnumerator.ThrowIfDisposed(); return _bucketEnumerator.Current; } } object? IEnumerator.Current => Current; internal Enumerator(SortedInt32KeyNode<HashBucket> root, Builder? builder = null) { _builder = builder; _mapEnumerator = new SortedInt32KeyNode<HashBucket>.Enumerator(root); _bucketEnumerator = default(HashBucket.Enumerator); _enumeratingBuilderVersion = builder?.Version ?? (-1); } public bool MoveNext() { ThrowIfChanged(); if (_bucketEnumerator.MoveNext()) { return true; } if (_mapEnumerator.MoveNext()) { _bucketEnumerator = new HashBucket.Enumerator(_mapEnumerator.Current.Value); return _bucketEnumerator.MoveNext(); } return false; } public void Reset() { _enumeratingBuilderVersion = ((_builder != null) ? _builder.Version : (-1)); _mapEnumerator.Reset(); _bucketEnumerator.Dispose(); _bucketEnumerator = default(HashBucket.Enumerator); } public void Dispose() { _mapEnumerator.Dispose(); _bucketEnumerator.Dispose(); } private void ThrowIfChanged() { if (_builder != null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(System.SR.CollectionModifiedDuringEnumeration); } } } internal enum OperationResult { SizeChanged, NoChangeRequired } internal readonly struct HashBucket { internal struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable { private enum Position { BeforeFirst, First, Additional, End } private readonly HashBucket _bucket; private bool _disposed; private Position _currentPosition; private ImmutableList<T>.Enumerator _additionalEnumerator; object? IEnumerator.Current => Current; public T Current { get { ThrowIfDisposed(); return _currentPosition switch { Position.First => _bucket._firstValue, Position.Additional => _additionalEnumerator.Current, _ => throw new InvalidOperationException(), }; } } internal Enumerator(HashBucket bucket) { _disposed = false; _bucket = bucket; _currentPosition = Position.BeforeFirst; _additionalEnumerator = default(ImmutableList<T>.Enumerator); } public bool MoveNext() { ThrowIfDisposed(); if (_bucket.IsEmpty) { _currentPosition = Position.End; return false; } switch (_currentPosition) { case Position.BeforeFirst: _currentPosition = Position.First; return true; case Position.First: if (_bucket._additionalElements.IsEmpty) { _currentPosition = Position.End; return false; } _currentPosition = Position.Additional; _additionalEnumerator = new ImmutableList<T>.Enumerator(_bucket._additionalElements); return _additionalEnumerator.MoveNext(); case Position.Additional: return _additionalEnumerator.MoveNext(); case Position.End: return false; default: throw new InvalidOperationException(); } } public void Reset() { ThrowIfDisposed(); _additionalEnumerator.Dispose(); _currentPosition = Position.BeforeFirst; } public void Dispose() { _disposed = true; _additionalEnumerator.Dispose(); } private void ThrowIfDisposed() { if (_disposed) { Requires.FailObjectDisposed(this); } } } private readonly T _firstValue; private readonly ImmutableList<T>.Node _additionalElements; internal bool IsEmpty => _additionalElements == null; private HashBucket(T firstElement, ImmutableList<T>.Node additionalElements = null) { _firstValue = firstElement; _additionalElements = additionalElements ?? ImmutableList<T>.Node.EmptyNode; } public Enumerator GetEnumerator() { return new Enumerator(this); } public override bool Equals(object? obj) { throw new NotSupportedException(); } public override int GetHashCode() { throw new NotSupportedException(); } internal bool EqualsByRef(HashBucket other) { if ((object)_firstValue == (object)other._firstValue) { return _additionalElements == other._additionalElements; } return false; } internal bool EqualsByValue(HashBucket other, IEqualityComparer<T> valueComparer) { if (valueComparer.Equals(_firstValue, other._firstValue)) { return _additionalElements == other._additionalElements; } return false; } internal HashBucket Add(T value, IEqualityComparer<T> valueComparer, out OperationResult result) { if (IsEmpty) { result = OperationResult.SizeChanged; return new HashBucket(value); } if (valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0) { result = OperationResult.NoChangeRequired; return this; } result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.Add(value)); } internal bool Contains(T value, IEqualityComparer<T> valueComparer) { if (IsEmpty) { return false; } if (!valueComparer.Equals(value, _firstValue)) { return _additionalElements.IndexOf(value, valueComparer) >= 0; } return true; } internal bool TryExchange(T value, IEqualityComparer<T> valueComparer, out T existingValue) { if (!IsEmpty) { if (valueComparer.Equals(value, _firstValue)) { existingValue = _firstValue; return true; } int num = _additionalElements.IndexOf(value, valueComparer); if (num >= 0) { existingValue = _additionalElements.ItemRef(num); return true; } } existingValue = value; return false; } internal HashBucket Remove(T value, IEqualityComparer<T> equalityComparer, out OperationResult result) { if (IsEmpty) { result = OperationResult.NoChangeRequired; return this; } if (equalityComparer.Equals(_firstValue, value)) { if (_additionalElements.IsEmpty) { result = OperationResult.SizeChanged; return default(HashBucket); } int count = _additionalElements.Left.Count; result = OperationResult.SizeChanged; return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(count)); } int num = _additionalElements.IndexOf(value, equalityComparer); if (num < 0) { result = OperationResult.NoChangeRequired; return this; } result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.RemoveAt(num)); } internal void Freeze() { _additionalElements?.Freeze(); } } private readonly struct MutationInput { private readonly SortedInt32KeyNode<HashBucket> _root; private readonly IEqualityComparer<T> _equalityComparer; private readonly int _count; private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer; internal SortedInt32KeyNode<HashBucket> Root => _root; internal IEqualityComparer<T> EqualityComparer => _equalityComparer; internal int Count => _count; internal IEqualityComparer<HashBucket> HashBucketEqualityComparer => _hashBucketEqualityComparer; internal MutationInput(ImmutableHashSet<T> set) { Requires.NotNull(set, "set"); _root = set._root; _equalityComparer = set._equalityComparer; _count = set._count; _hashBucketEqualityComparer = set._hashBucketEqualityComparer; } internal MutationInput(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, IEqualityComparer<HashBucket> hashBucketEqualityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.Range(count >= 0, "count"); Requires.NotNull(hashBucketEqualityComparer, "hashBucketEqualityComparer"); _root = root; _equalityComparer = equalityComparer; _count = count; _hashBucketEqualityComparer = hashBucketEqualityComparer; } } private enum CountType { Adjustment, FinalValue } private readonly struct MutationResult { private readonly SortedInt32KeyNode<HashBucket> _root; private readonly int _count; private readonly CountType _countType; internal SortedInt32KeyNode<HashBucket> Root => _root; internal int Count => _count; internal CountType CountType => _countType; internal MutationResult(SortedInt32KeyNode<HashBucket> root, int count, CountType countType = CountType.Adjustment) { Requires.NotNull(root, "root"); _root = root; _count = count; _countType = countType; } internal ImmutableHashSet<T> Finalize(ImmutableHashSet<T> priorSet) { Requires.NotNull(priorSet, "priorSet"); int num = Count; if (CountType == CountType.Adjustment) { num += priorSet._count; } return priorSet.Wrap(Root, num); } } private readonly struct NodeEnumerable : IEnumerable<T>, IEnumerable { private readonly SortedInt32KeyNode<HashBucket> _root; internal NodeEnumerable(SortedInt32KeyNode<HashBucket> root) { Requires.NotNull(root, "root"); _root = root; } public Enumerator GetEnumerator() { return new Enumerator(_root); } [ExcludeFromCodeCoverage] IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static readonly ImmutableHashSet<T> Empty = new ImmutableHashSet<T>(SortedInt32KeyNode<HashBucket>.EmptyNode, EqualityComparer<T>.Default, 0); private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = delegate(KeyValuePair<int, HashBucket> kv) { kv.Value.Freeze(); }; private readonly IEqualityComparer<T> _equalityComparer; private readonly int _count; private readonly SortedInt32KeyNode<HashBucket> _root; private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer; public int Count => _count; public bool IsEmpty => Count == 0; public IEqualityComparer<T> KeyComparer => _equalityComparer; [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot => this; [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized => true; internal IBinaryTree Root => _root; private MutationInput Origin => new MutationInput(this); bool ICollection<T>.IsReadOnly => true; internal ImmutableHashSet(IEqualityComparer<T> equalityComparer) : this(SortedInt32KeyNode<HashBucket>.EmptyNode, equalityComparer, 0) { } private ImmutableHashSet(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); root.Freeze(s_FreezeBucketAction); _root = root; _count = count; _equalityComparer = equalityComparer; _hashBucketEqualityComparer = GetHashBucketEqualityComparer(equalityComparer); } public ImmutableHashSet<T> Clear() { if (!IsEmpty) { return Empty.WithComparer(_equalityComparer); } return this; } IImmutableSet<T> IImmutableSet<T>.Clear() { return Clear(); } public Builder ToBuilder() { return new Builder(this); } public ImmutableHashSet<T> Add(T item) { return Add(item, Origin).Finalize(this); } public ImmutableHashSet<T> Remove(T item) { return Remove(item, Origin).Finalize(this); } public bool TryGetValue(T equalValue, out T actualValue) { int key = ((equalValue != null) ? _equalityComparer.GetHashCode(equalValue) : 0); if (_root.TryGetValue(key, out var value)) { return value.TryExchange(equalValue, _equalityComparer, out actualValue); } actualValue = equalValue; return false; } public ImmutableHashSet<T> Union(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Union(other, avoidWithComparer: false); } internal ImmutableHashSet<T> Union(ReadOnlySpan<T> other) { return Union(other, Origin).Finalize(this); } public ImmutableHashSet<T> Intersect(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Intersect(other, Origin).Finalize(this); } public ImmutableHashSet<T> Except(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Except(other, _equalityComparer, _hashBucketEqualityComparer, _root).Finalize(this); } public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other) { Requires.NotNull(other, "other"); return SymmetricExcept(other, Origin).Finalize(this); } public bool SetEquals(IEnumerable<T> other) { Requires.NotNull(other, "other"); if (this == other) { return true; } return SetEquals(other, Origin); } public bool IsProperSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsProperSubsetOf(other, Origin); } public bool IsProperSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsProperSupersetOf(other, Origin); } public bool IsSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsSubsetOf(other, Origin); } public bool IsSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsSupersetOf(other, Origin); } public bool Overlaps(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Overlaps(other, Origin); } IImmutableSet<T> IImmutableSet<T>.Add(T item) { return Add(item); } IImmutableSet<T> IImmutableSet<T>.Remove(T item) { return Remove(item); } IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other) { return Union(other); } IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other) { return Intersect(other); } IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other) { return Except(other); } IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other) { return SymmetricExcept(other); } public bool Contains(T item) { return Contains(item, Origin); } public ImmutableHashSet<T> WithComparer(IEqualityComparer<T>? equalityComparer) { if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == _equalityComparer) { return this; } return new ImmutableHashSet<T>(equalityComparer).Union(this, avoidWithComparer: true); } bool ISet<T>.Add(T item) { throw new NotSupportedException(); } void ISet<T>.ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } void ISet<T>.IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } void ISet<T>.UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); using Enumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; array[arrayIndex++] = current; } } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex"); using Enumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; array.SetValue(current, arrayIndex++); } } public Enumerator GetEnumerator() { return new Enumerator(_root); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { if (!IsEmpty) { return GetEnumerator(); } return Enumerable.Empty<T>().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private static bool IsSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (!Contains(item, origin)) { return false; } } return true; } private static MutationResult Add(T item, MutationInput origin) { int num = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); OperationResult result; HashBucket newBucket = origin.Root.GetValueOrDefault(num).Add(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } return new MutationResult(UpdateRoot(origin.Root, num, origin.HashBucketEqualityComparer, newBucket), 1); } private static MutationResult Remove(T item, MutationInput origin) { OperationResult result = OperationResult.NoChangeRequired; int num = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); SortedInt32KeyNode<HashBucket> root = origin.Root; if (origin.Root.TryGetValue(num, out var value)) { HashBucket newBucket = value.Remove(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } root = UpdateRoot(origin.Root, num, origin.HashBucketEqualityComparer, newBucket); } return new MutationResult(root, (result == OperationResult.SizeChanged) ? (-1) : 0); } private static bool Contains(T item, MutationInput origin) { int key = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); if (origin.Root.TryGetValue(key, out var value)) { return value.Contains(item, origin.EqualityComparer); } return false; } private static MutationResult Union(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); int num = 0; SortedInt32KeyNode<HashBucket> sortedInt32KeyNode = origin.Root; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { int num2 = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0); OperationResult result; HashBucket newBucket = sortedInt32KeyNode.GetValueOrDefault(num2).Add(item, origin.EqualityComparer, out result); if (result == OperationResult.SizeChanged) { sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, origin.HashBucketEqualityComparer, newBucket); num++; } } return new MutationResult(sortedInt32KeyNode, num); } private static MutationResult Union(ReadOnlySpan<T> other, MutationInput origin) { int num = 0; SortedInt32KeyNode<HashBucket> sortedInt32KeyNode = origin.Root; ReadOnlySpan<T> readOnlySpan = other; for (int i = 0; i < readOnlySpan.Length; i++) { T val = readOnlySpan[i]; int num2 = ((val != null) ? origin.EqualityComparer.GetHashCode(val) : 0); OperationResult result; HashBucket newBucket = sortedInt32KeyNode.GetValueOrDefault(num2).Add(val, origin.EqualityComparer, out result); if (result == OperationResult.SizeChanged) { sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, origin.HashBucketEqualityComparer, newBucket); num++; } } return new MutationResult(sortedInt32KeyNode, num); } private static bool Overlaps(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return false; } foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (Contains(item, origin)) { return true; } } return false; } private static bool SetEquals(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count != hashSet.Count) { return false; } foreach (T item in hashSet) { if (!Contains(item, origin)) { return false; } } return true; } private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, IEqualityComparer<HashBucket> hashBucketEqualityComparer, HashBucket newBucket) { bool mutated; if (newBucket.IsEmpty) { return root.Remove(hashCode, out mutated); } bool mutated2; return root.SetItem(hashCode, newBucket, hashBucketEqualityComparer, out mutated, out mutated2); } private static MutationResult Intersect(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); SortedInt32KeyNode<HashBucket> root = SortedInt32KeyNode<HashBucket>.EmptyNode; int num = 0; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (Contains(item, origin)) { MutationResult mutationResult = Add(item, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); root = mutationResult.Root; num += mutationResult.Count; } } return new MutationResult(root, num, CountType.FinalValue); } private static MutationResult Except(IEnumerable<T> other, IEqualityComparer<T> equalityComparer, IEqualityComparer<HashBucket> hashBucketEqualityComparer, SortedInt32KeyNode<HashBucket> root) { Requires.NotNull(other, "other"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.NotNull(root, "root"); int num = 0; SortedInt32KeyNode<HashBucket> sortedInt32KeyNode = root; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { int num2 = ((item != null) ? equalityComparer.GetHashCode(item) : 0); if (sortedInt32KeyNode.TryGetValue(num2, out var value)) { OperationResult result; HashBucket newBucket = value.Remove(item, equalityComparer, out result); if (result == OperationResult.SizeChanged) { num--; sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, hashBucketEqualityComparer, newBucket); } } } return new MutationResult(sortedInt32KeyNode, num); } private static MutationResult SymmetricExcept(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); ImmutableHashSet<T> immutableHashSet = ImmutableHashSet.CreateRange(origin.EqualityComparer, other); int num = 0; SortedInt32KeyNode<HashBucket> root = SortedInt32KeyNode<HashBucket>.EmptyNode; foreach (T item in new NodeEnumerable(origin.Root)) { if (!immutableHashSet.Contains(item)) { MutationResult mutationResult = Add(item, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); root = mutationResult.Root; num += mutationResult.Count; } } foreach (T item2 in immutableHashSet) { if (!Contains(item2, origin)) { MutationResult mutationResult2 = Add(item2, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num)); root = mutationResult2.Root; num += mutationResult2.Count; } } return new MutationResult(root, num, CountType.FinalValue); } private static bool IsProperSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return other.Any(); } HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count >= hashSet.Count) { return false; } int num = 0; bool flag = false; foreach (T item in hashSet) { if (Contains(item, origin)) { num++; } else { flag = true; } if (num == origin.Count && flag) { return true; } } return false; } private static bool IsProperSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return false; } int num = 0; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { num++; if (!Contains(item, origin)) { return false; } } return origin.Count > num; } private static bool IsSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return true; } HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer); int num = 0; foreach (T item in hashSet) { if (Contains(item, origin)) { num++; } } return num == origin.Count; } private static ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.Range(count >= 0, "count"); return new ImmutableHashSet<T>(root, equalityComparer, count); } private static IEqualityComparer<HashBucket> GetHashBucketEqualityComparer(IEqualityComparer<T> valueComparer) { if (!ImmutableExtensions.IsValueType<T>()) { return HashBucketByRefEqualityComparer.DefaultInstance; } if (valueComparer == EqualityComparer<T>.Default) { return HashBucketByValueEqualityComparer.DefaultInstance; } return new HashBucketByValueEqualityComparer(valueComparer); } private ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot) { if (root == _root) { return this; } return new ImmutableHashSet<T>(root, _equalityComparer, adjustedCountIfDifferentRoot); } private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer) { Requires.NotNull(items, "items"); if (IsEmpty && !avoidWithComparer && items is ImmutableHashSet<T> immutableHashSet) { return immutableHashSet.WithComparer(KeyComparer); } return Union(items, Origin).Finalize(this); } } internal interface IStrongEnumerable<out T, TEnumerator> where TEnumerator : struct, IStrongEnumerator<T> { TEnumerator GetEnumerator(); } internal interface IStrongEnumerator<T> { T Current { get; } bool MoveNext(); } internal interface IOrderedCollection<out T> : IEnumerable<T>, IEnumerable { int Count { get; } T this[int index] { get; } } public static class ImmutableArray { internal static readonly byte[] TwoElementArray = new byte[2]; public static ImmutableArray<T> Create<T>() { return ImmutableArray<T>.Empty; } public static ImmutableArray<T> Create<T>(T item) { return new ImmutableArray<T>(new T[1] { item }); } public static ImmutableArray<T> Create<T>(T item1, T item2) { return new ImmutableArray<T>(new T[2] { item1, item2 }); } public static ImmutableArray<T> Create<T>(T item1, T item2, T item3) { return new ImmutableArray<T>(new T[3] { item1, item2, item3 }); } public static ImmutableArray<T> Create<T>(T item1, T item2, T item3, T item4) { return new ImmutableArray<T>(new T[4] { item1, item2, item3, item4 }); } public static ImmutableArray<T> Create<T>([ParamCollection] scoped ReadOnlySpan<T> items) { if (items.IsEmpty) { return ImmutableArray<T>.Empty; } return new ImmutableArray<T>(items.ToArray()); } public static ImmutableArray<T> Create<T>(Span<T> items) { return Create((ReadOnlySpan<T>)items); } public static ImmutableArray<T> ToImmutableArray<T>(this ReadOnlySpan<T> items) { return Create(items); } public static ImmutableArray<T> ToImmutableArray<T>(this Span<T> items) { return Create((ReadOnlySpan<T>)items); } public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items) { Requires.NotNull(items, "items"); if (items is IImmutableArray immutableArray) { return new ImmutableArray<T>((T[])(immutableArray.Array ?? throw new InvalidOperationException(System.SR.InvalidOperationOnDefaultArray))); } if (items.TryGetCount(out var count)) { return new ImmutableArray<T>(items.ToArray(count)); } return new ImmutableArray<T>(items.ToArray()); } public static ImmutableArray<T> Create<T>(params T[]? items) { if (items == null || items.Length == 0) { return ImmutableArray<T>.Empty; } T[] array = new T[items.Length]; Array.Copy(items, array, items.Length); return new ImmutableArray<T>(array); } public static ImmutableArray<T> Create<T>(T[] items, int start, int length) { Requires.NotNull(items, "items"); Requires.Range(start >= 0 && start <= items.Length, "start"); Requires.Range(length >= 0 && start + length <= items.Length, "length"); if (length == 0) { return Create<T>(); } T[] array = new T[length]; for (int i = 0; i < array.Length; i++) { array[i] = items[start + i]; } return new ImmutableArray<T>(array); } public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length) { Requires.Range(start >= 0 && start <= items.Length, "start"); Requires.Range(length >= 0 && start + length <= items.Length, "length"); if (length == 0) { return Create<T>(); } if (start == 0 && length == items.Length) { return items; } T[] array = new T[length]; Array.Copy(items.array, start, array, 0, length); return new ImmutableArray<T>(array); } public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, Func<TSource, TResult> selector) { Requires.NotNull(selector, "selector"); int length = items.Length; if (length == 0) { return Create<TResult>(); } TResult[] array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i]); } return new ImmutableArray<TResult>(array); } public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TResult> selector) { int length2 = items.Length; Requires.Range(start >= 0 && start <= length2, "start"); Requires.Range(length >= 0 && start + length <= length2, "length"); Requires.NotNull(selector, "selector"); if (length == 0) { return Create<TResult>(); } TResult[] array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i + start]); } return new ImmutableArray<TResult>(array); } public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, Func<TSource, TArg, TResult> selector, TArg arg) { Requires.NotNull(selector, "selector"); int length = items.Length; if (length == 0) { return Create<TResult>(); } TResult[] array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i], arg); } return new ImmutableArray<TResult>(array); } public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TArg, TResult> selector, TArg arg) { int length2 = items.Length; Requires.Range(start >= 0 && start <= length2, "start"); Requires.Range(length >= 0 && start + length <= length2, "length"); Requires.NotNull(selector, "selector"); if (length == 0) { return Create<TResult>(); } TResult[] array = new TResult[length]; for (int i = 0; i < array.Length; i++) { array[i] = selector(items[i + start], arg); } return new ImmutableArray<TResult>(array); } public static ImmutableArray<T>.Builder CreateBuilder<T>() { return Create<T>().ToBuilder(); } public static ImmutableArray<T>.Builder CreateBuilder<T>(int initialCapacity) { return new ImmutableArray<T>.Builder(initialCapacity); } public static ImmutableArray<TSource> ToImmutableArray<TSource>(this IEnumerable<TSource> items) { if (items is ImmutableArray<TSource>) { return (ImmutableArray<TSource>)(object)items; } return CreateRange(items); } public static ImmutableArray<TSource> ToImmutableArray<TSource>(this ImmutableArray<TSource>.Builder builder) { Requires.NotNull(builder, "builder"); return builder.ToImmutable(); } public static int BinarySearch<T>(this ImmutableArray<T> array, T value) { return Array.BinarySearch(array.array, value); } public static int BinarySearch<T>(this ImmutableArray<T> array, T value, IComparer<T>? comparer) { return Array.BinarySearch(array.array, value, comparer); } public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value) { return Array.BinarySearch(array.array, index, length, value); } public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value, IComparer<T>? comparer) { return Array.BinarySearch(array.array, index, length, value, comparer); } } [CollectionBuilder(typeof(ImmutableArray), "Create")] [DebuggerDisplay("{DebuggerDisplay,nq}")] [System.Runtime.Versioning.NonVersionable] public readonly struct ImmutableArray<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T>, IList<T>, ICollection<T>, IEquatable<ImmutableArray<T>>, IList, ICollection, IImmutableArray, IStructuralComparable, IStructuralEquatable, IImmutableList<T> { [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))] public sealed class Builder : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyList<T>, IReadOnlyCollection<T> { private T[] _elements; private int _count; public int Capacity { get { return _elements.Length; } set { if (value < _count) { throw new ArgumentException(System.SR.CapacityMustBeGreaterThanOrEqualToCount, "value"); } if (value == _elements.Length) { return; } if (value > 0) { T[] array = new T[value]; if (_count > 0) { Array.Copy(_elements, array, _count); } _elements = array; } else { _elements = ImmutableArray<T>.Empty.array; } } } public int Count { get { return _count; } set { Requires.Range(value >= 0, "value"); if (value < _count) { if (_count - value > 64) { Array.Clear(_elements, value, _count - value); } else { for (int i = value; i < Count; i++) { _elements[i] = default(T); } } } else if (value > _count) { EnsureCapacity(value); } _count = value; } } public T this[int index] { get { if (index >= Count) { ThrowIndexOutOfRangeException(); } return _elements[index]; } set { if (index >= Count) { ThrowIndexOutOfRangeException(); } _elements[index] = value; } } bool ICollection<T>.IsReadOnly => false; internal Builder(int capacity) { Requires.Range(capacity >= 0, "capacity"); _elements = new T[capacity]; _count = 0; } internal Builder() : this(8) { } private static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } public ref readonly T ItemRef(int index) { if (index >= Count) { ThrowIndexOutOfRangeException(); } return ref _elements[index]; } public ImmutableArray<T> ToImmutable() { return new ImmutableArray<T>(ToArray()); } public ImmutableArray<T> MoveToImmutable() { if (Capacity != Count) { throw new InvalidOperationException(System.SR.CapacityMustEqualCountOnMove); } T[] elements = _elements; _elements = ImmutableArray<T>.Empty.array; _count = 0; return new ImmutableArray<T>(elements); } public ImmutableArray<T> DrainToImmutable() { T[] array = _elements; if (array.Length != _count) { array = ToArray(); } _elements = ImmutableArray<T>.Empty.array; _count = 0; return new ImmutableArray<T>(array); } public void Clear() { Count = 0; } public void Insert(int index, T item) { Requires.Range(index >= 0 && index <= Count, "index"); EnsureCapacity(Count + 1); if (index < Count) { Array.Copy(_elements, index, _elements, index + 1, Count - index); } _count++; _elements[index] = item; } public void InsertRange(int index, IEnumerable<T> items) { Requires.Range(index >= 0 && index <= Count, "index"); Requires.NotNull(items, "items"); int count = ImmutableExtensions.GetCount(ref items); EnsureCapacity(Count + count); if (index != Count) { Array.Copy(_elements, index, _elements, index + count, _count - index); } if (!items.TryCopyTo(_elements, index)) { foreach (T item in items) { _elements[index++] = item; } } _count += count; } public void InsertRange(int index, ImmutableArray<T> items) { Requires.Range(index >= 0 && index <= Count, "index"); if (!items.IsEmpty) { EnsureCapacity(Count + items.Length); if (index != Count) { Array.Copy(_elements, index, _elements, index + items.Length, _count - index); } Array.Copy(items.array, 0, _elements, index, items.Length); _count += items.Length; } } public void Add(T item) { int num = _count + 1; EnsureCapacity(num); _elements[_count] = item; _count = num; } public void AddRange(IEnumerable<T> items) { Requires.NotNull(items, "items"); if (items.TryGetCount(out var count)) { EnsureCapacity(Count + count); if (items.TryCopyTo(_elements, _count)) { _count += count; return; } } foreach (T item in items) { Add(item); } } public void AddRange(params T[] items) { Requires.NotNull(items, "items"); int count = Count; Count += items.Length; Array.Copy(items, 0, _elements, count, items.Length); } public void AddRange<TDerived>(TDerived[] items) where TDerived : T { Requires.NotNull(items, "items"); int count = Count; Count += items.Length; Array.Copy(items, 0, _elements, count, items.Length); } public void AddRange(T[] items, int length) { Requires.NotNull(items, "items"); Requires.Range(length >= 0 && length <= items.Length, "length"); int count = Count; Count += length; Array.Copy(items, 0, _elements, count, length); } public void AddRange(ImmutableArray<T> items) { AddRange(items, items.Length); } public void AddRange(ImmutableArray<T> items, int length) { Requires.Range(length >= 0, "length"); if (items.array != null) { AddRange(items.array, length); } } public void AddRange([ParamCollection] scoped ReadOnlySpan<T> items) { int count = Count; Count += items.Length; items.CopyTo(new Span<T>(_elements, count, items.Length)); } public void AddRange<TDerived>([ParamCollection] scoped ReadOnlySpan<TDerived> items) where TDerived : T { int count = Count; Count += items.Length; Span<T> span = new Span<T>(_elements, count, items.Length); for (int i = 0; i < items.Length; i++) { span[i] = (T)(object)items[i]; } } public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T { if (items.array != null) { this.AddRange<TDerived>(items.array); } } public void AddRange(Builder items) { Requires.NotNull(items, "items"); AddRange(items._elements, items.Count); } public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T { Requires.NotNull(items, "items"); AddRange<TDerived>(items._elements, items.Count); } public bool Remove(T element) { int num = IndexOf(element); if (num >= 0) { RemoveAt(num); return true; } return false; } public bool Remove(T element, IEqualityComparer<T>? equalityComparer) { int num = IndexOf(element, 0, _count, equalityComparer); if (num >= 0) { RemoveAt(num); return true; } return false; } public void RemoveAll(Predicate<T> match) { List<int> list = null; for (int i = 0; i < _count; i++) { if (match(_elements[i])) { if (list == null) { list = new List<int>(); } list.Add(i); } } if (list != null) { RemoveAtRange(list); } } public void RemoveAt(int index) { Requires.Range(index >= 0 && index < Count, "index"); if (index < Count - 1) { Array.Copy(_elements, index + 1, _elements, index, Count - index - 1); } Count--; } public void RemoveRange(int index, int length) { Requires.Range(index >= 0 && index <= _count, "index"); Requires.Range(length >= 0 && index <= _count - length, "length"); if (length != 0) { if (index + length < _count) { Array.Copy(_elements, index + length, _elements, index, Count - index - length); } _count -= length; } } public void RemoveRange(IEnumerable<T> items) { RemoveRange(items, EqualityComparer<T>.Default); } public void RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer) { Requires.NotNull(items, "items"); SortedSet<int> sortedSet = new SortedSet<int>(); foreach (T item in items) { int num = IndexOf(item, 0, _count, equalityComparer); while (num >= 0 && !sortedSet.Add(num) && num + 1 < _count) { num = IndexOf(item, num + 1, equalityComparer); } } RemoveAtRange(sortedSet); } public void Replace(T oldValue, T newValue) { Replace(oldValue, newValue, EqualityComparer<T>.Default); } public void Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer) { int num = IndexOf(oldValue, 0, _count, equalityComparer); if (num >= 0) { _elements[num] = newValue; } } public bool Contains(T item) { return IndexOf(item) >= 0; } public T[] ToArray() { if (Count == 0) { return ImmutableArray<T>.Empty.array; } T[] array = new T[Count]; Array.Copy(_elements, array, Count); return array; } public void CopyTo(T[] array, int index) { Requires.NotNull(array, "array"); Requires.Range(index >= 0 && index + Count <= array.Length, "index"); Array.Copy(_elements, 0, array, index, Count); } public void CopyTo(T[] destination) { Requires.NotNull(destination, "destination"); Array.Copy(_elements, 0, destination, 0, Count); } public void CopyTo(int sourceIndex, T[] destination, int destinationIndex, int length) { Requires.NotNull(destination, "destination"); Requires.Range(length >= 0, "length"); Requires.Range(sourceIndex >= 0 && sourceIndex + length <= Count, "sourceIndex"); Requires.Range(destinationIndex >= 0 && destinationIndex + length <= destination.Length, "destinationIndex"); Array.Copy(_elements, sourceIndex, destination, destinationIndex, length); } private void EnsureCapacity(int capacity) { if (_elements.Length < capacity) { int newSize = Math.Max(_elements.Length * 2, capacity); Array.Resize(ref _elements, newSize); } } public int IndexOf(T item) { return IndexOf(item, 0, _count, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex) { return IndexOf(item, startIndex, Count - startIndex, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, int count) { return IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); Requires.Range(count >= 0 && startIndex + count <= Count, "count"); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(_elements, item, startIndex, count); } for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(_elements[i], item)) { return i; } } return -1; } public int IndexOf(T item, int startIndex, IEqualityComparer<T>? equalityComparer) { return IndexOf(item, startIndex, Count - startIndex, equalityComparer); } public int LastIndexOf(T item) { if (Count == 0) { return -1; } return LastIndexOf(item, Count - 1, Count, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex) { if (Count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); return LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex, int count) { return LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex"); Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count"); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == EqualityComparer<T>.Default) { return Array.LastIndexOf(_elements, item, startIndex, count); } for (int num = startIndex; num >= startIndex - count + 1; num--) { if (equalityComparer.Equals(item, _elements[num])) { return num; } } return -1; } public void Reverse() { int num = 0; int num2 = _count - 1; T[] elements = _elements; while (num < num2) { T val = elements[num]; elements[num] = elements[num2]; elements[num2] = val; num++; num2--; } } public void Sort() { if (Count > 1) { Array.Sort(_elements, 0, Count, Comparer<T>.Default); } } public void Sort(Comparison<T> comparison) { Requires.NotNull(comparison, "comparison"); if (Count > 1) { Array.Sort(_elements, 0, _count, Comparer<T>.Create(comparison)); } } public void Sort(IComparer<T>? comparer) { if (Count > 1) { Array.Sort(_elements, 0, _count, comparer); } } public void Sort(int index, int count, IComparer<T>? comparer) { Requires.Range(index >= 0, "index"); Requires.Range(count >= 0 && index + count <= Count, "count"); if (count > 1) { Array.Sort(_elements, index, count, comparer); } } public void CopyTo(Span<T> destination) { Requires.Range(Count <= destination.Length, "destination"); new ReadOnlySpan<T>(_elements, 0, Count).CopyTo(destination); } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < Count; i++) { yield return this[i]; } } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T { EnsureCapacity(Count + length); int count = Count; Count += length; T[] elements = _elements; for (int i = 0; i < length; i++) { elements[count + i] = (T)(object)items[i]; } } private void RemoveAtRange(ICollection<int> indicesToRemove) { Requires.NotNull(indicesToRemove, "indicesToRemove"); if (indicesToRemove.Count == 0) { return; } int num = 0; int num2 = 0; int num3 = -1; foreach (int item in indicesToRemove) { int num4 = ((num3 == -1) ? item : (item - num3 - 1)); Array.Copy(_elements, num + num2, _elements, num, num4); num2++; num += num4; num3 = item; } Array.Copy(_elements, num + num2, _elements, num, _elements.Length - (num + num2)); _count -= indicesToRemove.Count; } } public struct Enumerator { private readonly T[] _array; private int _index; public T Current => _array[_index]; internal Enumerator(T[] array) { _array = array; _index = -1; } public bool MoveNext() { return ++_index < _array.Length; } } private sealed class EnumeratorObject : IEnumerator<T>, IEnumerator, IDisposable { private static readonly IEnumerator<T> s_EmptyEnumerator = new EnumeratorObject(ImmutableArray<T>.Empty.array); private readonly T[] _array; private int _index; public T Current { get { if ((uint)_index < (uint)_array.Length) { return _array[_index]; } throw new InvalidOperationException(); } } object IEnumerator.Current => Current; private EnumeratorObject(T[] array) { _index = -1; _array = array; } public bool MoveNext() { int num = _index + 1; int num2 = _array.Length; if ((uint)num <= (uint)num2) { _index = num; return (uint)num < (uint)num2; } return false; } void IEnumerator.Reset() { _index = -1; } public void Dispose() { } internal static IEnumerator<T> Create(T[] array) { if (array.Length != 0) { return new EnumeratorObject(array); } return s_EmptyEnumerator; } } public static readonly ImmutableArray<T> Empty = new ImmutableArray<T>(new T[0]); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly T[]? array; T IList<T>.this[int index] { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray[index]; } set { throw new NotSupportedException(); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection<T>.IsReadOnly => true; [DebuggerBrowsable(DebuggerBrowsableState.Never)] int ICollection<T>.Count { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] int IReadOnlyCollection<T>.Count { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray.Length; } } T IReadOnlyList<T>.this[int index] { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray[index]; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool IList.IsFixedSize => true; [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool IList.IsReadOnly => true; [DebuggerBrowsable(DebuggerBrowsableState.Never)] int ICollection.Count { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized => true; [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { throw new NotSupportedException(); } } object? IList.this[int index] { get { ImmutableArray<T> immutableArray = this; immutableArray.ThrowInvalidOperationIfNotInitialized(); return immutableArray[index]; } set { throw new NotSupportedException(); } } public T this[int index] { [System.Runtime.Versioning.NonVersionable] get { return array[index]; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsEmpty { [System.Runtime.Versioning.NonVersionable] get { return array.Length == 0; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int Length { [System.Runtime.Versioning.NonVersionable] get { return array.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsDefault => array == null; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool IsDefaultOrEmpty { get { ImmutableArray<T> immutableArray = this; if (immutableArray.array != null) { return immutableArray.array.Length == 0; } return true; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Array? IImmutableArray.Array => array; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { ImmutableArray<T> immutableArray = this; if (!immutableArray.IsDefault) { return $"Length = {immutableArray.Length}"; } return "Uninitialized"; } } public ReadOnlySpan<T> AsSpan() { return new ReadOnlySpan<T>(array); } public ReadOnlyMemory<T> AsMemory() { return new ReadOnlyMemory<T>(array); } public int IndexOf(T item) { ImmutableArray<T> immutableArray = this; return immutableArray.IndexOf(item, 0, immutableArray.Length, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, IEqualityComparer<T>? equalityComparer) { ImmutableArray<T> immutableArray = this; return immutableArray.IndexOf(item, startIndex, immutableArray.Length - startIndex, equalityComparer); } public int IndexOf(T item, int startIndex) { ImmutableArray<T> immutableArray = this; return immutableArray.IndexOf(item, startIndex, immutableArray.Length - startIndex, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, int count) { return IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer) { ImmutableArray<T> immutableArray = this; immutableArray.ThrowNullRefIfNotInitialized(); if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < immutableArray.Length, "startIndex"); Requires.Range(count >= 0 && startIndex + count <= immutableArray.Length, "count"); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(immutableArray.array, item, startIndex, count); } for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(immutableArray.array[i], item)) { return i; } } return -1; } public int LastIndexOf(T item) { ImmutableArray<T> immutableArray = this; if (immutableArray.IsEmpty) { return -1; } return immutableArray.LastIndexOf(item, immutableArray.Length - 1, immutableArray.Length, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex) { ImmutableArray<T> immutableArray = this; if (immutableArray.IsEmpty && startIndex == 0) { return -1; } return immutableArray.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex, int count) { return LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equali
deps/System.ComponentModel.Composition.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.Composition; using System.ComponentModel.Composition.AttributedModel; using System.ComponentModel.Composition.Diagnostics; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.ComponentModel.Composition.ReflectionModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Threading; using Microsoft.Internal; using Microsoft.Internal.Collections; using Microsoft.Internal.Runtime.Serialization; using Unity; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.ComponentModel.Composition.dll")] [assembly: AssemblyDescription("System.ComponentModel.Composition.dll")] [assembly: AssemblyDefaultAlias("System.ComponentModel.Composition.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Microsoft Corporation. All rights reserved.")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: InternalsVisibleTo("net_4_x_System.ComponentModel.Composition_xunit-test, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")] [assembly: SecurityCritical] [assembly: AllowPartiallyTrustedCallers] [assembly: ComVisible(false)] [assembly: AssemblyVersion("4.0.0.0")] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } namespace Microsoft.Internal { internal static class Assumes { [Serializable] private class InternalErrorException : Exception { public InternalErrorException(string message) : base(string.Format(CultureInfo.CurrentCulture, Strings.InternalExceptionMessage, message)) { } [SecuritySafeCritical] protected InternalErrorException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [DebuggerStepThrough] internal static void NotNull<T>(T value) where T : class { IsTrue(value != null); } [DebuggerStepThrough] internal static void NotNull<T1, T2>(T1 value1, T2 value2) where T1 : class where T2 : class { NotNull(value1); NotNull(value2); } [DebuggerStepThrough] internal static void NotNull<T1, T2, T3>(T1 value1, T2 value2, T3 value3) where T1 : class where T2 : class where T3 : class { NotNull(value1); NotNull(value2); NotNull(value3); } [DebuggerStepThrough] internal static void NotNullOrEmpty(string value) { NotNull(value); IsTrue(value.Length > 0); } [DebuggerStepThrough] internal static void IsTrue(bool condition) { if (!condition) { throw UncatchableException(null); } } [DebuggerStepThrough] internal static void IsTrue(bool condition, string message) { if (!condition) { throw UncatchableException(message); } } [DebuggerStepThrough] internal static T NotReachable<T>() { throw UncatchableException("Code path should never be reached!"); } [DebuggerStepThrough] private static Exception UncatchableException(string message) { return new InternalErrorException(message); } } internal static class AttributeServices { public static T[] GetAttributes<T>(this ICustomAttributeProvider attributeProvider) where T : class { return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit: false); } public static T[] GetAttributes<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class { return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit); } public static T GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider) where T : class { return attributeProvider.GetAttributes<T>().FirstOrDefault(); } public static T GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class { return attributeProvider.GetAttributes<T>(inherit).FirstOrDefault(); } public static bool IsAttributeDefined<T>(this ICustomAttributeProvider attributeProvider) where T : class { return attributeProvider.IsDefined(typeof(T), inherit: false); } public static bool IsAttributeDefined<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class { return attributeProvider.IsDefined(typeof(T), inherit); } } internal static class ContractServices { public static bool TryCast(Type contractType, object value, out object result) { if (value == null) { result = null; return true; } if (contractType.IsInstanceOfType(value)) { result = value; return true; } if (typeof(Delegate).IsAssignableFrom(contractType) && value is ExportedDelegate exportedDelegate) { result = exportedDelegate.CreateDelegate(contractType.UnderlyingSystemType); return result != null; } result = null; return false; } } internal static class GenerationServices { private static readonly MethodInfo _typeGetTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle"); private static readonly Type TypeType = typeof(Type); private static readonly Type StringType = typeof(string); private static readonly Type CharType = typeof(char); private static readonly Type BooleanType = typeof(bool); private static readonly Type ByteType = typeof(byte); private static readonly Type SByteType = typeof(sbyte); private static readonly Type Int16Type = typeof(short); private static readonly Type UInt16Type = typeof(ushort); private static readonly Type Int32Type = typeof(int); private static readonly Type UInt32Type = typeof(uint); private static readonly Type Int64Type = typeof(long); private static readonly Type UInt64Type = typeof(ulong); private static readonly Type DoubleType = typeof(double); private static readonly Type SingleType = typeof(float); private static readonly Type IEnumerableTypeofT = typeof(IEnumerable<>); private static readonly Type IEnumerableType = typeof(IEnumerable); private static readonly MethodInfo ExceptionGetData = typeof(Exception).GetProperty("Data").GetGetMethod(); private static readonly MethodInfo DictionaryAdd = typeof(IDictionary).GetMethod("Add"); private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes); public static ILGenerator CreateGeneratorForPublicConstructor(this TypeBuilder typeBuilder, Type[] ctrArgumentTypes) { ILGenerator iLGenerator = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctrArgumentTypes).GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Call, ObjectCtor); return iLGenerator; } public static void LoadValue(this ILGenerator ilGenerator, object value) { Assumes.NotNull(ilGenerator); if (value == null) { ilGenerator.LoadNull(); return; } Type type = value.GetType(); object obj = value; if (type.IsEnum) { obj = Convert.ChangeType(value, Enum.GetUnderlyingType(type), null); type = obj.GetType(); } if (type == StringType) { ilGenerator.LoadString((string)obj); return; } if (TypeType.IsAssignableFrom(type)) { ilGenerator.LoadTypeOf((Type)obj); return; } if (IEnumerableType.IsAssignableFrom(type)) { ilGenerator.LoadEnumerable((IEnumerable)obj); return; } if (type == CharType || type == BooleanType || type == ByteType || type == SByteType || type == Int16Type || type == UInt16Type || type == Int32Type) { ilGenerator.LoadInt((int)Convert.ChangeType(obj, typeof(int), CultureInfo.InvariantCulture)); return; } if (type == UInt32Type) { ilGenerator.LoadInt((int)(uint)obj); return; } if (type == Int64Type) { ilGenerator.LoadLong((long)obj); return; } if (type == UInt64Type) { ilGenerator.LoadLong((long)(ulong)obj); return; } if (type == SingleType) { ilGenerator.LoadFloat((float)obj); return; } if (type == DoubleType) { ilGenerator.LoadDouble((double)obj); return; } throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.InvalidMetadataValue, value.GetType().FullName)); } public static void AddItemToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, object value) { Assumes.NotNull(ilGenerator); Assumes.NotNull(dictionary); Assumes.NotNull(key); Assumes.NotNull(value); ilGenerator.Emit(OpCodes.Ldloc, dictionary); ilGenerator.LoadValue(key); ilGenerator.LoadValue(value); ilGenerator.Emit(OpCodes.Callvirt, DictionaryAdd); } public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, LocalBuilder value) { Assumes.NotNull(ilGenerator); Assumes.NotNull(dictionary); Assumes.NotNull(key); Assumes.NotNull(value); ilGenerator.Emit(OpCodes.Ldloc, dictionary); ilGenerator.LoadValue(key); ilGenerator.Emit(OpCodes.Ldloc, value); ilGenerator.Emit(OpCodes.Callvirt, DictionaryAdd); } public static void GetExceptionDataAndStoreInLocal(this ILGenerator ilGenerator, LocalBuilder exception, LocalBuilder dataStore) { Assumes.NotNull(ilGenerator); Assumes.NotNull(exception); Assumes.NotNull(dataStore); ilGenerator.Emit(OpCodes.Ldloc, exception); ilGenerator.Emit(OpCodes.Callvirt, ExceptionGetData); ilGenerator.Emit(OpCodes.Stloc, dataStore); } private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enumerable) { Assumes.NotNull(ilGenerator); Assumes.NotNull(enumerable); Type type = null; Type targetClosedInterfaceType = null; type = ((!ReflectionServices.TryGetGenericInterfaceType(enumerable.GetType(), IEnumerableTypeofT, out targetClosedInterfaceType)) ? typeof(object) : targetClosedInterfaceType.GetGenericArguments()[0]); Type localType = type.MakeArrayType(); LocalBuilder local = ilGenerator.DeclareLocal(localType); ilGenerator.LoadInt(enumerable.Cast<object>().Count()); ilGenerator.Emit(OpCodes.Newarr, type); ilGenerator.Emit(OpCodes.Stloc, local); int num = 0; foreach (object item in enumerable) { ilGenerator.Emit(OpCodes.Ldloc, local); ilGenerator.LoadInt(num); ilGenerator.LoadValue(item); if (IsBoxingRequiredForValue(item) && !type.IsValueType) { ilGenerator.Emit(OpCodes.Box, item.GetType()); } ilGenerator.Emit(OpCodes.Stelem, type); num++; } ilGenerator.Emit(OpCodes.Ldloc, local); } private static bool IsBoxingRequiredForValue(object value) { return value?.GetType().IsValueType ?? false; } private static void LoadNull(this ILGenerator ilGenerator) { ilGenerator.Emit(OpCodes.Ldnull); } private static void LoadString(this ILGenerator ilGenerator, string s) { Assumes.NotNull(ilGenerator); if (s == null) { ilGenerator.LoadNull(); } else { ilGenerator.Emit(OpCodes.Ldstr, s); } } private static void LoadInt(this ILGenerator ilGenerator, int value) { Assumes.NotNull(ilGenerator); ilGenerator.Emit(OpCodes.Ldc_I4, value); } private static void LoadLong(this ILGenerator ilGenerator, long value) { Assumes.NotNull(ilGenerator); ilGenerator.Emit(OpCodes.Ldc_I8, value); } private static void LoadFloat(this ILGenerator ilGenerator, float value) { Assumes.NotNull(ilGenerator); ilGenerator.Emit(OpCodes.Ldc_R4, value); } private static void LoadDouble(this ILGenerator ilGenerator, double value) { Assumes.NotNull(ilGenerator); ilGenerator.Emit(OpCodes.Ldc_R8, value); } private static void LoadTypeOf(this ILGenerator ilGenerator, Type type) { Assumes.NotNull(ilGenerator); ilGenerator.Emit(OpCodes.Ldtoken, type); ilGenerator.EmitCall(OpCodes.Call, _typeGetTypeFromHandleMethod, null); } } internal static class LazyServices { public static T GetNotNullValue<T>(this Lazy<T> lazy, string argument) where T : class { Assumes.NotNull(lazy); return lazy.Value ?? throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.LazyServices_LazyResolvesToNull, typeof(T), argument)); } } internal struct ReadLock : IDisposable { private readonly Lock _lock; private int _isDisposed; public ReadLock(Lock @lock) { _isDisposed = 0; _lock = @lock; _lock.EnterReadLock(); } public void Dispose() { if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0) { _lock.ExitReadLock(); } } } internal struct WriteLock : IDisposable { private readonly Lock _lock; private int _isDisposed; public WriteLock(Lock @lock) { _isDisposed = 0; _lock = @lock; _lock.EnterWriteLock(); } public void Dispose() { if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0) { _lock.ExitWriteLock(); } } } internal sealed class Lock : IDisposable { private ReaderWriterLockSlim _thisLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); private int _isDisposed; public void EnterReadLock() { _thisLock.EnterReadLock(); } public void EnterWriteLock() { _thisLock.EnterWriteLock(); } public void ExitReadLock() { _thisLock.ExitReadLock(); } public void ExitWriteLock() { _thisLock.ExitWriteLock(); } public void Dispose() { if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0) { _thisLock.Dispose(); } } } internal static class ReflectionInvoke { public static object SafeCreateInstance(this Type type, params object[] arguments) { DemandMemberAccessIfNeeded(type); return Activator.CreateInstance(type, arguments); } public static object SafeInvoke(this ConstructorInfo constructor, params object[] arguments) { DemandMemberAccessIfNeeded(constructor); return constructor.Invoke(arguments); } public static object SafeInvoke(this MethodInfo method, object instance, params object[] arguments) { DemandMemberAccessIfNeeded(method); return method.Invoke(instance, arguments); } public static object SafeGetValue(this FieldInfo field, object instance) { DemandMemberAccessIfNeeded(field); return field.GetValue(instance); } public static void SafeSetValue(this FieldInfo field, object instance, object value) { DemandMemberAccessIfNeeded(field); field.SetValue(instance, value); } public static void DemandMemberAccessIfNeeded(MethodInfo method) { } private static void DemandMemberAccessIfNeeded(ConstructorInfo constructor) { } private static void DemandMemberAccessIfNeeded(FieldInfo field) { } public static void DemandMemberAccessIfNeeded(Type type) { } } internal static class ReflectionServices { public static Assembly Assembly(this MemberInfo member) { Type type = member as Type; if (type != null) { return type.Assembly; } return member.DeclaringType.Assembly; } public static bool IsVisible(this ConstructorInfo constructor) { if (constructor.DeclaringType.IsVisible) { return constructor.IsPublic; } return false; } public static bool IsVisible(this FieldInfo field) { if (field.DeclaringType.IsVisible) { return field.IsPublic; } return false; } public static bool IsVisible(this MethodInfo method) { if (!method.DeclaringType.IsVisible) { return false; } if (!method.IsPublic) { return false; } if (method.IsGenericMethod) { Type[] genericArguments = method.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (!genericArguments[i].IsVisible) { return false; } } } return true; } public static string GetDisplayName(Type declaringType, string name) { Assumes.NotNull(declaringType); return declaringType.GetDisplayName() + "." + name; } public static string GetDisplayName(this MemberInfo member) { Assumes.NotNull(member); MemberTypes memberType = member.MemberType; if (memberType == MemberTypes.TypeInfo || memberType == MemberTypes.NestedType) { return AttributedModelServices.GetTypeIdentity((Type)member); } return GetDisplayName(member.DeclaringType, member.Name); } internal static bool TryGetGenericInterfaceType(Type instanceType, Type targetOpenInterfaceType, out Type targetClosedInterfaceType) { Assumes.IsTrue(targetOpenInterfaceType.IsInterface); Assumes.IsTrue(targetOpenInterfaceType.IsGenericTypeDefinition); Assumes.IsTrue(!instanceType.IsGenericTypeDefinition); if (instanceType.IsInterface && instanceType.IsGenericType && instanceType.UnderlyingSystemType.GetGenericTypeDefinition() == targetOpenInterfaceType.UnderlyingSystemType) { targetClosedInterfaceType = instanceType; return true; } try { Type @interface = instanceType.GetInterface(targetOpenInterfaceType.Name, ignoreCase: false); if (@interface != null && @interface.UnderlyingSystemType.GetGenericTypeDefinition() == targetOpenInterfaceType.UnderlyingSystemType) { targetClosedInterfaceType = @interface; return true; } } catch (AmbiguousMatchException) { } targetClosedInterfaceType = null; return false; } internal static IEnumerable<PropertyInfo> GetAllProperties(this Type type) { return type.GetInterfaces().Concat(new Type[1] { type }).SelectMany((Type itf) => itf.GetProperties()); } internal static IEnumerable<MethodInfo> GetAllMethods(this Type type) { IEnumerable<MethodInfo> declaredMethods = type.GetDeclaredMethods(); Type baseType = type.BaseType; if (baseType.UnderlyingSystemType != typeof(object)) { return declaredMethods.Concat(baseType.GetAllMethods()); } return declaredMethods; } private static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type) { MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { yield return methods[i]; } } public static IEnumerable<FieldInfo> GetAllFields(this Type type) { IEnumerable<FieldInfo> declaredFields = type.GetDeclaredFields(); Type baseType = type.BaseType; if (baseType.UnderlyingSystemType != typeof(object)) { return declaredFields.Concat(baseType.GetAllFields()); } return declaredFields; } private static IEnumerable<FieldInfo> GetDeclaredFields(this Type type) { FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < fields.Length; i++) { yield return fields[i]; } } } internal static class Requires { [DebuggerStepThrough] public static void NotNull<T>(T value, string parameterName) where T : class { if (value == null) { throw new ArgumentNullException(parameterName); } } [DebuggerStepThrough] public static void NotNullOrEmpty(string value, string parameterName) { NotNull(value, parameterName); if (value.Length == 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.ArgumentException_EmptyString, parameterName), parameterName); } } [DebuggerStepThrough] public static void NotNullOrNullElements<T>(IEnumerable<T> values, string parameterName) where T : class { NotNull(values, parameterName); NotNullElements(values, parameterName); } [DebuggerStepThrough] public static void NullOrNotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> values, string parameterName) where TKey : class where TValue : class { NotNullElements(values, parameterName); } [DebuggerStepThrough] public static void NullOrNotNullElements<T>(IEnumerable<T> values, string parameterName) where T : class { NotNullElements(values, parameterName); } private static void NotNullElements<T>(IEnumerable<T> values, string parameterName) where T : class { if (values != null && !Contract.ForAll(values, (T value) => value != null)) { throw ExceptionBuilder.CreateContainsNullElement(parameterName); } } private static void NotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> values, string parameterName) where TKey : class where TValue : class { if (values != null && !Contract.ForAll(values, (KeyValuePair<TKey, TValue> keyValue) => keyValue.Key != null && keyValue.Value != null)) { throw ExceptionBuilder.CreateContainsNullElement(parameterName); } } [DebuggerStepThrough] public static void IsInMembertypeSet(MemberTypes value, string parameterName, MemberTypes enumFlagSet) { if ((value & enumFlagSet) != value || (value & (value - 1)) != 0) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.ArgumentOutOfRange_InvalidEnumInSet, parameterName, value, enumFlagSet.ToString()), parameterName); } } } internal static class StringComparers { public static StringComparer ContractName => StringComparer.Ordinal; public static StringComparer MetadataKeyNames => StringComparer.Ordinal; } [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Strings { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { resourceMan = new ResourceManager("Microsoft.Internal.Strings", typeof(Strings).Assembly); } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string Argument_AssemblyReflectionOnly => ResourceManager.GetString("Argument_AssemblyReflectionOnly", resourceCulture); internal static string Argument_ElementReflectionOnlyType => ResourceManager.GetString("Argument_ElementReflectionOnlyType", resourceCulture); internal static string Argument_ExportsEmpty => ResourceManager.GetString("Argument_ExportsEmpty", resourceCulture); internal static string Argument_ExportsTooMany => ResourceManager.GetString("Argument_ExportsTooMany", resourceCulture); internal static string Argument_NullElement => ResourceManager.GetString("Argument_NullElement", resourceCulture); internal static string Argument_ReflectionContextReturnsReflectionOnlyType => ResourceManager.GetString("Argument_ReflectionContextReturnsReflectionOnlyType", resourceCulture); internal static string ArgumentException_EmptyString => ResourceManager.GetString("ArgumentException_EmptyString", resourceCulture); internal static string ArgumentOutOfRange_InvalidEnum => ResourceManager.GetString("ArgumentOutOfRange_InvalidEnum", resourceCulture); internal static string ArgumentOutOfRange_InvalidEnumInSet => ResourceManager.GetString("ArgumentOutOfRange_InvalidEnumInSet", resourceCulture); internal static string ArgumentValueType => ResourceManager.GetString("ArgumentValueType", resourceCulture); internal static string AssemblyFileNotFoundOrWrongType => ResourceManager.GetString("AssemblyFileNotFoundOrWrongType", resourceCulture); internal static string AtomicComposition_AlreadyCompleted => ResourceManager.GetString("AtomicComposition_AlreadyCompleted", resourceCulture); internal static string AtomicComposition_AlreadyNested => ResourceManager.GetString("AtomicComposition_AlreadyNested", resourceCulture); internal static string AtomicComposition_PartOfAnotherAtomicComposition => ResourceManager.GetString("AtomicComposition_PartOfAnotherAtomicComposition", resourceCulture); internal static string CardinalityMismatch_NoExports => ResourceManager.GetString("CardinalityMismatch_NoExports", resourceCulture); internal static string CardinalityMismatch_TooManyExports => ResourceManager.GetString("CardinalityMismatch_TooManyExports", resourceCulture); internal static string CatalogMutation_Invalid => ResourceManager.GetString("CatalogMutation_Invalid", resourceCulture); internal static string CompositionElement_UnknownOrigin => ResourceManager.GetString("CompositionElement_UnknownOrigin", resourceCulture); internal static string CompositionException_ChangesRejected => ResourceManager.GetString("CompositionException_ChangesRejected", resourceCulture); internal static string CompositionException_ElementPrefix => ResourceManager.GetString("CompositionException_ElementPrefix", resourceCulture); internal static string CompositionException_ErrorPrefix => ResourceManager.GetString("CompositionException_ErrorPrefix", resourceCulture); internal static string CompositionException_MetadataViewInvalidConstructor => ResourceManager.GetString("CompositionException_MetadataViewInvalidConstructor", resourceCulture); internal static string CompositionException_MultipleErrorsWithMultiplePaths => ResourceManager.GetString("CompositionException_MultipleErrorsWithMultiplePaths", resourceCulture); internal static string CompositionException_OriginFormat => ResourceManager.GetString("CompositionException_OriginFormat", resourceCulture); internal static string CompositionException_OriginSeparator => ResourceManager.GetString("CompositionException_OriginSeparator", resourceCulture); internal static string CompositionException_PathsCountSeparator => ResourceManager.GetString("CompositionException_PathsCountSeparator", resourceCulture); internal static string CompositionException_ReviewErrorProperty => ResourceManager.GetString("CompositionException_ReviewErrorProperty", resourceCulture); internal static string CompositionException_SingleErrorWithMultiplePaths => ResourceManager.GetString("CompositionException_SingleErrorWithMultiplePaths", resourceCulture); internal static string CompositionException_SingleErrorWithSinglePath => ResourceManager.GetString("CompositionException_SingleErrorWithSinglePath", resourceCulture); internal static string CompositionTrace_Discovery_AssemblyLoadFailed => ResourceManager.GetString("CompositionTrace_Discovery_AssemblyLoadFailed", resourceCulture); internal static string CompositionTrace_Discovery_DefinitionContainsNoExports => ResourceManager.GetString("CompositionTrace_Discovery_DefinitionContainsNoExports", resourceCulture); internal static string CompositionTrace_Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute => ResourceManager.GetString("CompositionTrace_Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute", resourceCulture); internal static string CompositionTrace_Discovery_DefinitionMismatchedExportArity => ResourceManager.GetString("CompositionTrace_Discovery_DefinitionMismatchedExportArity", resourceCulture); internal static string CompositionTrace_Discovery_MemberMarkedWithMultipleImportAndImportMany => ResourceManager.GetString("CompositionTrace_Discovery_MemberMarkedWithMultipleImportAndImportMany", resourceCulture); internal static string CompositionTrace_Rejection_DefinitionRejected => ResourceManager.GetString("CompositionTrace_Rejection_DefinitionRejected", resourceCulture); internal static string CompositionTrace_Rejection_DefinitionResurrected => ResourceManager.GetString("CompositionTrace_Rejection_DefinitionResurrected", resourceCulture); internal static string ContractMismatch_ExportedValueCannotBeCastToT => ResourceManager.GetString("ContractMismatch_ExportedValueCannotBeCastToT", resourceCulture); internal static string ContractMismatch_InvalidCastOnMetadataField => ResourceManager.GetString("ContractMismatch_InvalidCastOnMetadataField", resourceCulture); internal static string ContractMismatch_MetadataViewImplementationCanNotBeNull => ResourceManager.GetString("ContractMismatch_MetadataViewImplementationCanNotBeNull", resourceCulture); internal static string ContractMismatch_MetadataViewImplementationDoesNotImplementViewInterface => ResourceManager.GetString("ContractMismatch_MetadataViewImplementationDoesNotImplementViewInterface", resourceCulture); internal static string ContractMismatch_NullReferenceOnMetadataField => ResourceManager.GetString("ContractMismatch_NullReferenceOnMetadataField", resourceCulture); internal static string DirectoryNotFound => ResourceManager.GetString("DirectoryNotFound", resourceCulture); internal static string Discovery_DuplicateMetadataNameValues => ResourceManager.GetString("Discovery_DuplicateMetadataNameValues", resourceCulture); internal static string Discovery_MetadataContainsValueWithInvalidType => ResourceManager.GetString("Discovery_MetadataContainsValueWithInvalidType", resourceCulture); internal static string Discovery_ReservedMetadataNameUsed => ResourceManager.GetString("Discovery_ReservedMetadataNameUsed", resourceCulture); internal static string ExportDefinitionNotOnThisComposablePart => ResourceManager.GetString("ExportDefinitionNotOnThisComposablePart", resourceCulture); internal static string ExportFactory_TooManyGenericParameters => ResourceManager.GetString("ExportFactory_TooManyGenericParameters", resourceCulture); internal static string ExportNotValidOnIndexers => ResourceManager.GetString("ExportNotValidOnIndexers", resourceCulture); internal static string ImportDefinitionNotOnThisComposablePart => ResourceManager.GetString("ImportDefinitionNotOnThisComposablePart", resourceCulture); internal static string ImportEngine_ComposeTookTooManyIterations => ResourceManager.GetString("ImportEngine_ComposeTookTooManyIterations", resourceCulture); internal static string ImportEngine_InvalidStateForRecomposition => ResourceManager.GetString("ImportEngine_InvalidStateForRecomposition", resourceCulture); internal static string ImportEngine_PartCannotActivate => ResourceManager.GetString("ImportEngine_PartCannotActivate", resourceCulture); internal static string ImportEngine_PartCannotGetExportedValue => ResourceManager.GetString("ImportEngine_PartCannotGetExportedValue", resourceCulture); internal static string ImportEngine_PartCannotSetImport => ResourceManager.GetString("ImportEngine_PartCannotSetImport", resourceCulture); internal static string ImportEngine_PartCycle => ResourceManager.GetString("ImportEngine_PartCycle", resourceCulture); internal static string ImportEngine_PreventedByExistingImport => ResourceManager.GetString("ImportEngine_PreventedByExistingImport", resourceCulture); internal static string ImportNotSetOnPart => ResourceManager.GetString("ImportNotSetOnPart", resourceCulture); internal static string ImportNotValidOnIndexers => ResourceManager.GetString("ImportNotValidOnIndexers", resourceCulture); internal static string InternalExceptionMessage => ResourceManager.GetString("InternalExceptionMessage", resourceCulture); internal static string InvalidArgument_ReflectionContext => ResourceManager.GetString("InvalidArgument_ReflectionContext", resourceCulture); internal static string InvalidMetadataValue => ResourceManager.GetString("InvalidMetadataValue", resourceCulture); internal static string InvalidMetadataView => ResourceManager.GetString("InvalidMetadataView", resourceCulture); internal static string InvalidOperation_DefinitionCannotBeRecomposed => ResourceManager.GetString("InvalidOperation_DefinitionCannotBeRecomposed", resourceCulture); internal static string InvalidOperation_GetExportedValueBeforePrereqImportSet => ResourceManager.GetString("InvalidOperation_GetExportedValueBeforePrereqImportSet", resourceCulture); internal static string InvalidOperationReentrantCompose => ResourceManager.GetString("InvalidOperationReentrantCompose", resourceCulture); internal static string InvalidPartCreationPolicyOnImport => ResourceManager.GetString("InvalidPartCreationPolicyOnImport", resourceCulture); internal static string InvalidPartCreationPolicyOnPart => ResourceManager.GetString("InvalidPartCreationPolicyOnPart", resourceCulture); internal static string InvalidSetterOnMetadataField => ResourceManager.GetString("InvalidSetterOnMetadataField", resourceCulture); internal static string LazyMemberInfo_AccessorsNull => ResourceManager.GetString("LazyMemberInfo_AccessorsNull", resourceCulture); internal static string LazyMemberInfo_InvalidAccessorOnSimpleMember => ResourceManager.GetString("LazyMemberInfo_InvalidAccessorOnSimpleMember", resourceCulture); internal static string LazyMemberinfo_InvalidEventAccessors_AccessorType => ResourceManager.GetString("LazyMemberinfo_InvalidEventAccessors_AccessorType", resourceCulture); internal static string LazyMemberInfo_InvalidEventAccessors_Cardinality => ResourceManager.GetString("LazyMemberInfo_InvalidEventAccessors_Cardinality", resourceCulture); internal static string LazyMemberinfo_InvalidPropertyAccessors_AccessorType => ResourceManager.GetString("LazyMemberinfo_InvalidPropertyAccessors_AccessorType", resourceCulture); internal static string LazyMemberInfo_InvalidPropertyAccessors_Cardinality => ResourceManager.GetString("LazyMemberInfo_InvalidPropertyAccessors_Cardinality", resourceCulture); internal static string LazyMemberInfo_NoAccessors => ResourceManager.GetString("LazyMemberInfo_NoAccessors", resourceCulture); internal static string LazyServices_LazyResolvesToNull => ResourceManager.GetString("LazyServices_LazyResolvesToNull", resourceCulture); internal static string MetadataItemNotSupported => ResourceManager.GetString("MetadataItemNotSupported", resourceCulture); internal static string NotImplemented_NotOverriddenByDerived => ResourceManager.GetString("NotImplemented_NotOverriddenByDerived", resourceCulture); internal static string NotSupportedCatalogChanges => ResourceManager.GetString("NotSupportedCatalogChanges", resourceCulture); internal static string NotSupportedInterfaceMetadataView => ResourceManager.GetString("NotSupportedInterfaceMetadataView", resourceCulture); internal static string NotSupportedReadOnlyDictionary => ResourceManager.GetString("NotSupportedReadOnlyDictionary", resourceCulture); internal static string ObjectAlreadyInitialized => ResourceManager.GetString("ObjectAlreadyInitialized", resourceCulture); internal static string ObjectMustBeInitialized => ResourceManager.GetString("ObjectMustBeInitialized", resourceCulture); internal static string ReentrantCompose => ResourceManager.GetString("ReentrantCompose", resourceCulture); internal static string ReflectionContext_Requires_DefaultConstructor => ResourceManager.GetString("ReflectionContext_Requires_DefaultConstructor", resourceCulture); internal static string ReflectionContext_Type_Required => ResourceManager.GetString("ReflectionContext_Type_Required", resourceCulture); internal static string ReflectionModel_ExportNotReadable => ResourceManager.GetString("ReflectionModel_ExportNotReadable", resourceCulture); internal static string ReflectionModel_ExportThrewException => ResourceManager.GetString("ReflectionModel_ExportThrewException", resourceCulture); internal static string ReflectionModel_ImportCollectionAddThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionAddThrewException", resourceCulture); internal static string ReflectionModel_ImportCollectionClearThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionClearThrewException", resourceCulture); internal static string ReflectionModel_ImportCollectionConstructionThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionConstructionThrewException", resourceCulture); internal static string ReflectionModel_ImportCollectionGetThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionGetThrewException", resourceCulture); internal static string ReflectionModel_ImportCollectionIsReadOnlyThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionIsReadOnlyThrewException", resourceCulture); internal static string ReflectionModel_ImportCollectionNotWritable => ResourceManager.GetString("ReflectionModel_ImportCollectionNotWritable", resourceCulture); internal static string ReflectionModel_ImportCollectionNull => ResourceManager.GetString("ReflectionModel_ImportCollectionNull", resourceCulture); internal static string ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned => ResourceManager.GetString("ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned", resourceCulture); internal static string ReflectionModel_ImportNotAssignableFromExport => ResourceManager.GetString("ReflectionModel_ImportNotAssignableFromExport", resourceCulture); internal static string ReflectionModel_ImportNotWritable => ResourceManager.GetString("ReflectionModel_ImportNotWritable", resourceCulture); internal static string ReflectionModel_ImportThrewException => ResourceManager.GetString("ReflectionModel_ImportThrewException", resourceCulture); internal static string ReflectionModel_InvalidExportDefinition => ResourceManager.GetString("ReflectionModel_InvalidExportDefinition", resourceCulture); internal static string ReflectionModel_InvalidImportDefinition => ResourceManager.GetString("ReflectionModel_InvalidImportDefinition", resourceCulture); internal static string ReflectionModel_InvalidMemberImportDefinition => ResourceManager.GetString("ReflectionModel_InvalidMemberImportDefinition", resourceCulture); internal static string ReflectionModel_InvalidParameterImportDefinition => ResourceManager.GetString("ReflectionModel_InvalidParameterImportDefinition", resourceCulture); internal static string ReflectionModel_InvalidPartDefinition => ResourceManager.GetString("ReflectionModel_InvalidPartDefinition", resourceCulture); internal static string ReflectionModel_PartConstructorMissing => ResourceManager.GetString("ReflectionModel_PartConstructorMissing", resourceCulture); internal static string ReflectionModel_PartConstructorThrewException => ResourceManager.GetString("ReflectionModel_PartConstructorThrewException", resourceCulture); internal static string ReflectionModel_PartOnImportsSatisfiedThrewException => ResourceManager.GetString("ReflectionModel_PartOnImportsSatisfiedThrewException", resourceCulture); internal static string TypeCatalog_DisplayNameFormat => ResourceManager.GetString("TypeCatalog_DisplayNameFormat", resourceCulture); internal static string TypeCatalog_Empty => ResourceManager.GetString("TypeCatalog_Empty", resourceCulture); internal Strings() { } } } namespace Microsoft.Internal.Runtime.Serialization { internal static class SerializationServices { public static T GetValue<T>(this SerializationInfo info, string name) { Assumes.NotNull(info, name); return (T)info.GetValue(name, typeof(T)); } } } namespace Microsoft.Internal.Collections { internal static class CollectionServices { private class CollectionOfObjectList : ICollection<object>, IEnumerable<object>, IEnumerable { private readonly IList _list; public int Count => Assumes.NotReachable<int>(); public bool IsReadOnly => _list.IsReadOnly; public CollectionOfObjectList(IList list) { _list = list; } public void Add(object item) { _list.Add(item); } public void Clear() { _list.Clear(); } public bool Contains(object item) { return Assumes.NotReachable<bool>(); } public void CopyTo(object[] array, int arrayIndex) { Assumes.NotReachable<object>(); } public bool Remove(object item) { return Assumes.NotReachable<bool>(); } public IEnumerator<object> GetEnumerator() { return Assumes.NotReachable<IEnumerator<object>>(); } IEnumerator IEnumerable.GetEnumerator() { return Assumes.NotReachable<IEnumerator>(); } } private class CollectionOfObject<T> : ICollection<object>, IEnumerable<object>, IEnumerable { private readonly ICollection<T> _collectionOfT; public int Count => Assumes.NotReachable<int>(); public bool IsReadOnly => _collectionOfT.IsReadOnly; public CollectionOfObject(object collectionOfT) { _collectionOfT = (ICollection<T>)collectionOfT; } public void Add(object item) { _collectionOfT.Add((T)item); } public void Clear() { _collectionOfT.Clear(); } public bool Contains(object item) { return Assumes.NotReachable<bool>(); } public void CopyTo(object[] array, int arrayIndex) { Assumes.NotReachable<object>(); } public bool Remove(object item) { return Assumes.NotReachable<bool>(); } public IEnumerator<object> GetEnumerator() { return Assumes.NotReachable<IEnumerator<object>>(); } IEnumerator IEnumerable.GetEnumerator() { return Assumes.NotReachable<IEnumerator>(); } } private static readonly Type StringType = typeof(string); private static readonly Type IEnumerableType = typeof(IEnumerable); private static readonly Type IEnumerableOfTType = typeof(IEnumerable<>); private static readonly Type ICollectionOfTType = typeof(ICollection<>); public static ICollection<object> GetCollectionWrapper(Type itemType, object collectionObject) { Assumes.NotNull(itemType, collectionObject); Type underlyingSystemType = itemType.UnderlyingSystemType; if (underlyingSystemType == typeof(object)) { return (ICollection<object>)collectionObject; } if (typeof(IList).IsAssignableFrom(collectionObject.GetType())) { return new CollectionOfObjectList((IList)collectionObject); } return (ICollection<object>)Activator.CreateInstance(typeof(CollectionOfObject<>).MakeGenericType(underlyingSystemType), collectionObject); } public static bool IsEnumerableOfT(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition().UnderlyingSystemType == IEnumerableOfTType) { return true; } return false; } public static Type GetEnumerableElementType(Type type) { if (type.UnderlyingSystemType == StringType || !IEnumerableType.IsAssignableFrom(type)) { return null; } if (ReflectionServices.TryGetGenericInterfaceType(type, IEnumerableOfTType, out var targetClosedInterfaceType)) { return targetClosedInterfaceType.GetGenericArguments()[0]; } return null; } public static Type GetCollectionElementType(Type type) { if (ReflectionServices.TryGetGenericInterfaceType(type, ICollectionOfTType, out var targetClosedInterfaceType)) { return targetClosedInterfaceType.GetGenericArguments()[0]; } return null; } public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> source) { Assumes.NotNull(source); return new ReadOnlyCollection<T>(source.AsArray()); } public static IEnumerable<T> ConcatAllowingNull<T>(this IEnumerable<T> source, IEnumerable<T> second) { if (second == null || !second.FastAny()) { return source; } if (source == null || !source.FastAny()) { return second; } return source.Concat(second); } public static ICollection<T> ConcatAllowingNull<T>(this ICollection<T> source, ICollection<T> second) { if (second == null || second.Count == 0) { return source; } if (source == null || source.Count == 0) { return second; } List<T> list = new List<T>(source); list.AddRange(second); return list; } public static List<T> FastAppendToListAllowNulls<T>(this List<T> source, IEnumerable<T> second) { if (second == null) { return source; } if (source == null || source.Count == 0) { return second.AsList(); } if (second is List<T> list) { if (list.Count == 0) { return source; } if (list.Count == 1) { source.Add(list[0]); return source; } } source.AddRange(second); return source; } public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { foreach (T item in source) { action(item); } } public static EnumerableCardinality GetCardinality<T>(this IEnumerable<T> source) { Assumes.NotNull(source); if (source is ICollection collection) { return collection.Count switch { 0 => EnumerableCardinality.Zero, 1 => EnumerableCardinality.One, _ => EnumerableCardinality.TwoOrMore, }; } using IEnumerator<T> enumerator = source.GetEnumerator(); if (!enumerator.MoveNext()) { return EnumerableCardinality.Zero; } if (!enumerator.MoveNext()) { return EnumerableCardinality.One; } return EnumerableCardinality.TwoOrMore; } public static bool FastAny<T>(this IEnumerable<T> source) { if (source is ICollection collection) { return collection.Count > 0; } return source.Any(); } public static Stack<T> Copy<T>(this Stack<T> stack) { Assumes.NotNull(stack); return new Stack<T>(stack.Reverse()); } public static T[] AsArray<T>(this IEnumerable<T> enumerable) { if (enumerable is T[] result) { return result; } return enumerable.ToArray(); } public static List<T> AsList<T>(this IEnumerable<T> enumerable) { if (enumerable is List<T> result) { return result; } return enumerable.ToList(); } public static bool IsArrayEqual<T>(this T[] thisArray, T[] thatArray) { if (thisArray.Length != thatArray.Length) { return false; } for (int i = 0; i < thisArray.Length; i++) { if (!thisArray[i].Equals(thatArray[i])) { return false; } } return true; } public static bool IsCollectionEqual<T>(this IList<T> thisList, IList<T> thatList) { if (thisList.Count != thatList.Count) { return false; } for (int i = 0; i < thisList.Count; i++) { if (!thisList[i].Equals(thatList[i])) { return false; } } return true; } } internal enum EnumerableCardinality { Zero, One, TwoOrMore } internal class WeakReferenceCollection<T> where T : class { private readonly List<WeakReference> _items = new List<WeakReference>(); public void Add(T item) { if (_items.Capacity == _items.Count) { CleanupDeadReferences(); } _items.Add(new WeakReference(item)); } public void Remove(T item) { int num = IndexOf(item); if (num != -1) { _items.RemoveAt(num); } } public bool Contains(T item) { return IndexOf(item) >= 0; } public void Clear() { _items.Clear(); } private int IndexOf(T item) { int count = _items.Count; for (int i = 0; i < count; i++) { if (_items[i].Target == item) { return i; } } return -1; } private void CleanupDeadReferences() { _items.RemoveAll((WeakReference w) => !w.IsAlive); } public List<T> AliveItemsToList() { List<T> list = new List<T>(); foreach (WeakReference item2 in _items) { if (item2.Target is T item) { list.Add(item); } } return list; } } } namespace System { [Serializable] public class Lazy<T, TMetadata> : Lazy<T> { private TMetadata _metadata; public TMetadata Metadata => _metadata; public Lazy(Func<T> valueFactory, TMetadata metadata) : base(valueFactory) { _metadata = metadata; } public Lazy(TMetadata metadata) { _metadata = metadata; } public Lazy(TMetadata metadata, bool isThreadSafe) : base(isThreadSafe) { _metadata = metadata; } public Lazy(Func<T> valueFactory, TMetadata metadata, bool isThreadSafe) : base(valueFactory, isThreadSafe) { _metadata = metadata; } public Lazy(TMetadata metadata, LazyThreadSafetyMode mode) : base(mode) { _metadata = metadata; } public Lazy(Func<T> valueFactory, TMetadata metadata, LazyThreadSafetyMode mode) : base(valueFactory, mode) { _metadata = metadata; } } } namespace System.ComponentModel { [Conditional("NOT_FEATURE_LEGACYCOMPONENTMODEL")] internal sealed class LocalizableAttribute : Attribute { public LocalizableAttribute(bool isLocalizable) { } } } namespace System.ComponentModel.Composition { public static class AttributedModelServices { public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata) { Requires.NotNull(metadata, "metadata"); return MetadataViewProvider.GetMetadataView<TMetadataView>(metadata); } public static ComposablePart CreatePart(object attributedPart) { Requires.NotNull(attributedPart, "attributedPart"); return AttributedModelDiscovery.CreatePart(attributedPart); } public static ComposablePart CreatePart(object attributedPart, ReflectionContext reflectionContext) { Requires.NotNull(attributedPart, "attributedPart"); Requires.NotNull(reflectionContext, "reflectionContext"); return AttributedModelDiscovery.CreatePart(attributedPart, reflectionContext); } public static ComposablePart CreatePart(ComposablePartDefinition partDefinition, object attributedPart) { Requires.NotNull(partDefinition, "partDefinition"); Requires.NotNull(attributedPart, "attributedPart"); return AttributedModelDiscovery.CreatePart((partDefinition as ReflectionComposablePartDefinition) ?? throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition("partDefinition", partDefinition.GetType()), attributedPart); } public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin) { Requires.NotNull(type, "type"); return CreatePartDefinition(type, origin, ensureIsDiscoverable: false); } public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin, bool ensureIsDiscoverable) { Requires.NotNull(type, "type"); if (ensureIsDiscoverable) { return AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, origin); } return AttributedModelDiscovery.CreatePartDefinition(type, null, ignoreConstructorImports: false, origin); } public static string GetTypeIdentity(Type type) { Requires.NotNull(type, "type"); return ContractNameServices.GetTypeIdentity(type); } public static string GetTypeIdentity(MethodInfo method) { Requires.NotNull(method, "method"); return ContractNameServices.GetTypeIdentityFromMethod(method); } public static string GetContractName(Type type) { Requires.NotNull(type, "type"); return GetTypeIdentity(type); } public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, T exportedValue) { Requires.NotNull(batch, "batch"); string contractName = GetContractName(typeof(T)); return batch.AddExportedValue(contractName, exportedValue); } public static void ComposeExportedValue<T>(this CompositionContainer container, T exportedValue) { Requires.NotNull(container, "container"); CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue(exportedValue); container.Compose(batch); } public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, string contractName, T exportedValue) { Requires.NotNull(batch, "batch"); string typeIdentity = GetTypeIdentity(typeof(T)); IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("ExportTypeIdentity", typeIdentity); return batch.AddExport(new Export(contractName, dictionary, () => exportedValue)); } public static void ComposeExportedValue<T>(this CompositionContainer container, string contractName, T exportedValue) { Requires.NotNull(container, "container"); CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue(contractName, exportedValue); container.Compose(batch); } public static ComposablePart AddPart(this CompositionBatch batch, object attributedPart) { Requires.NotNull(batch, "batch"); Requires.NotNull(attributedPart, "attributedPart"); ComposablePart composablePart = CreatePart(attributedPart); batch.AddPart(composablePart); return composablePart; } public static void ComposeParts(this CompositionContainer container, params object[] attributedParts) { Requires.NotNull(container, "container"); Requires.NotNullOrNullElements(attributedParts, "attributedParts"); CompositionBatch batch = new CompositionBatch(attributedParts.Select((object attributedPart) => CreatePart(attributedPart)).ToArray(), Enumerable.Empty<ComposablePart>()); container.Compose(batch); } public static ComposablePart SatisfyImportsOnce(this ICompositionService compositionService, object attributedPart) { Requires.NotNull(compositionService, "compositionService"); Requires.NotNull(attributedPart, "attributedPart"); ComposablePart composablePart = CreatePart(attributedPart); compositionService.SatisfyImportsOnce(composablePart); return composablePart; } public static ComposablePart SatisfyImportsOnce(this ICompositionService compositionService, object attributedPart, ReflectionContext reflectionContext) { Requires.NotNull(compositionService, "compositionService"); Requires.NotNull(attributedPart, "attributedPart"); Requires.NotNull(reflectionContext, "reflectionContext"); ComposablePart composablePart = CreatePart(attributedPart, reflectionContext); compositionService.SatisfyImportsOnce(composablePart); return composablePart; } public static bool Exports(this ComposablePartDefinition part, Type contractType) { Requires.NotNull(part, "part"); Requires.NotNull(contractType, "contractType"); return part.Exports(GetContractName(contractType)); } public static bool Exports<T>(this ComposablePartDefinition part) { Requires.NotNull(part, "part"); return part.Exports(typeof(T)); } public static bool Imports(this ComposablePartDefinition part, Type contractType) { Requires.NotNull(part, "part"); Requires.NotNull(contractType, "contractType"); return part.Imports(GetContractName(contractType)); } public static bool Imports<T>(this ComposablePartDefinition part) { Requires.NotNull(part, "part"); return part.Imports(typeof(T)); } public static bool Imports(this ComposablePartDefinition part, Type contractType, ImportCardinality importCardinality) { Requires.NotNull(part, "part"); Requires.NotNull(contractType, "contractType"); return part.Imports(GetContractName(contractType), importCardinality); } public static bool Imports<T>(this ComposablePartDefinition part, ImportCardinality importCardinality) { Requires.NotNull(part, "part"); return part.Imports(typeof(T), importCardinality); } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = true)] public class CatalogReflectionContextAttribute : Attribute { private Type _reflectionContextType; public CatalogReflectionContextAttribute(Type reflectionContextType) { Requires.NotNull(reflectionContextType, "reflectionContextType"); _reflectionContextType = reflectionContextType; } public ReflectionContext CreateReflectionContext() { Assumes.NotNull(_reflectionContextType); ReflectionContext reflectionContext = null; try { return (ReflectionContext)Activator.CreateInstance(_reflectionContextType); } catch (InvalidCastException innerException) { throw new InvalidOperationException(Strings.ReflectionContext_Type_Required, innerException); } catch (MissingMethodException inner) { throw new MissingMethodException(Strings.ReflectionContext_Requires_DefaultConstructor, inner); } } } [Serializable] public class ChangeRejectedException : CompositionException { public override string Message => string.Format(CultureInfo.CurrentCulture, Strings.CompositionException_ChangesRejected, base.Message); public ChangeRejectedException() : this(null, null) { } public ChangeRejectedException(string message) : this(message, null) { } public ChangeRejectedException(string message, Exception innerException) : base(message, innerException, null) { } public ChangeRejectedException(IEnumerable<CompositionError> errors) : base(null, null, errors) { } } [Serializable] public class CompositionContractMismatchException : Exception { public CompositionContractMismatchException() : this(null, null) { } public CompositionContractMismatchException(string message) : this(message, null) { } public CompositionContractMismatchException(string message, Exception innerException) : base(message, innerException) { } [SecuritySafeCritical] protected CompositionContractMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [DebuggerTypeProxy(typeof(CompositionErrorDebuggerProxy))] public class CompositionError { private readonly CompositionErrorId _id; private readonly string _description; private readonly Exception _exception; private readonly ICompositionElement _element; public ICompositionElement Element => _element; public string Description => _description; public Exception Exception => _exception; internal CompositionErrorId Id => _id; internal Exception InnerException => Exception; public CompositionError(string message) : this(CompositionErrorId.Unknown, message, null, null) { } public CompositionError(string message, ICompositionElement element) : this(CompositionErrorId.Unknown, message, element, null) { } public CompositionError(string message, Exception exception) : this(CompositionErrorId.Unknown, message, null, exception) { } public CompositionError(string message, ICompositionElement element, Exception exception) : this(CompositionErrorId.Unknown, message, element, exception) { } internal CompositionError(CompositionErrorId id, string description, ICompositionElement element, Exception exception) { _id = id; _description = description ?? string.Empty; _element = element; _exception = exception; } public override string ToString() { return Description; } internal static CompositionError Create(CompositionErrorId id, string format, params object[] parameters) { return Create(id, null, null, format, parameters); } internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, string format, params object[] parameters) { return Create(id, element, null, format, parameters); } internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, Exception exception, string format, params object[] parameters) { return new CompositionError(id, string.Format(CultureInfo.CurrentCulture, format, parameters), element, exception); } } internal class CompositionErrorDebuggerProxy { private readonly CompositionError _error; public string Description => _error.Description; public Exception Exception => _error.Exception; public ICompositionElement Element => _error.Element; public CompositionErrorDebuggerProxy(CompositionError error) { Requires.NotNull(error, "error"); _error = error; } } internal enum CompositionErrorId { Unknown, InvalidExportMetadata, ImportNotSetOnPart, ImportEngine_ComposeTookTooManyIterations, ImportEngine_ImportCardinalityMismatch, ImportEngine_PartCycle, ImportEngine_PartCannotSetImport, ImportEngine_PartCannotGetExportedValue, ImportEngine_PartCannotActivate, ImportEngine_PreventedByExistingImport, ImportEngine_InvalidStateForRecomposition, ReflectionModel_ImportThrewException, ReflectionModel_ImportNotAssignableFromExport, ReflectionModel_ImportCollectionNull, ReflectionModel_ImportCollectionNotWritable, ReflectionModel_ImportCollectionConstructionThrewException, ReflectionModel_ImportCollectionGetThrewException, ReflectionModel_ImportCollectionIsReadOnlyThrewException, ReflectionModel_ImportCollectionClearThrewException, ReflectionModel_ImportCollectionAddThrewException, ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned } [Serializable] [DebuggerDisplay("{Message}")] [DebuggerTypeProxy(typeof(CompositionExceptionDebuggerProxy))] public class CompositionException : Exception { [Serializable] private struct CompositionExceptionData : ISafeSerializationData { public CompositionError[] _errors; void ISafeSerializationData.CompleteDeserialization(object obj) { (obj as CompositionException)._errors = new ReadOnlyCollection<CompositionError>(_errors); } } private struct VisitContext { public Stack<CompositionError> Path; public Action<Stack<CompositionError>> LeafVisitor; } private const string ErrorsKey = "Errors"; private ReadOnlyCollection<CompositionError> _errors; public ReadOnlyCollection<CompositionError> Errors => _errors; public override string Message { get { if (Errors.Count == 0) { return base.Message; } return BuildDefaultMessage(); } } public ReadOnlyCollection<Exception> RootCauses { get { //IL_0007: Expected O, but got I4 ThrowStub.ThrowNotSupportedException(); return (ReadOnlyCollection<Exception>)0; } } public CompositionException() : this(null, null, null) { } public CompositionException(string message) : this(message, null, null) { } public CompositionException(string message, Exception innerException) : this(message, innerException, null) { } internal CompositionException(CompositionError error) : this(new CompositionError[1] { error }) { } public CompositionException(IEnumerable<CompositionError> errors) : this(null, null, errors) { } internal CompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors) : base(message, innerException) { Requires.NullOrNotNullElements(errors, "errors"); base.SerializeObjectState += delegate(object exception, SafeSerializationEventArgs eventArgs) { CompositionExceptionData compositionExceptionData = default(CompositionExceptionData); if (_errors != null) { compositionExceptionData._errors = _errors.Select((CompositionError error) => new CompositionError(error.Id, error.Description, error.Element.ToSerializableElement(), error.Exception)).ToArray(); } else { compositionExceptionData._errors = new CompositionError[0]; } eventArgs.AddSerializedState(compositionExceptionData); }; _errors = new ReadOnlyCollection<CompositionError>((errors == null) ? ((IList<CompositionError>)new CompositionError[0]) : ((IList<CompositionError>)errors.ToArray())); } private string BuildDefaultMessage() { IEnumerable<IEnumerable<CompositionError>> enumerable = CalculatePaths(this); StringBuilder stringBuilder = new StringBuilder(); WriteHeader(stringBuilder, Errors.Count, enumerable.Count()); WritePaths(stringBuilder, enumerable); return stringBuilder.ToString(); } private static void WriteHeader(StringBuilder writer, int errorsCount, int pathCount) { if (errorsCount > 1 && pathCount > 1) { writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_MultipleErrorsWithMultiplePaths, pathCount); } else if (errorsCount == 1 && pathCount > 1) { writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_SingleErrorWithMultiplePaths, pathCount); } else { Assumes.IsTrue(errorsCount == 1); Assumes.IsTrue(pathCount == 1); writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_SingleErrorWithSinglePath, pathCount); } writer.Append(' '); writer.AppendLine(Strings.CompositionException_ReviewErrorProperty); } private static void WritePaths(StringBuilder writer, IEnumerable<IEnumerable<CompositionError>> paths) { int num = 0; foreach (IEnumerable<CompositionError> path in paths) { num++; WritePath(writer, path, num); } } private static void WritePath(StringBuilder writer, IEnumerable<CompositionError> path, int ordinal) { writer.AppendLine(); writer.Append(ordinal.ToString(CultureInfo.CurrentCulture)); writer.Append(Strings.CompositionException_PathsCountSeparator); writer.Append(' '); WriteError(writer, path.First()); foreach (CompositionError item in path.Skip(1)) { writer.AppendLine(); writer.Append(Strings.CompositionException_ErrorPrefix); writer.Append(' '); WriteError(writer, item); } } private static void WriteError(StringBuilder writer, CompositionError error) { writer.AppendLine(error.Description); if (error.Element != null) { WriteElementGraph(writer, error.Element); } } private static void WriteElementGraph(StringBuilder writer, ICompositionElement element) { writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_ElementPrefix, element.DisplayName); while ((element = element.Origin) != null) { writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_OriginFormat, Strings.CompositionException_OriginSeparator, element.DisplayName); } writer.AppendLine(); } private static IEnumerable<IEnumerable<CompositionError>> CalculatePaths(CompositionException exception) { List<IEnumerable<CompositionError>> paths = new List<IEnumerable<CompositionError>>(); VisitContext context = default(VisitContext); context.Path = new Stack<CompositionError>(); context.LeafVisitor = delegate(Stack<CompositionError> path) { paths.Add(path.Copy()); }; VisitCompositionException(exception, context); return paths; } private static void VisitCompositionException(CompositionException exception, VisitContext context) { foreach (CompositionError error in exception.Errors) { VisitError(error, context); } if (exception.InnerException != null) { VisitException(exception.InnerException, context); } } private static void VisitError(CompositionError error, VisitContext context) { context.Path.Push(error); if (error.Exception == null) { context.LeafVisitor(context.Path); } else { VisitException(error.Exception, context); } context.Path.Pop(); } private static void VisitException(Exception exception, VisitContext context) { if (exception is CompositionException exception2) { VisitCompositionException(exception2, context); } else { VisitError(new CompositionError(exception.Message, exception.InnerException), context); } } } internal class CompositionExceptionDebuggerProxy { private readonly CompositionException _exception; public ReadOnlyCollection<Exception> Exceptions { get { List<Exception> list = new List<Exception>(); foreach (CompositionError error in _exception.Errors) { if (error.Exception != null) { list.Add(error.Exception); } } return list.ToReadOnlyCollection(); } } public string Message => _exception.Message; public ReadOnlyCollection<Exception> RootCauses { get { List<Exception> list = new List<Exception>(); foreach (CompositionError error in _exception.Errors) { if (error.Exception == null) { continue; } if (error.Exception is CompositionException exception) { CompositionExceptionDebuggerProxy compositionExceptionDebuggerProxy = new CompositionExceptionDebuggerProxy(exception); if (compositionExceptionDebuggerProxy.RootCauses.Count > 0) { list.AddRange(compositionExceptionDebuggerProxy.RootCauses); continue; } } list.Add(error.Exception); } return list.ToReadOnlyCollection(); } } public CompositionExceptionDebuggerProxy(CompositionException exception) { Requires.NotNull(exception, "exception"); _exception = exception; } } internal struct CompositionResult { public static readonly CompositionResult SucceededResult; private readonly IEnumerable<CompositionError> _errors; public bool Succeeded { get { if (_errors != null) { return !_errors.FastAny(); } return true; } } public IEnumerable<CompositionError> Errors => _errors ?? Enumerable.Empty<CompositionError>(); public CompositionResult(params CompositionError[] errors) : this((IEnumerable<CompositionError>)errors) { } public CompositionResult(IEnumerable<CompositionError> errors) { _errors = errors; } public CompositionResult MergeResult(CompositionResult result) { if (Succeeded) { return result; } if (result.Succeeded) { return this; } return MergeErrors(result._errors); } public CompositionResult MergeError(CompositionError error) { return MergeErrors(new CompositionError[1] { error }); } public CompositionResult MergeErrors(IEnumerable<CompositionError> errors) { return new CompositionResult(_errors.ConcatAllowingNull(errors)); } public CompositionResult<T> ToResult<T>(T value) { return new CompositionResult<T>(value, _errors); } public void ThrowOnErrors() { ThrowOnErrors(null); } public void ThrowOnErrors(AtomicComposition atomicComposition) { if (!Succeeded) { if (atomicComposition == null) { throw new CompositionException(_errors); } throw new ChangeRejectedException(_errors); } } } internal struct CompositionResult<T> { private readonly IEnumerable<CompositionError> _errors; private readonly T _value; public bool Succeeded { get { if (_errors != null) { return !_errors.FastAny(); } return true; } } public IEnumerable<CompositionError> Errors => _errors ?? Enumerable.Empty<CompositionError>(); public T Value { get { ThrowOnErrors(); return _value; } } public CompositionResult(T value) : this(value, null) { } public CompositionResult(params CompositionError[] errors) : this(default(T), errors) { } public CompositionResult(IEnumerable<CompositionError> errors) : this(default(T), errors) { } internal CompositionResult(T value, IEnumerable<CompositionError> errors) { _errors = errors; _value = value; } internal CompositionResult<TValue> ToResult<TValue>() { return new CompositionResult<TValue>(_errors); } internal CompositionResult ToResult() { return new CompositionResult(_errors); } private void ThrowOnErrors() { if (!Succeeded) { throw new CompositionException(_errors); } } } internal static class ConstraintServices { private static readonly PropertyInfo _exportDefinitionContractNameProperty = typeof(ExportDefinition).GetProperty("ContractName"); private static readonly PropertyInfo _exportDefinitionMetadataProperty = typeof(ExportDefinition).GetProperty("Metadata"); private static readonly MethodInfo _metadataContainsKeyMethod = typeof(IDictionary<string, object>).GetMethod("ContainsKey"); private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary<string, object>).GetMethod("get_Item"); private static readonly MethodInfo _metadataEqualsMethod = typeof(object).GetMethod("Equals", new Type[1] { typeof(object) }); private static readonly MethodInfo _typeIsInstanceOfTypeMethod = typeof(Type).GetMethod("IsInstanceOfType"); public static Expression<Func<ExportDefinition, bool>> CreateConstraint(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, CreationPolicy requiredCreationPolicy) { ParameterExpression parameterExpression = Expression.Parameter(typeof(ExportDefinition), "exportDefinition"); Expression expression = CreateContractConstraintBody(contractName, parameterExpression); if (!string.IsNullOrEmpty(requiredTypeIdentity)) { Expression right = CreateTypeIdentityContraint(requiredTypeIdentity, parameterExpression); expression = Expression.AndAlso(expression, right); } if (requiredMetadata != null) { Expression expression2 = CreateMetadataConstraintBody(requiredMetadata, parameterExpression); if (expression2 != null) { expression = Expression.AndAlso(expression, expression2); } } if (requiredCreationPolicy != 0) { Expression right2 = CreateCreationPolicyContraint(requiredCreationPolicy, parameterExpression); expression = Expression.AndAlso(expression, right2); } return Expression.Lambda<Func<ExportDefinition, bool>>(expression, new ParameterExpression[1] { parameterExpression }); } private static Expression CreateContractConstraintBody(string contractName, ParameterExpression parameter) { Assumes.NotNull(parameter); return Expression.Equal(Expression.Property(parameter, _exportDefinitionContractNameProperty), Expression.Constant(contractName ?? string.Empty, typeof(string))); } private static Expression CreateMetadataConstraintBody(IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ParameterExpression parameter) { Assumes.NotNull(requiredMetadata); Assumes.NotNull(parameter); Expression expression = null; foreach (KeyValuePair<string, Type> requiredMetadatum in requiredMetadata) { Expression expression2 = CreateMetadataContainsKeyExpression(parameter, requiredMetadatum.Key); expression = ((expression != null) ? Expression.AndAlso(expression, expression2) : expression2); expression = Expression.AndAlso(expression, CreateMetadataOfTypeExpression(parameter, requiredMetadatum.Key, requiredMetadatum.Value)); } return expression; } private static Expression CreateCreationPolicyContraint(CreationPolicy policy, ParameterExpression parameter) { Assumes.IsTrue(policy != CreationPolicy.Any); Assumes.NotNull(parameter); return Expression.MakeBinary(ExpressionType.OrElse, Expression.MakeBinary(ExpressionType.OrElse, Expression.Not(CreateMetadataContainsKeyExpression(parameter, "System.ComponentModel.Composition.CreationPolicy")), CreateMetadataValueEqualsExpression(parameter, CreationPolicy.Any, "System.ComponentModel.Composition.CreationPolicy")), CreateMetadataValueEqualsExpression(parameter, policy, "System.ComponentModel.Composition.CreationPolicy")); } private static Expression CreateTypeIdentityContraint(string requiredTypeIdentity, ParameterExpression parameter) { Assumes.NotNull(requiredTypeIdentity); Assumes.NotNull(parameter); return Expression.MakeBinary(ExpressionType.AndAlso, CreateMetadataContainsKeyExpression(parameter, "ExportTypeIdentity"), CreateMetadataValueEqualsExpression(parameter, requiredTypeIdentity, "ExportTypeIdentity")); } private static Expression CreateMetadataContainsKeyExpression(ParameterExpression parameter, string constantKey) { Assumes.NotNull(parameter, constantKey); return Expression.Call(Expression.Property(parameter, _exportDefinitionMetadataProperty), _metadataContainsKeyMethod, Expression.Constant(constantKey)); } private static Expression CreateMetadataOfTypeExpression(ParameterExpression parameter, string constantKey, Type constantType) { Assumes.NotNull(parameter, constantKey); Assumes.NotNull(parameter, constantType); return Expression.Call(Expression.Constant(constantType, typeof(Type)), _typeIsInstanceOfTypeMethod, Expression.Call(Expression.Property(parameter, _exportDefinitionMetadataProperty), _metadataItemMethod, Expression.Constant(constantKey))); } private static Expression CreateMetadataValueEqualsExpression(ParameterExpression parameter, object constantValue, string metadataName) { Assumes.NotNull(parameter, constantValue); return Expression.Call(Expression.Constant(constantValue), _metadataEqualsMethod, Expression.Call(Expression.Property(parameter, _exportDefinitionMetadataProperty), _metadataItemMethod, Expression.Constant(metadataName))); } public static Expression<Func<ExportDefinition, bool>> CreatePartCreatorConstraint(Expression<Func<ExportDefinition, bool>> baseConstraint, ImportDefinition productImportDefinition) { ParameterExpression parameterExpression = baseConstraint.Parameters[0]; Expression instance = Expression.Property(parameterExpression, _exportDefinitionMetadataProperty); Expression left = Expression.Call(instance, _metadataContainsKeyMethod, Expression.Constant("ProductDefinition")); Expression expression = Expression.Call(instance, _metadataItemMethod, Expression.Constant("ProductDefinition")); Expression right = Expression.Invoke(productImportDefinition.Constraint, Expression.Convert(expression, typeof(ExportDefinition))); return Expression.Lambda<Func<ExportDefinition, bool>>(Expression.AndAlso(baseConstraint.Body, Expression.AndAlso(left, right)), new ParameterExpression[1] { parameterExpression }); } } internal static class ContractNameServices { private const char NamespaceSeparator = '.'; private const char ArrayOpeningBracket = '['; private const char ArrayClosingBracket = ']'; private const char ArraySeparator = ','; private const char PointerSymbol = '*'; private const char ReferenceSymbol = '&'; private const char GenericArityBackQuote = '`'; private const char NestedClassSeparator = '+'; private const char ContractNameGenericOpeningBracket = '('; private const char ContractNameGenericClosingBracket = ')'; private const char ContractNameGenericArgumentSeparator = ','; private const char CustomModifiersSeparator = ' '; private const char GenericFormatOpeningBracket = '{'; private const char GenericFormatClosingBracket = '}'; [ThreadStatic] private static Dictionary<Type, string> typeIdentityCache; private static Dictionary<Type, string> TypeIdentityCache { get { Dictionary<Type, string> result = typeIdentityCache ?? new Dictionary<Type, string>(); typeIdentityCache = result; return result; } } internal static string GetTypeIdentity(Type type) { return GetTypeIdentity(type, formatGenericName: true); } internal static string GetTypeIdentity(Type type, bool formatGenericName) { Assumes.NotNull(type); string value = null; if (!TypeIdentityCache.TryGetValue(type, out value)) { if (!type.IsAbstract && type.IsSubclassOf(typeof(Delegate))) { value = GetTypeIdentityFromMethod(type.GetMethod("Invoke")); } else if (type.IsGenericParameter) { StringBuilder stringBuilder = new StringBuilder(); WriteTypeArgument(stringBuilder, isDefinition: false, type, formatGenericName); stringBuilder.Remove(stringBuilder.Length - 1, 1); value = stringBuilder.ToString(); } else { StringBuilder stringBuilder2 = new StringBuilder(); WriteTypeWithNamespace(stringBuilder2, type, formatGenericName); value = stringBuilder2.ToString(); } Assumes.IsTrue(!string.IsNullOrEmpty(value)); TypeIdentityCache.Add(type, value); } return value; } internal static string GetTypeIdentityFromMethod(MethodInfo method) { return GetTypeIdentityFromMethod(method, formatGenericName: true); } internal static string GetTypeIdentityFromMethod(MethodInfo method, bool formatGenericName) { StringBuilder stringBuilder = new StringBuilder(); WriteTypeWithNamespace(stringBuilder, method.ReturnType, formatGenericName); stringBuilder.Append("("); ParameterInfo[] parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (i != 0) { stringBuilder.Append(","); } WriteTypeWithNamespace(stringBuilder, parameters[i].ParameterType, formatGenericName); } stringBuilder.Append(")"); return stringBuilder.ToString(); } private static void WriteTypeWithNamespace(StringBuilder typeName, Type type, bool formatGenericName) { if (!string.IsNullOrEmpty(type.Namespace)) { typeName.Append(type.Namespace); typeName.Append('.'); } WriteType(typeName, type, formatGenericName); } private static void WriteType(StringBuilder typeName, Type type, bool formatGenericName) { if (type.IsGenericType) { Queue<Type> queue = new Queue<Type>(type.GetGenericArguments()); WriteGenericType(typeName, type, type.IsGenericTypeDefinition, queue, formatGenericName); Assumes.IsTrue(queue.Count == 0, "Expecting genericTypeArguments queue to be empty."); } else { WriteNonGenericType(typeName, type, formatGenericName); } } private static void WriteNonGenericType(StringBuilder typeName, Type type, bool formatGenericName) { if (type.DeclaringType != null) { WriteType(typeName, type.DeclaringType, formatGenericName); typeName.Append('+'); } if (type.IsArray) { WriteArrayType(typeName, type, formatGenericName); } else if (type.IsPointer) { WritePointerType(typeName, type, formatGenericName); } else if (type.IsByRef) { WriteByRefType(typeName, type, formatGenericName); } else { typeName.Append(type.Name); } } private static void WriteArrayType(StringBuilder typeName, Type type, bool formatGenericName) { Type type2 = FindArrayElementType(type); WriteType(typeName, type2, formatGenericName); Type type3 = type; do { WriteArrayTypeDimensions(typeName, type3); } while ((type3 = type3.GetElementType()) != null && type3.IsArray); } private static void WritePointerType(StringBuilder typeName, Type type, bool formatGenericName) { WriteType(typeName, type.GetElementType(), formatGenericName); typeName.Append('*'); } private static void WriteByRefType(StringBuilder typeName, Type type, bool formatGenericName) { WriteType(typeName, type.GetElementType(), formatGenericName); typeName.Append('&'); } private static void WriteArrayTypeDimensions(StringBuilder typeName, Type type) { typeName.Append('['); int arrayRank = type.GetArrayRank(); for (int i = 1; i < arrayRank; i++) { typeName.Append(','); } typeName.Append(']'); } private static void WriteGenericType(StringBuilder typeName, Type type, bool isDefinition, Queue<Type> genericTypeArguments, bool formatGenericName) { if (type.DeclaringType != null) { if (type.DeclaringType.IsGenericType) { WriteGenericType(typeName, type.DeclaringType, isDefinition, genericTypeArguments, formatGenericName); } else { WriteNonGenericType(typeName, type.DeclaringType, formatGenericName); } typeName.Append('+'); } WriteGenericTypeName(typeName, type, isDefinition, genericTypeArguments, formatGenericName); } private static void WriteGenericTypeName(StringBuilder typeName, Type type, bool isDefinition, Queue<Type> genericTypeArguments, bool formatGenericName) { Assumes.IsTrue(type.IsGenericType, "Expecting type to be a generic type"); int genericArity = GetGenericArity(type); string value = FindGenericTypeName(type.GetGenericTypeDefinition().Name); typeName.Append(value); WriteTypeArgumentsString(typeName, genericArity, isDefinition, genericTypeArguments, formatGenericName); } private static void WriteTypeArgumentsString(StringBuilder typeName, int argumentsCount, bool isDefinition, Queue<Type> genericTypeArguments, bool formatGenericName) { if (argumentsCount != 0) { typeName.Append('('); for (int i = 0; i < argumentsCount; i++) { Assumes.IsTrue(genericTypeArguments.Count > 0, "Expecting genericTypeArguments to contain at least one Type"); Type genericTypeArgument = genericTypeArguments.Dequeue(); WriteTypeArgument(typeName, isDefinition, genericTypeArgument, formatGenericName); } typeName.Remove(typeName.Length - 1, 1); typeName.Append(')'); } } private static void WriteTypeArgument(StringBuilder typeName, bool isDefinition, Type genericTypeArgument, bool formatGenericName) { if (!isDefinition && !genericTypeArgument.IsGenericParameter) { WriteTypeWithNamespace(typeName, genericTypeArgument, formatGenericName); } if (formatGenericName && genericTypeArgument.IsGenericParameter) { typeName.Append('{'); typeName.Append(genericTypeArgument.GenericParameterPosition); typeName.Append('}'); } typeName.Append(','); } internal static void WriteCustomModifiers(StringBuilder typeName, string customKeyword, Type[] types, bool formatGenericName) { typeName.Append(' '); typeName.Append(customKeyword); Queue<Type> queue = new Queue<Type>(types); WriteTypeArgumentsString(typeName, types.Length, isDefinition: false, queue, formatGenericName); Assumes.IsTrue(queue.Count == 0, "Expecting genericTypeArguments queue to be empty."); } private static Type FindArrayElementType(Type type) { Type type2 = type; while ((type2 = type2.GetElementType()) != null && type2.IsArray) { } return type2; } private static string FindGenericTypeName(string genericName) { int num = genericName.IndexOf('`'); if (num > -1) { genericName = genericName.Substring(0, num); } return genericName; } private static int GetGenericArity(Type type) { if (type.DeclaringType == null) { return type.GetGenericArguments().Length; } int num = type.DeclaringType.GetGenericArguments().Length; int num2 = type.GetGenericArguments().Length; Assumes.IsTrue(num2 >= num); return num2 - num; } } public enum CreationPolicy { Any, Shared, NonShared, NewScope } internal static class ErrorBuilder { public static CompositionError PreventedByExistingImport(ComposablePart part, ImportDefinition import) { return CompositionError.Create(CompositionErrorId.ImportEngine_PreventedByExistingImport, Strings.ImportEngine_PreventedByExistingImport, import.ToElement().DisplayName, part.ToElement().DisplayName); } public static CompositionError InvalidStateForRecompposition(ComposablePart part) { return CompositionError.Create(CompositionErrorId.ImportEngine_InvalidStateForRecomposition, Strings.ImportEngine_InvalidStateForRecomposition, part.ToElement().DisplayName); } public static CompositionError ComposeTookTooManyIterations(int maximumNumberOfCompositionIterations) { return CompositionError.Create(CompositionErrorId.ImportEngine_ComposeTookTooManyIterations, Strings.ImportEngine_ComposeTookTooManyIterations, maximumNumberOfCompositionIterations); } public static CompositionError CreateImportCardinalityMismatch(ImportCardinalityMismatchException exception, ImportDefinition definition) { Assumes.NotNull(exception, definition); return CompositionError.Create(CompositionErrorId.ImportEngine_ImportCardinalityMismatch, exception.Message, definition.ToElement(), null); } public static CompositionError CreatePartCannotActivate(ComposablePart part, Exception innerException) { Assumes.NotNull(part, innerException); ICompositionElement compositionElement = part.ToElement(); return CompositionError.Create(CompositionErrorId.ImportEngine_PartCannotActivate, compositionElement, innerException, Strings.ImportEngine_PartCannotActivate, compositionElement.DisplayName); } public static CompositionError CreatePartCannotSetImport(ComposablePart part, ImportDefinition definition, Exception innerException) { Assumes.NotNull(part, definition, innerException); ICompositionElement compositionElement = definition.ToElement(); return CompositionError.Create(CompositionErrorId.ImportEngine_PartCannotSetImport, compositionElement, innerException, Strings.ImportEngine_PartCannotSetImport, compositionElement.DisplayName, part.ToElement().DisplayName); } public static CompositionError CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException) { Assumes.NotNull(part, definition, innerException); ICompositionElement compositionElement = definition.ToElement(); return CompositionError.Create(CompositionErrorId.ImportEngine_PartCannotGetExportedValue, compositionElement, innerException, Strings.ImportEngine_PartCannotGetExportedValue, compositionElement.DisplayName, part.ToElement().DisplayName); } public static CompositionError CreatePartCycle(ComposablePart part) { Assumes.NotNull(part); ICompositionElement compositionElement = part.ToElement(); return CompositionError.Create(CompositionErrorId.ImportEngine_PartCycle, compositionElement, Strings.ImportEngine_PartCycle, compositionElement.DisplayName); } } internal static class ExceptionBuilder { public static Exception CreateDiscoveryException(string messageFormat, params string[] arguments) { return new InvalidOperationException(Format(messageFormat, arguments)); } public static ArgumentException CreateContainsNullElement(string parameterName) { Assumes.NotNull(parameterName); return new ArgumentException(Format(Strings.Argument_NullElement, parameterName), parameterName); } public static ObjectDisposedException CreateObjectDisposed(object instance) { Assumes.NotNull(instance); return new ObjectDisposedException(instance.GetType().ToString()); } public static NotImplementedException CreateNotOverriddenByDerived(string memberName) { Assumes.NotNullOrEmpty(memberName); return new NotImplementedException(Format(Strings.NotImplemented_NotOverriddenByDerived, memberName)); } public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(string parameterName) { Assumes.NotNullOrEmpty(parameterName); return new ArgumentException(Format(Strings.ExportDefinitionNotOnThisComposablePart, parameterName), parameterName); } public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(string parameterName) { Assumes.NotNullOrEmpty(parameterName); return new ArgumentException(Format(Strings.ImportDefinitionNotOnThisComposablePart, parameterName), parameterName); } public static CompositionException CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException) { Assumes.NotNull(part, definition, innerException); return new CompositionException(ErrorBuilder.CreateCannotGetExportedValue(part, definition, innerException)); } public static ArgumentException CreateReflectionModelInvalidPartDefinition(string parameterName, Type partDefinitionType) { Assumes.NotNullOrEmpty(parameterName); Assumes.NotNull(partDefinitionType); return new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidPartDefinition, partDefinitionType), parameterName); } public static ArgumentException ExportFactory_TooManyGenericParameters(string typeName) { Assumes.NotNullOrEmpty(typeName); return new ArgumentException(Format(Strings.ExportFactory_TooManyGenericParameters, typeName), typeName); } private static string Format(string format, params string[] arguments) { return string.Format(CultureInfo.CurrentCulture, format, arguments); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] public class ExportAttribute : Attribute { public string ContractName { get; private set; } public Type ContractType { get; private set; } public ExportAttribute() : this(null, null) { } public ExportAttribute(Type contractType) : this(null, contractType) { } public ExportAttribute(string contractName) : this(contractName, null) { } public ExportAttribute(string contractName, Type contractType) { ContractName = contractName; ContractType = contractType; } } internal enum ExportCardinalityCheckResult { Match, NoExports, TooManyExports } public class ExportFactory<T> { private Func<Tuple<T, Action>> _exportLifetimeContextCreator; public ExportFactory(Func<Tuple<T, Action>> exportLifetimeContextCreator) { if (exportLifetimeContextCreator == null) { throw new ArgumentNullException("exportLifetimeContextCreator"); } _exportLifetimeContextCreator = exportLifetimeContextCreator; } public ExportLifetimeContext<T> CreateExport() { Tuple<T, Action> tuple = _exportLifetimeContextCreator(); return new ExportLifetimeContext<T>(tuple.Item1, tuple.Item2); } internal bool IncludeInScopedCatalog(ComposablePartDefinition composablePartDefinition) { return OnFilterScopedCatalog(composablePartDefinition); } protected virtual bool OnFilterScopedCatalog(ComposablePartDefinition composablePartDefinition) { return true; } } public class ExportFactory<T, TMetadata> : ExportFactory<T> { private readonly TMetadata _metadata; public TMetadata Metadata => _metadata; public ExportFactory(Func<Tuple<T, Action>> exportLifetimeContextCreator, TMetadata metadata) : base(exportLifetimeContextCreator) { _metadata = metadata; } } public sealed class ExportLifetimeContext<T> : IDisposable { private readonly T _value; private readonly Action _disposeAction; public T Value => _value; public ExportLifetimeContext(T value, Action disposeAction) { _value = value; _disposeAction = disposeAction; } public void Dispose() { if (_disposeAction != null) { _disposeAction(); } } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] public sealed class ExportMetadataAttribute : Attribute { public string Name { get; private set; } public object Value { get; private set; } public bool IsMultiple { get; set; } public ExportMetadataAttribute(string name, object value) { Name = name ?? string.Empty; Value = value; } } internal static class ExportServices { private sealed class DisposableLazy<T, TMetadataView> : Lazy<T, TMetadataView>, IDisposable { private IDisposable _disposable; public DisposableLazy(Func<T> valueFactory, TMetadataView metadataView, IDisposable disposable, LazyThreadSafetyMode mode) : base(valueFactory, metadataView, mode) { Assumes.NotNull(disposable); _disposable = disposable; } void IDisposable.Dispose() { _disposable.Dispose(); } } private sealed class DisposableLazy<T> : Lazy<T>, IDisposable { private IDisposable _disposable; public DisposableLazy(Func<T> valueFactory, IDisposable disposable, LazyThreadSafetyMode mode) : base(valueFactory, mode) { Assumes.NotNull(disposable); _disposable = disposable; } void IDisposable.Dispose() { _disposable.Dispose(); } } private static readonly MethodInfo _createStronglyTypedLazyOfTM = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfTM", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo _createStronglyTypedLazyOfT = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfT", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo _createSemiStronglyTypedLazy = typeof(ExportServices).GetMethod("CreateSemiStronglyTypedLazy", BindingFlags.Static | BindingFlags.NonPublic); internal static readonly Type DefaultMetadataViewType = typeof(IDictionary<string, object>); internal static readonly Type DefaultExportedValueType = typeof(object); internal static bool IsDefaultMetadataViewType(Type metadataViewType) { Assumes.NotNull(metadataViewType); return metadataViewType.IsAssignableFrom(DefaultMetadataViewType); } internal static bool IsDictionaryConstructorViewType(Type metadataViewType) { Assumes.NotNull(metadataViewType); return metadataViewType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new Type[1] { typeof(IDictionary<string, object>) }, new ParameterModifier[0]) != null; } internal static Func<Export, object> CreateStronglyTypedLazyFactory(Type exportType, Type metadataViewType) { MethodInfo methodInfo = null; methodInfo = ((!(metadataViewType != null)) ? _createStronglyTypedLazyOfT.MakeGenericMethod(exportType ?? DefaultExportedValueType) : _createStronglyTypedLazyOfTM.MakeGenericMethod(exportType ?? DefaultExportedValueType, metadataViewType)); Assumes.NotNull(methodInfo); return (Func<Export, object>)Delegate.CreateDelegate(typeof(Func<Export, object>), methodInfo); } internal static Func<Export, Lazy<object
deps/System.Composition.AttributedModel.dll
Decompiled a day agousing System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Composition.AttributedModel")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides the foundational attributes that allow you to declare parts for composition, such as imports, exports, and metadata with the Managed Extensibility Framework (MEF).")] [assembly: AssemblyFileVersion("9.0.24.52809")] [assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Composition.AttributedModel")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("9.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Composition { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = false)] public class ExportAttribute : Attribute { public string ContractName { get; } public Type ContractType { get; } public ExportAttribute() : this(null, null) { } public ExportAttribute(Type contractType) : this(null, contractType) { } public ExportAttribute(string contractName) : this(contractName, null) { } public ExportAttribute(string contractName, Type contractType) { ContractName = contractName; ContractType = contractType; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] public sealed class ExportMetadataAttribute : Attribute { public string Name { get; } public object Value { get; } public ExportMetadataAttribute(string name, object value) { Name = name ?? string.Empty; Value = value; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class ImportAttribute : Attribute { public string ContractName { get; } public bool AllowDefault { get; set; } public ImportAttribute() : this(null) { } public ImportAttribute(string contractName) { ContractName = contractName; } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] public sealed class ImportingConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class ImportManyAttribute : Attribute { public string ContractName { get; } public ImportManyAttribute() : this(null) { } public ImportManyAttribute(string contractName) { ContractName = contractName; } } [AttributeUsage(AttributeTargets.Property, Inherited = false)] public sealed class ImportMetadataConstraintAttribute : Attribute { public string Name { get; } public object Value { get; } public ImportMetadataConstraintAttribute(string name, object value) { Name = name; Value = value; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class MetadataAttributeAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class OnImportsSatisfiedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class PartMetadataAttribute : Attribute { public string Name { get; } public object Value { get; } public PartMetadataAttribute(string name, object value) { Name = name ?? throw new ArgumentNullException("name"); Value = value; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class PartNotDiscoverableAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, Inherited = false)] public class SharedAttribute : PartMetadataAttribute { private const string SharingBoundaryPartMetadataName = "SharingBoundary"; public string SharingBoundary => (string)base.Value; public SharedAttribute() : base("SharingBoundary", null) { } public SharedAttribute(string sharingBoundaryName) : base("SharingBoundary", sharingBoundaryName) { } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, Inherited = false)] [MetadataAttribute] [CLSCompliant(false)] public sealed class SharingBoundaryAttribute : Attribute { private readonly string[] _sharingBoundaryNames; public ReadOnlyCollection<string> SharingBoundaryNames => Array.AsReadOnly(_sharingBoundaryNames); public SharingBoundaryAttribute(params string[] sharingBoundaryNames) { _sharingBoundaryNames = sharingBoundaryNames ?? throw new ArgumentNullException("sharingBoundaryNames"); } } } namespace System.Composition.Convention { public abstract class AttributedModelProvider { public abstract IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, MemberInfo member); public abstract IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, ParameterInfo parameter); } }
deps/System.Composition.Convention.dll
Decompiled a day agousing System; using System.Collections.Generic; using System.Composition.Diagnostics; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using FxResources.System.Composition.Convention; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Composition.Convention")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides types that support using Managed Extensibility Framework (MEF) with a convention-based configuration model.")] [assembly: AssemblyFileVersion("9.0.24.52809")] [assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Composition.Convention")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("9.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Composition.Convention { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue(); private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArgumentOutOfRange_InvalidEnumInSet => GetResourceString("ArgumentOutOfRange_InvalidEnumInSet"); internal static string Argument_ExpressionMustBeNew => GetResourceString("Argument_ExpressionMustBeNew"); internal static string Argument_ExpressionMustBePropertyMember => GetResourceString("Argument_ExpressionMustBePropertyMember"); internal static string Registration_ConstructorConventionOverridden => GetResourceString("Registration_ConstructorConventionOverridden"); internal static string Registration_TypeExportConventionOverridden => GetResourceString("Registration_TypeExportConventionOverridden"); internal static string Registration_MemberExportConventionOverridden => GetResourceString("Registration_MemberExportConventionOverridden"); internal static string Registration_MemberImportConventionOverridden => GetResourceString("Registration_MemberImportConventionOverridden"); internal static string Registration_MemberImportConventionMatchedTwice => GetResourceString("Registration_MemberImportConventionMatchedTwice"); internal static string Registration_ParameterImportConventionOverridden => GetResourceString("Registration_ParameterImportConventionOverridden"); internal static string Registration_PartCreationConventionOverridden => GetResourceString("Registration_PartCreationConventionOverridden"); internal static string Registration_PartMetadataConventionOverridden => GetResourceString("Registration_PartMetadataConventionOverridden"); internal static string Argument_ExpressionMustBeVoidMethodWithNoArguments => GetResourceString("Argument_ExpressionMustBeVoidMethodWithNoArguments"); internal static string Registration_OnSatisfiedImportNotificationOverridden => GetResourceString("Registration_OnSatisfiedImportNotificationOverridden"); internal static string Diagnostic_InternalExceptionMessage => GetResourceString("Diagnostic_InternalExceptionMessage"); internal static string Diagnostic_TraceUnnecessaryWork => GetResourceString("Diagnostic_TraceUnnecessaryWork"); internal static string ArgumentException_EmptyString => GetResourceString("ArgumentException_EmptyString"); private static bool GetUsingResourceKeysSwitchValue() { if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled)) { return false; } return isEnabled; } internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Composition.Diagnostics { internal static class CompositionTrace { public static void Registration_ConstructorConventionOverridden(Type type) { if (type == null) { throw new Exception(System.SR.Diagnostic_InternalExceptionMessage); } if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Registration_ConstructorConventionOverridden, System.SR.Registration_ConstructorConventionOverridden, type.FullName); } } public static void Registration_TypeExportConventionOverridden(Type type) { if (type == null) { throw new Exception(System.SR.Diagnostic_InternalExceptionMessage); } if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_TypeExportConventionOverridden, System.SR.Registration_TypeExportConventionOverridden, type.FullName); } } public static void Registration_MemberExportConventionOverridden(Type type, MemberInfo member) { if ((object)type == null) { throw new ArgumentNullException("type"); } if ((object)member == null) { throw new ArgumentNullException("member"); } if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberExportConventionOverridden, System.SR.Registration_MemberExportConventionOverridden, member.Name, type.FullName); } } public static void Registration_MemberImportConventionOverridden(Type type, MemberInfo member) { if ((object)type == null) { throw new ArgumentNullException("type"); } if ((object)member == null) { throw new ArgumentNullException("member"); } if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionOverridden, System.SR.Registration_MemberImportConventionOverridden, member.Name, type.FullName); } } public static void Registration_OnSatisfiedImportNotificationOverridden(Type type, MemberInfo member) { if ((object)type == null) { throw new ArgumentNullException("type"); } if ((object)member == null) { throw new ArgumentNullException("member"); } if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_OnSatisfiedImportNotificationOverridden, System.SR.Registration_OnSatisfiedImportNotificationOverridden, member.Name, type.FullName); } } public static void Registration_PartCreationConventionOverridden(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartCreationConventionOverridden, System.SR.Registration_PartCreationConventionOverridden, type.FullName); } } public static void Registration_MemberImportConventionMatchedTwice(Type type, MemberInfo member) { if ((object)type == null) { throw new ArgumentNullException("type"); } if ((object)member == null) { throw new ArgumentNullException("member"); } if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionMatchedTwice, System.SR.Registration_MemberImportConventionMatchedTwice, member.Name, type.FullName); } } public static void Registration_PartMetadataConventionOverridden(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartMetadataConventionOverridden, System.SR.Registration_PartMetadataConventionOverridden, type.FullName); } } public static void Registration_ParameterImportConventionOverridden(ParameterInfo parameter, ConstructorInfo constructor) { if (parameter == null) { throw new ArgumentNullException("parameter"); } if ((object)constructor == null) { throw new ArgumentNullException("constructor"); } if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_ParameterImportConventionOverridden, System.SR.Registration_ParameterImportConventionOverridden, parameter.Name, constructor.Name); } } } internal enum CompositionTraceId : ushort { Rejection_DefinitionRejected = 1, Rejection_DefinitionResurrected = 2, Discovery_AssemblyLoadFailed = 3, Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute = 4, Discovery_DefinitionMismatchedExportArity = 5, Discovery_DefinitionContainsNoExports = 6, Discovery_MemberMarkedWithMultipleImportAndImportMany = 7, Registration_ConstructorConventionOverridden = 101, Registration_TypeExportConventionOverridden = 102, Registration_MemberExportConventionOverridden = 103, Registration_MemberImportConventionOverridden = 104, Registration_PartCreationConventionOverridden = 105, Registration_MemberImportConventionMatchedTwice = 106, Registration_PartMetadataConventionOverridden = 107, Registration_ParameterImportConventionOverridden = 108, Registration_OnSatisfiedImportNotificationOverridden = 109 } internal static class CompositionTraceSource { private static readonly DebuggerTraceWriter s_source = new DebuggerTraceWriter(); public static bool CanWriteInformation => s_source.CanWriteInformation; public static bool CanWriteWarning => s_source.CanWriteWarning; public static bool CanWriteError => s_source.CanWriteError; public static void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments) { EnsureEnabled(CanWriteInformation); s_source.WriteInformation(traceId, format, arguments); } public static void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments) { EnsureEnabled(CanWriteWarning); s_source.WriteWarning(traceId, format, arguments); } public static void WriteError(CompositionTraceId traceId, string format, params object[] arguments) { EnsureEnabled(CanWriteError); s_source.WriteError(traceId, format, arguments); } private static void EnsureEnabled(bool condition) { if (!condition) { throw new Exception(System.SR.Format(System.SR.Diagnostic_InternalExceptionMessage, System.SR.Diagnostic_TraceUnnecessaryWork)); } } } internal sealed class DebuggerTraceWriter : TraceWriter { public enum TraceEventType { Error = 2, Warning = 4, Information = 8 } private static readonly string s_sourceName = typeof(DebuggerTraceWriter).Assembly.GetName().Name; public override bool CanWriteInformation => false; public override bool CanWriteWarning => Debugger.IsLogging(); public override bool CanWriteError => Debugger.IsLogging(); public override void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments) { WriteEvent(TraceEventType.Information, traceId, format, arguments); } public override void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments) { WriteEvent(TraceEventType.Warning, traceId, format, arguments); } public override void WriteError(CompositionTraceId traceId, string format, params object[] arguments) { WriteEvent(TraceEventType.Error, traceId, format, arguments); } private static void WriteEvent(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments) { if (Debugger.IsLogging()) { string message = CreateLogMessage(eventType, traceId, format, arguments); Debugger.Log(0, null, message); } } private static string CreateLogMessage(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append($"{s_sourceName} {eventType}: {(int)traceId} : "); if (arguments == null) { stringBuilder.Append(format); } else { stringBuilder.AppendFormat(CultureInfo.InvariantCulture, format, arguments); } stringBuilder.AppendLine(); return stringBuilder.ToString(); } } internal abstract class TraceWriter { public abstract bool CanWriteInformation { get; } public abstract bool CanWriteWarning { get; } public abstract bool CanWriteError { get; } public abstract void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments); public abstract void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments); public abstract void WriteError(CompositionTraceId traceId, string format, params object[] arguments); } } namespace System.Composition.Convention { public class ConventionBuilder : AttributedModelProvider { private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); private readonly List<PartConventionBuilder> _conventions = new List<PartConventionBuilder>(); private readonly Dictionary<MemberInfo, List<Attribute>> _memberInfos = new Dictionary<MemberInfo, List<Attribute>>(); private readonly Dictionary<ParameterInfo, List<Attribute>> _parameters = new Dictionary<ParameterInfo, List<Attribute>>(); public PartConventionBuilder<T> ForTypesDerivedFrom<T>() { PartConventionBuilder<T> partConventionBuilder = new PartConventionBuilder<T>((Type t) => IsDescendentOf(t, typeof(T))); _conventions.Add(partConventionBuilder); return partConventionBuilder; } public PartConventionBuilder ForTypesDerivedFrom(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } PartConventionBuilder partConventionBuilder = new PartConventionBuilder((Type t) => IsDescendentOf(t, type)); _conventions.Add(partConventionBuilder); return partConventionBuilder; } public PartConventionBuilder<T> ForType<T>() { PartConventionBuilder<T> partConventionBuilder = new PartConventionBuilder<T>((Type t) => t == typeof(T)); _conventions.Add(partConventionBuilder); return partConventionBuilder; } public PartConventionBuilder ForType(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } PartConventionBuilder partConventionBuilder = new PartConventionBuilder((Type t) => t == type); _conventions.Add(partConventionBuilder); return partConventionBuilder; } public PartConventionBuilder<T> ForTypesMatching<T>(Predicate<Type> typeFilter) { if (typeFilter == null) { throw new ArgumentNullException("typeFilter"); } PartConventionBuilder<T> partConventionBuilder = new PartConventionBuilder<T>(typeFilter); _conventions.Add(partConventionBuilder); return partConventionBuilder; } public PartConventionBuilder ForTypesMatching(Predicate<Type> typeFilter) { if (typeFilter == null) { throw new ArgumentNullException("typeFilter"); } PartConventionBuilder partConventionBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partConventionBuilder); return partConventionBuilder; } private List<Tuple<object, List<Attribute>>> EvaluateThisTypeInfoAgainstTheConvention(TypeInfo typeInfo) { List<Attribute> list = new List<Attribute>(); List<Tuple<object, List<Attribute>>> configuredMembers = new List<Tuple<object, List<Attribute>>>(); bool flag = false; bool flag2 = false; Type type = typeInfo.AsType(); foreach (PartConventionBuilder item in _conventions.Where((PartConventionBuilder c) => c.SelectType(type))) { list.AddRange(item.BuildTypeAttributes(type)); flag |= item.BuildConstructorAttributes(type, ref configuredMembers); item.BuildPropertyAttributes(type, ref configuredMembers); item.BuildOnImportsSatisfiedNotification(type, ref configuredMembers); flag2 = true; } if (flag2 && !flag) { PartConventionBuilder.BuildDefaultConstructorAttributes(type, ref configuredMembers); } configuredMembers.Add(Tuple.Create((object)type.GetTypeInfo(), list)); return configuredMembers; } public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, MemberInfo member) { if ((object)member == null) { throw new ArgumentNullException("member"); } List<Attribute> value = null; TypeInfo typeInfo = member as TypeInfo; if (typeInfo != null) { MemberInfo key = typeInfo; _lock.EnterReadLock(); try { _memberInfos.TryGetValue(key, out value); } finally { _lock.ExitReadLock(); } if (value == null) { _lock.EnterWriteLock(); try { if (!_memberInfos.TryGetValue(key, out value)) { foreach (Tuple<object, List<Attribute>> item in EvaluateThisTypeInfoAgainstTheConvention(typeInfo)) { if (item.Item2 == null) { continue; } MemberInfo memberInfo = item.Item1 as MemberInfo; if (memberInfo != null) { if (memberInfo != null && (memberInfo is ConstructorInfo || memberInfo is TypeInfo || memberInfo is PropertyInfo || memberInfo is MethodInfo) && !_memberInfos.TryGetValue(memberInfo, out var _)) { _memberInfos.Add(memberInfo, item.Item2); } continue; } if (!(item.Item1 is ParameterInfo key2)) { throw new Exception(System.SR.Diagnostic_InternalExceptionMessage); } if (!_parameters.TryGetValue(key2, out var _)) { _parameters.Add(key2, item.Item2); } } } _memberInfos.TryGetValue(key, out value); } finally { _lock.ExitWriteLock(); } } } else if (member is PropertyInfo || member is ConstructorInfo || member is MethodInfo) { value = ReadMemberCustomAttributes(reflectedType, member); } IEnumerable<Attribute> enumerable = ((member is TypeInfo || !(member.DeclaringType != reflectedType)) ? member.GetCustomAttributes<Attribute>(inherit: false) : Enumerable.Empty<Attribute>()); if (value != null) { return enumerable.Concat(value); } return enumerable; } private List<Attribute> ReadMemberCustomAttributes(Type reflectedType, MemberInfo member) { List<Attribute> value = null; bool flag = false; _lock.EnterReadLock(); try { if (!_memberInfos.TryGetValue(member, out value)) { if (reflectedType != null && !_memberInfos.TryGetValue(member.DeclaringType.GetTypeInfo(), out value)) { flag = true; } value = null; } } finally { _lock.ExitReadLock(); } if (flag) { ((AttributedModelProvider)this).GetCustomAttributes((Type)null, (MemberInfo)reflectedType.GetTypeInfo()); _lock.EnterReadLock(); try { _memberInfos.TryGetValue(member, out value); } finally { _lock.ExitReadLock(); } } return value; } public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, ParameterInfo parameter) { if (parameter == null) { throw new ArgumentNullException("parameter"); } IEnumerable<Attribute> customAttributes = parameter.GetCustomAttributes<Attribute>(inherit: false); List<Attribute> list = ReadParameterCustomAttributes(reflectedType, parameter); if (list != null) { return customAttributes.Concat(list); } return customAttributes; } private List<Attribute> ReadParameterCustomAttributes(Type reflectedType, ParameterInfo parameter) { List<Attribute> value = null; bool flag = false; _lock.EnterReadLock(); try { if (!_parameters.TryGetValue(parameter, out value)) { if (reflectedType != null && !_memberInfos.TryGetValue(reflectedType.GetTypeInfo(), out value)) { flag = true; } value = null; } } finally { _lock.ExitReadLock(); } if (flag) { ((AttributedModelProvider)this).GetCustomAttributes((Type)null, (MemberInfo)reflectedType.GetTypeInfo()); _lock.EnterReadLock(); try { _parameters.TryGetValue(parameter, out value); } finally { _lock.ExitReadLock(); } } return value; } private static bool IsGenericDescendentOf(TypeInfo derivedType, TypeInfo baseType) { if (derivedType.BaseType == null) { return false; } if (derivedType.BaseType == baseType.AsType()) { return true; } foreach (Type implementedInterface in derivedType.ImplementedInterfaces) { if (implementedInterface.IsConstructedGenericType && implementedInterface.GetGenericTypeDefinition() == baseType.AsType()) { return true; } } return IsGenericDescendentOf(derivedType.BaseType.GetTypeInfo(), baseType); } private static bool IsDescendentOf(Type type, Type baseType) { if (type == baseType || type == typeof(object) || type == null) { return false; } TypeInfo typeInfo = type.GetTypeInfo(); TypeInfo typeInfo2 = baseType.GetTypeInfo(); if (typeInfo.IsGenericTypeDefinition || typeInfo2.IsGenericTypeDefinition) { return IsGenericDescendentOf(typeInfo, typeInfo2); } return typeInfo2.IsAssignableFrom(typeInfo); } } public sealed class ExportConventionBuilder { private string _contractName; private Type _contractType; private List<Tuple<string, object>> _metadataItems; private List<Tuple<string, Func<Type, object>>> _metadataItemFuncs; private Func<Type, string> _getContractNameFromPartType; internal ExportConventionBuilder() { } public ExportConventionBuilder AsContractType<T>() { return AsContractType(typeof(T)); } public ExportConventionBuilder AsContractType(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } _contractType = type; return this; } public ExportConventionBuilder AsContractName(string contractName) { if (contractName == null) { throw new ArgumentNullException("contractName"); } if (contractName.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "contractName"), "contractName"); } _contractName = contractName; return this; } public ExportConventionBuilder AsContractName(Func<Type, string> getContractNameFromPartType) { if (getContractNameFromPartType == null) { throw new ArgumentNullException("getContractNameFromPartType"); } _getContractNameFromPartType = getContractNameFromPartType; return this; } public ExportConventionBuilder AddMetadata(string name, object value) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name"); } if (_metadataItems == null) { _metadataItems = new List<Tuple<string, object>>(); } _metadataItems.Add(Tuple.Create(name, value)); return this; } public ExportConventionBuilder AddMetadata(string name, Func<Type, object> getValueFromPartType) { if (name == null) { throw new ArgumentNullException("name"); } if (getValueFromPartType == null) { throw new ArgumentNullException("getValueFromPartType"); } if (name.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name"); } if (_metadataItemFuncs == null) { _metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>(); } _metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType)); return this; } internal void BuildAttributes(Type type, ref List<Attribute> attributes) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown if (attributes == null) { attributes = new List<Attribute>(); } string text = ((_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName); attributes.Add((Attribute)new ExportAttribute(text, _contractType)); if (_metadataItems != null) { foreach (Tuple<string, object> metadataItem in _metadataItems) { attributes.Add((Attribute)new ExportMetadataAttribute(metadataItem.Item1, metadataItem.Item2)); } } if (_metadataItemFuncs == null) { return; } foreach (Tuple<string, Func<Type, object>> metadataItemFunc in _metadataItemFuncs) { string item = metadataItemFunc.Item1; object obj = ((metadataItemFunc.Item2 != null) ? metadataItemFunc.Item2(type) : null); attributes.Add((Attribute)new ExportMetadataAttribute(item, obj)); } } } public sealed class ImportConventionBuilder { private static readonly Type[] s_supportedImportManyTypes = new Type[3] { typeof(IList<>), typeof(ICollection<>), typeof(IEnumerable<>) }; private string _contractName; private bool? _asMany; private bool _allowDefault; private Func<Type, string> _getContractNameFromPartType; private List<Tuple<string, object>> _metadataConstraintItems; private List<Tuple<string, Func<Type, object>>> _metadataConstraintItemFuncs; internal ImportConventionBuilder() { } public ImportConventionBuilder AsContractName(string contractName) { if (contractName == null) { throw new ArgumentNullException("contractName"); } if (contractName.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "contractName"), "contractName"); } _contractName = contractName; return this; } public ImportConventionBuilder AsContractName(Func<Type, string> getContractNameFromPartType) { if (getContractNameFromPartType == null) { throw new ArgumentNullException("getContractNameFromPartType"); } _getContractNameFromPartType = getContractNameFromPartType; return this; } public ImportConventionBuilder AsMany() { return AsMany(isMany: true); } public ImportConventionBuilder AsMany(bool isMany) { _asMany = isMany; return this; } public ImportConventionBuilder AllowDefault() { _allowDefault = true; return this; } public ImportConventionBuilder AddMetadataConstraint(string name, object value) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name"); } if (_metadataConstraintItems == null) { _metadataConstraintItems = new List<Tuple<string, object>>(); } _metadataConstraintItems.Add(Tuple.Create(name, value)); return this; } public ImportConventionBuilder AddMetadataConstraint(string name, Func<Type, object> getConstraintValueFromPartType) { if (name == null) { throw new ArgumentNullException("name"); } if (getConstraintValueFromPartType == null) { throw new ArgumentNullException("getConstraintValueFromPartType"); } if (name.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name"); } if (_metadataConstraintItemFuncs == null) { _metadataConstraintItemFuncs = new List<Tuple<string, Func<Type, object>>>(); } _metadataConstraintItemFuncs.Add(Tuple.Create(name, getConstraintValueFromPartType)); return this; } internal void BuildAttributes(Type type, ref List<Attribute> attributes) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_0044: 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_0056: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown string text = ((_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName); Attribute item = ((_asMany ?? IsSupportedImportManyType(type.GetTypeInfo())) ? ((Attribute)new ImportManyAttribute(text)) : ((Attribute)new ImportAttribute(text) { AllowDefault = _allowDefault })); if (attributes == null) { attributes = new List<Attribute>(); } attributes.Add(item); if (_metadataConstraintItems != null) { foreach (Tuple<string, object> metadataConstraintItem in _metadataConstraintItems) { attributes.Add((Attribute)new ImportMetadataConstraintAttribute(metadataConstraintItem.Item1, metadataConstraintItem.Item2)); } } if (_metadataConstraintItemFuncs == null) { return; } foreach (Tuple<string, Func<Type, object>> metadataConstraintItemFunc in _metadataConstraintItemFuncs) { string item2 = metadataConstraintItemFunc.Item1; object obj = ((metadataConstraintItemFunc.Item2 != null) ? metadataConstraintItemFunc.Item2(type) : null); attributes.Add((Attribute)new ImportMetadataConstraintAttribute(item2, obj)); } } private static bool IsSupportedImportManyType(TypeInfo typeInfo) { if (!typeInfo.IsArray && (!typeInfo.IsGenericTypeDefinition || !s_supportedImportManyTypes.Contains(typeInfo.AsType()))) { if (typeInfo.AsType().IsConstructedGenericType) { return s_supportedImportManyTypes.Contains(typeInfo.GetGenericTypeDefinition()); } return false; } return true; } } public abstract class ParameterImportConventionBuilder { private ParameterImportConventionBuilder() { } public T Import<T>() { return default(T); } public T Import<T>(Action<ImportConventionBuilder> configure) { return default(T); } } public class PartConventionBuilder { private readonly Type[] _emptyTypeArray = Type.EmptyTypes; private static List<Attribute> s_onImportsSatisfiedAttributeList; private static readonly List<Attribute> s_importingConstructorList = new List<Attribute> { (Attribute)new ImportingConstructorAttribute() }; private static readonly Type s_exportAttributeType = typeof(ExportAttribute); private readonly List<ExportConventionBuilder> _typeExportBuilders; private bool _isShared; private string _sharingBoundary; private List<Tuple<string, object>> _metadataItems; private List<Tuple<string, Func<Type, object>>> _metadataItemFuncs; private Func<IEnumerable<ConstructorInfo>, ConstructorInfo> _constructorFilter; private Action<ParameterInfo, ImportConventionBuilder> _configureConstructorImports; private readonly List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type>> _propertyExports; private readonly List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>>> _propertyImports; private readonly List<Tuple<Predicate<Type>, Action<Type, ExportConventionBuilder>>> _interfaceExports; private readonly List<Predicate<MethodInfo>> _methodImportsSatisfiedNotifications; internal Predicate<Type> SelectType { get; } internal PartConventionBuilder(Predicate<Type> selectType) { SelectType = selectType; _typeExportBuilders = new List<ExportConventionBuilder>(); _propertyExports = new List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type>>(); _propertyImports = new List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>>>(); _interfaceExports = new List<Tuple<Predicate<Type>, Action<Type, ExportConventionBuilder>>>(); _methodImportsSatisfiedNotifications = new List<Predicate<MethodInfo>>(); } public PartConventionBuilder Export() { ExportConventionBuilder item = new ExportConventionBuilder(); _typeExportBuilders.Add(item); return this; } public PartConventionBuilder Export(Action<ExportConventionBuilder> exportConfiguration) { if (exportConfiguration == null) { throw new ArgumentNullException("exportConfiguration"); } ExportConventionBuilder exportConventionBuilder = new ExportConventionBuilder(); exportConfiguration(exportConventionBuilder); _typeExportBuilders.Add(exportConventionBuilder); return this; } public PartConventionBuilder Export<T>() { ExportConventionBuilder item = new ExportConventionBuilder().AsContractType<T>(); _typeExportBuilders.Add(item); return this; } public PartConventionBuilder Export<T>(Action<ExportConventionBuilder> exportConfiguration) { if (exportConfiguration == null) { throw new ArgumentNullException("exportConfiguration"); } ExportConventionBuilder exportConventionBuilder = new ExportConventionBuilder().AsContractType<T>(); exportConfiguration(exportConventionBuilder); _typeExportBuilders.Add(exportConventionBuilder); return this; } public PartConventionBuilder SelectConstructor(Func<IEnumerable<ConstructorInfo>, ConstructorInfo> constructorSelector) { if (constructorSelector == null) { throw new ArgumentNullException("constructorSelector"); } _constructorFilter = constructorSelector; return this; } public PartConventionBuilder SelectConstructor(Func<IEnumerable<ConstructorInfo>, ConstructorInfo> constructorSelector, Action<ParameterInfo, ImportConventionBuilder> importConfiguration) { if (importConfiguration == null) { throw new ArgumentNullException("importConfiguration"); } _configureConstructorImports = importConfiguration; SelectConstructor(constructorSelector); return this; } public PartConventionBuilder ExportInterfaces(Predicate<Type> interfaceFilter) { if (interfaceFilter == null) { throw new ArgumentNullException("interfaceFilter"); } return ExportInterfacesImpl(interfaceFilter, null); } public PartConventionBuilder ExportInterfaces() { return ExportInterfaces((Type t) => true); } public PartConventionBuilder ExportInterfaces(Predicate<Type> interfaceFilter, Action<Type, ExportConventionBuilder> exportConfiguration) { if (interfaceFilter == null) { throw new ArgumentNullException("interfaceFilter"); } if (exportConfiguration == null) { throw new ArgumentNullException("exportConfiguration"); } return ExportInterfacesImpl(interfaceFilter, exportConfiguration); } private PartConventionBuilder ExportInterfacesImpl(Predicate<Type> interfaceFilter, Action<Type, ExportConventionBuilder> exportConfiguration) { _interfaceExports.Add(Tuple.Create(interfaceFilter, exportConfiguration)); return this; } public PartConventionBuilder ExportProperties(Predicate<PropertyInfo> propertyFilter) { if (propertyFilter == null) { throw new ArgumentNullException("propertyFilter"); } return ExportPropertiesImpl(propertyFilter, null); } public PartConventionBuilder ExportProperties(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ExportConventionBuilder> exportConfiguration) { if (propertyFilter == null) { throw new ArgumentNullException("propertyFilter"); } if (exportConfiguration == null) { throw new ArgumentNullException("exportConfiguration"); } return ExportPropertiesImpl(propertyFilter, exportConfiguration); } private PartConventionBuilder ExportPropertiesImpl(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ExportConventionBuilder> exportConfiguration) { _propertyExports.Add(Tuple.Create<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type>(propertyFilter, exportConfiguration, null)); return this; } public PartConventionBuilder ExportProperties<T>(Predicate<PropertyInfo> propertyFilter) { if (propertyFilter == null) { throw new ArgumentNullException("propertyFilter"); } return ExportPropertiesImpl<T>(propertyFilter, null); } public PartConventionBuilder ExportProperties<T>(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ExportConventionBuilder> exportConfiguration) { if (propertyFilter == null) { throw new ArgumentNullException("propertyFilter"); } if (exportConfiguration == null) { throw new ArgumentNullException("exportConfiguration"); } return ExportPropertiesImpl<T>(propertyFilter, exportConfiguration); } private PartConventionBuilder ExportPropertiesImpl<T>(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ExportConventionBuilder> exportConfiguration) { _propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, typeof(T))); return this; } public PartConventionBuilder ImportProperties(Predicate<PropertyInfo> propertyFilter) { if (propertyFilter == null) { throw new ArgumentNullException("propertyFilter"); } return ImportPropertiesImpl(propertyFilter, null); } public PartConventionBuilder ImportProperties(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ImportConventionBuilder> importConfiguration) { if (propertyFilter == null) { throw new ArgumentNullException("propertyFilter"); } if (importConfiguration == null) { throw new ArgumentNullException("importConfiguration"); } return ImportPropertiesImpl(propertyFilter, importConfiguration); } private PartConventionBuilder ImportPropertiesImpl(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ImportConventionBuilder> importConfiguration) { _propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration)); return this; } public PartConventionBuilder ImportProperties<T>(Predicate<PropertyInfo> propertyFilter) { if (propertyFilter == null) { throw new ArgumentNullException("propertyFilter"); } return ImportPropertiesImpl<T>(propertyFilter, null); } public PartConventionBuilder ImportProperties<T>(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ImportConventionBuilder> importConfiguration) { if (propertyFilter == null) { throw new ArgumentNullException("propertyFilter"); } if (importConfiguration == null) { throw new ArgumentNullException("importConfiguration"); } return ImportPropertiesImpl<T>(propertyFilter, importConfiguration); } private PartConventionBuilder ImportPropertiesImpl<T>(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ImportConventionBuilder> importConfiguration) { Predicate<PropertyInfo> item = (PropertyInfo pi) => pi.PropertyType.Equals(typeof(T)) && (propertyFilter == null || propertyFilter(pi)); _propertyImports.Add(Tuple.Create(item, importConfiguration)); return this; } public PartConventionBuilder NotifyImportsSatisfied(Predicate<MethodInfo> methodFilter) { _methodImportsSatisfiedNotifications.Add(methodFilter); return this; } public PartConventionBuilder Shared() { return SharedImpl(null); } public PartConventionBuilder Shared(string sharingBoundary) { if (sharingBoundary == null) { throw new ArgumentNullException("sharingBoundary"); } if (sharingBoundary.Length == 0) { throw new ArgumentException(System.SR.ArgumentException_EmptyString); } return SharedImpl(sharingBoundary); } private PartConventionBuilder SharedImpl(string sharingBoundary) { _isShared = true; _sharingBoundary = sharingBoundary; return this; } public PartConventionBuilder AddPartMetadata(string name, object value) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name"); } if (_metadataItems == null) { _metadataItems = new List<Tuple<string, object>>(); } _metadataItems.Add(Tuple.Create(name, value)); return this; } public PartConventionBuilder AddPartMetadata(string name, Func<Type, object> getValueFromPartType) { if (name == null) { throw new ArgumentNullException("name"); } if (getValueFromPartType == null) { throw new ArgumentNullException("getValueFromPartType"); } if (name.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name"); } if (_metadataItemFuncs == null) { _metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>(); } _metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType)); return this; } private static bool MemberHasExportMetadata(MemberInfo member) { foreach (Attribute customAttribute in member.GetCustomAttributes<Attribute>(inherit: false)) { if (customAttribute is ExportMetadataAttribute) { return true; } Type type = customAttribute.GetType(); if (type != s_exportAttributeType && type.GetTypeInfo().IsDefined(typeof(MetadataAttributeAttribute), inherit: true)) { return true; } } return false; } internal IEnumerable<Attribute> BuildTypeAttributes(Type type) { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Expected O, but got Unknown //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown List<Attribute> attributes = new List<Attribute>(); if (_typeExportBuilders != null) { if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<ExportAttribute>(inherit: false).FirstOrDefault() != null || MemberHasExportMetadata(type.GetTypeInfo())) { CompositionTrace.Registration_TypeExportConventionOverridden(type); } else { foreach (ExportConventionBuilder typeExportBuilder in _typeExportBuilders) { typeExportBuilder.BuildAttributes(type, ref attributes); } } } if (_isShared) { if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<SharedAttribute>(inherit: false).FirstOrDefault() != null) { CompositionTrace.Registration_PartCreationConventionOverridden(type); } else { attributes.Add((Attribute)((_sharingBoundary == null) ? new SharedAttribute() : new SharedAttribute(_sharingBoundary))); } } if (_metadataItems != null) { if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<PartMetadataAttribute>(inherit: false).FirstOrDefault() != null) { CompositionTrace.Registration_PartMetadataConventionOverridden(type); } else { foreach (Tuple<string, object> metadataItem in _metadataItems) { attributes.Add((Attribute)new PartMetadataAttribute(metadataItem.Item1, metadataItem.Item2)); } } } if (_metadataItemFuncs != null) { if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<PartMetadataAttribute>(inherit: false).FirstOrDefault() != null) { CompositionTrace.Registration_PartMetadataConventionOverridden(type); } else { foreach (Tuple<string, Func<Type, object>> metadataItemFunc in _metadataItemFuncs) { string item = metadataItemFunc.Item1; object obj = ((metadataItemFunc.Item2 != null) ? metadataItemFunc.Item2(type) : null); attributes.Add((Attribute)new PartMetadataAttribute(item, obj)); } } } if (_interfaceExports.Count != 0 && _typeExportBuilders != null) { if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<ExportAttribute>(inherit: false).FirstOrDefault() != null || MemberHasExportMetadata(type.GetTypeInfo())) { CompositionTrace.Registration_TypeExportConventionOverridden(type); } else { foreach (Type implementedInterface in type.GetTypeInfo().ImplementedInterfaces) { if (implementedInterface == typeof(IDisposable)) { continue; } foreach (Tuple<Predicate<Type>, Action<Type, ExportConventionBuilder>> interfaceExport in _interfaceExports) { if (interfaceExport.Item1 != null && interfaceExport.Item1(implementedInterface)) { ExportConventionBuilder exportConventionBuilder = new ExportConventionBuilder(); exportConventionBuilder.AsContractType(implementedInterface); interfaceExport.Item2?.Invoke(implementedInterface, exportConventionBuilder); exportConventionBuilder.BuildAttributes(implementedInterface, ref attributes); } } } } } return attributes; } internal bool BuildConstructorAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers) { ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); ConstructorInfo[] array = constructors; for (int i = 0; i < array.Length; i++) { if (Attribute.GetCustomAttributes(array[i], typeof(ImportingConstructorAttribute), inherit: false).Length != 0) { CompositionTrace.Registration_ConstructorConventionOverridden(type); return true; } } if (_constructorFilter != null) { ConstructorInfo constructorInfo = _constructorFilter(constructors); if (constructorInfo != null) { ConfigureConstructorAttributes(constructorInfo, ref configuredMembers, _configureConstructorImports); } return true; } if (_configureConstructorImports != null) { bool result = false; { foreach (ConstructorInfo item in FindLongestConstructors(constructors)) { ConfigureConstructorAttributes(item, ref configuredMembers, _configureConstructorImports); result = true; } return result; } } return false; } internal static void BuildDefaultConstructorAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers) { foreach (ConstructorInfo item in FindLongestConstructors(type.GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))) { ConfigureConstructorAttributes(item, ref configuredMembers, null); } } private static void ConfigureConstructorAttributes(ConstructorInfo constructorInfo, ref List<Tuple<object, List<Attribute>>> configuredMembers, Action<ParameterInfo, ImportConventionBuilder> configureConstructorImports) { if (configuredMembers == null) { configuredMembers = new List<Tuple<object, List<Attribute>>>(); } configuredMembers.Add(Tuple.Create((object)constructorInfo, s_importingConstructorList)); ParameterInfo[] parameters = constructorInfo.GetParameters(); foreach (ParameterInfo parameterInfo in parameters) { if (parameterInfo.GetCustomAttributes<ImportAttribute>(inherit: false).FirstOrDefault() != null || parameterInfo.GetCustomAttributes<ImportManyAttribute>(inherit: false).FirstOrDefault() != null) { CompositionTrace.Registration_ParameterImportConventionOverridden(parameterInfo, constructorInfo); continue; } ImportConventionBuilder importConventionBuilder = new ImportConventionBuilder(); configureConstructorImports?.Invoke(parameterInfo, importConventionBuilder); List<Attribute> attributes = null; importConventionBuilder.BuildAttributes(parameterInfo.ParameterType, ref attributes); configuredMembers.Add(Tuple.Create((object)parameterInfo, attributes)); } } internal void BuildOnImportsSatisfiedNotification(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers) { //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown if (_methodImportsSatisfiedNotifications == null) { return; } foreach (MethodInfo runtimeMethod2 in type.GetRuntimeMethods()) { if (!(runtimeMethod2.ReturnParameter.ParameterType == typeof(void)) || runtimeMethod2.GetParameters().Length != 0) { continue; } MethodInfo runtimeMethod = runtimeMethod2.DeclaringType.GetRuntimeMethod(runtimeMethod2.Name, _emptyTypeArray); if (!(runtimeMethod != null)) { continue; } bool flag = false; bool flag2 = false; foreach (Predicate<MethodInfo> methodImportsSatisfiedNotification in _methodImportsSatisfiedNotifications) { if (methodImportsSatisfiedNotification(runtimeMethod)) { if (!flag) { flag2 = ((MemberInfo)runtimeMethod2).GetCustomAttributes<OnImportsSatisfiedAttribute>(inherit: false).FirstOrDefault() != null; flag = true; } if (flag2) { CompositionTrace.Registration_OnSatisfiedImportNotificationOverridden(type, runtimeMethod2); break; } if (s_onImportsSatisfiedAttributeList == null) { s_onImportsSatisfiedAttributeList = new List<Attribute> { (Attribute)new OnImportsSatisfiedAttribute() }; } configuredMembers.Add(new Tuple<object, List<Attribute>>(runtimeMethod2, s_onImportsSatisfiedAttributeList)); } } } } internal void BuildPropertyAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers) { if (_propertyImports.Count == 0 && _propertyExports.Count == 0) { return; } foreach (PropertyInfo runtimeProperty in type.GetRuntimeProperties()) { List<Attribute> attributes = null; int num = 0; bool flag = false; bool flag2 = false; PropertyInfo propertyInfo = null; foreach (Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>> propertyImport in _propertyImports) { if ((object)propertyInfo == null) { propertyInfo = runtimeProperty.DeclaringType.GetRuntimeProperty(runtimeProperty.Name); } if (propertyImport.Item1 != null && propertyImport.Item1(propertyInfo)) { ImportConventionBuilder importConventionBuilder = new ImportConventionBuilder(); propertyImport.Item2?.Invoke(runtimeProperty, importConventionBuilder); if (!flag) { flag2 = ((MemberInfo)runtimeProperty).GetCustomAttributes<ImportAttribute>(inherit: false).FirstOrDefault() != null || ((MemberInfo)runtimeProperty).GetCustomAttributes<ImportManyAttribute>(inherit: false).FirstOrDefault() != null; flag = true; } if (flag2) { CompositionTrace.Registration_MemberImportConventionOverridden(type, runtimeProperty); break; } importConventionBuilder.BuildAttributes(runtimeProperty.PropertyType, ref attributes); num++; } if (num > 1) { CompositionTrace.Registration_MemberImportConventionMatchedTwice(type, runtimeProperty); } } flag = false; flag2 = false; foreach (Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type> propertyExport in _propertyExports) { if ((object)propertyInfo == null) { propertyInfo = runtimeProperty.DeclaringType.GetRuntimeProperty(runtimeProperty.Name); } if (propertyExport.Item1 != null && propertyExport.Item1(propertyInfo)) { ExportConventionBuilder exportConventionBuilder = new ExportConventionBuilder(); if (propertyExport.Item3 != null) { exportConventionBuilder.AsContractType(propertyExport.Item3); } propertyExport.Item2?.Invoke(runtimeProperty, exportConventionBuilder); if (!flag) { flag2 = ((MemberInfo)runtimeProperty).GetCustomAttributes<ExportAttribute>(inherit: false).FirstOrDefault() != null || MemberHasExportMetadata(runtimeProperty); flag = true; } if (flag2) { CompositionTrace.Registration_MemberExportConventionOverridden(type, runtimeProperty); break; } exportConventionBuilder.BuildAttributes(runtimeProperty.PropertyType, ref attributes); } } if (attributes != null) { if (configuredMembers == null) { configuredMembers = new List<Tuple<object, List<Attribute>>>(); } configuredMembers.Add(Tuple.Create((object)runtimeProperty, attributes)); } } } private static IEnumerable<ConstructorInfo> FindLongestConstructors(ConstructorInfo[] constructors) { ConstructorInfo constructorInfo = null; int argumentsCount = 0; int num = 0; foreach (ConstructorInfo constructorInfo2 in constructors) { int num2 = constructorInfo2.GetParameters().Length; if (num2 != 0) { if (num2 > argumentsCount) { constructorInfo = constructorInfo2; argumentsCount = num2; num = 1; } else if (num2 == argumentsCount) { num++; } } } if (num > 1) { foreach (ConstructorInfo constructorInfo3 in constructors) { if (constructorInfo3.GetParameters().Length == argumentsCount) { yield return constructorInfo3; } } } else if (num == 1) { yield return constructorInfo; } } } public class PartConventionBuilder<T> : PartConventionBuilder { private sealed class MethodExpressionAdapter { private readonly MethodInfo _methodInfo; public MethodExpressionAdapter(Expression<Action<T>> methodSelector) { _methodInfo = SelectMethods(methodSelector); } public bool VerifyMethodInfo(MethodInfo mi) { return mi == _methodInfo; } private static MethodInfo SelectMethods(Expression<Action<T>> methodSelector) { if (methodSelector == null) { throw new ArgumentNullException("methodSelector"); } Expression body = Reduce(methodSelector).Body; if (body.NodeType == ExpressionType.Call) { MethodInfo method = ((MethodCallExpression)body).Method; if (method != null) { return method; } } throw new ArgumentException(System.SR.Format(System.SR.Argument_ExpressionMustBeVoidMethodWithNoArguments, "methodSelector"), "methodSelector"); } private static Expression<Func<T, object>> Reduce(Expression<Func<T, object>> expr) { while (expr.CanReduce) { expr = (Expression<Func<T, object>>)expr.Reduce(); } return expr; } private static Expression<Action<T>> Reduce(Expression<Action<T>> expr) { while (expr.CanReduce) { expr = (Expression<Action<T>>)expr.Reduce(); } return expr; } } private sealed class PropertyExpressionAdapter { private readonly PropertyInfo _propertyInfo; private readonly Action<ImportConventionBuilder> _configureImport; private readonly Action<ExportConventionBuilder> _configureExport; public PropertyExpressionAdapter(Expression<Func<T, object>> propertySelector, Action<ImportConventionBuilder> configureImport = null, Action<ExportConventionBuilder> configureExport = null) { _propertyInfo = SelectProperties(propertySelector); _configureImport = configureImport; _configureExport = configureExport; } public bool VerifyPropertyInfo(PropertyInfo pi) { return pi == _propertyInfo; } public void ConfigureImport(PropertyInfo _, ImportConventionBuilder importBuilder) { _configureImport?.Invoke(importBuilder); } public void ConfigureExport(PropertyInfo _, ExportConventionBuilder exportBuilder) { _configureExport?.Invoke(exportBuilder); } private static PropertyInfo SelectProperties(Expression<Func<T, object>> propertySelector) { if (propertySelector == null) { throw new ArgumentNullException("propertySelector"); } Expression body = Reduce(propertySelector).Body; if (body.NodeType == ExpressionType.MemberAccess) { PropertyInfo propertyInfo = ((MemberExpression)body).Member as PropertyInfo; if (propertyInfo != null) { return propertyInfo; } } throw new ArgumentException(System.SR.Format(System.SR.Argument_ExpressionMustBePropertyMember, "propertySelector"), "propertySelector"); } private static Expression<Func<T, object>> Reduce(Expression<Func<T, object>> expr) { while (expr.CanReduce) { expr = (Expression<Func<T, object>>)expr.Reduce(); } return expr; } } private sealed class ConstructorExpressionAdapter { private ConstructorInfo _constructorInfo; private Dictionary<ParameterInfo, Action<ImportConventionBuilder>> _importBuilders; public ConstructorExpressionAdapter(Expression<Func<ParameterImportConventionBuilder, T>> selectConstructor) { ParseSelectConstructor(selectConstructor); } public ConstructorInfo SelectConstructor(IEnumerable<ConstructorInfo> _) { return _constructorInfo; } public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportConventionBuilder importBuilder) { if (_importBuilders != null && _importBuilders.TryGetValue(parameterInfo, out var value)) { value(importBuilder); } } private void ParseSelectConstructor(Expression<Func<ParameterImportConventionBuilder, T>> constructorSelector) { if (constructorSelector == null) { throw new ArgumentNullException("constructorSelector"); } Expression body = Reduce(constructorSelector).Body; if (body.NodeType != ExpressionType.New) { throw new ArgumentException(System.SR.Format(System.SR.Argument_ExpressionMustBeNew, "constructorSelector"), "constructorSelector"); } NewExpression newExpression = (NewExpression)body; _constructorInfo = newExpression.Constructor; int num = 0; ParameterInfo[] parameters = _constructorInfo.GetParameters(); foreach (Expression argument in newExpression.Arguments) { if (argument.NodeType != ExpressionType.Call) { continue; } MethodCallExpression methodCallExpression = (MethodCallExpression)argument; if (methodCallExpression.Arguments.Count != 1) { continue; } Expression expression = methodCallExpression.Arguments[0]; if (expression.NodeType == ExpressionType.Lambda) { Delegate @delegate = ((LambdaExpression)expression).Compile(); if (_importBuilders == null) { _importBuilders = new Dictionary<ParameterInfo, Action<ImportConventionBuilder>>(); } _importBuilders.Add(parameters[num], (Action<ImportConventionBuilder>)@delegate); num++; } } } private static Expression<Func<ParameterImportConventionBuilder, T>> Reduce(Expression<Func<ParameterImportConventionBuilder, T>> expr) { while (expr.CanReduce) { expr.Reduce(); } return expr; } } internal PartConventionBuilder(Predicate<Type> selectType) : base(selectType) { } public PartConventionBuilder<T> SelectConstructor(Expression<Func<ParameterImportConventionBuilder, T>> constructorSelector) { if (constructorSelector == null) { throw new ArgumentNullException("constructorSelector"); } ConstructorExpressionAdapter @object = new ConstructorExpressionAdapter(constructorSelector); SelectConstructor(@object.SelectConstructor, @object.ConfigureConstructorImports); return this; } public PartConventionBuilder<T> ExportProperty(Expression<Func<T, object>> propertySelector) { return ExportProperty(propertySelector, null); } public PartConventionBuilder<T> ExportProperty(Expression<Func<T, object>> propertySelector, Action<ExportConventionBuilder> exportConfiguration) { if (propertySelector == null) { throw new ArgumentNullException("propertySelector"); } PropertyExpressionAdapter @object = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration); ExportProperties(@object.VerifyPropertyInfo, @object.ConfigureExport); return this; } public PartConventionBuilder<T> ExportProperty<TContract>(Expression<Func<T, object>> propertySelector) { return ExportProperty<TContract>(propertySelector, null); } public PartConventionBuilder<T> ExportProperty<TContract>(Expression<Func<T, object>> propertySelector, Action<ExportConventionBuilder> exportConfiguration) { if (propertySelector == null) { throw new ArgumentNullException("propertySelector"); } PropertyExpressionAdapter @object = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration); ExportProperties<TContract>(@object.VerifyPropertyInfo, @object.ConfigureExport); return this; } public PartConventionBuilder<T> ImportProperty(Expression<Func<T, object>> propertySelector) { return ImportProperty(propertySelector, null); } public PartConventionBuilder<T> ImportProperty(Expression<Func<T, object>> propertySelector, Action<ImportConventionBuilder> importConfiguration) { if (propertySelector == null) { throw new ArgumentNullException("propertySelector"); } PropertyExpressionAdapter @object = new PropertyExpressionAdapter(propertySelector, importConfiguration); ImportProperties(@object.VerifyPropertyInfo, @object.ConfigureImport); return this; } public PartConventionBuilder<T> ImportProperty<TContract>(Expression<Func<T, object>> propertySelector) { return ImportProperty<TContract>(propertySelector, null); } public PartConventionBuilder<T> ImportProperty<TContract>(Expression<Func<T, object>> propertySelector, Action<ImportConventionBuilder> importConfiguration) { if (propertySelector == null) { throw new ArgumentNullException("propertySelector"); } PropertyExpressionAdapter @object = new PropertyExpressionAdapter(propertySelector, importConfiguration); ImportProperties<TContract>(@object.VerifyPropertyInfo, @object.ConfigureImport); return this; } public PartConventionBuilder<T> NotifyImportsSatisfied(Expression<Action<T>> methodSelector) { if (methodSelector == null) { throw new ArgumentNullException("methodSelector"); } MethodExpressionAdapter @object = new MethodExpressionAdapter(methodSelector); NotifyImportsSatisfied(@object.VerifyMethodInfo); return this; } } }
deps/System.Diagnostics.DiagnosticSource.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Globalization; using System.Net; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using FxResources.System.Diagnostics.DiagnosticSource; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Diagnostics.DiagnosticSource")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides Classes that allow you to decouple code logging rich (unserializable) diagnostics/telemetry (e.g. framework) from code that consumes it (e.g. tools)\r\n\r\nCommonly Used Types:\r\nSystem.Diagnostics.DiagnosticListener\r\nSystem.Diagnostics.DiagnosticSource")] [assembly: AssemblyFileVersion("8.0.424.16909")] [assembly: AssemblyInformationalVersion("8.0.4+2d7eea252964e69be94cb9c847b371b23e4dd470")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Diagnostics.DiagnosticSource")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] 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] internal sealed class IsByRefLikeAttribute : 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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 FxResources.System.Diagnostics.DiagnosticSource { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { byte value = readOnlySpan[i]; ToCharsBuffer(value, buffer, num, casing); num += 2; } return buffer.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { if (IntPtr.Size == 8) { ulong num = (uint)(c - 48); ulong num2 = (ulong)(-17875860044349952L << (int)num); ulong num3 = num - 64; return (long)(num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ActivityIdFormatInvalid => GetResourceString("ActivityIdFormatInvalid"); internal static string ActivityNotRunning => GetResourceString("ActivityNotRunning"); internal static string ActivityNotStarted => GetResourceString("ActivityNotStarted"); internal static string ActivityStartAlreadyStarted => GetResourceString("ActivityStartAlreadyStarted"); internal static string ActivitySetParentAlreadyStarted => GetResourceString("ActivitySetParentAlreadyStarted"); internal static string EndTimeNotUtc => GetResourceString("EndTimeNotUtc"); internal static string OperationNameInvalid => GetResourceString("OperationNameInvalid"); internal static string ParentIdAlreadySet => GetResourceString("ParentIdAlreadySet"); internal static string ParentIdInvalid => GetResourceString("ParentIdInvalid"); internal static string SetFormatOnStartedActivity => GetResourceString("SetFormatOnStartedActivity"); internal static string SetParentIdOnActivityWithParent => GetResourceString("SetParentIdOnActivityWithParent"); internal static string StartTimeNotUtc => GetResourceString("StartTimeNotUtc"); internal static string KeyAlreadyExist => GetResourceString("KeyAlreadyExist"); internal static string InvalidTraceParent => GetResourceString("InvalidTraceParent"); internal static string UnableAccessServicePointTable => GetResourceString("UnableAccessServicePointTable"); internal static string UnableToInitialize => GetResourceString("UnableToInitialize"); internal static string UnsupportedType => GetResourceString("UnsupportedType"); internal static string Arg_BufferTooSmall => GetResourceString("Arg_BufferTooSmall"); internal static string InvalidInstrumentType => GetResourceString("InvalidInstrumentType"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Runtime.Versioning { internal abstract class OSPlatformAttribute : Attribute { public string PlatformName { get; } private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } public UnsupportedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public string Url { get; set; } public ObsoletedOSPlatformAttribute(string platformName) : base(platformName) { } public ObsoletedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute { public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute { public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } } namespace System.Diagnostics { public readonly struct ActivityChangedEventArgs { public Activity? Previous { get; init; } public Activity? Current { get; init; } internal ActivityChangedEventArgs(Activity previous, Activity current) { Previous = previous; Current = current; } } public class Activity : IDisposable { public struct Enumerator<T> { private static readonly DiagNode<T> s_Empty = new DiagNode<T>(default(T)); private DiagNode<T> _nextNode; private DiagNode<T> _currentNode; public readonly ref T Current => ref _currentNode.Value; internal Enumerator(DiagNode<T> head) { _nextNode = head; _currentNode = s_Empty; } [EditorBrowsable(EditorBrowsableState.Never)] public readonly Enumerator<T> GetEnumerator() { return this; } public bool MoveNext() { if (_nextNode == null) { _currentNode = s_Empty; return false; } _currentNode = _nextNode; _nextNode = _nextNode.Next; return true; } } private sealed class BaggageLinkedList : IEnumerable<KeyValuePair<string, string>>, IEnumerable { private DiagNode<KeyValuePair<string, string>> _first; public DiagNode<KeyValuePair<string, string>> First => _first; public BaggageLinkedList(KeyValuePair<string, string> firstValue, bool set = false) { _first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, string>>(firstValue)); } public void Add(KeyValuePair<string, string> value) { DiagNode<KeyValuePair<string, string>> diagNode = new DiagNode<KeyValuePair<string, string>>(value); lock (this) { diagNode.Next = _first; _first = diagNode; } } public void Set(KeyValuePair<string, string> value) { if (value.Value == null) { Remove(value.Key); return; } lock (this) { for (DiagNode<KeyValuePair<string, string>> diagNode = _first; diagNode != null; diagNode = diagNode.Next) { if (diagNode.Value.Key == value.Key) { diagNode.Value = value; return; } } DiagNode<KeyValuePair<string, string>> diagNode2 = new DiagNode<KeyValuePair<string, string>>(value); diagNode2.Next = _first; _first = diagNode2; } } public void Remove(string key) { lock (this) { if (_first == null) { return; } if (_first.Value.Key == key) { _first = _first.Next; return; } DiagNode<KeyValuePair<string, string>> diagNode = _first; while (diagNode.Next != null) { if (diagNode.Next.Value.Key == key) { diagNode.Next = diagNode.Next.Next; break; } diagNode = diagNode.Next; } } } public DiagEnumerator<KeyValuePair<string, string>> GetEnumerator() { return new DiagEnumerator<KeyValuePair<string, string>>(_first); } IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal sealed class TagsLinkedList : IEnumerable<KeyValuePair<string, object>>, IEnumerable { private DiagNode<KeyValuePair<string, object>> _first; private DiagNode<KeyValuePair<string, object>> _last; private StringBuilder _stringBuilder; public DiagNode<KeyValuePair<string, object>> First => _first; public TagsLinkedList(KeyValuePair<string, object> firstValue, bool set = false) { _last = (_first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, object>>(firstValue))); } public TagsLinkedList(IEnumerator<KeyValuePair<string, object>> e) { _last = (_first = new DiagNode<KeyValuePair<string, object>>(e.Current)); while (e.MoveNext()) { _last.Next = new DiagNode<KeyValuePair<string, object>>(e.Current); _last = _last.Next; } } public TagsLinkedList(IEnumerable<KeyValuePair<string, object>> list) { Add(list); } public void Add(IEnumerable<KeyValuePair<string, object>> list) { IEnumerator<KeyValuePair<string, object>> enumerator = list.GetEnumerator(); if (enumerator.MoveNext()) { if (_first == null) { _last = (_first = new DiagNode<KeyValuePair<string, object>>(enumerator.Current)); } else { _last.Next = new DiagNode<KeyValuePair<string, object>>(enumerator.Current); _last = _last.Next; } while (enumerator.MoveNext()) { _last.Next = new DiagNode<KeyValuePair<string, object>>(enumerator.Current); _last = _last.Next; } } } public void Add(KeyValuePair<string, object> value) { DiagNode<KeyValuePair<string, object>> diagNode = new DiagNode<KeyValuePair<string, object>>(value); lock (this) { if (_first == null) { _first = (_last = diagNode); return; } _last.Next = diagNode; _last = diagNode; } } public object Get(string key) { for (DiagNode<KeyValuePair<string, object>> diagNode = _first; diagNode != null; diagNode = diagNode.Next) { if (diagNode.Value.Key == key) { return diagNode.Value.Value; } } return null; } public void Remove(string key) { lock (this) { if (_first == null) { return; } if (_first.Value.Key == key) { _first = _first.Next; if (_first == null) { _last = null; } return; } DiagNode<KeyValuePair<string, object>> diagNode = _first; while (diagNode.Next != null) { if (diagNode.Next.Value.Key == key) { if (_last == diagNode.Next) { _last = diagNode; } diagNode.Next = diagNode.Next.Next; break; } diagNode = diagNode.Next; } } } public void Set(KeyValuePair<string, object> value) { if (value.Value == null) { Remove(value.Key); return; } lock (this) { for (DiagNode<KeyValuePair<string, object>> diagNode = _first; diagNode != null; diagNode = diagNode.Next) { if (diagNode.Value.Key == value.Key) { diagNode.Value = value; return; } } DiagNode<KeyValuePair<string, object>> diagNode2 = new DiagNode<KeyValuePair<string, object>>(value); if (_first == null) { _first = (_last = diagNode2); return; } _last.Next = diagNode2; _last = diagNode2; } } public DiagEnumerator<KeyValuePair<string, object>> GetEnumerator() { return new DiagEnumerator<KeyValuePair<string, object>>(_first); } IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerable<KeyValuePair<string, string>> EnumerateStringValues() { for (DiagNode<KeyValuePair<string, object>> current = _first; current != null; current = current.Next) { if (current.Value.Value is string || current.Value.Value == null) { yield return new KeyValuePair<string, string>(current.Value.Key, (string)current.Value.Value); } } } public override string ToString() { lock (this) { if (_first == null) { return string.Empty; } if (_stringBuilder == null) { _stringBuilder = new StringBuilder(); } _stringBuilder.Append(_first.Value.Key); _stringBuilder.Append(':'); _stringBuilder.Append(_first.Value.Value); for (DiagNode<KeyValuePair<string, object>> next = _first.Next; next != null; next = next.Next) { _stringBuilder.Append(", "); _stringBuilder.Append(next.Value.Key); _stringBuilder.Append(':'); _stringBuilder.Append(next.Value.Value); } string result = _stringBuilder.ToString(); _stringBuilder.Clear(); return result; } } } [Flags] private enum State : byte { None = 0, FormatUnknown = 0, FormatHierarchical = 1, FormatW3C = 2, FormatFlags = 3, IsStopped = 0x80 } private static readonly IEnumerable<KeyValuePair<string, string>> s_emptyBaggageTags = new KeyValuePair<string, string>[0]; private static readonly IEnumerable<KeyValuePair<string, object>> s_emptyTagObjects = new KeyValuePair<string, object>[0]; private static readonly IEnumerable<ActivityLink> s_emptyLinks = new ActivityLink[0]; private static readonly IEnumerable<ActivityEvent> s_emptyEvents = new ActivityEvent[0]; private static readonly ActivitySource s_defaultSource = new ActivitySource(string.Empty); private const byte ActivityTraceFlagsIsSet = 128; private const int RequestIdMaxLength = 1024; private static readonly string s_uniqSuffix = $"-{GetRandomNumber():x}."; private static long s_currentRootId = (uint)GetRandomNumber(); private static ActivityIdFormat s_defaultIdFormat; private string _traceState; private State _state; private int _currentChildId; private string _id; private string _rootId; private string _parentId; private string _parentSpanId; private string _traceId; private string _spanId; private byte _w3CIdFlags; private byte _parentTraceFlags; private TagsLinkedList _tags; private BaggageLinkedList _baggage; private DiagLinkedList<ActivityLink> _links; private DiagLinkedList<ActivityEvent> _events; private Dictionary<string, object> _customProperties; private string _displayName; private ActivityStatusCode _statusCode; private string _statusDescription; private Activity _previousActiveActivity; private static readonly AsyncLocal<Activity> s_current = new AsyncLocal<Activity>(); public static bool ForceDefaultIdFormat { get; set; } public ActivityStatusCode Status => _statusCode; public string? StatusDescription => _statusDescription; public bool HasRemoteParent { get; private set; } public ActivityKind Kind { get; private set; } public string OperationName { get; } public string DisplayName { get { return _displayName ?? OperationName; } set { _displayName = value ?? throw new ArgumentNullException("value"); } } public ActivitySource Source { get; private set; } public Activity? Parent { get; private set; } public TimeSpan Duration { get; private set; } public DateTime StartTimeUtc { get; private set; } public string? Id { get { if (_id == null && _spanId != null) { Span<char> buffer = stackalloc char[2]; System.HexConverter.ToCharsBuffer((byte)(0xFFFFFF7Fu & _w3CIdFlags), buffer, 0, System.HexConverter.Casing.Lower); string value = "00-" + _traceId + "-" + _spanId + "-" + buffer; Interlocked.CompareExchange(ref _id, value, null); } return _id; } } public string? ParentId { get { if (_parentId == null) { if (_parentSpanId != null) { Span<char> buffer = stackalloc char[2]; System.HexConverter.ToCharsBuffer((byte)(0xFFFFFF7Fu & _parentTraceFlags), buffer, 0, System.HexConverter.Casing.Lower); string value = "00-" + _traceId + "-" + _parentSpanId + "-" + buffer; Interlocked.CompareExchange(ref _parentId, value, null); } else if (Parent != null) { Interlocked.CompareExchange(ref _parentId, Parent.Id, null); } } return _parentId; } } public string? RootId { get { if (_rootId == null) { string text = null; if (Id != null) { text = GetRootId(Id); } else if (ParentId != null) { text = GetRootId(ParentId); } if (text != null) { Interlocked.CompareExchange(ref _rootId, text, null); } } return _rootId; } } public IEnumerable<KeyValuePair<string, string?>> Tags => _tags?.EnumerateStringValues() ?? s_emptyBaggageTags; public IEnumerable<KeyValuePair<string, object?>> TagObjects { get { IEnumerable<KeyValuePair<string, object>> tags = _tags; return tags ?? s_emptyTagObjects; } } public IEnumerable<ActivityEvent> Events { get { IEnumerable<ActivityEvent> events = _events; return events ?? s_emptyEvents; } } public IEnumerable<ActivityLink> Links { get { IEnumerable<ActivityLink> links = _links; return links ?? s_emptyLinks; } } public IEnumerable<KeyValuePair<string, string?>> Baggage { get { for (Activity activity2 = this; activity2 != null; activity2 = activity2.Parent) { if (activity2._baggage != null) { return Iterate(activity2); } } return s_emptyBaggageTags; static IEnumerable<KeyValuePair<string, string>> Iterate(Activity activity) { do { if (activity._baggage != null) { for (DiagNode<KeyValuePair<string, string>> current = activity._baggage.First; current != null; current = current.Next) { yield return current.Value; } } activity = activity.Parent; } while (activity != null); } } } public ActivityContext Context => new ActivityContext(TraceId, SpanId, ActivityTraceFlags, TraceStateString); public string? TraceStateString { get { for (Activity activity = this; activity != null; activity = activity.Parent) { string traceState = activity._traceState; if (traceState != null) { return traceState; } } return null; } set { _traceState = value; } } public ActivitySpanId SpanId { get { if (_spanId == null && _id != null && IdFormat == ActivityIdFormat.W3C) { string value = ActivitySpanId.CreateFromString(_id.AsSpan(36, 16)).ToHexString(); Interlocked.CompareExchange(ref _spanId, value, null); } return new ActivitySpanId(_spanId); } } public ActivityTraceId TraceId { get { if (_traceId == null) { TrySetTraceIdFromParent(); } return new ActivityTraceId(_traceId); } } public bool Recorded => (ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0; public bool IsAllDataRequested { get; set; } public ActivityTraceFlags ActivityTraceFlags { get { if (!W3CIdFlagsSet) { TrySetTraceFlagsFromParent(); } return (ActivityTraceFlags)(-129 & (int)_w3CIdFlags); } set { _w3CIdFlags = (byte)(0x80u | (byte)value); } } public ActivitySpanId ParentSpanId { get { if (_parentSpanId == null) { string text = null; if (_parentId != null && IsW3CId(_parentId)) { try { text = ActivitySpanId.CreateFromString(_parentId.AsSpan(36, 16)).ToHexString(); } catch { } } else if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C) { text = Parent.SpanId.ToHexString(); } if (text != null) { Interlocked.CompareExchange(ref _parentSpanId, text, null); } } return new ActivitySpanId(_parentSpanId); } } public static Func<ActivityTraceId>? TraceIdGenerator { get; set; } public static ActivityIdFormat DefaultIdFormat { get { if (s_defaultIdFormat == ActivityIdFormat.Unknown) { s_defaultIdFormat = ActivityIdFormat.Hierarchical; } return s_defaultIdFormat; } set { if (ActivityIdFormat.Hierarchical > value || value > ActivityIdFormat.W3C) { throw new ArgumentException(System.SR.ActivityIdFormatInvalid); } s_defaultIdFormat = value; } } private bool W3CIdFlagsSet => (_w3CIdFlags & 0x80) != 0; public bool IsStopped { get { return (_state & State.IsStopped) != 0; } private set { if (value) { _state |= State.IsStopped; } else { _state &= ~State.IsStopped; } } } public ActivityIdFormat IdFormat { get { return (ActivityIdFormat)(_state & State.FormatFlags); } private set { _state = (_state & ~State.FormatFlags) | (State)((byte)value & 3u); } } public static Activity? Current { get { return s_current.Value; } set { if (ValidateSetCurrent(value)) { SetCurrent(value); } } } public static event EventHandler<ActivityChangedEventArgs>? CurrentChanged; public Activity SetStatus(ActivityStatusCode code, string? description = null) { _statusCode = code; _statusDescription = ((code == ActivityStatusCode.Error) ? description : null); return this; } public Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects() { return new Enumerator<KeyValuePair<string, object>>(_tags?.First); } public Enumerator<ActivityEvent> EnumerateEvents() { return new Enumerator<ActivityEvent>(_events?.First); } public Enumerator<ActivityLink> EnumerateLinks() { return new Enumerator<ActivityLink>(_links?.First); } public string? GetBaggageItem(string key) { foreach (KeyValuePair<string, string> item in Baggage) { if (key == item.Key) { return item.Value; } } return null; } public object? GetTagItem(string key) { return _tags?.Get(key) ?? null; } public Activity(string operationName) { Source = s_defaultSource; IsAllDataRequested = true; if (string.IsNullOrEmpty(operationName)) { NotifyError(new ArgumentException(System.SR.OperationNameInvalid)); } OperationName = operationName ?? string.Empty; } public Activity AddTag(string key, string? value) { return AddTag(key, (object?)value); } public Activity AddTag(string key, object? value) { KeyValuePair<string, object> keyValuePair = new KeyValuePair<string, object>(key, value); if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(keyValuePair), null) != null) { _tags.Add(keyValuePair); } return this; } public Activity SetTag(string key, object? value) { KeyValuePair<string, object> keyValuePair = new KeyValuePair<string, object>(key, value); if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(keyValuePair, set: true), null) != null) { _tags.Set(keyValuePair); } return this; } public Activity AddEvent(ActivityEvent e) { if (_events != null || Interlocked.CompareExchange(ref _events, new DiagLinkedList<ActivityEvent>(e), null) != null) { _events.Add(e); } return this; } public Activity AddBaggage(string key, string? value) { KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(key, value); if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(keyValuePair), null) != null) { _baggage.Add(keyValuePair); } return this; } public Activity SetBaggage(string key, string? value) { KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(key, value); if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(keyValuePair, set: true), null) != null) { _baggage.Set(keyValuePair); } return this; } public Activity SetParentId(string parentId) { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(System.SR.ActivitySetParentAlreadyStarted)); } else if (Parent != null) { NotifyError(new InvalidOperationException(System.SR.SetParentIdOnActivityWithParent)); } else if (ParentId != null || _parentSpanId != null) { NotifyError(new InvalidOperationException(System.SR.ParentIdAlreadySet)); } else if (string.IsNullOrEmpty(parentId)) { NotifyError(new ArgumentException(System.SR.ParentIdInvalid)); } else { _parentId = parentId; } return this; } public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags activityTraceFlags = ActivityTraceFlags.None) { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(System.SR.ActivitySetParentAlreadyStarted)); } else if (Parent != null) { NotifyError(new InvalidOperationException(System.SR.SetParentIdOnActivityWithParent)); } else if (ParentId != null || _parentSpanId != null) { NotifyError(new InvalidOperationException(System.SR.ParentIdAlreadySet)); } else { _traceId = traceId.ToHexString(); _parentSpanId = spanId.ToHexString(); ActivityTraceFlags = activityTraceFlags; _parentTraceFlags = (byte)activityTraceFlags; } return this; } public Activity SetStartTime(DateTime startTimeUtc) { if (startTimeUtc.Kind != DateTimeKind.Utc) { NotifyError(new InvalidOperationException(System.SR.StartTimeNotUtc)); } else { StartTimeUtc = startTimeUtc; } return this; } public Activity SetEndTime(DateTime endTimeUtc) { if (endTimeUtc.Kind != DateTimeKind.Utc) { NotifyError(new InvalidOperationException(System.SR.EndTimeNotUtc)); } else { Duration = endTimeUtc - StartTimeUtc; if (Duration.Ticks <= 0) { Duration = new TimeSpan(1L); } } return this; } public Activity Start() { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(System.SR.ActivityStartAlreadyStarted)); } else { _previousActiveActivity = Current; if (_parentId == null && _parentSpanId == null && _previousActiveActivity != null) { Parent = _previousActiveActivity; } if (StartTimeUtc == default(DateTime)) { StartTimeUtc = GetUtcNow(); } if (IdFormat == ActivityIdFormat.Unknown) { IdFormat = (ForceDefaultIdFormat ? DefaultIdFormat : ((Parent != null) ? Parent.IdFormat : ((_parentSpanId != null) ? ActivityIdFormat.W3C : ((_parentId == null) ? DefaultIdFormat : ((!IsW3CId(_parentId)) ? ActivityIdFormat.Hierarchical : ActivityIdFormat.W3C))))); } if (IdFormat == ActivityIdFormat.W3C) { GenerateW3CId(); } else { _id = GenerateHierarchicalId(); } SetCurrent(this); Source.NotifyActivityStart(this); } return this; } public void Stop() { if (_id == null && _spanId == null) { NotifyError(new InvalidOperationException(System.SR.ActivityNotStarted)); } else if (!IsStopped) { IsStopped = true; if (Duration == TimeSpan.Zero) { SetEndTime(GetUtcNow()); } Source.NotifyActivityStop(this); SetCurrent(_previousActiveActivity); } } public Activity SetIdFormat(ActivityIdFormat format) { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(System.SR.SetFormatOnStartedActivity)); } else { IdFormat = format; } return this; } private static bool IsW3CId(string id) { if (id.Length == 55 && (('0' <= id[0] && id[0] <= '9') || ('a' <= id[0] && id[0] <= 'f')) && (('0' <= id[1] && id[1] <= '9') || ('a' <= id[1] && id[1] <= 'f'))) { if (id[0] == 'f') { return id[1] != 'f'; } return true; } return false; } internal static bool TryConvertIdToContext(string traceParent, string traceState, bool isRemote, out ActivityContext context) { context = default(ActivityContext); if (!IsW3CId(traceParent)) { return false; } ReadOnlySpan<char> idData = traceParent.AsSpan(3, 32); ReadOnlySpan<char> idData2 = traceParent.AsSpan(36, 16); if (!ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData) || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData2) || !System.HexConverter.IsHexLowerChar(traceParent[53]) || !System.HexConverter.IsHexLowerChar(traceParent[54])) { return false; } context = new ActivityContext(new ActivityTraceId(idData.ToString()), new ActivitySpanId(idData2.ToString()), (ActivityTraceFlags)ActivityTraceId.HexByteFromChars(traceParent[53], traceParent[54]), traceState, isRemote); return true; } public void Dispose() { if (!IsStopped) { Stop(); } Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public void SetCustomProperty(string propertyName, object? propertyValue) { if (_customProperties == null) { Interlocked.CompareExchange(ref _customProperties, new Dictionary<string, object>(), null); } lock (_customProperties) { if (propertyValue == null) { _customProperties.Remove(propertyName); } else { _customProperties[propertyName] = propertyValue; } } } public object? GetCustomProperty(string propertyName) { if (_customProperties == null) { return null; } lock (_customProperties) { object value; return _customProperties.TryGetValue(propertyName, out value) ? value : null; } } internal static Activity Create(ActivitySource source, string name, ActivityKind kind, string parentId, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, DateTimeOffset startTime, ActivityTagsCollection samplerTags, ActivitySamplingResult request, bool startIt, ActivityIdFormat idFormat, string traceState) { Activity activity = new Activity(name); activity.Source = source; activity.Kind = kind; activity.IdFormat = idFormat; activity._traceState = traceState; if (links != null) { using IEnumerator<ActivityLink> enumerator = links.GetEnumerator(); if (enumerator.MoveNext()) { activity._links = new DiagLinkedList<ActivityLink>(enumerator); } } if (tags != null) { using IEnumerator<KeyValuePair<string, object>> enumerator2 = tags.GetEnumerator(); if (enumerator2.MoveNext()) { activity._tags = new TagsLinkedList(enumerator2); } } if (samplerTags != null) { if (activity._tags == null) { activity._tags = new TagsLinkedList(samplerTags); } else { activity._tags.Add(samplerTags); } } if (parentId != null) { activity._parentId = parentId; } else if (parentContext != default(ActivityContext)) { activity._traceId = parentContext.TraceId.ToString(); if (parentContext.SpanId != default(ActivitySpanId)) { activity._parentSpanId = parentContext.SpanId.ToString(); } activity.ActivityTraceFlags = parentContext.TraceFlags; activity._parentTraceFlags = (byte)parentContext.TraceFlags; activity.HasRemoteParent = parentContext.IsRemote; } activity.IsAllDataRequested = request == ActivitySamplingResult.AllData || request == ActivitySamplingResult.AllDataAndRecorded; if (request == ActivitySamplingResult.AllDataAndRecorded) { activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded; } if (startTime != default(DateTimeOffset)) { activity.StartTimeUtc = startTime.UtcDateTime; } if (startIt) { activity.Start(); } return activity; } private void GenerateW3CId() { if (_traceId == null && !TrySetTraceIdFromParent()) { _traceId = (TraceIdGenerator?.Invoke() ?? ActivityTraceId.CreateRandom()).ToHexString(); } if (!W3CIdFlagsSet) { TrySetTraceFlagsFromParent(); } _spanId = ActivitySpanId.CreateRandom().ToHexString(); } private static void NotifyError(Exception exception) { try { throw exception; } catch { } } private string GenerateHierarchicalId() { if (Parent != null) { return AppendSuffix(Parent.Id, Interlocked.Increment(ref Parent._currentChildId).ToString(), '.'); } if (ParentId != null) { string text = ((ParentId[0] == '|') ? ParentId : ("|" + ParentId)); char c = text[text.Length - 1]; if (c != '.' && c != '_') { text += "."; } return AppendSuffix(text, Interlocked.Increment(ref s_currentRootId).ToString("x"), '_'); } return GenerateRootId(); } private string GetRootId(string id) { if (IdFormat == ActivityIdFormat.W3C) { return id.Substring(3, 32); } int num = id.IndexOf('.'); if (num < 0) { num = id.Length; } int num2 = ((id[0] == '|') ? 1 : 0); return id.Substring(num2, num - num2); } private string AppendSuffix(string parentId, string suffix, char delimiter) { if (parentId.Length + suffix.Length < 1024) { return parentId + suffix + delimiter; } int num = 1015; while (num > 1 && parentId[num - 1] != '.' && parentId[num - 1] != '_') { num--; } if (num == 1) { return GenerateRootId(); } string text = ((int)GetRandomNumber()).ToString("x8"); return parentId.Substring(0, num) + text + "#"; } private unsafe static long GetRandomNumber() { Guid guid = Guid.NewGuid(); return *(long*)(&guid); } private static bool ValidateSetCurrent(Activity activity) { bool flag = activity == null || (activity.Id != null && !activity.IsStopped); if (!flag) { NotifyError(new InvalidOperationException(System.SR.ActivityNotRunning)); } return flag; } private bool TrySetTraceIdFromParent() { if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C) { _traceId = Parent.TraceId.ToHexString(); } else if (_parentId != null && IsW3CId(_parentId)) { try { _traceId = ActivityTraceId.CreateFromString(_parentId.AsSpan(3, 32)).ToHexString(); } catch { } } return _traceId != null; } private void TrySetTraceFlagsFromParent() { if (W3CIdFlagsSet) { return; } if (Parent != null) { ActivityTraceFlags = Parent.ActivityTraceFlags; } else if (_parentId != null && IsW3CId(_parentId)) { if (System.HexConverter.IsHexLowerChar(_parentId[53]) && System.HexConverter.IsHexLowerChar(_parentId[54])) { _w3CIdFlags = (byte)(ActivityTraceId.HexByteFromChars(_parentId[53], _parentId[54]) | 0x80u); } else { _w3CIdFlags = 128; } } } private static void SetCurrent(Activity activity) { EventHandler<ActivityChangedEventArgs> currentChanged = Activity.CurrentChanged; if (currentChanged == null) { s_current.Value = activity; return; } Activity value = s_current.Value; s_current.Value = activity; currentChanged(null, new ActivityChangedEventArgs(value, activity)); } private static string GenerateRootId() { return $"|{Interlocked.Increment(ref s_currentRootId):x}{s_uniqSuffix}"; } internal static DateTime GetUtcNow() { return DateTime.UtcNow; } } [Flags] public enum ActivityTraceFlags { None = 0, Recorded = 1 } public enum ActivityIdFormat { Unknown, Hierarchical, W3C } public readonly struct ActivityTraceId : IEquatable<ActivityTraceId> { private readonly string _hexString; internal ActivityTraceId(string hexString) { _hexString = hexString; } public static ActivityTraceId CreateRandom() { Span<byte> span = stackalloc byte[16]; SetToRandomBytes(span); return CreateFromBytes(span); } public static ActivityTraceId CreateFromBytes(ReadOnlySpan<byte> idData) { if (idData.Length != 16) { throw new ArgumentOutOfRangeException("idData"); } return new ActivityTraceId(System.HexConverter.ToString(idData, System.HexConverter.Casing.Lower)); } public static ActivityTraceId CreateFromUtf8String(ReadOnlySpan<byte> idData) { return new ActivityTraceId(idData); } public static ActivityTraceId CreateFromString(ReadOnlySpan<char> idData) { if (idData.Length != 32 || !IsLowerCaseHexAndNotAllZeros(idData)) { throw new ArgumentOutOfRangeException("idData"); } return new ActivityTraceId(idData.ToString()); } public string ToHexString() { return _hexString ?? "00000000000000000000000000000000"; } public override string ToString() { return ToHexString(); } public static bool operator ==(ActivityTraceId traceId1, ActivityTraceId traceId2) { return traceId1._hexString == traceId2._hexString; } public static bool operator !=(ActivityTraceId traceId1, ActivityTraceId traceId2) { return traceId1._hexString != traceId2._hexString; } public bool Equals(ActivityTraceId traceId) { return _hexString == traceId._hexString; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ActivityTraceId activityTraceId) { return _hexString == activityTraceId._hexString; } return false; } public override int GetHashCode() { return ToHexString().GetHashCode(); } private ActivityTraceId(ReadOnlySpan<byte> idData) { if (idData.Length != 32) { throw new ArgumentOutOfRangeException("idData"); } Span<ulong> span = stackalloc ulong[2]; if (!Utf8Parser.TryParse(idData.Slice(0, 16), out span[0], out int bytesConsumed, 'x')) { _hexString = CreateRandom()._hexString; return; } if (!Utf8Parser.TryParse(idData.Slice(16, 16), out span[1], out bytesConsumed, 'x')) { _hexString = CreateRandom()._hexString; return; } if (BitConverter.IsLittleEndian) { span[0] = BinaryPrimitives.ReverseEndianness(span[0]); span[1] = BinaryPrimitives.ReverseEndianness(span[1]); } _hexString = System.HexConverter.ToString(MemoryMarshal.AsBytes(span), System.HexConverter.Casing.Lower); } public void CopyTo(Span<byte> destination) { SetSpanFromHexChars(ToHexString().AsSpan(), destination); } internal static void SetToRandomBytes(Span<byte> outBytes) { RandomNumberGenerator current = RandomNumberGenerator.Current; Unsafe.WriteUnaligned(ref outBytes[0], current.Next()); if (outBytes.Length == 16) { Unsafe.WriteUnaligned(ref outBytes[8], current.Next()); } } internal static void SetSpanFromHexChars(ReadOnlySpan<char> charData, Span<byte> outBytes) { for (int i = 0; i < outBytes.Length; i++) { outBytes[i] = HexByteFromChars(charData[i * 2], charData[i * 2 + 1]); } } internal static byte HexByteFromChars(char char1, char char2) { int num = System.HexConverter.FromLowerChar(char1); int num2 = System.HexConverter.FromLowerChar(char2); if ((num | num2) == 255) { throw new ArgumentOutOfRangeException("idData"); } return (byte)((num << 4) | num2); } internal static bool IsLowerCaseHexAndNotAllZeros(ReadOnlySpan<char> idData) { bool result = false; for (int i = 0; i < idData.Length; i++) { char c = idData[i]; if (!System.HexConverter.IsHexLowerChar(c)) { return false; } if (c != '0') { result = true; } } return result; } } public readonly struct ActivitySpanId : IEquatable<ActivitySpanId> { private readonly string _hexString; internal ActivitySpanId(string hexString) { _hexString = hexString; } public unsafe static ActivitySpanId CreateRandom() { ulong num = default(ulong); ActivityTraceId.SetToRandomBytes(new Span<byte>(&num, 8)); return new ActivitySpanId(System.HexConverter.ToString(new ReadOnlySpan<byte>(&num, 8), System.HexConverter.Casing.Lower)); } public static ActivitySpanId CreateFromBytes(ReadOnlySpan<byte> idData) { if (idData.Length != 8) { throw new ArgumentOutOfRangeException("idData"); } return new ActivitySpanId(System.HexConverter.ToString(idData, System.HexConverter.Casing.Lower)); } public static ActivitySpanId CreateFromUtf8String(ReadOnlySpan<byte> idData) { return new ActivitySpanId(idData); } public static ActivitySpanId CreateFromString(ReadOnlySpan<char> idData) { if (idData.Length != 16 || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData)) { throw new ArgumentOutOfRangeException("idData"); } return new ActivitySpanId(idData.ToString()); } public string ToHexString() { return _hexString ?? "0000000000000000"; } public override string ToString() { return ToHexString(); } public static bool operator ==(ActivitySpanId spanId1, ActivitySpanId spandId2) { return spanId1._hexString == spandId2._hexString; } public static bool operator !=(ActivitySpanId spanId1, ActivitySpanId spandId2) { return spanId1._hexString != spandId2._hexString; } public bool Equals(ActivitySpanId spanId) { return _hexString == spanId._hexString; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ActivitySpanId activitySpanId) { return _hexString == activitySpanId._hexString; } return false; } public override int GetHashCode() { return ToHexString().GetHashCode(); } private unsafe ActivitySpanId(ReadOnlySpan<byte> idData) { if (idData.Length != 16) { throw new ArgumentOutOfRangeException("idData"); } if (!Utf8Parser.TryParse(idData, out ulong value, out int _, 'x')) { _hexString = CreateRandom()._hexString; return; } if (BitConverter.IsLittleEndian) { value = BinaryPrimitives.ReverseEndianness(value); } _hexString = System.HexConverter.ToString(new ReadOnlySpan<byte>(&value, 8), System.HexConverter.Casing.Lower); } public void CopyTo(Span<byte> destination) { ActivityTraceId.SetSpanFromHexChars(ToHexString().AsSpan(), destination); } } public enum ActivityStatusCode { Unset, Ok, Error } public class ActivityTagsCollection : IDictionary<string, object?>, ICollection<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable { public struct Enumerator : IEnumerator<KeyValuePair<string, object?>>, IEnumerator, IDisposable { private List<KeyValuePair<string, object>>.Enumerator _enumerator; public KeyValuePair<string, object?> Current => _enumerator.Current; object IEnumerator.Current => ((IEnumerator)_enumerator).Current; internal Enumerator(List<KeyValuePair<string, object>> list) { _enumerator = list.GetEnumerator(); } public void Dispose() { _enumerator.Dispose(); } public bool MoveNext() { return _enumerator.MoveNext(); } void IEnumerator.Reset() { ((IEnumerator)_enumerator).Reset(); } } private readonly List<KeyValuePair<string, object>> _list = new List<KeyValuePair<string, object>>(); public object? this[string key] { get { int num = FindIndex(key); if (num >= 0) { return _list[num].Value; } return null; } set { if (key == null) { throw new ArgumentNullException("key"); } int num = FindIndex(key); if (value == null) { if (num >= 0) { _list.RemoveAt(num); } } else if (num >= 0) { _list[num] = new KeyValuePair<string, object>(key, value); } else { _list.Add(new KeyValuePair<string, object>(key, value)); } } } public ICollection<string> Keys { get { List<string> list = new List<string>(_list.Count); foreach (KeyValuePair<string, object> item in _list) { list.Add(item.Key); } return list; } } public ICollection<object?> Values { get { List<object> list = new List<object>(_list.Count); foreach (KeyValuePair<string, object> item in _list) { list.Add(item.Value); } return list; } } public bool IsReadOnly => false; public int Count => _list.Count; public ActivityTagsCollection() { } public ActivityTagsCollection(IEnumerable<KeyValuePair<string, object?>> list) { if (list == null) { throw new ArgumentNullException("list"); } foreach (KeyValuePair<string, object> item in list) { if (item.Key != null) { this[item.Key] = item.Value; } } } public void Add(string key, object? value) { if (key == null) { throw new ArgumentNullException("key"); } int num = FindIndex(key); if (num >= 0) { throw new InvalidOperationException(System.SR.Format(System.SR.KeyAlreadyExist, key)); } _list.Add(new KeyValuePair<string, object>(key, value)); } public void Add(KeyValuePair<string, object?> item) { if (item.Key == null) { throw new ArgumentNullException("item"); } int num = FindIndex(item.Key); if (num >= 0) { throw new InvalidOperationException(System.SR.Format(System.SR.KeyAlreadyExist, item.Key)); } _list.Add(item); } public void Clear() { _list.Clear(); } public bool Contains(KeyValuePair<string, object?> item) { return _list.Contains(item); } public bool ContainsKey(string key) { return FindIndex(key) >= 0; } public void CopyTo(KeyValuePair<string, object?>[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { return new Enumerator(_list); } public Enumerator GetEnumerator() { return new Enumerator(_list); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_list); } public bool Remove(string key) { if (key == null) { throw new ArgumentNullException("key"); } int num = FindIndex(key); if (num >= 0) { _list.RemoveAt(num); return true; } return false; } public bool Remove(KeyValuePair<string, object?> item) { return _list.Remove(item); } public bool TryGetValue(string key, out object? value) { int num = FindIndex(key); if (num >= 0) { value = _list[num].Value; return true; } value = null; return false; } private int FindIndex(string key) { for (int i = 0; i < _list.Count; i++) { if (_list[i].Key == key) { return i; } } return -1; } } public readonly struct ActivityContext : IEquatable<ActivityContext> { public ActivityTraceId TraceId { get; } public ActivitySpanId SpanId { get; } public ActivityTraceFlags TraceFlags { get; } public string? TraceState { get; } public bool IsRemote { get; } public ActivityContext(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags traceFlags, string? traceState = null, bool isRemote = false) { TraceId = traceId; SpanId = spanId; TraceFlags = traceFlags; TraceState = traceState; IsRemote = isRemote; } public static bool TryParse(string? traceParent, string? traceState, bool isRemote, out ActivityContext context) { if (traceParent == null) { context = default(ActivityContext); return false; } return Activity.TryConvertIdToContext(traceParent, traceState, isRemote, out context); } public static bool TryParse(string? traceParent, string? traceState, out ActivityContext context) { return TryParse(traceParent, traceState, isRemote: false, out context); } public static ActivityContext Parse(string traceParent, string? traceState) { if (traceParent == null) { throw new ArgumentNullException("traceParent"); } if (!Activity.TryConvertIdToContext(traceParent, traceState, isRemote: false, out var context)) { throw new ArgumentException(System.SR.InvalidTraceParent); } return context; } public bool Equals(ActivityContext value) { if (SpanId.Equals(value.SpanId) && TraceId.Equals(value.TraceId) && TraceFlags == value.TraceFlags && TraceState == value.TraceState) { return IsRemote == value.IsRemote; } return false; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is ActivityContext value)) { return false; } return Equals(value); } public static bool operator ==(ActivityContext left, ActivityContext right) { return left.Equals(right); } public static bool operator !=(ActivityContext left, ActivityContext right) { return !(left == right); } public override int GetHashCode() { if (this == default(ActivityContext)) { return 0; } int num = 5381; num = (num << 5) + num + TraceId.GetHashCode(); num = (num << 5) + num + SpanId.GetHashCode(); num = (int)((num << 5) + num + TraceFlags); return (num << 5) + num + ((TraceState != null) ? TraceState.GetHashCode() : 0); } } public readonly struct ActivityCreationOptions<T> { private readonly ActivityTagsCollection _samplerTags; private readonly ActivityContext _context; private readonly string _traceState; public ActivitySource Source { get; } public string Name { get; } public ActivityKind Kind { get; } public T Parent { get; } public IEnumerable<KeyValuePair<string, object?>>? Tags { get; } public IEnumerable<ActivityLink>? Links { get; } public ActivityTagsCollection SamplingTags { get { if (_samplerTags == null) { Unsafe.AsRef(in _samplerTags) = new ActivityTagsCollection(); } return _samplerTags; } } public ActivityTraceId TraceId { get { if (Parent is ActivityContext && IdFormat == ActivityIdFormat.W3C && _context == default(ActivityContext)) { ActivityTraceId traceId = Activity.TraceIdGenerator?.Invoke() ?? ActivityTraceId.CreateRandom(); Unsafe.AsRef(in _context) = new ActivityContext(traceId, default(ActivitySpanId), ActivityTraceFlags.None); } return _context.TraceId; } } public string? TraceState { get { return _traceState; } init { _traceState = value; } } internal ActivityIdFormat IdFormat { get; } internal ActivityCreationOptions(ActivitySource source, string name, T parent, ActivityKind kind, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, ActivityIdFormat idFormat) { Source = source; Name = name; Kind = kind; Parent = parent; Tags = tags; Links = links; IdFormat = idFormat; if (IdFormat == ActivityIdFormat.Unknown && Activity.ForceDefaultIdFormat) { IdFormat = Activity.DefaultIdFormat; } _samplerTags = null; _traceState = null; if (parent is ActivityContext) { object obj = parent; ActivityContext activityContext = (ActivityContext)((obj is ActivityContext) ? obj : null); if (activityContext != default(ActivityContext)) { _context = activityContext; if (IdFormat == ActivityIdFormat.Unknown) { IdFormat = ActivityIdFormat.W3C; } _traceState = activityContext.TraceState; return; } } if ((object)parent is string traceParent) { if (IdFormat != ActivityIdFormat.Hierarchical) { if (ActivityContext.TryParse(traceParent, null, out _context)) { IdFormat = ActivityIdFormat.W3C; } if (IdFormat == ActivityIdFormat.Unknown) { IdFormat = ActivityIdFormat.Hierarchical; } } else { _context = default(ActivityContext); } } else { _context = default(ActivityContext); if (IdFormat == ActivityIdFormat.Unknown) { IdFormat = ((Activity.Current != null) ? Activity.Current.IdFormat : Activity.DefaultIdFormat); } } } internal void SetTraceState(string traceState) { Unsafe.AsRef(in _traceState) = traceState; } internal ActivityTagsCollection GetSamplingTags() { return _samplerTags; } internal ActivityContext GetContext() { return _context; } } public enum ActivitySamplingResult { None, PropagationData, AllData, AllDataAndRecorded } public readonly struct ActivityEvent { private static readonly IEnumerable<KeyValuePair<string, object>> s_emptyTags = Array.Empty<KeyValuePair<string, object>>(); private readonly Activity.TagsLinkedList _tags; public string Name { get; } public DateTimeOffset Timestamp { get; } public IEnumerable<KeyValuePair<string, object?>> Tags { get { IEnumerable<KeyValuePair<string, object>> tags = _tags; return tags ?? s_emptyTags; } } public ActivityEvent(string name) : this(name, DateTimeOffset.UtcNow) { } public ActivityEvent(string name, DateTimeOffset timestamp = default(DateTimeOffset), ActivityTagsCollection? tags = null) { Name = name ?? string.Empty; Timestamp = ((timestamp != default(DateTimeOffset)) ? timestamp : DateTimeOffset.UtcNow); _tags = ((tags != null && tags.Count > 0) ? new Activity.TagsLinkedList(tags) : null); } public Activity.Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects() { return new Activity.Enumerator<KeyValuePair<string, object>>(_tags?.First); } } public enum ActivityKind { Internal, Server, Client, Producer, Consumer } public readonly struct ActivityLink : IEquatable<ActivityLink> { private readonly Activity.TagsLinkedList _tags; public ActivityContext Context { get; } public IEnumerable<KeyValuePair<string, object?>>? Tags => _tags; public ActivityLink(ActivityContext context, ActivityTagsCollection? tags = null) { Context = context; _tags = ((tags != null && tags.Count > 0) ? new Activity.TagsLinkedList(tags) : null); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ActivityLink value) { return Equals(value); } return false; } public bool Equals(ActivityLink value) { if (Context == value.Context) { return value.Tags == Tags; } return false; } public static bool operator ==(ActivityLink left, ActivityLink right) { return left.Equals(right); } public static bool operator !=(ActivityLink left, ActivityLink right) { return !left.Equals(right); } public Activity.Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects() { return new Activity.Enumerator<KeyValuePair<string, object>>(_tags?.First); } public override int GetHashCode() { if (this == default(ActivityLink)) { return 0; } int num = 5381; num = (num << 5) + num + Context.GetHashCode(); if (Tags != null) { foreach (KeyValuePair<string, object> tag in Tags) { num = (num << 5) + num + tag.Key.GetHashCode(); if (tag.Value != null) { num = (num << 5) + num + tag.Value.GetHashCode(); } } } return num; } } public delegate ActivitySamplingResult SampleActivity<T>(ref ActivityCreationOptions<T> options); public sealed class ActivityListener : IDisposable { public Action<Activity>? ActivityStarted { get; set; } public Action<Activity>? ActivityStopped { get; set; } public Func<ActivitySource, bool>? ShouldListenTo { get; set; } public SampleActivity<string>? SampleUsingParentId { get; set; } public SampleActivity<ActivityContext>? Sample { get; set; } public void Dispose() { ActivitySource.DetachListener(this); } } public sealed class ActivitySource : IDisposable { internal delegate void Function<T, TParent>(T item, ref ActivityCreationOptions<TParent> data, ref ActivitySamplingResult samplingResult, ref ActivityCreationOptions<ActivityContext> dataWithContext); private static readonly SynchronizedList<ActivitySource> s_activeSources = new SynchronizedList<ActivitySource>(); private static readonly SynchronizedList<ActivityListener> s_allListeners = new SynchronizedList<ActivityListener>(); private SynchronizedList<ActivityListener> _listeners; public string Name { get; } public string? Version { get; } public ActivitySource(string name, string? version = "") { Name = name ?? throw new ArgumentNullException("name"); Version = version; s_activeSources.Add(this); if (s_allListeners.Count > 0) { s_allListeners.EnumWithAction(delegate(ActivityListener listener, object source) { Func<ActivitySource, bool> shouldListenTo = listener.ShouldListenTo; if (shouldListenTo != null) { ActivitySource activitySource = (ActivitySource)source; if (shouldListenTo(activitySource)) { activitySource.AddListener(listener); } } }, this); } GC.KeepAlive(DiagnosticSourceEventSource.Log); } public bool HasListeners() { SynchronizedList<ActivityListener> listeners = _listeners; if (listeners != null) { return listeners.Count > 0; } return false; } public Activity? CreateActivity(string name, ActivityKind kind) { return CreateActivity(name, kind, default(ActivityContext), null, null, null, default(DateTimeOffset), startIt: false); } public Activity? CreateActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, ActivityIdFormat idFormat = ActivityIdFormat.Unknown) { return CreateActivity(name, kind, parentContext, null, tags, links, default(DateTimeOffset), startIt: false, idFormat); } public Activity? CreateActivity(string name, ActivityKind kind, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, ActivityIdFormat idFormat = ActivityIdFormat.Unknown) { return CreateActivity(name, kind, default(ActivityContext), parentId, tags, links, default(DateTimeOffset), startIt: false, idFormat); } public Activity? StartActivity([CallerMemberName] string name = "", ActivityKind kind = ActivityKind.Internal) { return CreateActivity(name, kind, default(ActivityContext), null, null, null, default(DateTimeOffset)); } public Activity? StartActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset)) { return CreateActivity(name, kind, parentContext, null, tags, links, startTime); } public Activity? StartActivity(string name, ActivityKind kind, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset)) { return CreateActivity(name, kind, default(ActivityContext), parentId, tags, links, startTime); } public Activity? StartActivity(ActivityKind kind, ActivityContext parentContext = default(ActivityContext), IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset), [CallerMemberName] string name = "") { return CreateActivity(name, kind, parentContext, null, tags, links, startTime); } private Activity CreateActivity(string name, ActivityKind kind, ActivityContext context, string parentId, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, DateTimeOffset startTime, bool startIt = true, ActivityIdFormat idFormat = ActivityIdFormat.Unknown) { SynchronizedList<ActivityListener> listeners = _listeners; if (listeners == null || listeners.Count == 0) { return null; } Activity result2 = null; ActivitySamplingResult samplingResult = ActivitySamplingResult.None; ActivityTagsCollection activityTagsCollection; string traceState; if (parentId != null) { ActivityCreationOptions<string> activityCreationOptions = default(ActivityCreationOptions<string>); ActivityCreationOptions<ActivityContext> dataWithContext2 = default(ActivityCreationOptions<ActivityContext>); activityCreationOptions = new ActivityCreationOptions<string>(this, name, parentId, kind, tags, links, idFormat); if (activityCreationOptions.IdFormat == ActivityIdFormat.W3C) { dataWithContext2 = new ActivityCreationOptions<ActivityContext>(this, name, activityCreationOptions.GetContext(), kind, tags, links, ActivityIdFormat.W3C); } listeners.EnumWithFunc(delegate(ActivityListener listener, ref ActivityCreationOptions<string> data, ref ActivitySamplingResult result, ref ActivityCreationOptions<ActivityContext> dataWithContext) { SampleActivity<string> sampleUsingParentId = listener.SampleUsingParentId; if (sampleUsingParentId != null) { ActivitySamplingResult activitySamplingResult2 = sampleUsingParentId(ref data); dataWithContext.SetTraceState(data.TraceState); if (activitySamplingResult2 > result) { result = activitySamplingResult2; } } else if (data.IdFormat == ActivityIdFormat.W3C) { SampleActivity<ActivityContext> sample2 = listener.Sample; if (sample2 != null) { ActivitySamplingResult activitySamplingResult3 = sample2(ref dataWithContext); data.SetTraceState(dataWithContext.TraceState); if (activitySamplingResult3 > result) { result = activitySamplingResult3; } } } }, ref activityCreationOptions, ref samplingResult, ref dataWithContext2); if (context == default(ActivityContext)) { if (activityCreationOptions.GetContext() != default(ActivityContext)) { context = activityCreationOptions.GetContext(); parentId = null; } else if (dataWithContext2.GetContext() != default(ActivityContext)) { context = dataWithContext2.GetContext(); parentId = null; } } activityTagsCollection = activityCreationOptions.GetSamplingTags(); ActivityTagsCollection samplingTags = dataWithContext2.GetSamplingTags(); if (samplingTags != null) { if (activityTagsCollection == null) { activityTagsCollection = samplingTags; } else { foreach (KeyValuePair<string, object?> item in samplingTags) { activityTagsCollection.Add(item); } } } idFormat = activityCreationOptions.IdFormat; traceState = activityCreationOptions.TraceState; } else { bool flag = context == default(ActivityContext) && Activity.Current != null; ActivityCreationOptions<ActivityContext> data2 = new ActivityCreationOptions<ActivityContext>(this, name, flag ? Activity.Current.Context : context, kind, tags, links, idFormat); listeners.EnumWithFunc(delegate(ActivityListener listener, ref ActivityCreationOptions<ActivityContext> data, ref ActivitySamplingResult result, ref ActivityCreationOptions<ActivityContext> unused) { SampleActivity<ActivityContext> sample = listener.Sample; if (sample != null) { ActivitySamplingResult activitySamplingResult = sample(ref data); if (activitySamplingResult > result) { result = activitySamplingResult; } } }, ref data2, ref samplingResult, ref data2); if (!flag) { context = data2.GetContext(); } activityTagsCollection = data2.GetSamplingTags(); idFormat = data2.IdFormat; traceState = data2.TraceState; } if (samplingResult != 0) { result2 = Activity.Create(this, name, kind, parentId, context, tags, links, startTime, activityTagsCollection, samplingResult, startIt, idFormat, traceState); } return result2; } public void Dispose() { _listeners = null; s_activeSources.Remove(this); } public static void AddActivityListener(ActivityListener listener) { if (listener == null) { throw new ArgumentNullException("listener"); } if (!s_allListeners.AddIfNotExist(listener)) { return; } s_activeSources.EnumWithAction(delegate(ActivitySource source, object obj) { Func<ActivitySource, bool> shouldListenTo = ((ActivityListener)obj).ShouldListenTo; if (shouldListenTo != null && shouldListenTo(source)) { source.AddListener((ActivityListener)obj); } }, listener); } internal void AddListener(ActivityListener listener) { if (_listeners == null) { Interlocked.CompareExchange(ref _listeners, new SynchronizedList<ActivityListener>(), null); } _listeners.AddIfNotExist(listener); } internal static void DetachListener(ActivityListener listener) { s_allListeners.Remove(listener); s_activeSources.EnumWithAction(delegate(ActivitySource source, object obj) { source._listeners?.Remove((ActivityListener)obj); }, listener); } internal void NotifyActivityStart(Activity activity) { SynchronizedList<ActivityListener> listeners = _listeners; if (listeners != null && listeners.Count > 0) { listeners.EnumWithAction(delegate(ActivityListener listener, object obj) { listener.ActivityStarted?.Invoke((Activity)obj); }, activity); } } internal void NotifyActivityStop(Activity activity) { SynchronizedList<ActivityListener> listeners = _listeners; if (listeners != null && listeners.Count > 0) { listeners.EnumWithAction(delegate(ActivityListener listener, object obj) { listener.ActivityStopped?.Invoke((Activity)obj); }, activity); } } } internal sealed class SynchronizedList<T> { private readonly List<T> _list; private uint _version; public int Count => _list.Count; public SynchronizedList() { _list = new List<T>(); } public void Add(T item) { lock (_list) { _list.Add(item); _version++; } } public bool AddIfNotExist(T item) { lock (_list) { if (!_list.Contains(item)) { _list.Add(item); _version++; return true; } return false; } } public bool Remove(T item) { lock (_list) { if (_list.Remove(item)) { _version++; return true; } return false; } } public void EnumWithFunc<TParent>(ActivitySource.Function<T, TParent> func, ref ActivityCreationOptions<TParent> data, ref ActivitySamplingResult samplingResult, ref ActivityCreationOptions<ActivityContext> dataWithContext) { uint version = _version; int num = 0; while (num < _list.Count) { T item; lock (_list) { if (version != _version) { version = _version; num = 0; continue; } item = _list[num]; num++; goto IL_004f; } IL_004f: func(item, ref data, ref samplingResult, ref dataWithContext); } } public void EnumWithAction(Action<T, object> action, object arg) { uint version = _version; int num = 0; while (num < _list.Count) { T arg2; lock (_list) { if (version != _version) { version = _version; num = 0; continue; } arg2 = _list[num]; num++; goto IL_004f; } IL_004f: action(arg2, arg); } } } public abstract class DiagnosticSource { internal const string WriteRequiresUnreferencedCode = "The type of object being written to DiagnosticSource cannot be discovered statically."; internal const string WriteOfTRequiresUnreferencedCode = "Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed."; [RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")] public abstract void Write(string name, object? value); [RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")] public void Write<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name, T value) { Write(name, (object?)value); } public abstract bool IsEnabled(string name); public virtual bool IsEnabled(string name, object? arg1, object? arg2 = null) { return IsEnabled(name); } [RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")] public Activity StartActivity(Activity activity, object? args) { activity.Start(); Write(activity.OperationName + ".Start", args); return activity; } [RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")] public Activity StartActivity<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(Activity activity, T args) { return StartActivity(activity, (object?)args); } [RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")] public void StopActivity(Activity activity, object? args) { if (activity.Duration == TimeSpan.Zero) { activity.SetEndTime(Activity.GetUtcNow()); } Write(activity.OperationName + ".Stop", args); activity.Stop(); } [RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")] public void StopActivity<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(Activity activity, T args) { StopActivity(activity, (object?)args); } public virtual void OnActivityImport(Activity activity, object? payload) { } public virtual void OnActivityExport(Activity activity, object? payload) { } } public class DiagnosticListener : DiagnosticSource, IObservable<KeyValuePair<string, object?>>, IDisposable { private sealed class DiagnosticSubscription : IDisposable { internal IObserver<KeyValuePair<string, object>> Observer; internal Predicate<string> IsEnabled1Arg; internal Func<string, object, object, bool> IsEnabled3Arg; internal Action<Activity, object> OnActivityImport; internal Action<Activity, object> OnActivityExport; internal DiagnosticListener Owner; internal DiagnosticSubscription Next; public void Dispose() { DiagnosticSubscription subscriptions; DiagnosticSubscription value; do { subscriptions = Owner._subscriptions; value = Remove(subscriptions, this); } while (Interlocked.CompareExchange(ref Owner._subscriptions, value, subscriptions) != subscriptions); } private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription) { if (subscriptions == null) { return null; } if (subscriptions.Observer == subscription.Observer && subscriptions.IsEnabled1Arg == subscription.IsEnabled1Arg && subscriptions.IsEnabled3Arg == subscription.IsEnabled3Arg) { return subscriptions.Next; } return new DiagnosticSubscription { Observer = subscriptions.Observer, Owner = subscriptions.Owner, IsEnabled1Arg = subscriptions.IsEnabled1Arg, IsEnabled3Arg = subscriptions.IsEnabled3Arg, Next = Remove(subscriptions.Next, subscription) }; } } private sealed class AllListenerObservable : IObservable<DiagnosticListener> { internal sealed class AllListenerSubscription : IDisposable { private readonly AllListenerObservable _owner; internal readonly IObserver<DiagnosticListener> Subscriber; internal AllListenerSubscription Next; internal AllListenerSubscription(AllListenerObservable owner, IObserver<DiagnosticListener> subscriber, AllListenerSubscription next) { _owner = owner; Subscriber = subscriber; Next = next; } public void Dispose() { if (_owner.Remove(this)) { Subscriber.OnCompleted(); } } } private AllListenerSubscription _subscriptions; public IDisposable Subscribe(IObserver<DiagnosticListener> observer) { lock (s_allListenersLock) { for (DiagnosticListener diagnosticListener = s_allListeners; diagnosticListener != null; diagnosticListener = diagnosticListener._next) { observer.OnNext(diagnosticListener); } _subscriptions = new AllListenerSubscription(this, observer, _subscriptions); return _subscriptions; } } internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener) { for (AllListenerSubscription allListenerSubscription = _subscriptions; allListenerSubscription != null; allListenerSubscription = allListenerSubscription.Next) { allListenerSubscription.Subscriber.OnNext(diagnosticListener); } } private bool Remove(AllListenerSubscription subscription) { lock (s_allListenersLock) { if (_subscriptions == subscription) { _subscriptions = subscription.Next; return true; } if (_subscriptions != null) { AllListenerSubscription allListenerSubscription = _subscriptions; while (allListenerSubscription.Next != null) { if (allListenerSubscription.Next == subscription) { allListenerSubscription.Next = allListenerSubscription.Next.Next; return true; } allListenerSubscription = allListenerSubscription.Next; } } return false; } } } private volatile DiagnosticSubscription _subscriptions; private DiagnosticListener _next; private bool _disposed; private static DiagnosticListener s_allListeners; private static volatile AllListenerObservable s_allListenerObservable; private static readonly object s_allListenersLock = new object(); public static IObservable<DiagnosticListener> AllListeners => s_allListenerObservable ?? Interlocked.CompareExchange(ref s_allListenerObservable, new AllListenerObservable(), null) ?? s_allListenerObservable; public string Name { get; private set; } public override void OnActivityImport(Activity activity, object? payload) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { diagnosticSubscription.OnActivityImport?.Invoke(activity, payload); } } public override void OnActivityExport(Activity activity, object? payload) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { diagnosticSubscription.OnActivityExport?.Invoke(activity, payload); } } public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Func<string, object?, object?, bool>? isEnabled, Action<Activity, object?>? onActivityImport = null, Action<Activity, object?>? onActivityExport = null) { if (isEnabled != null) { return SubscribeInternal(observer, (string name) => IsEnabled(name, null), isEnabled, onActivityImport, onActivityExport); } return SubscribeInternal(observer, null, null, onActivityImport, onActivityExport); } public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Predicate<string>? isEnabled) { if (isEnabled == null) { return SubscribeInternal(observer, null, null, null, null); } Predicate<string> localIsEnabled = isEnabled; return SubscribeInternal(observer, isEnabled, (string name, object arg1, object arg2) => localIsEnabled(name), null, null); } public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer, Func<string, object?, object?, bool>? isEnabled) { if (isEnabled != null) { return SubscribeInternal(observer, (string name) => IsEnabled(name, null), isEnabled, null, null); } return SubscribeInternal(observer, null, null, null, null); } public virtual IDisposable Subscribe(IObserver<KeyValuePair<string, object?>> observer) { return SubscribeInternal(observer, null, null, null, null); } public DiagnosticListener(string name) { Name = name; lock (s_allListenersLock) { s_allListenerObservable?.OnNewDiagnosticListener(this); _next = s_allListeners; s_allListeners = this; } GC.KeepAlive(DiagnosticSourceEventSource.Log); } public virtual void Dispose() { lock (s_allListenersLock) { if (_disposed) { return; } _disposed = true; if (s_allListeners == this) { s_allListeners = s_allListeners._next; } else { for (DiagnosticListener next = s_allListeners; next != null; next = next._next) { if (next._next == this) { next._next = _next; break; } } } _next = null; } DiagnosticSubscription location = null; Interlocked.Exchange(ref location, _subscriptions); while (location != null) { location.Observer.OnCompleted(); location = location.Next; } } public override string ToString() { return Name ?? string.Empty; } public bool IsEnabled() { return _subscriptions != null; } public override bool IsEnabled(string name) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { if (diagnosticSubscription.IsEnabled1Arg == null || diagnosticSubscription.IsEnabled1Arg(name)) { return true; } } return false; } public override bool IsEnabled(string name, object? arg1, object? arg2 = null) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { if (diagnosticSubscription.IsEnabled3Arg == null || diagnosticSubscription.IsEnabled3Arg(name, arg1, arg2)) { return true; } } return false; } [RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")] public override void Write(string name, object? value) { for (DiagnosticSubscription diagnosticSubscription = _subscriptions; diagnosticSubscription != null; diagnosticSubscription = diagnosticSubscription.Next) { diagnosticSubscription.Observer.OnNext(new KeyValuePair<string, object>(name, value)); } } private DiagnosticSubscription SubscribeInternal(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled1Arg, Func<string, object, object, bool> isEnabled3Arg, Action<Activity, object> onActivityImport, Action<Activity, object> onActivityExport) { if (_disposed) { return new DiagnosticSubscription { Owner = this }; } DiagnosticSubscription diagnosticSubscription = new DiagnosticSubscription { Observer = observer, IsEnabled1Arg = isEnabled1Arg, IsEnabled3Arg = isEnabled3Arg, OnActivityImport = onActivityImport, OnActivityExport = onActivityExport, Owner = this, Next = _subscriptions }; while (Interlocked.CompareExchange(ref _subscriptions, diagnosticSubscription, diagnosticSubscription.Next) != diagnosticSubscription.Next) { diagnosticSubscription.Next = _subscriptions; } return diagnosticSubscription; } } [EventSource(Name = "Microsoft-Diagnostics-DiagnosticSource")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2113:ReflectionToRequiresUnreferencedCode", Justification = "In EventSource, EnsureDescriptorsInitialized's use of GetType preserves methods on Delegate and MulticastDelegate because the nested type OverrideEventProvider's base type EventProvider defines a delegate. This includes Delegate and MulticastDelegate methods which require unreferenced code, but EnsureDescriptorsInitialized does not access these members and is safe to call.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2115:ReflectionToDynamicallyAccessedMembers", Justification = "In EventSource, EnsureDescriptorsInitialized's use of GetType preserves methods on Delegate and MulticastDelegate because the nested type OverrideEventProvider's base type EventProvider defines a delegate. This includes Delegate and MulticastDelegate methods which have dynamically accessed members requirements, but EnsureDescriptorsInitialized does not access these members and is safe to call.")] internal sealed class DiagnosticSourceEventSource : EventSource { public static class Keywords { public const EventKeywords Messages = (EventKeywords)1L; public const EventKeywords Events = (EventKeywords)2L; public const EventKeywords IgnoreShortCutKeywords = (EventKeywords)2048L; public const EventKeywords AspNetCoreHosting = (EventKeywords)4096L; public const EventKeywords EntityFrameworkCoreCommands = (EventKeywords)8192L; } [Flags] internal enum ActivityEvents { None = 0, ActivityStart = 1, ActivityStop = 2, All = 3 } internal sealed class FilterAndTransform { public FilterAndTransform Next; internal const string c_ActivitySourcePrefix = "[AS]"; private IDisposable _diagnosticsListenersSubscription; private Subscriptions _liveSubscriptions; private readonly bool _noImplicitTransforms; private ImplicitTransformEntry _firstImplicitTransformsEntry; private ConcurrentDictionary<Type, TransformSpec> _implicitTransformsTable; private readonly TransformSpec _explicitTransforms; private readonly DiagnosticSourceEventSource _eventSource; internal string SourceName { get; set; } internal string ActivityName { get; set; } internal ActivityEvents Events { get; set; } internal ActivitySamplingResult SamplingResult { get; set; } public static void CreateFilterAndTransformList(ref FilterAndTransform specList, string filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource) { DestroyFilterAndTransformList(ref specList, eventSource); if (filterAndPayloadSpecs == null) { filterAndPayloadSpecs = ""; } int num = filterAndPayloadSpecs.Length; while (true) { if (0 < num && char.IsWhiteSpace(filterAndPayloadSpecs[num - 1])) { num--; continue; } int num2 = filterAndPayloadSpecs.LastIndexOf('\n', num - 1, num); int i = 0; if (0 <= num2) { i = num2 + 1; } for (; i < num && char.IsWhiteSpace(filterAndPayloadSpecs[i]); i++) { } if (IsActivitySourceEntry(filterAndPayloadSpecs, i, num)) { AddNewActivitySourceTransform(filterAndPayloadSpecs, i, num, eventSource); } else { specList = new FilterAndTransform(filterAndPayloadSpecs, i, num, eventSource, specList); } num = num2; if (num < 0) { break; } } if (eventSource._activitySourceSpecs != null) { NormalizeActivitySourceSpecsList(eventSource); CreateActivityListener(eventSource); } } public static void DestroyFilterAndTransformList(ref FilterAndTransform specList, DiagnosticSourceEventSource eventSource) { eventSource._activityListener?.Dispose(); eventSource._activityListener = null; eventSource._activitySourceSpecs = null; FilterAndTransform filterAndTransform = specList; specList = null; while (filterAndTransform != null) { filterAndTransform.Dispose(); filterAndTransform = filterAndTransform.Next; } } public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, DiagnosticSourceEventSource eventSource, FilterAndTransform next) { FilterAndTransform filterAndTransform = this; Next = next; _eventSource = eventSource; string listenerNameFilter = null; string eventNameFilter = null; string text = null; int num = startIdx; int num2 = endIdx; int num3 = filterAndPayloadSpec.IndexOf(':', startIdx, endIdx - startIdx); if (0 <= num3) { num2 = num3; num = num3 + 1; } int num4 = filterAndPayloadSpec.IndexOf('/', startIdx, num2 - startIdx); if (0 <= num4) { listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, num4 - startIdx); int num5 = filterAndPayloadSpec.IndexOf('@', num4 + 1, num2 - num4 - 1); if (0 <= num5) { text = filterAndPayloadSpec.Substring(num5 + 1, num2 - num5 - 1); eventNameFilter = filterAndPayloadSpec.Substring(num4 + 1, num5 - num4 - 1); } else { eventNameFilter = filterAndPayloadSpec.Substring(num4 + 1, num2 - num4 - 1); } } else if (startIdx < num2) { listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, num2 - startIdx); } _eventSource.Message("DiagnosticSource: Enabling '" + (listenerNameFilter ?? "*") + "/" + (eventNameFilter ?? "*") + "'"); if (num < endIdx && filterAndPayloadSpec[num] == '-') { _eventSource.Message("DiagnosticSource: suppressing implicit transforms."); _noImplicitTransforms = true; num++; } if (num < endIdx) { while (true) { int num6 = num; int num7 = filterAndPayloadSpec.LastIndexOf(';', endIdx - 1, endIdx - num); if (0 <= num7) { num6 = num7 + 1; } if (num6 < endIdx) { if (_eventSource.IsEnabled(EventLevel.Informational, (EventKeywords)1L)) { _eventSource.Message("DiagnosticSource: Parsing Explicit Transform '" + filterAndPayloadSpec.Substring(num6, endIdx - num6) + "'"); } _explicitTransforms = new TransformSpec(filterAndPayloadSpec, num6, endIdx, _explicitTransforms); } if (num == num6) { break; } endIdx = num7; } } Action<string, string, IEnumerable<KeyValuePair<string, string>>> writeEvent = null; if (text != null && text.Contains("Activity")) { writeEvent = text switch { "Activity1Start" => _eventSource.Activity1Start, "Activity1Stop" => _eventSource.Activity1Stop, "Activity2Start" => _eventSource.Activity2Start, "Activity2Stop" => _eventSource.Activity2Stop, "RecursiveActivity1Start" => _eventSource.RecursiveActivity1Start, "RecursiveActivity1Stop" => _eventSource.RecursiveActivity1Stop, _ => null, }; if (writeEvent == null) { _eventSource.Message("DiagnosticSource: Could not find Event to log Activity " + text); } } if (writeEvent == null) { writeEvent = _eventSource.Event; } _diagnosticsListenersSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(delegate(DiagnosticListener newListener) { if (listenerNameFilter == null || listenerNameFilter == newListener.Name) { filterAndTransform._eventSource.NewDiagnosticListener(newListener.Name); Predicate<string> isEnabled = null; if (eventNameFilter != null) { isEnabled = (string eventName) => eventNameFilter == eventName; } IDisposable subscription = newListener.Subscribe(new CallbackObserver<KeyValuePair<string, object>>(OnEventWritten), isEnabled); filterAndTransform._liveSubscriptions = new Subscriptions(subscription, filterAndTransform._liveSubscriptions); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "DiagnosticSource.Write is marked with RequiresUnreferencedCode.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2119", Justification = "DAM on EventSource references this compiler-generated local function which calls a method that requires unreferenced code. EventSource will not access this local function.")] void OnEventWritten(KeyValuePair<string, object> evnt) { if (eventNameFilter == null || !(eventNameFilter != evnt.Key)) { List<KeyValuePair<string, string>> arg = filterAndTransform.Morph(evnt.Value); string key = evnt.Key; writeEvent(newListener.Name, key, arg); } } })); } internal FilterAndTransform(string filterAndPayloadSpec, int endIdx, int colonIdx, string activitySourceName, string activityName, ActivityEvents events, ActivitySamplingResult samplingResult, DiagnosticSourceEventSource eventSource) { _eventSource =
deps/System.IO.Pipelines.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using FxResources.System.IO.Pipelines; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("System.IO.Pipelines.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.IO.Pipelines")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Single producer single consumer byte buffer management.\r\n\r\nCommonly Used Types:\r\nSystem.IO.Pipelines.Pipe\r\nSystem.IO.Pipelines.PipeWriter\r\nSystem.IO.Pipelines.PipeReader")] [assembly: AssemblyFileVersion("9.0.24.52809")] [assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.IO.Pipelines")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("9.0.0.0")] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] 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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 FxResources.System.IO.Pipelines { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue(); private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string AdvanceToInvalidCursor => GetResourceString("AdvanceToInvalidCursor"); internal static string ArgumentOutOfRange_NeedPosNum => GetResourceString("ArgumentOutOfRange_NeedPosNum"); internal static string ConcurrentOperationsNotSupported => GetResourceString("ConcurrentOperationsNotSupported"); internal static string FlushCanceledOnPipeWriter => GetResourceString("FlushCanceledOnPipeWriter"); internal static string GetResultBeforeCompleted => GetResourceString("GetResultBeforeCompleted"); internal static string InvalidExaminedOrConsumedPosition => GetResourceString("InvalidExaminedOrConsumedPosition"); internal static string InvalidExaminedPosition => GetResourceString("InvalidExaminedPosition"); internal static string InvalidZeroByteRead => GetResourceString("InvalidZeroByteRead"); internal static string ObjectDisposed_StreamClosed => GetResourceString("ObjectDisposed_StreamClosed"); internal static string NoReadingOperationToComplete => GetResourceString("NoReadingOperationToComplete"); internal static string NotSupported_UnreadableStream => GetResourceString("NotSupported_UnreadableStream"); internal static string NotSupported_UnwritableStream => GetResourceString("NotSupported_UnwritableStream"); internal static string ReadCanceledOnPipeReader => GetResourceString("ReadCanceledOnPipeReader"); internal static string ReaderAndWriterHasToBeCompleted => GetResourceString("ReaderAndWriterHasToBeCompleted"); internal static string ReadingAfterCompleted => GetResourceString("ReadingAfterCompleted"); internal static string ReadingIsInProgress => GetResourceString("ReadingIsInProgress"); internal static string WritingAfterCompleted => GetResourceString("WritingAfterCompleted"); internal static string UnflushedBytesNotSupported => GetResourceString("UnflushedBytesNotSupported"); private static bool GetUsingResourceKeysSwitchValue() { if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled)) { return false; } return isEnabled; } internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Threading { internal static class CancellationTokenExtensions { internal static CancellationTokenRegistration UnsafeRegister(this CancellationToken cancellationToken, Action<object> callback, object state) { return cancellationToken.Register(callback, state); } } } namespace System.Threading.Tasks { internal static class TaskToAsyncResult { private sealed class TaskAsyncResult : IAsyncResult { internal readonly Task _task; private readonly AsyncCallback _callback; public object AsyncState { get; } public bool CompletedSynchronously { get; } public bool IsCompleted => _task.IsCompleted; public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle; internal TaskAsyncResult(Task task, object state, AsyncCallback callback) { _task = task; AsyncState = state; if (task.IsCompleted) { CompletedSynchronously = true; callback?.Invoke(this); } else if (callback != null) { _callback = callback; _task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().OnCompleted(delegate { _callback(this); }); } } } public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? state) { if (task == null) { throw new ArgumentNullException("task"); } return new TaskAsyncResult(task, state, callback); } public static void End(IAsyncResult asyncResult) { Unwrap(asyncResult).GetAwaiter().GetResult(); } public static TResult End<TResult>(IAsyncResult asyncResult) { return Unwrap<TResult>(asyncResult).GetAwaiter().GetResult(); } public static Task Unwrap(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } return (asyncResult as TaskAsyncResult)?._task ?? throw new ArgumentException(null, "asyncResult"); } public static Task<TResult> Unwrap<TResult>(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } return ((asyncResult as TaskAsyncResult)?._task as Task<TResult>) ?? throw new ArgumentException(null, "asyncResult"); } } } namespace System.IO { internal static class StreamHelpers { public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize) { if (destination == null) { throw new ArgumentNullException("destination"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize", bufferSize, System.SR.ArgumentOutOfRange_NeedPosNum); } bool canRead = source.CanRead; if (!canRead && !source.CanWrite) { throw new ObjectDisposedException(null, System.SR.ObjectDisposed_StreamClosed); } bool canWrite = destination.CanWrite; if (!canWrite && !destination.CanRead) { throw new ObjectDisposedException("destination", System.SR.ObjectDisposed_StreamClosed); } if (!canRead) { throw new NotSupportedException(System.SR.NotSupported_UnreadableStream); } if (!canWrite) { throw new NotSupportedException(System.SR.NotSupported_UnwritableStream); } } } } namespace System.IO.Pipelines { internal sealed class BufferSegment : ReadOnlySequenceSegment<byte> { private IMemoryOwner<byte> _memoryOwner; private byte[] _array; private BufferSegment _next; private int _end; public int End { get { return _end; } set { _end = value; base.Memory = AvailableMemory.Slice(0, value); } } public BufferSegment? NextSegment { get { return _next; } set { base.Next = value; _next = value; } } internal object? MemoryOwner => ((object)_memoryOwner) ?? ((object)_array); public Memory<byte> AvailableMemory { get; private set; } public int Length => End; public int WritableBytes { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return AvailableMemory.Length - End; } } public void SetOwnedMemory(IMemoryOwner<byte> memoryOwner) { _memoryOwner = memoryOwner; AvailableMemory = memoryOwner.Memory; } public void SetOwnedMemory(byte[] arrayPoolBuffer) { _array = arrayPoolBuffer; AvailableMemory = arrayPoolBuffer; } public void Reset() { ResetMemory(); base.Next = null; base.RunningIndex = 0L; _next = null; } public void ResetMemory() { IMemoryOwner<byte> memoryOwner = _memoryOwner; if (memoryOwner != null) { _memoryOwner = null; memoryOwner.Dispose(); } else { ArrayPool<byte>.Shared.Return(_array); _array = null; } base.Memory = default(ReadOnlyMemory<byte>); _end = 0; AvailableMemory = default(Memory<byte>); } public void SetNext(BufferSegment segment) { NextSegment = segment; segment = this; while (segment.Next != null) { segment.NextSegment.RunningIndex = segment.RunningIndex + segment.Length; segment = segment.NextSegment; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static long GetLength(BufferSegment startSegment, int startIndex, BufferSegment endSegment, int endIndex) { return endSegment.RunningIndex + (uint)endIndex - (startSegment.RunningIndex + (uint)startIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static long GetLength(long startPosition, BufferSegment endSegment, int endIndex) { return endSegment.RunningIndex + (uint)endIndex - startPosition; } } internal readonly struct CompletionData { public Action<object?> Completion { get; } public object? CompletionState { get; } public ExecutionContext? ExecutionContext { get; } public SynchronizationContext? SynchronizationContext { get; } public CompletionData(Action<object?> completion, object? completionState, ExecutionContext? executionContext, SynchronizationContext? synchronizationContext) { Completion = completion; CompletionState = completionState; ExecutionContext = executionContext; SynchronizationContext = synchronizationContext; } } public struct FlushResult { internal ResultFlags _resultFlags; public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0; public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0; public FlushResult(bool isCanceled, bool isCompleted) { _resultFlags = ResultFlags.None; if (isCanceled) { _resultFlags |= ResultFlags.Canceled; } if (isCompleted) { _resultFlags |= ResultFlags.Completed; } } } internal sealed class InlineScheduler : PipeScheduler { public override void Schedule(Action<object?> action, object? state) { action(state); } internal override void UnsafeSchedule(Action<object?> action, object? state) { action(state); } } public interface IDuplexPipe { PipeReader Input { get; } PipeWriter Output { get; } } internal struct BufferSegmentStack { private readonly struct SegmentAsValueType { private readonly BufferSegment _value; private SegmentAsValueType(BufferSegment value) { _value = value; } public static implicit operator SegmentAsValueType(BufferSegment s) { return new SegmentAsValueType(s); } public static implicit operator BufferSegment(SegmentAsValueType s) { return s._value; } } private SegmentAsValueType[] _array; private int _size; public int Count => _size; public BufferSegmentStack(int size) { _array = new SegmentAsValueType[size]; _size = 0; } public bool TryPop([NotNullWhen(true)] out BufferSegment? result) { int num = _size - 1; SegmentAsValueType[] array = _array; if ((uint)num >= (uint)array.Length) { result = null; return false; } _size = num; result = array[num]; array[num] = default(SegmentAsValueType); return true; } public void Push(BufferSegment item) { int size = _size; SegmentAsValueType[] array = _array; if ((uint)size < (uint)array.Length) { array[size] = item; _size = size + 1; } else { PushWithResize(item); } } [MethodImpl(MethodImplOptions.NoInlining)] private void PushWithResize(BufferSegment item) { Array.Resize(ref _array, 2 * _array.Length); _array[_size] = item; _size++; } } public sealed class Pipe { private sealed class DefaultPipeReader : PipeReader, IValueTaskSource<ReadResult> { private readonly Pipe _pipe; public DefaultPipeReader(Pipe pipe) { _pipe = pipe; } public override bool TryRead(out ReadResult result) { return _pipe.TryRead(out result); } public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _pipe.ReadAsync(cancellationToken); } protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumBytes, CancellationToken cancellationToken) { return _pipe.ReadAtLeastAsync(minimumBytes, cancellationToken); } public override void AdvanceTo(SequencePosition consumed) { _pipe.AdvanceReader(in consumed); } public override void AdvanceTo(SequencePosition consumed, SequencePosition examined) { _pipe.AdvanceReader(in consumed, in examined); } public override void CancelPendingRead() { _pipe.CancelPendingRead(); } public override void Complete(Exception exception = null) { _pipe.CompleteReader(exception); } public override void OnWriterCompleted(Action<Exception, object> callback, object state) { _pipe.OnWriterCompleted(callback, state); } public ValueTaskSourceStatus GetStatus(short token) { return _pipe.GetReadAsyncStatus(); } public ReadResult GetResult(short token) { return _pipe.GetReadAsyncResult(); } public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { _pipe.OnReadAsyncCompleted(continuation, state, flags); } } private sealed class DefaultPipeWriter : PipeWriter, IValueTaskSource<FlushResult> { private readonly Pipe _pipe; public override bool CanGetUnflushedBytes => true; public override long UnflushedBytes => _pipe.GetUnflushedBytes(); public DefaultPipeWriter(Pipe pipe) { _pipe = pipe; } public override void Complete(Exception exception = null) { _pipe.CompleteWriter(exception); } public override void CancelPendingFlush() { _pipe.CancelPendingFlush(); } public override void OnReaderCompleted(Action<Exception, object> callback, object state) { _pipe.OnReaderCompleted(callback, state); } public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _pipe.FlushAsync(cancellationToken); } public override void Advance(int bytes) { _pipe.Advance(bytes); } public override Memory<byte> GetMemory(int sizeHint = 0) { return _pipe.GetMemory(sizeHint); } public override Span<byte> GetSpan(int sizeHint = 0) { return _pipe.GetSpan(sizeHint); } public ValueTaskSourceStatus GetStatus(short token) { return _pipe.GetFlushAsyncStatus(); } public FlushResult GetResult(short token) { return _pipe.GetFlushAsyncResult(); } public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { _pipe.OnFlushAsyncCompleted(continuation, state, flags); } public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { return _pipe.WriteAsync(source, cancellationToken); } } private static readonly Action<object> s_signalReaderAwaitable = delegate(object state) { ((Pipe)state).ReaderCancellationRequested(); }; private static readonly Action<object> s_signalWriterAwaitable = delegate(object state) { ((Pipe)state).WriterCancellationRequested(); }; private static readonly Action<object> s_invokeCompletionCallbacks = delegate(object state) { ((PipeCompletionCallbacks)state).Execute(); }; private static readonly ContextCallback s_executionContextRawCallback = ExecuteWithoutExecutionContext; private static readonly SendOrPostCallback s_syncContextExecutionContextCallback = ExecuteWithExecutionContext; private static readonly SendOrPostCallback s_syncContextExecuteWithoutExecutionContextCallback = ExecuteWithoutExecutionContext; private static readonly Action<object> s_scheduleWithExecutionContextCallback = ExecuteWithExecutionContext; private BufferSegmentStack _bufferSegmentPool; private readonly DefaultPipeReader _reader; private readonly DefaultPipeWriter _writer; private readonly PipeOptions _options; private readonly object _sync = new object(); private long _unconsumedBytes; private long _unflushedBytes; private PipeAwaitable _readerAwaitable; private PipeAwaitable _writerAwaitable; private PipeCompletion _writerCompletion; private PipeCompletion _readerCompletion; private long _lastExaminedIndex = -1L; private BufferSegment _readHead; private int _readHeadIndex; private bool _disposed; private BufferSegment _readTail; private int _readTailIndex; private int _minimumReadBytes; private BufferSegment _writingHead; private Memory<byte> _writingHeadMemory; private int _writingHeadBytesBuffered; private PipeOperationState _operationState; private bool UseSynchronizationContext => _options.UseSynchronizationContext; private int MinimumSegmentSize => _options.MinimumSegmentSize; private long PauseWriterThreshold => _options.PauseWriterThreshold; private long ResumeWriterThreshold => _options.ResumeWriterThreshold; private PipeScheduler ReaderScheduler => _options.ReaderScheduler; private PipeScheduler WriterScheduler => _options.WriterScheduler; private object SyncObj => _sync; internal long Length => _unconsumedBytes; public PipeReader Reader => _reader; public PipeWriter Writer => _writer; public Pipe() : this(PipeOptions.Default) { } public Pipe(PipeOptions options) { if (options == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options); } _bufferSegmentPool = new BufferSegmentStack(options.InitialSegmentPoolSize); _operationState = default(PipeOperationState); _readerCompletion = default(PipeCompletion); _writerCompletion = default(PipeCompletion); _options = options; _readerAwaitable = new PipeAwaitable(completed: false, UseSynchronizationContext); _writerAwaitable = new PipeAwaitable(completed: true, UseSynchronizationContext); _reader = new DefaultPipeReader(this); _writer = new DefaultPipeWriter(this); } private void ResetState() { _readerCompletion.Reset(); _writerCompletion.Reset(); _readerAwaitable = new PipeAwaitable(completed: false, UseSynchronizationContext); _writerAwaitable = new PipeAwaitable(completed: true, UseSynchronizationContext); _readTailIndex = 0; _readHeadIndex = 0; _lastExaminedIndex = -1L; _unflushedBytes = 0L; _unconsumedBytes = 0L; } internal Memory<byte> GetMemory(int sizeHint) { if (_writerCompletion.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed(); } if (sizeHint < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint); } AllocateWriteHeadIfNeeded(sizeHint); return _writingHeadMemory; } internal Span<byte> GetSpan(int sizeHint) { if (_writerCompletion.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed(); } if (sizeHint < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint); } AllocateWriteHeadIfNeeded(sizeHint); return _writingHeadMemory.Span; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AllocateWriteHeadIfNeeded(int sizeHint) { if (!_operationState.IsWritingActive || _writingHeadMemory.Length == 0 || _writingHeadMemory.Length < sizeHint) { AllocateWriteHeadSynchronized(sizeHint); } } private void AllocateWriteHeadSynchronized(int sizeHint) { lock (SyncObj) { _operationState.BeginWrite(); if (_writingHead == null) { BufferSegment readTail = AllocateSegment(sizeHint); _writingHead = (_readHead = (_readTail = readTail)); _lastExaminedIndex = 0L; return; } int length = _writingHeadMemory.Length; if (length == 0 || length < sizeHint) { if (_writingHeadBytesBuffered > 0) { _writingHead.End += _writingHeadBytesBuffered; _writingHeadBytesBuffered = 0; } if (_writingHead.Length == 0) { _writingHead.ResetMemory(); RentMemory(_writingHead, sizeHint); } else { BufferSegment bufferSegment = AllocateSegment(sizeHint); _writingHead.SetNext(bufferSegment); _writingHead = bufferSegment; } } } } private BufferSegment AllocateSegment(int sizeHint) { BufferSegment bufferSegment = CreateSegmentUnsynchronized(); RentMemory(bufferSegment, sizeHint); return bufferSegment; } private void RentMemory(BufferSegment segment, int sizeHint) { MemoryPool<byte> memoryPool = null; int num = -1; if (!_options.IsDefaultSharedMemoryPool) { memoryPool = _options.Pool; num = memoryPool.MaxBufferSize; } if (sizeHint <= num) { segment.SetOwnedMemory(memoryPool.Rent(GetSegmentSize(sizeHint, num))); } else { int segmentSize = GetSegmentSize(sizeHint); segment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize)); } _writingHeadMemory = segment.AvailableMemory; } private int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue) { sizeHint = Math.Max(MinimumSegmentSize, sizeHint); return Math.Min(maxBufferSize, sizeHint); } private BufferSegment CreateSegmentUnsynchronized() { if (_bufferSegmentPool.TryPop(out BufferSegment result)) { return result; } return new BufferSegment(); } private void ReturnSegmentUnsynchronized(BufferSegment segment) { if (_bufferSegmentPool.Count < _options.MaxSegmentPoolSize) { _bufferSegmentPool.Push(segment); } } internal bool CommitUnsynchronized() { _operationState.EndWrite(); if (_unflushedBytes == 0L) { return false; } _writingHead.End += _writingHeadBytesBuffered; _readTail = _writingHead; _readTailIndex = _writingHead.End; long unconsumedBytes = _unconsumedBytes; _unconsumedBytes += _unflushedBytes; bool result = true; if (_unconsumedBytes < _minimumReadBytes) { result = false; } else if (PauseWriterThreshold > 0 && unconsumedBytes < PauseWriterThreshold && _unconsumedBytes >= PauseWriterThreshold && !_readerCompletion.IsCompleted) { _writerAwaitable.SetUncompleted(); } _unflushedBytes = 0L; _writingHeadBytesBuffered = 0; return result; } internal void Advance(int bytes) { lock (SyncObj) { if ((uint)bytes > (uint)_writingHeadMemory.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes); } if (!_readerCompletion.IsCompleted) { AdvanceCore(bytes); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AdvanceCore(int bytesWritten) { _unflushedBytes += bytesWritten; _writingHeadBytesBuffered += bytesWritten; _writingHeadMemory = _writingHeadMemory.Slice(bytesWritten); } internal ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken)); } CompletionData completionData; ValueTask<FlushResult> result; lock (SyncObj) { PrepareFlushUnsynchronized(out completionData, out result, cancellationToken); } TrySchedule(ReaderScheduler, in completionData); return result; } private void PrepareFlushUnsynchronized(out CompletionData completionData, out ValueTask<FlushResult> result, CancellationToken cancellationToken) { bool num = CommitUnsynchronized(); _writerAwaitable.BeginOperation(cancellationToken, s_signalWriterAwaitable, this); if (_writerAwaitable.IsCompleted) { FlushResult result2 = default(FlushResult); GetFlushResult(ref result2); result = new ValueTask<FlushResult>(result2); } else { result = new ValueTask<FlushResult>(_writer, 0); } if (num) { _readerAwaitable.Complete(out completionData); } else { completionData = default(CompletionData); } } internal void CompleteWriter(Exception? exception) { PipeCompletionCallbacks pipeCompletionCallbacks; CompletionData completionData; bool isCompleted; lock (SyncObj) { CommitUnsynchronized(); pipeCompletionCallbacks = _writerCompletion.TryComplete(exception); _readerAwaitable.Complete(out completionData); isCompleted = _readerCompletion.IsCompleted; } if (isCompleted) { CompletePipe(); } if (pipeCompletionCallbacks != null) { ScheduleCallbacks(ReaderScheduler, pipeCompletionCallbacks); } TrySchedule(ReaderScheduler, in completionData); } internal void AdvanceReader(in SequencePosition consumed) { AdvanceReader(in consumed, in consumed); } internal void AdvanceReader(in SequencePosition consumed, in SequencePosition examined) { if (_readerCompletion.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed(); } AdvanceReader((BufferSegment)consumed.GetObject(), consumed.GetInteger(), (BufferSegment)examined.GetObject(), examined.GetInteger()); } private void AdvanceReader(BufferSegment consumedSegment, int consumedIndex, BufferSegment examinedSegment, int examinedIndex) { if (consumedSegment != null && examinedSegment != null && BufferSegment.GetLength(consumedSegment, consumedIndex, examinedSegment, examinedIndex) < 0) { ThrowHelper.ThrowInvalidOperationException_InvalidExaminedOrConsumedPosition(); } BufferSegment bufferSegment = null; BufferSegment returnEnd = null; CompletionData completionData = default(CompletionData); lock (SyncObj) { bool flag = false; if (examinedSegment == _readTail) { flag = examinedIndex == _readTailIndex; } if (examinedSegment != null && _lastExaminedIndex >= 0) { long length = BufferSegment.GetLength(_lastExaminedIndex, examinedSegment, examinedIndex); long unconsumedBytes = _unconsumedBytes; if (length < 0) { ThrowHelper.ThrowInvalidOperationException_InvalidExaminedPosition(); } _unconsumedBytes -= length; _lastExaminedIndex = examinedSegment.RunningIndex + examinedIndex; if (unconsumedBytes >= ResumeWriterThreshold && _unconsumedBytes < ResumeWriterThreshold) { _writerAwaitable.Complete(out completionData); } } if (consumedSegment != null) { if (_readHead == null) { ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor(); return; } bufferSegment = _readHead; returnEnd = consumedSegment; if (consumedIndex == returnEnd.Length) { if (_writingHead != returnEnd) { MoveReturnEndToNextBlock(); } else if (_writingHeadBytesBuffered == 0 && !_operationState.IsWritingActive) { _writingHead = null; _writingHeadMemory = default(Memory<byte>); MoveReturnEndToNextBlock(); } else { _readHead = consumedSegment; _readHeadIndex = consumedIndex; } } else { _readHead = consumedSegment; _readHeadIndex = consumedIndex; } } if (flag && !_writerCompletion.IsCompleted) { _readerAwaitable.SetUncompleted(); } while (bufferSegment != null && bufferSegment != returnEnd) { BufferSegment? nextSegment = bufferSegment.NextSegment; bufferSegment.Reset(); ReturnSegmentUnsynchronized(bufferSegment); bufferSegment = nextSegment; } _operationState.EndRead(); } TrySchedule(WriterScheduler, in completionData); void MoveReturnEndToNextBlock() { BufferSegment nextSegment2 = returnEnd.NextSegment; if (_readTail == returnEnd) { _readTail = nextSegment2; _readTailIndex = 0; } _readHead = nextSegment2; _readHeadIndex = 0; returnEnd = nextSegment2; } } internal void CompleteReader(Exception? exception) { PipeCompletionCallbacks pipeCompletionCallbacks; CompletionData completionData; bool isCompleted; lock (SyncObj) { if (_operationState.IsReadingActive) { _operationState.EndRead(); } pipeCompletionCallbacks = _readerCompletion.TryComplete(exception); _writerAwaitable.Complete(out completionData); isCompleted = _writerCompletion.IsCompleted; } if (isCompleted) { CompletePipe(); } if (pipeCompletionCallbacks != null) { ScheduleCallbacks(WriterScheduler, pipeCompletionCallbacks); } TrySchedule(WriterScheduler, in completionData); } internal void OnWriterCompleted(Action<Exception?, object?> callback, object? state) { if (callback == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback); } PipeCompletionCallbacks pipeCompletionCallbacks; lock (SyncObj) { pipeCompletionCallbacks = _writerCompletion.AddCallback(callback, state); } if (pipeCompletionCallbacks != null) { ScheduleCallbacks(ReaderScheduler, pipeCompletionCallbacks); } } internal void CancelPendingRead() { CompletionData completionData; lock (SyncObj) { _readerAwaitable.Cancel(out completionData); } TrySchedule(ReaderScheduler, in completionData); } internal void CancelPendingFlush() { CompletionData completionData; lock (SyncObj) { _writerAwaitable.Cancel(out completionData); } TrySchedule(WriterScheduler, in completionData); } internal void OnReaderCompleted(Action<Exception?, object?> callback, object? state) { if (callback == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback); } PipeCompletionCallbacks pipeCompletionCallbacks; lock (SyncObj) { pipeCompletionCallbacks = _readerCompletion.AddCallback(callback, state); } if (pipeCompletionCallbacks != null) { ScheduleCallbacks(WriterScheduler, pipeCompletionCallbacks); } } internal ValueTask<ReadResult> ReadAtLeastAsync(int minimumBytes, CancellationToken token) { if (_readerCompletion.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed(); } if (token.IsCancellationRequested) { return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(token)); } CompletionData completionData = default(CompletionData); ValueTask<ReadResult> result2; lock (SyncObj) { _readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this); if (_readerAwaitable.IsCompleted) { GetReadResult(out var result); if (_unconsumedBytes >= minimumBytes || result.IsCanceled || result.IsCompleted) { return new ValueTask<ReadResult>(result); } _readerAwaitable.SetUncompleted(); _operationState.EndRead(); _readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this); } if (!_writerAwaitable.IsCompleted) { _writerAwaitable.Complete(out completionData); } _minimumReadBytes = minimumBytes; result2 = new ValueTask<ReadResult>(_reader, 0); } TrySchedule(WriterScheduler, in completionData); return result2; } internal ValueTask<ReadResult> ReadAsync(CancellationToken token) { if (_readerCompletion.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed(); } if (token.IsCancellationRequested) { return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(token)); } lock (SyncObj) { _readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this); if (_readerAwaitable.IsCompleted) { GetReadResult(out var result); return new ValueTask<ReadResult>(result); } return new ValueTask<ReadResult>(_reader, 0); } } internal bool TryRead(out ReadResult result) { lock (SyncObj) { if (_readerCompletion.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed(); } if (_unconsumedBytes > 0 || _readerAwaitable.IsCompleted) { GetReadResult(out result); return true; } if (_readerAwaitable.IsRunning) { ThrowHelper.ThrowInvalidOperationException_AlreadyReading(); } _operationState.BeginReadTentative(); result = default(ReadResult); return false; } } private static void ScheduleCallbacks(PipeScheduler scheduler, PipeCompletionCallbacks completionCallbacks) { scheduler.UnsafeSchedule(s_invokeCompletionCallbacks, completionCallbacks); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void TrySchedule(PipeScheduler scheduler, in CompletionData completionData) { Action<object> completion = completionData.Completion; if (completion != null) { if (completionData.SynchronizationContext == null && completionData.ExecutionContext == null) { scheduler.UnsafeSchedule(completion, completionData.CompletionState); } else { ScheduleWithContext(scheduler, in completionData); } } } [MethodImpl(MethodImplOptions.NoInlining)] private static void ScheduleWithContext(PipeScheduler scheduler, in CompletionData completionData) { if (completionData.SynchronizationContext == null) { scheduler.UnsafeSchedule(s_scheduleWithExecutionContextCallback, completionData); } else if (completionData.ExecutionContext == null) { completionData.SynchronizationContext.Post(s_syncContextExecuteWithoutExecutionContextCallback, completionData); } else { completionData.SynchronizationContext.Post(s_syncContextExecutionContextCallback, completionData); } } private static void ExecuteWithoutExecutionContext(object state) { CompletionData completionData = (CompletionData)state; completionData.Completion(completionData.CompletionState); } private static void ExecuteWithExecutionContext(object state) { ExecutionContext.Run(((CompletionData)state).ExecutionContext, s_executionContextRawCallback, state); } private void CompletePipe() { lock (SyncObj) { if (!_disposed) { _disposed = true; BufferSegment bufferSegment = _readHead ?? _readTail; while (bufferSegment != null) { BufferSegment bufferSegment2 = bufferSegment; bufferSegment = bufferSegment.NextSegment; bufferSegment2.Reset(); } _writingHead = null; _writingHeadMemory = default(Memory<byte>); _readHead = null; _readTail = null; _lastExaminedIndex = -1L; } } } internal ValueTaskSourceStatus GetReadAsyncStatus() { if (_readerAwaitable.IsCompleted) { if (_writerCompletion.IsFaulted) { return ValueTaskSourceStatus.Faulted; } return ValueTaskSourceStatus.Succeeded; } return ValueTaskSourceStatus.Pending; } internal void OnReadAsyncCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags) { CompletionData completionData; bool doubleCompletion; lock (SyncObj) { _readerAwaitable.OnCompleted(continuation, state, flags, out completionData, out doubleCompletion); } if (doubleCompletion) { Writer.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation()); } TrySchedule(ReaderScheduler, in completionData); } internal ReadResult GetReadAsyncResult() { CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration); CancellationToken cancellationToken = default(CancellationToken); ReadResult result; try { lock (SyncObj) { if (!_readerAwaitable.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted(); } cancellationTokenRegistration = _readerAwaitable.ReleaseCancellationTokenRegistration(out cancellationToken); GetReadResult(out result); } } finally { cancellationTokenRegistration.Dispose(); } if (result.IsCanceled) { cancellationToken.ThrowIfCancellationRequested(); } return result; } private void GetReadResult(out ReadResult result) { bool isCompleted = _writerCompletion.IsCompletedOrThrow(); bool flag = _readerAwaitable.ObserveCancellation(); BufferSegment readHead = _readHead; if (readHead != null) { ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(readHead, _readHeadIndex, _readTail, _readTailIndex); result = new ReadResult(buffer, flag, isCompleted); } else { result = new ReadResult(default(ReadOnlySequence<byte>), flag, isCompleted); } if (flag) { _operationState.BeginReadTentative(); } else { _operationState.BeginRead(); } _minimumReadBytes = 0; } internal ValueTaskSourceStatus GetFlushAsyncStatus() { if (_writerAwaitable.IsCompleted) { if (_readerCompletion.IsFaulted) { return ValueTaskSourceStatus.Faulted; } return ValueTaskSourceStatus.Succeeded; } return ValueTaskSourceStatus.Pending; } internal FlushResult GetFlushAsyncResult() { FlushResult result = default(FlushResult); CancellationToken cancellationToken = default(CancellationToken); CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration); try { lock (SyncObj) { if (!_writerAwaitable.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted(); } GetFlushResult(ref result); cancellationTokenRegistration = _writerAwaitable.ReleaseCancellationTokenRegistration(out cancellationToken); return result; } } finally { cancellationTokenRegistration.Dispose(); cancellationToken.ThrowIfCancellationRequested(); } } internal long GetUnflushedBytes() { return _unflushedBytes; } private void GetFlushResult(ref FlushResult result) { if (_writerAwaitable.ObserveCancellation()) { result._resultFlags |= ResultFlags.Canceled; } if (_readerCompletion.IsCompletedOrThrow()) { result._resultFlags |= ResultFlags.Completed; } } internal ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { if (_writerCompletion.IsCompleted) { ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed(); } if (_readerCompletion.IsCompletedOrThrow()) { return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: true)); } if (cancellationToken.IsCancellationRequested) { return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken)); } CompletionData completionData; ValueTask<FlushResult> result; lock (SyncObj) { AllocateWriteHeadIfNeeded(0); if (source.Length <= _writingHeadMemory.Length) { source.CopyTo(_writingHeadMemory); AdvanceCore(source.Length); } else { WriteMultiSegment(source.Span); } PrepareFlushUnsynchronized(out completionData, out result, cancellationToken); } TrySchedule(ReaderScheduler, in completionData); return result; } private void WriteMultiSegment(ReadOnlySpan<byte> source) { Span<byte> span = _writingHeadMemory.Span; while (true) { int num = Math.Min(span.Length, source.Length); source.Slice(0, num).CopyTo(span); source = source.Slice(num); AdvanceCore(num); if (source.Length != 0) { _writingHead.End += _writingHeadBytesBuffered; _writingHeadBytesBuffered = 0; BufferSegment bufferSegment = AllocateSegment(0); _writingHead.SetNext(bufferSegment); _writingHead = bufferSegment; span = _writingHeadMemory.Span; continue; } break; } } internal void OnFlushAsyncCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags) { CompletionData completionData; bool doubleCompletion; lock (SyncObj) { _writerAwaitable.OnCompleted(continuation, state, flags, out completionData, out doubleCompletion); } if (doubleCompletion) { Reader.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation()); } TrySchedule(WriterScheduler, in completionData); } private void ReaderCancellationRequested() { CompletionData completionData; lock (SyncObj) { _readerAwaitable.CancellationTokenFired(out completionData); } TrySchedule(ReaderScheduler, in completionData); } private void WriterCancellationRequested() { CompletionData completionData; lock (SyncObj) { _writerAwaitable.CancellationTokenFired(out completionData); } TrySchedule(WriterScheduler, in completionData); } public void Reset() { lock (SyncObj) { if (!_disposed) { ThrowHelper.ThrowInvalidOperationException_ResetIncompleteReaderWriter(); } _disposed = false; ResetState(); } } } [DebuggerDisplay("CanceledState = {_awaitableState}, IsCompleted = {IsCompleted}")] internal struct PipeAwaitable { [Flags] private enum AwaitableState { None = 0, Completed = 1, Running = 2, Canceled = 4, UseSynchronizationContext = 8 } private sealed class SchedulingContext { public SynchronizationContext SynchronizationContext { get; set; } public ExecutionContext ExecutionContext { get; set; } } private AwaitableState _awaitableState; private Action<object> _completion; private object _completionState; private SchedulingContext _schedulingContext; private CancellationTokenRegistration _cancellationTokenRegistration; private CancellationToken _cancellationToken; private CancellationToken CancellationToken => _cancellationToken; public bool IsCompleted => (_awaitableState & (AwaitableState.Completed | AwaitableState.Canceled)) != 0; public bool IsRunning => (_awaitableState & AwaitableState.Running) != 0; public PipeAwaitable(bool completed, bool useSynchronizationContext) { _awaitableState = (completed ? AwaitableState.Completed : AwaitableState.None) | (useSynchronizationContext ? AwaitableState.UseSynchronizationContext : AwaitableState.None); _completion = null; _completionState = null; _cancellationTokenRegistration = default(CancellationTokenRegistration); _schedulingContext = null; _cancellationToken = CancellationToken.None; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BeginOperation(CancellationToken cancellationToken, Action<object?> callback, object? state) { if (cancellationToken.CanBeCanceled && !IsCompleted) { _cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, callback, state); if (_cancellationTokenRegistration == default(CancellationTokenRegistration)) { cancellationToken.ThrowIfCancellationRequested(); } _cancellationToken = cancellationToken; } _awaitableState |= AwaitableState.Running; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Complete(out CompletionData completionData) { ExtractCompletion(out completionData); _awaitableState |= AwaitableState.Completed; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ExtractCompletion(out CompletionData completionData) { Action<object> completion = _completion; object completionState = _completionState; SchedulingContext schedulingContext = _schedulingContext; ExecutionContext executionContext = schedulingContext?.ExecutionContext; SynchronizationContext synchronizationContext = schedulingContext?.SynchronizationContext; _completion = null; _completionState = null; _schedulingContext = null; completionData = ((completion != null) ? new CompletionData(completion, completionState, executionContext, synchronizationContext) : default(CompletionData)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetUncompleted() { _awaitableState &= ~AwaitableState.Completed; } public void OnCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags, out CompletionData completionData, out bool doubleCompletion) { completionData = default(CompletionData); doubleCompletion = _completion != null; if (IsCompleted | doubleCompletion) { completionData = new CompletionData(continuation, state, _schedulingContext?.ExecutionContext, _schedulingContext?.SynchronizationContext); return; } _completion = continuation; _completionState = state; if ((_awaitableState & AwaitableState.UseSynchronizationContext) != 0 && (flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { SynchronizationContext current = SynchronizationContext.Current; if (current != null && current.GetType() != typeof(SynchronizationContext)) { if (_schedulingContext == null) { _schedulingContext = new SchedulingContext(); } _schedulingContext.SynchronizationContext = current; } } if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { if (_schedulingContext == null) { _schedulingContext = new SchedulingContext(); } _schedulingContext.ExecutionContext = ExecutionContext.Capture(); } } public void Cancel(out CompletionData completionData) { ExtractCompletion(out completionData); _awaitableState |= AwaitableState.Canceled; } public void CancellationTokenFired(out CompletionData completionData) { if (CancellationToken.IsCancellationRequested) { Cancel(out completionData); } else { completionData = default(CompletionData); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ObserveCancellation() { bool result = (_awaitableState & AwaitableState.Canceled) == AwaitableState.Canceled; _awaitableState &= ~(AwaitableState.Running | AwaitableState.Canceled); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public CancellationTokenRegistration ReleaseCancellationTokenRegistration(out CancellationToken cancellationToken) { cancellationToken = CancellationToken; CancellationTokenRegistration cancellationTokenRegistration = _cancellationTokenRegistration; _cancellationToken = default(CancellationToken); _cancellationTokenRegistration = default(CancellationTokenRegistration); return cancellationTokenRegistration; } } [DebuggerDisplay("IsCompleted = {IsCompleted}")] internal struct PipeCompletion { private static readonly object s_completedSuccessfully = new object(); private object _state; private List<PipeCompletionCallback> _callbacks; public bool IsCompleted => _state != null; public bool IsFaulted => _state is ExceptionDispatchInfo; public PipeCompletionCallbacks? TryComplete(Exception? exception = null) { if (_state == null) { if (exception != null) { _state = ExceptionDispatchInfo.Capture(exception); } else { _state = s_completedSuccessfully; } } return GetCallbacks(); } public PipeCompletionCallbacks? AddCallback(Action<Exception?, object?> callback, object? state) { if (_callbacks == null) { _callbacks = new List<PipeCompletionCallback>(); } _callbacks.Add(new PipeCompletionCallback(callback, state)); if (IsCompleted) { return GetCallbacks(); } return null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsCompletedOrThrow() { if (!IsCompleted) { return false; } if (_state is ExceptionDispatchInfo exceptionDispatchInfo) { exceptionDispatchInfo.Throw(); } return true; } private PipeCompletionCallbacks GetCallbacks() { List<PipeCompletionCallback> callbacks = _callbacks; if (callbacks == null) { return null; } _callbacks = null; return new PipeCompletionCallbacks(callbacks, _state as ExceptionDispatchInfo); } public void Reset() { _state = null; } public override string ToString() { return string.Format("{0}: {1}", "IsCompleted", IsCompleted); } } internal readonly struct PipeCompletionCallback { public readonly Action<Exception?, object?> Callback; public readonly object? State; public PipeCompletionCallback(Action<Exception?, object?> callback, object? state) { Callback = callback; State = state; } } internal sealed class PipeCompletionCallbacks { private readonly List<PipeCompletionCallback> _callbacks; private readonly Exception _exception; public PipeCompletionCallbacks(List<PipeCompletionCallback> callbacks, ExceptionDispatchInfo? edi) { _callbacks = callbacks; _exception = edi?.SourceException; } public void Execute() { int count = _callbacks.Count; if (count != 0) { List<Exception> exceptions = null; for (int i = 0; i < count; i++) { PipeCompletionCallback callback = _callbacks[i]; Execute(callback, ref exceptions); } if (exceptions != null) { throw new AggregateException(exceptions); } } } private void Execute(PipeCompletionCallback callback, ref List<Exception> exceptions) { try { callback.Callback(_exception, callback.State); } catch (Exception item) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(item); } } } public class PipeOptions { private const int DefaultMinimumSegmentSize = 4096; public static PipeOptions Default { get; } = new PipeOptions(null, null, null, -1L, -1L); public bool UseSynchronizationContext { get; } public long PauseWriterThreshold { get; } public long ResumeWriterThreshold { get; } public int MinimumSegmentSize { get; } public PipeScheduler WriterScheduler { get; } public PipeScheduler ReaderScheduler { get; } public MemoryPool<byte> Pool { get; } internal bool IsDefaultSharedMemoryPool { get; } internal int InitialSegmentPoolSize { get; } internal int MaxSegmentPoolSize { get; } public PipeOptions(MemoryPool<byte>? pool = null, PipeScheduler? readerScheduler = null, PipeScheduler? writerScheduler = null, long pauseWriterThreshold = -1L, long resumeWriterThreshold = -1L, int minimumSegmentSize = -1, bool useSynchronizationContext = true) { MinimumSegmentSize = ((minimumSegmentSize == -1) ? 4096 : minimumSegmentSize); InitialSegmentPoolSize = 4; MaxSegmentPoolSize = 256; if (pauseWriterThreshold == -1) { pauseWriterThreshold = 65536L; } else if (pauseWriterThreshold < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.pauseWriterThreshold); } switch (resumeWriterThreshold) { case -1L: resumeWriterThreshold = 32768L; break; case 0L: resumeWriterThreshold = 1L; break; } if (resumeWriterThreshold < 0 || (pauseWriterThreshold > 0 && resumeWriterThreshold > pauseWriterThreshold)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.resumeWriterThreshold); } Pool = pool ?? MemoryPool<byte>.Shared; IsDefaultSharedMemoryPool = Pool == MemoryPool<byte>.Shared; ReaderScheduler = readerScheduler ?? PipeScheduler.ThreadPool; WriterScheduler = writerScheduler ?? PipeScheduler.ThreadPool; PauseWriterThreshold = pauseWriterThreshold; ResumeWriterThreshold = resumeWriterThreshold; UseSynchronizationContext = useSynchronizationContext; } } public abstract class PipeReader { private PipeReaderStream _stream; public abstract bool TryRead(out ReadResult result); public abstract ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)); public ValueTask<ReadResult> ReadAtLeastAsync(int minimumSize, CancellationToken cancellationToken = default(CancellationToken)) { if (minimumSize < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.minimumSize); } return ReadAtLeastAsyncCore(minimumSize, cancellationToken); } protected virtual async ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken) { ReadResult result; while (true) { result = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); ReadOnlySequence<byte> buffer = result.Buffer; if (buffer.Length >= minimumSize || result.IsCompleted || result.IsCanceled) { break; } AdvanceTo(buffer.Start, buffer.End); } return result; } public abstract void AdvanceTo(SequencePosition consumed); public abstract void AdvanceTo(SequencePosition consumed, SequencePosition examined); public virtual Stream AsStream(bool leaveOpen = false) { if (_stream == null) { _stream = new PipeReaderStream(this, leaveOpen); } else if (leaveOpen) { _stream.LeaveOpen = leaveOpen; } return _stream; } public abstract void CancelPendingRead(); public abstract void Complete(Exception? exception = null); public virtual ValueTask CompleteAsync(Exception? exception = null) { try { Complete(exception); return default(ValueTask); } catch (Exception exception2) { return new ValueTask(Task.FromException(exception2)); } } [Obsolete("OnWriterCompleted has been deprecated and may not be invoked on all implementations of PipeReader.")] public virtual void OnWriterCompleted(Action<Exception?, object?> callback, object? state) { } public static PipeReader Create(Stream stream, StreamPipeReaderOptions? readerOptions = null) { return new StreamPipeReader(stream, readerOptions ?? StreamPipeReaderOptions.s_default); } public static PipeReader Create(ReadOnlySequence<byte> sequence) { return new SequencePipeReader(sequence); } public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken)) { if (destination == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } return CopyToAsyncCore(destination, (PipeWriter destination, ReadOnlyMemory<byte> memory, CancellationToken cancellationToken) => destination.WriteAsync(memory, cancellationToken), cancellationToken); } public virtual Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken)) { if (destination == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } return CopyToAsyncCore(destination, delegate(Stream destination, ReadOnlyMemory<byte> memory, CancellationToken cancellationToken) { ValueTask writeTask2 = StreamExtensions.WriteAsync(destination, memory, cancellationToken); if (writeTask2.IsCompletedSuccessfully) { writeTask2.GetAwaiter().GetResult(); return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: false)); } return Awaited(writeTask2); }, cancellationToken); static async ValueTask<FlushResult> Awaited(ValueTask writeTask) { await writeTask.ConfigureAwait(continueOnCapturedContext: false); return new FlushResult(isCanceled: false, isCompleted: false); } } private async Task CopyToAsyncCore<TStream>(TStream destination, Func<TStream, ReadOnlyMemory<byte>, CancellationToken, ValueTask<FlushResult>> writeAsync, CancellationToken cancellationToken) { while (true) { ReadResult result = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); ReadOnlySequence<byte> buffer = result.Buffer; SequencePosition position = buffer.Start; SequencePosition consumed = position; try { if (result.IsCanceled) { ThrowHelper.ThrowOperationCanceledException_ReadCanceled(); } ReadOnlyMemory<byte> memory; while (buffer.TryGet(ref position, out memory)) { if (memory.IsEmpty) { consumed = position; continue; } FlushResult flushResult = await writeAsync(destination, memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (flushResult.IsCanceled) { ThrowHelper.ThrowOperationCanceledException_FlushCanceled(); } consumed = position; if (!flushResult.IsCompleted) { continue; } return; } consumed = buffer.End; if (result.IsCompleted) { break; } } finally { AdvanceTo(consumed); } } } } [DebuggerDisplay("State = {_state}")] internal struct PipeOperationState { [Flags] internal enum State : byte { Reading = 1, ReadingTentative = 2, Writing = 4 } private State _state; public bool IsWritingActive => (_state & State.Writing) == State.Writing; public bool IsReadingActive => (_state & State.Reading) == State.Reading; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BeginRead() { if ((_state & State.Reading) == State.Reading) { ThrowHelper.ThrowInvalidOperationException_AlreadyReading(); } _state |= State.Reading; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BeginReadTentative() { if ((_state & State.Reading) == State.Reading) { ThrowHelper.ThrowInvalidOperationException_AlreadyReading(); } _state |= State.ReadingTentative; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void EndRead() { if ((_state & State.Reading) != State.Reading && (_state & State.ReadingTentative) != State.ReadingTentative) { ThrowHelper.ThrowInvalidOperationException_NoReadToComplete(); } _state &= ~(State.Reading | State.ReadingTentative); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void BeginWrite() { _state |= State.Writing; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void EndWrite() { _state &= ~State.Writing; } } internal sealed class PipeReaderStream : Stream { private readonly PipeReader _pipeReader; public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } internal bool LeaveOpen { get; set; } public PipeReaderStream(PipeReader pipeReader, bool leaveOpen) { _pipeReader = pipeReader; LeaveOpen = leaveOpen; } protected override void Dispose(bool disposing) { if (!LeaveOpen) { _pipeReader.Complete(); } base.Dispose(disposing); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); } return ReadInternal(new Span<byte>(buffer, offset, count)); } public override int ReadByte() { Span<byte> buffer = stackalloc byte[1]; if (ReadInternal(buffer) != 0) { return buffer[0]; } return -1; } private int ReadInternal(Span<byte> buffer) { ValueTask<ReadResult> valueTask = _pipeReader.ReadAsync(); ReadResult result = (valueTask.IsCompletedSuccessfully ? valueTask.Result : valueTask.AsTask().GetAwaiter().GetResult()); return HandleReadResult(result, buffer); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public sealed override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) { return TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count, default(CancellationToken)), callback, state); } public sealed override int EndRead(IAsyncResult asyncResult) { return TaskToAsyncResult.End<int>(asyncResult); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); } return ReadAsyncInternal(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); } private async ValueTask<int> ReadAsyncInternal(Memory<byte> buffer, CancellationToken cancellationToken) { return HandleReadResult(await _pipeReader.ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false), buffer.Span); } private int HandleReadResult(ReadResult result, Span<byte> buffer) { if (result.IsCanceled) { ThrowHelper.ThrowOperationCanceledException_ReadCanceled(); } ReadOnlySequence<byte> buffer2 = result.Buffer; long length = buffer2.Length; SequencePosition consumed = buffer2.Start; try { if (length != 0L) { int num = (int)Math.Min(length, buffer.Length); ReadOnlySequence<byte> source = ((num == length) ? buffer2 : buffer2.Slice(0, num)); consumed = source.End; source.CopyTo(buffer); return num; } if (result.IsCompleted) { return 0; } } finally { _pipeReader.AdvanceTo(consumed); } ThrowHelper.ThrowInvalidOperationException_InvalidZeroByteRead(); return 0; } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); return _pipeReader.CopyToAsync(destination, cancellationToken); } } public abstract class PipeScheduler { private static readonly ThreadPoolScheduler s_threadPoolScheduler = new ThreadPoolScheduler(); private static readonly InlineScheduler s_inlineScheduler = new InlineScheduler(); public static PipeScheduler ThreadPool => s_threadPoolScheduler; public static PipeScheduler Inline => s_inlineScheduler; public abstract void Schedule(Action<object?> action, object? state); internal virtual void UnsafeSchedule(Action<object?> action, object? state) { Schedule(action, state); } } public abstract class PipeWriter : IBufferWriter<byte> { private PipeWriterStream _stream; public virtual bool CanGetUnflushedBytes => false; public virtual long UnflushedBytes { get { throw ThrowHelper.CreateNotSupportedException_UnflushedBytes(); } } public abstract void Complete(Exception? exception = null); public virtual ValueTask CompleteAsync(Exception? exception = null) { try { Complete(exception); return default(ValueTask); } catch (Exception exception2) { return new ValueTask(Task.FromException(exception2)); } } public abstract void CancelPendingFlush(); [Obsolete("OnReaderCompleted has been deprecated and may not be invoked on all implementations of PipeWriter.")] public virtual void OnReaderCompleted(Action<Exception?, object?> callback, object? state) { } public abstract ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken)); public abstract void Advance(int bytes); public abstract Memory<byte> GetMemory(int sizeHint = 0); public abstract Span<byte> GetSpan(int sizeHint = 0); public virtual Stream AsStream(bool leaveOpen = false) { if (_stream == null) { _stream = new PipeWriterStream(this, leaveOpen); } else if (leaveOpen) { _stream.LeaveOpen = leaveOpen; } return _stream; } public static PipeWriter Create(Stream stream, StreamPipeWriterOptions? writerOptions = null) { return new StreamPipeWriter(stream, writerOptions ?? StreamPipeWriterOptions.s_default); } public virtual ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { this.Write(source.Span); return FlushAsync(cancellationToken); } protected internal virtual async Task CopyFromAsync(Stream source, CancellationToken cancellationToken = default(CancellationToken)) { FlushResult flushResult; do { Memory<byte> memory = GetMemory(); int num = await StreamExtensions.ReadAsync(source, memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (num != 0) { Advance(num); flushResult = await FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (flushResult.IsCanceled) { ThrowHelper.ThrowOperationCanceledException_FlushCanceled(); } continue; } break; } while (!flushResult.IsCompleted); } } internal sealed class PipeWriterStream : Stream { private readonly PipeWriter _pipeWriter; internal bool LeaveOpen { get; set; } public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public PipeWriterStream(PipeWriter pipeWriter, bool leaveOpen) { _pipeWriter = pipeWriter; LeaveOpen = leaveOpen; } protected override void Dispose(bool disposing) { if (!LeaveOpen) { _pipeWriter.Complete(); } } public override void Flush() { FlushAsync().GetAwaiter().GetResult(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public sealed override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) { return TaskToAsyncResult.Begin(WriteAsync(buffer, offset, count, default(CancellationToken)), callback, state); } public sealed override void EndWrite(IAsyncResult asyncResult) { TaskToAsyncResult.End(asyncResult); } public override void Write(byte[] buffer, int offset, int count) { WriteAsync(buffer, offset, count).GetAwaiter().GetResult(); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); } return GetFlushResultAsTask(_pipeWriter.WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken)); } public override Task FlushAsync(CancellationToken cancellationToken) { return GetFlushResultAsTask(_pipeWriter.FlushAsync(cancellationToken)); } private static Task GetFlushResultAsTask(ValueTask<FlushResult> valueTask) { if (valueTask.IsCompletedSuccessfully) { if (valueTask.Result.IsCanceled) { ThrowHelper.ThrowOperationCanceledException_FlushCanceled(); } return Task.CompletedTask; } return AwaitTask(valueTask); static async Task AwaitTask(ValueTask<FlushResult> valueTask) { if ((await valueTask.ConfigureAwait(continueOnCapturedContext: false)).IsCanceled) { ThrowHelper.ThrowOperationCanceledException_FlushCanceled(); } } } } public readonly struct ReadResult { internal readonly ReadOnlySequence<byte> _resultBuffer; internal readonly ResultFlags _resultFlags; public ReadOnlySequence<byte> Buffer => _resultBuffer; public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0; public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0; public ReadResult(ReadOnlySequence<byte> buffer, bool isCanceled, bool isCompleted) { _resultBuffer = buffer; _resultFlags = ResultFlags.None; if (isCompleted) { _resultFlags |= ResultFlags.Completed; } if (isCanceled) { _resultFlags |= ResultFlags.Canceled; } } } [Flags] internal enum ResultFlags : byte { None = 0, Canceled = 1, Completed = 2 } internal sealed class SequencePipeReader : PipeReader { private ReadOnlySequence<byte> _sequence; private bool _isReaderCompleted; private int _cancelNext; public SequencePipeReader(ReadOnlySequence<byte> sequence) { _sequence = sequence; } public override void AdvanceTo(SequencePosition consumed) { AdvanceTo(consumed, consumed); } public override void AdvanceTo(SequencePosition consumed, SequencePosition examined) { ThrowIfCompleted(); if (consumed.Equals(_sequence.End)) { _sequence = ReadOnlySequence<byte>.Empty; } else { _sequence = _sequence.Slice(consumed); } } public override void CancelPendingRead() { Interlocked.Exchange(ref _cancelNext, 1); } public override void Complete(Exception? exception = null) { if (!_isReaderCompleted) { _isReaderCompleted = true; _sequence = ReadOnlySequence<byte>.Empty; } } public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (TryRead(out var result)) { return new ValueTask<ReadResult>(result); } result = new ReadResult(ReadOnlySequence<byte>.Empty, isCanceled: false, isCompleted: true); return new ValueTask<ReadResult>(result); } public override bool TryRead(out ReadResult result) { ThrowIfCompleted(); bool flag = Interlocked.Exchange(ref _cancelNext, 0) == 1; if (flag || _sequence.Length > 0) { result = new ReadResult(_sequence, flag, isCompleted: true); return true; } result = default(ReadResult); return false; } private void ThrowIfCompleted() { if (_isReaderCompleted) { ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed(); } } } public static class StreamPipeExtensions { public static Task CopyToAsync(this Stream source, PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken)) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (destination == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } return destination.CopyFromAsync(source, cancellationToken); } } internal sealed class StreamPipeReader : PipeReader { internal const int InitialSegmentPoolSize = 4; internal const int MaxSegmentPoolSize = 256; private CancellationTokenSource _internalTokenSource; private bool _isReaderCompleted; private bool _isStreamCompleted; private BufferSegment _readHead; private int _readIndex; private BufferSegment _readTail; private long _bufferedBytes; private bool _examinedEverything; private readonly object _lock = new object(); private BufferSegmentStack _bufferSegmentPool; private readonly StreamPipeReaderOptions _options; private bool LeaveOpen => _options.LeaveOpen; private bool UseZeroByteReads => _options.UseZeroByteReads; private int BufferSize => _options.BufferSize; private int MaxBufferSize => _options.MaxBufferSize; private int MinimumReadThreshold => _options.MinimumReadSize; private MemoryPool<byte> Pool => _options.Pool; public Stream InnerStream { get; } private CancellationTokenSource InternalTokenSource { get { lock (_lock) { return _internalTokenSource ?? (_internalTokenSource = new CancellationTokenSource()); } } } public StreamPipeReader(Stream readingStream, StreamPipeReaderOptions options) { if (readingStream == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.readingStream); } if (options == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options); } InnerStream = readingStream; _options = options; _bufferSegmentPool = new BufferSegmentStack(4); } public override void AdvanceTo(SequencePosition consumed) { AdvanceTo(consumed, consumed); } public override void AdvanceTo(SequencePosition consumed, SequencePosition examined) { ThrowIfCompleted(); AdvanceTo((BufferSegment)consumed.GetObject(), consumed.GetInteger(), (BufferSegment)examined.GetObject(), examined.GetInteger()); } private void AdvanceTo(BufferSegment consumedSegment, int consumedIndex, BufferSegment examinedSegment, int examinedIndex) { if (consumedSegment != null && examinedSegment != null) { if (_readHead == null) { ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor(); } BufferSegment bufferSegment = _readHead; BufferSegment bufferSegment2 = consumedSegment; long length = BufferSegment.GetLength(bufferSegment, _readIndex, consumedSegment, consumedIndex); _bufferedBytes -= length; _examinedEverything = false; if (examinedSegment == _readTail) { _examinedEverything = examinedIndex == _readTail.End; } if (_bufferedBytes == 0L) { bufferSegment2 = null; _readHead = null; _readTail = null; _readIndex = 0; } else if (consumedIndex == bufferSegment2.Length) { BufferSegment bufferSegment3 = (_readHead = bufferSegment2.NextSegment); _readIndex = 0; bufferSegment2 = bufferSegment3; } else { _readHead = consumedSegment; _readIndex = consumedIndex; } while (bufferSegment != bufferSegment2) { BufferSegment? nextSegment = bufferSegment.NextSegment; ReturnSegmentUnsynchronized(bufferSegment); bufferSegment = nextSegment; } } } public override void CancelPendingRead() { InternalTokenSource.Cancel(); } public override void Complete(Exception? exception = null) { if (CompleteAndGetNeedsDispose()) { InnerStream.Dispose(); } } private bool CompleteAndGetNeedsDispose() { if (_isReaderCompleted) { return false; } _isReaderCompleted = true; BufferSegment bufferSegment = _readHead; while (bufferSegment != null) { BufferSegment bufferSegment2 = bufferSegment; bufferSegment = bufferSegment.NextSegment; bufferSegment2.Reset(); } return !LeaveOpen; } public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return ReadInternalAsync(null, cancellationToken); } protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken) { return ReadInternalAsync(minimumSize, cancellationToken); } private ValueTask<ReadResult> ReadInternalAsync(int? minimumSize, CancellationToken cancellationToken) { ThrowIfCompleted(); if (cancellationToken.IsCancellationRequested) { return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(cancellationToken)); } CancellationTokenSource internalTokenSource = InternalTokenSource; if (TryReadInternal(internalTokenSource, out var result) && (!minimumSize.HasValue || result.Buffer.Length >= minimumSize || result.IsCompleted || result.IsCanceled)) { return new ValueTask<ReadResult>(result); } if (_isStreamCompleted) { return new ValueTask<ReadResult>(new ReadResult(default(ReadOnlySequence<byte>), isCanceled: false, isCompleted: true)); } return Core(this, minimumSize, internalTokenSource, cancellationToken); static async ValueTask<ReadResult> Core(StreamPipeReader reader, int? minimumSize, CancellationTokenSource tokenSource, CancellationToken cancellationToken) { CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration); if (cancellationToken.CanBeCanceled) { cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state) { ((StreamPipeReader)state).Cancel(); }, reader); } using (cancellationTokenRegistration) { bool isCanceled = false; try { if (reader.UseZeroByteReads && reader._bufferedBytes == 0L) { await StreamExtensions.ReadAsync(reader.InnerStream, Memory<byte>.Empty, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false); } do { reader.AllocateReadTail(minimumSize); Memory<byte> buffer = reader._readTail.AvailableMemory.Slice(reader._readTail.End); int num = await StreamExtensions.ReadAsync(reader.InnerStream, buffer, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false); reader._readTail.End += num; reader._bufferedBytes += num; if (num == 0) { reader._isStreamCompleted = true; break; } } while (minimumSize.HasValue && reader._bufferedBytes < minimumSize); } catch (OperationCanceledException ex) { reader.ClearCancellationToken(); if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(ex.Message, ex, cancellationToken); } if (!tokenSource.IsCancellationRequested) { throw; } isCanceled = true; } return new ReadResult(reader.GetCurrentReadOnlySequence(), isCanceled, reader._isStreamCompleted); } } } public override async Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfCompleted(); CancellationTokenSource tokenSource = InternalTokenSource; if (tokenSource.IsCancellationRequested) { ThrowHelper.ThrowOperationCanceledException_ReadCanceled(); } CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration); if (cancellationToken.CanBeCanceled) { cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state) { ((StreamPipeReader)state).Cancel(); }, this); } using (cancellationTokenRegistration) { _ = 1; try { BufferSegment segment = _readHead; int start = _readIndex; try { while (segment != null) { FlushResult flushResult = await destination.WriteAsync(segment.Memory.Slice(start), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false); if (flushResult.IsCanceled) { ThrowHelper.ThrowOperationCanceledException_FlushCanceled(); } segment = segment.NextSegment; start = 0; if (flushResult.IsCompleted) { return; } } } finally { if (segment != null) { AdvanceTo(segment, segment.End, segment, segment.End); } } if (_isStreamCompleted) { return; } await InnerStream.CopyToAsync(destination, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException) { ClearCancellationToken(); throw; } } } public override async Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfCompleted(); CancellationTokenSource tokenSource = InternalTokenSource; if (tokenSource.IsCancellationRequested) { ThrowHelper.ThrowOperationCanceledException_ReadCanceled(); } CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration); if (cancellationToken.CanBeCanceled) { cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state) { ((StreamPipeReader)state).Cancel(); }, this); } using (cancellationTokenRegistration) { _ = 1; try { BufferSegment segment = _readHead; int start = _readIndex; try { while (segment != null) { await StreamExtensions.WriteAsync(destination, segment.Memory.Slice(start), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false); segment = segment.NextSegment; start = 0; } } finally { if (segment != null) { AdvanceTo(segment, segment.End, segment, segment.End); } } if (_isStreamCompleted) { return; } await StreamExtensions.CopyToAsync(InnerStream, destination, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false); } catch (OperationCanceledException) { ClearCancellationToken(); throw; } } } private void ClearCancellationToken() { lock (_lock) { _internalTokenSource = null; } } private void ThrowIfCompleted() { if (_isReaderCompleted) { ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed(); } } public override bool TryRead(out ReadResult result) { ThrowIfCompleted(); return TryReadInternal(InternalTokenSource, out result); } private bool TryReadInternal(CancellationTokenSource source, out ReadResult result) { bool isCancellationRequested = source.IsCancellationRequested; if (isCancellationRequested || (_bufferedBytes > 0 && (!_examinedEverything || _isStreamCompleted))) { if (isCancellationRequested) { ClearCancellationToken(); } ReadOnlySequence<byte> currentReadOnlySequence = GetCurrentReadOnlySequence(); result = new ReadResult(currentReadOnlySequence, isCancellationRequested, _isStreamCompleted); return true; } result = default(ReadResult); return false; } private ReadOnlySequence<byte> GetCurrentReadOnlySequence() { if (_readHead != null) { return new ReadOnlySequence<byte>(_readHead, _readIndex, _readTail, _readTail.End); } return default(ReadOnlySequence<byte>); } private void AllocateReadTail(int? minimumSize = null) { if (_readHead == null) { _readHead = AllocateSegment(minimumSize); _readTail = _readHead; } else if (_readTail.WritableBytes < MinimumReadThreshold) { BufferSegment bufferSegment = AllocateSegment(minimumSize); _readTail.SetNext(bufferSegment); _readTail = bufferSegment; } } private BufferSegment AllocateSegment(int? minimumSize = null) { BufferSegment bufferSegment = CreateSegmentUnsynchronized(); int num = minimumSize ?? BufferSize; int num2 = ((!_options.IsDefaultSharedMemoryPool) ? _options.Pool.MaxBufferSize : (-1)); if (num <= num2) { int segmentSize = GetSegmentSize(num, num2); bufferSegment.SetOwnedMemory(_options.Pool.Rent(segmentSize)); } else { int segmentSize2 = GetSegmentSize(num, MaxBufferSize); bufferSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize2)); } return bufferSegment; } private int GetSegmentSize(int sizeHint, int maxBufferSize) { sizeHint = Math.Max(BufferSize, sizeHint); return Math.Min(maxBufferSize, sizeHint); } private BufferSegment CreateSegmentUnsynchronized() { if (_bufferSegmentPool.TryPop(out BufferSegment result)) { return result; } return new BufferSegment(); } private void ReturnSegmentUnsynchronized(BufferSegment segment) { segment.Reset(); if (_bufferSegmentPool.Count < 256) { _bufferSegmentPool.Push(segment); } } private void Cancel() { InternalTokenSource.Cancel(); } } public class StreamPipeReaderOptions { private const int DefaultBufferSize = 4096; internal const int DefaultMaxBufferSize = 2097152; private const int DefaultMinimumReadSize = 1024; internal static readonly StreamPipeReaderOptions s_default = new StreamPipeReaderOptions(); public int BufferSize { get; } internal int MaxBufferSize { get; } = 2097152; public int MinimumReadSize { get; } public MemoryPool<byte> Pool { get; } public bool LeaveOpen { get; } public bool UseZeroByteReads { get; } internal bool IsDefaultSharedMemoryPool { get; } public StreamPipeReaderOptions(MemoryPool<byte>? pool, int bufferSize, int minimumReadSize, bool leaveOpen) : this(pool, bufferSize, minimumReadSize, leaveOpen, useZeroByteReads: false) { } public StreamPipeReaderOptions(MemoryPool<byte>? pool = null, int bufferSize = -1, int minimumReadSize = -1, bool leaveOpen = false, bool useZeroByteReads = false) { Pool = pool ?? MemoryPool<byte>.Shared; IsDefaultSharedMemoryPool = Pool == MemoryPool<byte>.Shared; int num; if (bufferSize != -1) { if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } num = bufferSize; } else { num = 4096; } BufferSize = num; int num2; if (minimumReadSize != -1) { if (minimumReadSize <= 0) { throw new ArgumentOutOfRangeException("minimumReadSize"); } num2 = minimumReadSize; } else { num2 = 1024; } MinimumReadSize = num2; LeaveOpen = leaveOpen; UseZeroByteReads = useZeroByteReads; } } internal sealed class StreamPipeWriter : PipeWriter { internal const int InitialSegmentPoolSize = 4; internal const int MaxSegmentPoolSize = 256; private readonly int _minimumBufferSize; private BufferSegment _head; private BufferSegment _tail; private Memory<byte> _tailMemory; private int _tailBytesBuffered; private int _bytesBuffered; private readonly MemoryPool<byte> _pool; private readonly int _maxPooledBufferSize; private CancellationTokenSource _internalTokenSource; private bool _isCompleted; private readonly object _lockObject = new object(); private BufferSegmentStack _bufferSegmentPool; private readonly bool _leaveOpen; private CancellationTokenSource InternalTokenSource { get { lock (_lockObject) { return _internalTokenSource ?? (_internalTokenSource = new CancellationTokenSource()); } } } public Stream InnerStream { get; } public override bool CanGetUnflushedBytes => true; public override long UnflushedBytes => _bytesBuffered; public StreamPipeWriter(Stream writingStream, StreamPipeWriterOptions options) { if (writingStream == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.writingStream); } if (options == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options); } InnerStream = writingStream; _minimumBufferSize = options.MinimumBufferSize; _pool = ((options.Pool == MemoryPool<byte>.Shared) ? null : options.Pool); _maxPooledBufferSize = _pool?.MaxBufferSize ?? (-1); _bufferSegmentPool = new BufferSegmentStack(4); _leaveOpen = options.LeaveOpen; } public override void Advance(int bytes) { if ((uint)bytes > (uint)_tailMemory.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes); } _tailBytesBuffered += bytes; _bytesBuffered += bytes; _tailMemory = _tailMemory.Slice(bytes); } public override Memory<byte> GetMemory(int sizeHint = 0) { if (_isCompleted) { ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed(); } if (sizeHint < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint); } AllocateMemory(sizeHint); return _tailMemory; } public override Span<byte> GetSpan(int sizeHint = 0) { if (_isCompleted) { ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed(); } if (sizeHint < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint); } AllocateMemory(sizeHint); return _tailMemory.Span; } private void AllocateMemory(int sizeHint) { if (_head == null) { BufferSegment tail = AllocateSegment(sizeHint); _head = (_tail = tail); _tailBytesBuffered = 0; return; } int length = _tailMemory.Length; if (length == 0 || length < sizeHint) { if (_tailBytesBuffered > 0) { _tail.End += _tailBytesBuffered; _tailBytesBuffered = 0; } BufferSegment bufferSegment = AllocateSegment(sizeHint); _tail.SetNext(bufferSegment); _tail = bufferSegment; } } private BufferSegment AllocateSegment(int sizeHint) { BufferSegment bufferSegment = CreateSegmentUnsynchronized(); int maxPooledBufferSize = _maxPooledBufferSize; if (sizeHint <= maxPooledBufferSize) { bufferSegment.SetOwnedMemory(_pool.Rent(GetSegmentSize(sizeHint, maxPooledBufferSize))); } else { int segmentSize = GetSegmentSize(sizeHint); bufferSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize)); } _tailMemory = bufferSegment.AvailableMemory; return bufferSegment; } private int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue) { sizeHint = Math.Max(_minimumBufferSize, sizeHint); return Math.Min(maxBufferSize, sizeHint); } private BufferSegment CreateSegmentUnsynchronized() { if (_bufferSegmentPool.TryPop(out BufferSegment result)) { return result; } return new BufferSegment(); } private void ReturnSegmentUnsynchronized(BufferSegment segment) { segment.Reset(); if (_bufferSegmentPool.Count < 256) { _bufferSegmentPool.Push(segment); } } public override void CancelPendingFlush() { Cancel(); } public override void Complete(Exception? exception = null) { if (_isCompleted) { return; } _isCompleted = true; try { FlushInternal(exception == null); } finally { _internalTokenSource?.Dispose(); if (!_leaveOpen) { InnerStream.Dispose(); } } } public override async ValueTask CompleteAsync(Exception? exception = null) { if (_isCompleted) { return; } _isCompleted = true; try { await FlushAsyncInternal(exception == null, Memory<byte>.Empty).ConfigureAwait(continueOnCapturedContext: false); } finally { _internalTokenSource?.Dispose(); if (!_leaveOpen) { InnerStream.Dispose(); } } } public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (_bytesBuffered == 0) { return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: false)); } return FlushAsyncInternal(writeToStream: true, Memory<byte>.Empty, cancellationToken); } public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { return FlushAsyncInternal(writeToStream: true, source, cancellationToken); } private void Cancel() { InternalTokenSource.Cancel(); } private async ValueTask<FlushResult> FlushAsyncInternal(bool writeToStream, ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default(CancellationToken)) { CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration); if (cancellationToken.CanBeCanceled) { cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state) { ((StreamPipeWriter)state).Cancel(); }, this); } if (_tailBytesBuffered > 0) { _tail.End += _tailBytesBuffered; _tailBytesBuffered = 0; } using (cancellationTokenRegistration) { CancellationToken localToken = InternalTokenSource.Token; try { BufferSegment segment = _head; while (segment != null) { BufferSegment returnSegment = segment; segment = segment.NextSegment; if (returnSegment.Length > 0 && writeToStream) { await StreamExtensions.WriteAsync(InnerStream, returnSegment.Memory, localToken).ConfigureAwait(continueOnCapturedContext: false); } ReturnSegmentUnsynchronized(returnSegment); _head = segment; } if (writeToStream) { if (data.Length > 0) { await StreamExtensions.WriteAsync(InnerStream, data, localToken).ConfigureAwait(continueOnCapturedContext: false); } if (_bytesBuffered > 0 || data.Length > 0) { await InnerStream.FlushAsync(localToken).ConfigureAwait(continueOnCapturedContext: false); } } _head = null; _tail = null; _tailMemory =
deps/System.Numerics.Vectors.dll
Decompiled a day agousing System; using System.Diagnostics; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Numerics.Vectors.dll")] [assembly: AssemblyDescription("System.Numerics.Vectors.dll")] [assembly: AssemblyDefaultAlias("System.Numerics.Vectors.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: SecurityCritical] [assembly: ComVisible(false)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [assembly: TypeForwardedTo(typeof(Matrix3x2))] [assembly: TypeForwardedTo(typeof(Matrix4x4))] [assembly: TypeForwardedTo(typeof(Plane))] [assembly: TypeForwardedTo(typeof(Quaternion))] [assembly: TypeForwardedTo(typeof(Vector))] [assembly: TypeForwardedTo(typeof(Vector<>))] [assembly: TypeForwardedTo(typeof(Vector2))] [assembly: TypeForwardedTo(typeof(Vector3))] [assembly: TypeForwardedTo(typeof(Vector4))] [module: UnverifiableCode] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; }
deps/System.Reflection.Metadata.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Configuration.Assemblies; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using FxResources.System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("System.Reflection.Metadata.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Reflection.Metadata")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("This package provides a low-level .NET (ECMA-335) metadata reader and writer. It's geared for performance and is the ideal choice for building higher-level libraries that intend to provide their own object model, such as compilers. The metadata format is defined by the ECMA-335 - Common Language Infrastructure (CLI) specification.\r\n\r\nThe System.Reflection.Metadata library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] [assembly: AssemblyFileVersion("9.0.24.52809")] [assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Reflection.Metadata")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("9.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] 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] internal sealed class IsByRefLikeAttribute : 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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [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; } } } internal static class Interop { internal static class Libraries { internal const string Activeds = "activeds.dll"; internal const string Advapi32 = "advapi32.dll"; internal const string Authz = "authz.dll"; internal const string BCrypt = "BCrypt.dll"; internal const string Credui = "credui.dll"; internal const string Crypt32 = "crypt32.dll"; internal const string CryptUI = "cryptui.dll"; internal const string Dsrole = "dsrole.dll"; internal const string Gdi32 = "gdi32.dll"; internal const string HttpApi = "httpapi.dll"; internal const string IpHlpApi = "iphlpapi.dll"; internal const string Kernel32 = "kernel32.dll"; internal const string Logoncli = "logoncli.dll"; internal const string Mswsock = "mswsock.dll"; internal const string NCrypt = "ncrypt.dll"; internal const string Netapi32 = "netapi32.dll"; internal const string Netutils = "netutils.dll"; internal const string NtDll = "ntdll.dll"; internal const string Odbc32 = "odbc32.dll"; internal const string Ole32 = "ole32.dll"; internal const string OleAut32 = "oleaut32.dll"; internal const string Pdh = "pdh.dll"; internal const string Secur32 = "secur32.dll"; internal const string Shell32 = "shell32.dll"; internal const string SspiCli = "sspicli.dll"; internal const string User32 = "user32.dll"; internal const string Version = "version.dll"; internal const string WebSocket = "websocket.dll"; internal const string Wevtapi = "wevtapi.dll"; internal const string WinHttp = "winhttp.dll"; internal const string WinMM = "winmm.dll"; internal const string Wkscli = "wkscli.dll"; internal const string Wldap32 = "wldap32.dll"; internal const string Ws2_32 = "ws2_32.dll"; internal const string Wtsapi32 = "wtsapi32.dll"; internal const string CompressionNative = "System.IO.Compression.Native"; internal const string GlobalizationNative = "System.Globalization.Native"; internal const string MsQuic = "msquic.dll"; internal const string HostPolicy = "hostpolicy"; internal const string Ucrtbase = "ucrtbase.dll"; internal const string Xolehlp = "xolehlp.dll"; internal const string Comdlg32 = "comdlg32.dll"; internal const string Gdiplus = "gdiplus.dll"; internal const string Oleaut32 = "oleaut32.dll"; internal const string Winspool = "winspool.drv"; } internal static class Kernel32 { [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] [LibraryImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero); } } namespace FxResources.System.Reflection.Metadata { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { ToCharsBuffer(readOnlySpan[i], buffer, num, casing); num += 2; } return buffer.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { return TryDecodeFromUtf16_Scalar(chars, bytes, out charsProcessed); } private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { if (IntPtr.Size == 8) { ulong num = (uint)(c - 48); long num2 = -17875860044349952L << (int)num; ulong num3 = num - 64; return (long)((ulong)num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "AuthenticationManager is not supported. Methods will no-op or throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use X509CertificateLoader to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; internal const string EncryptionPolicyDiagId = "SYSLIB0040"; internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations."; internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041"; internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys."; internal const string EccXmlExportImportDiagId = "SYSLIB0042"; internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead."; internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043"; internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."; internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044"; internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead."; internal const string CryptoStringFactoryDiagId = "SYSLIB0045"; internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code."; internal const string ControlledExecutionRunDiagId = "SYSLIB0046"; internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution."; internal const string XmlSecureResolverDiagId = "SYSLIB0047"; internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead."; internal const string RsaEncryptDecryptDiagId = "SYSLIB0048"; internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties."; internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049"; internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used."; internal const string LegacyFormatterDiagId = "SYSLIB0050"; internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code."; internal const string LegacyFormatterImplDiagId = "SYSLIB0051"; internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported."; internal const string RegexExtensibilityDiagId = "SYSLIB0052"; internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size."; internal const string AesGcmTagConstructorDiagId = "SYSLIB0053"; internal const string ThreadVolatileReadWriteMessage = "Thread.VolatileRead and Thread.VolatileWrite are obsolete. Use Volatile.Read or Volatile.Write respectively instead."; internal const string ThreadVolatileReadWriteDiagId = "SYSLIB0054"; internal const string ArmIntrinsicPerformsUnsignedOperationMessage = "The underlying hardware instruction does not perform a signed saturate narrowing operation, and it always returns an unsigned result. Use the unsigned overload instead."; internal const string ArmIntrinsicPerformsUnsignedOperationDiagId = "SYSLIB0055"; internal const string LoadFromHashAlgorithmMessage = "LoadFrom with a custom AssemblyHashAlgorithm is obsolete. Use overloads without an AssemblyHashAlgorithm."; internal const string LoadFromHashAlgorithmDiagId = "SYSLIB0056"; internal const string X509CtorCertDataObsoleteMessage = "Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates."; internal const string X509CtorCertDataObsoleteDiagId = "SYSLIB0057"; } internal static class SR { private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue(); private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ImageTooSmall => GetResourceString("ImageTooSmall"); internal static string InvalidCorHeaderSize => GetResourceString("InvalidCorHeaderSize"); internal static string InvalidHandle => GetResourceString("InvalidHandle"); internal static string UnexpectedHandleKind => GetResourceString("UnexpectedHandleKind"); internal static string UnexpectedOpCode => GetResourceString("UnexpectedOpCode"); internal static string InvalidLocalSignatureToken => GetResourceString("InvalidLocalSignatureToken"); internal static string InvalidMetadataSectionSpan => GetResourceString("InvalidMetadataSectionSpan"); internal static string InvalidMethodHeader1 => GetResourceString("InvalidMethodHeader1"); internal static string InvalidMethodHeader2 => GetResourceString("InvalidMethodHeader2"); internal static string InvalidPESignature => GetResourceString("InvalidPESignature"); internal static string InvalidSehHeader => GetResourceString("InvalidSehHeader"); internal static string InvalidToken => GetResourceString("InvalidToken"); internal static string MetadataImageDoesNotRepresentAnAssembly => GetResourceString("MetadataImageDoesNotRepresentAnAssembly"); internal static string StandaloneDebugMetadataImageDoesNotContainModuleTable => GetResourceString("StandaloneDebugMetadataImageDoesNotContainModuleTable"); internal static string PEImageNotAvailable => GetResourceString("PEImageNotAvailable"); internal static string MissingDataDirectory => GetResourceString("MissingDataDirectory"); internal static string NotMetadataHeapHandle => GetResourceString("NotMetadataHeapHandle"); internal static string NotMetadataTableOrUserStringHandle => GetResourceString("NotMetadataTableOrUserStringHandle"); internal static string SectionTooSmall => GetResourceString("SectionTooSmall"); internal static string StreamMustSupportReadAndSeek => GetResourceString("StreamMustSupportReadAndSeek"); internal static string UnknownFileFormat => GetResourceString("UnknownFileFormat"); internal static string UnknownPEMagicValue => GetResourceString("UnknownPEMagicValue"); internal static string MetadataTableNotSorted => GetResourceString("MetadataTableNotSorted"); internal static string ModuleTableInvalidNumberOfRows => GetResourceString("ModuleTableInvalidNumberOfRows"); internal static string UnknownTables => GetResourceString("UnknownTables"); internal static string IllegalTablesInCompressedMetadataStream => GetResourceString("IllegalTablesInCompressedMetadataStream"); internal static string TableRowCountSpaceTooSmall => GetResourceString("TableRowCountSpaceTooSmall"); internal static string OutOfBoundsRead => GetResourceString("OutOfBoundsRead"); internal static string OutOfBoundsWrite => GetResourceString("OutOfBoundsWrite"); internal static string MetadataHeaderTooSmall => GetResourceString("MetadataHeaderTooSmall"); internal static string MetadataSignature => GetResourceString("MetadataSignature"); internal static string NotEnoughSpaceForVersionString => GetResourceString("NotEnoughSpaceForVersionString"); internal static string StreamHeaderTooSmall => GetResourceString("StreamHeaderTooSmall"); internal static string NotEnoughSpaceForStreamHeaderName => GetResourceString("NotEnoughSpaceForStreamHeaderName"); internal static string NotEnoughSpaceForStringStream => GetResourceString("NotEnoughSpaceForStringStream"); internal static string NotEnoughSpaceForBlobStream => GetResourceString("NotEnoughSpaceForBlobStream"); internal static string NotEnoughSpaceForGUIDStream => GetResourceString("NotEnoughSpaceForGUIDStream"); internal static string NotEnoughSpaceForMetadataStream => GetResourceString("NotEnoughSpaceForMetadataStream"); internal static string InvalidMetadataStreamFormat => GetResourceString("InvalidMetadataStreamFormat"); internal static string MetadataTablesTooSmall => GetResourceString("MetadataTablesTooSmall"); internal static string MetadataTableHeaderTooSmall => GetResourceString("MetadataTableHeaderTooSmall"); internal static string WinMDMissingMscorlibRef => GetResourceString("WinMDMissingMscorlibRef"); internal static string UnexpectedStreamEnd => GetResourceString("UnexpectedStreamEnd"); internal static string InvalidMethodRva => GetResourceString("InvalidMethodRva"); internal static string CantGetOffsetForVirtualHeapHandle => GetResourceString("CantGetOffsetForVirtualHeapHandle"); internal static string InvalidNumberOfSections => GetResourceString("InvalidNumberOfSections"); internal static string InvalidSignature => GetResourceString("InvalidSignature"); internal static string PEImageDoesNotHaveMetadata => GetResourceString("PEImageDoesNotHaveMetadata"); internal static string InvalidCodedIndex => GetResourceString("InvalidCodedIndex"); internal static string InvalidCompressedInteger => GetResourceString("InvalidCompressedInteger"); internal static string InvalidDocumentName => GetResourceString("InvalidDocumentName"); internal static string RowIdOrHeapOffsetTooLarge => GetResourceString("RowIdOrHeapOffsetTooLarge"); internal static string EnCMapNotSorted => GetResourceString("EnCMapNotSorted"); internal static string InvalidSerializedString => GetResourceString("InvalidSerializedString"); internal static string StreamTooLarge => GetResourceString("StreamTooLarge"); internal static string ImageTooSmallOrContainsInvalidOffsetOrCount => GetResourceString("ImageTooSmallOrContainsInvalidOffsetOrCount"); internal static string MetadataStringDecoderEncodingMustBeUtf8 => GetResourceString("MetadataStringDecoderEncodingMustBeUtf8"); internal static string InvalidConstantValue => GetResourceString("InvalidConstantValue"); internal static string InvalidConstantValueOfType => GetResourceString("InvalidConstantValueOfType"); internal static string InvalidImportDefinitionKind => GetResourceString("InvalidImportDefinitionKind"); internal static string ValueTooLarge => GetResourceString("ValueTooLarge"); internal static string BlobTooLarge => GetResourceString("BlobTooLarge"); internal static string InvalidTypeSize => GetResourceString("InvalidTypeSize"); internal static string HandleBelongsToFutureGeneration => GetResourceString("HandleBelongsToFutureGeneration"); internal static string InvalidRowCount => GetResourceString("InvalidRowCount"); internal static string InvalidEntryPointToken => GetResourceString("InvalidEntryPointToken"); internal static string TooManySubnamespaces => GetResourceString("TooManySubnamespaces"); internal static string TooManyExceptionRegions => GetResourceString("TooManyExceptionRegions"); internal static string SequencePointValueOutOfRange => GetResourceString("SequencePointValueOutOfRange"); internal static string InvalidDirectoryRVA => GetResourceString("InvalidDirectoryRVA"); internal static string InvalidDirectorySize => GetResourceString("InvalidDirectorySize"); internal static string InvalidDebugDirectoryEntryCharacteristics => GetResourceString("InvalidDebugDirectoryEntryCharacteristics"); internal static string UnexpectedCodeViewDataSignature => GetResourceString("UnexpectedCodeViewDataSignature"); internal static string UnexpectedEmbeddedPortablePdbDataSignature => GetResourceString("UnexpectedEmbeddedPortablePdbDataSignature"); internal static string InvalidPdbChecksumDataFormat => GetResourceString("InvalidPdbChecksumDataFormat"); internal static string UnexpectedSignatureHeader => GetResourceString("UnexpectedSignatureHeader"); internal static string UnexpectedSignatureHeader2 => GetResourceString("UnexpectedSignatureHeader2"); internal static string NotTypeDefOrRefHandle => GetResourceString("NotTypeDefOrRefHandle"); internal static string UnexpectedSignatureTypeCode => GetResourceString("UnexpectedSignatureTypeCode"); internal static string SignatureTypeSequenceMustHaveAtLeastOneElement => GetResourceString("SignatureTypeSequenceMustHaveAtLeastOneElement"); internal static string NotTypeDefOrRefOrSpecHandle => GetResourceString("NotTypeDefOrRefOrSpecHandle"); internal static string UnexpectedDebugDirectoryType => GetResourceString("UnexpectedDebugDirectoryType"); internal static string HeapSizeLimitExceeded => GetResourceString("HeapSizeLimitExceeded"); internal static string BuilderMustAligned => GetResourceString("BuilderMustAligned"); internal static string BuilderAlreadyLinked => GetResourceString("BuilderAlreadyLinked"); internal static string ReturnedBuilderSizeTooSmall => GetResourceString("ReturnedBuilderSizeTooSmall"); internal static string SignatureNotVarArg => GetResourceString("SignatureNotVarArg"); internal static string LabelDoesntBelongToBuilder => GetResourceString("LabelDoesntBelongToBuilder"); internal static string ControlFlowBuilderNotAvailable => GetResourceString("ControlFlowBuilderNotAvailable"); internal static string BaseReaderMustBeFullMetadataReader => GetResourceString("BaseReaderMustBeFullMetadataReader"); internal static string ModuleAlreadyAdded => GetResourceString("ModuleAlreadyAdded"); internal static string AssemblyAlreadyAdded => GetResourceString("AssemblyAlreadyAdded"); internal static string ExpectedListOfSize => GetResourceString("ExpectedListOfSize"); internal static string ExpectedArrayOfSize => GetResourceString("ExpectedArrayOfSize"); internal static string ExpectedNonEmptyList => GetResourceString("ExpectedNonEmptyList"); internal static string ExpectedNonEmptyArray => GetResourceString("ExpectedNonEmptyArray"); internal static string ExpectedNonEmptyString => GetResourceString("ExpectedNonEmptyString"); internal static string ReadersMustBeDeltaReaders => GetResourceString("ReadersMustBeDeltaReaders"); internal static string SignatureProviderReturnedInvalidSignature => GetResourceString("SignatureProviderReturnedInvalidSignature"); internal static string UnknownSectionName => GetResourceString("UnknownSectionName"); internal static string HashTooShort => GetResourceString("HashTooShort"); internal static string UnexpectedArrayLength => GetResourceString("UnexpectedArrayLength"); internal static string ValueMustBeMultiple => GetResourceString("ValueMustBeMultiple"); internal static string MustNotReturnNull => GetResourceString("MustNotReturnNull"); internal static string MetadataVersionTooLong => GetResourceString("MetadataVersionTooLong"); internal static string RowCountMustBeZero => GetResourceString("RowCountMustBeZero"); internal static string RowCountOutOfRange => GetResourceString("RowCountOutOfRange"); internal static string SizeMismatch => GetResourceString("SizeMismatch"); internal static string DataTooBig => GetResourceString("DataTooBig"); internal static string UnsupportedFormatVersion => GetResourceString("UnsupportedFormatVersion"); internal static string DistanceBetweenInstructionAndLabelTooBig => GetResourceString("DistanceBetweenInstructionAndLabelTooBig"); internal static string LabelNotMarked => GetResourceString("LabelNotMarked"); internal static string MethodHasNoExceptionRegions => GetResourceString("MethodHasNoExceptionRegions"); internal static string InvalidExceptionRegionBounds => GetResourceString("InvalidExceptionRegionBounds"); internal static string UnexpectedValue => GetResourceString("UnexpectedValue"); internal static string UnexpectedValueUnknownType => GetResourceString("UnexpectedValueUnknownType"); internal static string SwitchInstructionEncoderTooFewBranches => GetResourceString("SwitchInstructionEncoderTooFewBranches"); internal static string SwitchInstructionEncoderTooManyBranches => GetResourceString("SwitchInstructionEncoderTooManyBranches"); internal static string Argument_InvalidTypeName => GetResourceString("Argument_InvalidTypeName"); internal static string InvalidOperation_MaxNodesExceeded => GetResourceString("InvalidOperation_MaxNodesExceeded"); internal static string Argument_HasToBeArrayClass => GetResourceString("Argument_HasToBeArrayClass"); internal static string InvalidOperation_NotGenericType => GetResourceString("InvalidOperation_NotGenericType"); internal static string InvalidOperation_NotNestedType => GetResourceString("InvalidOperation_NotNestedType"); internal static string InvalidOperation_NoElement => GetResourceString("InvalidOperation_NoElement"); internal static string InvalidAssemblyName => GetResourceString("InvalidAssemblyName"); internal static string Arg_NotSimpleTypeName => GetResourceString("Arg_NotSimpleTypeName"); private static bool GetUsingResourceKeysSwitchValue() { if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled)) { return false; } return isEnabled; } internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Text { internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span<char> RawChars => _chars; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if ((uint)capacity > (uint)_chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string? s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; Span<char> chars = _chars; if ((uint)pos < (uint)chars.Length) { chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string? s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.AsSpan().CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { if (_pos > _chars.Length - length) { Grow(length); } Span<char> span = _chars.Slice(_pos, length); for (int i = 0; i < span.Length; i++) { span[i] = *(value++); } _pos += length; } public void Append(scoped ReadOnlySpan<char> value) { if (_pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<char> AppendSpan(int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } _pos = pos + length; return _chars.Slice(pos, length); } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowAndAppend(char c) { Grow(1); Append(c); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalCapacityBeyondPos) { int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u)); char[] array = ArrayPool<char>.Shared.Rent(minimumLength); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(System.Text.ValueStringBuilder); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } } } namespace System.Reflection { internal static class BlobUtilities { public const int SizeOfSerializedDecimal = 13; public const int SizeOfGuid = 16; public static void WriteBytes(this byte[] buffer, int start, byte value, int byteCount) { new Span<byte>(buffer, start, byteCount).Fill(value); } public unsafe static void WriteDouble(this byte[] buffer, int start, double value) { buffer.WriteUInt64(start, *(ulong*)(&value)); } public unsafe static void WriteSingle(this byte[] buffer, int start, float value) { buffer.WriteUInt32(start, *(uint*)(&value)); } public static void WriteByte(this byte[] buffer, int start, byte value) { buffer[start] = value; } public static void WriteUInt16(this byte[] buffer, int start, ushort value) { Unsafe.WriteUnaligned(ref buffer[start], (!BitConverter.IsLittleEndian) ? BinaryPrimitives.ReverseEndianness(value) : value); } public static void WriteUInt16BE(this byte[] buffer, int start, ushort value) { Unsafe.WriteUnaligned(ref buffer[start], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value); } public static void WriteUInt32BE(this byte[] buffer, int start, uint value) { Unsafe.WriteUnaligned(ref buffer[start], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value); } public static void WriteUInt32(this byte[] buffer, int start, uint value) { Unsafe.WriteUnaligned(ref buffer[start], (!BitConverter.IsLittleEndian) ? BinaryPrimitives.ReverseEndianness(value) : value); } public static void WriteUInt64(this byte[] buffer, int start, ulong value) { Unsafe.WriteUnaligned(ref buffer[start], (!BitConverter.IsLittleEndian) ? BinaryPrimitives.ReverseEndianness(value) : value); } public static void WriteDecimal(this byte[] buffer, int start, decimal value) { value.GetBits(out var isNegative, out var scale, out var low, out var mid, out var high); buffer.WriteByte(start, (byte)(scale | (isNegative ? 128u : 0u))); buffer.WriteUInt32(start + 1, low); buffer.WriteUInt32(start + 5, mid); buffer.WriteUInt32(start + 9, high); } public unsafe static void WriteGuid(this byte[] buffer, int start, Guid value) { fixed (byte* ptr2 = &buffer[start]) { byte* ptr = (byte*)(&value); uint num = *(uint*)ptr; *ptr2 = (byte)num; ptr2[1] = (byte)(num >> 8); ptr2[2] = (byte)(num >> 16); ptr2[3] = (byte)(num >> 24); ushort num2 = *(ushort*)(ptr + 4); ptr2[4] = (byte)num2; ptr2[5] = (byte)(num2 >> 8); ushort num3 = *(ushort*)(ptr + 6); ptr2[6] = (byte)num3; ptr2[7] = (byte)(num3 >> 8); ptr2[8] = ptr[8]; ptr2[9] = ptr[9]; ptr2[10] = ptr[10]; ptr2[11] = ptr[11]; ptr2[12] = ptr[12]; ptr2[13] = ptr[13]; ptr2[14] = ptr[14]; ptr2[15] = ptr[15]; } } public unsafe static void WriteUTF8(this byte[] buffer, int start, char* charPtr, int charCount, int byteCount, bool allowUnpairedSurrogates) { char* ptr = charPtr + charCount; fixed (byte* ptr2 = &buffer[0]) { byte* ptr3 = ptr2 + start; if (byteCount == charCount) { while (charPtr < ptr) { *(ptr3++) = (byte)(*(charPtr++)); } return; } while (charPtr < ptr) { char c = *(charPtr++); if (c < '\u0080') { *(ptr3++) = (byte)c; continue; } if (c < 'ࠀ') { *ptr3 = (byte)(((uint)((int)c >> 6) & 0x1Fu) | 0xC0u); ptr3[1] = (byte)((c & 0x3Fu) | 0x80u); ptr3 += 2; continue; } if (IsSurrogateChar(c)) { if (IsHighSurrogateChar(c) && charPtr < ptr && IsLowSurrogateChar(*charPtr)) { char num = c; int num2 = *(charPtr++); int num3 = (num - 55296 << 10) + num2 - 56320 + 65536; *ptr3 = (byte)(((uint)(num3 >> 18) & 7u) | 0xF0u); ptr3[1] = (byte)(((uint)(num3 >> 12) & 0x3Fu) | 0x80u); ptr3[2] = (byte)(((uint)(num3 >> 6) & 0x3Fu) | 0x80u); ptr3[3] = (byte)(((uint)num3 & 0x3Fu) | 0x80u); ptr3 += 4; continue; } if (!allowUnpairedSurrogates) { c = '\ufffd'; } } *ptr3 = (byte)(((uint)((int)c >> 12) & 0xFu) | 0xE0u); ptr3[1] = (byte)(((uint)((int)c >> 6) & 0x3Fu) | 0x80u); ptr3[2] = (byte)((c & 0x3Fu) | 0x80u); ptr3 += 3; } } } internal unsafe static int GetUTF8ByteCount(string str) { fixed (char* str2 = str) { return GetUTF8ByteCount(str2, str.Length); } } internal unsafe static int GetUTF8ByteCount(char* str, int charCount) { char* remainder; return GetUTF8ByteCount(str, charCount, int.MaxValue, out remainder); } internal unsafe static int GetUTF8ByteCount(char* str, int charCount, int byteLimit, out char* remainder) { char* ptr = str + charCount; char* ptr2 = str; int num = 0; while (ptr2 < ptr) { char c = *(ptr2++); int num2; if (c < '\u0080') { num2 = 1; } else if (c < 'ࠀ') { num2 = 2; } else if (IsHighSurrogateChar(c) && ptr2 < ptr && IsLowSurrogateChar(*ptr2)) { num2 = 4; ptr2++; } else { num2 = 3; } if (num + num2 > byteLimit) { ptr2 -= ((num2 < 4) ? 1 : 2); break; } num += num2; } remainder = ptr2; return num; } internal static bool IsSurrogateChar(int c) { return (uint)(c - 55296) <= 2047u; } internal static bool IsHighSurrogateChar(int c) { return (uint)(c - 55296) <= 1023u; } internal static bool IsLowSurrogateChar(int c) { return (uint)(c - 56320) <= 1023u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ValidateRange(int bufferLength, int start, int byteCount, string byteCountParameterName) { if (start < 0 || start > bufferLength) { Throw.ArgumentOutOfRange("start"); } if (byteCount < 0 || byteCount > bufferLength - start) { Throw.ArgumentOutOfRange(byteCountParameterName); } } internal static int GetUserStringByteLength(int characterCount) { return characterCount * 2 + 1; } internal static byte GetUserStringTrailingByte(string str) { foreach (char c in str) { if (c >= '\u007f') { return 1; } switch (c) { case '\u0001': case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': case '\'': case '-': return 1; } } return 0; } } internal static class Throw { [DoesNotReturn] internal static void InvalidCast() { throw new InvalidCastException(); } [DoesNotReturn] internal static void InvalidArgument(string message, string parameterName) { throw new ArgumentException(message, parameterName); } [DoesNotReturn] internal static void InvalidArgument_OffsetForVirtualHeapHandle() { throw new ArgumentException(System.SR.CantGetOffsetForVirtualHeapHandle, "handle"); } [DoesNotReturn] internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind) { throw new ArgumentException(System.SR.Format(System.SR.UnexpectedHandleKind, kind)); } [DoesNotReturn] internal static Exception InvalidArgument_Handle(string parameterName) { throw new ArgumentException(System.SR.InvalidHandle, parameterName); } [DoesNotReturn] internal static void SignatureNotVarArg() { throw new InvalidOperationException(System.SR.SignatureNotVarArg); } [DoesNotReturn] internal static void ControlFlowBuilderNotAvailable() { throw new InvalidOperationException(System.SR.ControlFlowBuilderNotAvailable); } [DoesNotReturn] internal static void InvalidOperationBuilderAlreadyLinked() { throw new InvalidOperationException(System.SR.BuilderAlreadyLinked); } [DoesNotReturn] internal static void InvalidOperation(string message) { throw new InvalidOperationException(message); } [DoesNotReturn] internal static void InvalidOperation_LabelNotMarked(int id) { throw new InvalidOperationException(System.SR.Format(System.SR.LabelNotMarked, id)); } [DoesNotReturn] internal static void LabelDoesntBelongToBuilder(string parameterName) { throw new ArgumentException(System.SR.LabelDoesntBelongToBuilder, parameterName); } [DoesNotReturn] internal static void HeapHandleRequired() { throw new ArgumentException(System.SR.NotMetadataHeapHandle, "handle"); } [DoesNotReturn] internal static void EntityOrUserStringHandleRequired() { throw new ArgumentException(System.SR.NotMetadataTableOrUserStringHandle, "handle"); } [DoesNotReturn] internal static void InvalidToken() { throw new ArgumentException(System.SR.InvalidToken, "token"); } [DoesNotReturn] internal static void ArgumentNull(string parameterName) { throw new ArgumentNullException(parameterName); } [DoesNotReturn] internal static void ArgumentEmptyString(string parameterName) { throw new ArgumentException(System.SR.ExpectedNonEmptyString, parameterName); } [DoesNotReturn] internal static void ArgumentEmptyArray(string parameterName) { throw new ArgumentException(System.SR.ExpectedNonEmptyArray, parameterName); } [DoesNotReturn] internal static void ValueArgumentNull() { throw new ArgumentNullException("value"); } [DoesNotReturn] internal static void BuilderArgumentNull() { throw new ArgumentNullException("builder"); } [DoesNotReturn] internal static void ArgumentOutOfRange(string parameterName) { throw new ArgumentOutOfRangeException(parameterName); } [DoesNotReturn] internal static void ArgumentOutOfRange(string parameterName, string message) { throw new ArgumentOutOfRangeException(parameterName, message); } [DoesNotReturn] internal static void BlobTooLarge(string parameterName) { throw new ArgumentOutOfRangeException(parameterName, System.SR.BlobTooLarge); } [DoesNotReturn] internal static void IndexOutOfRange() { throw new ArgumentOutOfRangeException("index"); } [DoesNotReturn] internal static void TableIndexOutOfRange() { throw new ArgumentOutOfRangeException("tableIndex"); } [DoesNotReturn] internal static void ValueArgumentOutOfRange() { throw new ArgumentOutOfRangeException("value"); } [DoesNotReturn] internal static void OutOfBounds() { throw new BadImageFormatException(System.SR.OutOfBoundsRead); } [DoesNotReturn] internal static void WriteOutOfBounds() { throw new InvalidOperationException(System.SR.OutOfBoundsWrite); } [DoesNotReturn] internal static void InvalidCodedIndex() { throw new BadImageFormatException(System.SR.InvalidCodedIndex); } [DoesNotReturn] internal static void InvalidHandle() { throw new BadImageFormatException(System.SR.InvalidHandle); } [DoesNotReturn] internal static void InvalidCompressedInteger() { throw new BadImageFormatException(System.SR.InvalidCompressedInteger); } [DoesNotReturn] internal static void InvalidSerializedString() { throw new BadImageFormatException(System.SR.InvalidSerializedString); } [DoesNotReturn] internal static void ImageTooSmall() { throw new BadImageFormatException(System.SR.ImageTooSmall); } [DoesNotReturn] internal static void ImageTooSmallOrContainsInvalidOffsetOrCount() { throw new BadImageFormatException(System.SR.ImageTooSmallOrContainsInvalidOffsetOrCount); } [DoesNotReturn] internal static void ReferenceOverflow() { throw new BadImageFormatException(System.SR.RowIdOrHeapOffsetTooLarge); } [DoesNotReturn] internal static void TableNotSorted(TableIndex tableIndex) { throw new BadImageFormatException(System.SR.Format(System.SR.MetadataTableNotSorted, tableIndex)); } [DoesNotReturn] internal static void InvalidOperation_TableNotSorted(TableIndex tableIndex) { throw new InvalidOperationException(System.SR.Format(System.SR.MetadataTableNotSorted, tableIndex)); } [DoesNotReturn] internal static void InvalidOperation_PEImageNotAvailable() { throw new InvalidOperationException(System.SR.PEImageNotAvailable); } [DoesNotReturn] internal static void TooManySubnamespaces() { throw new BadImageFormatException(System.SR.TooManySubnamespaces); } [DoesNotReturn] internal static void ValueOverflow() { throw new BadImageFormatException(System.SR.ValueTooLarge); } [DoesNotReturn] internal static void SequencePointValueOutOfRange() { throw new BadImageFormatException(System.SR.SequencePointValueOutOfRange); } [DoesNotReturn] internal static void HeapSizeLimitExceeded(HeapIndex heap) { throw new ImageFormatLimitationException(System.SR.Format(System.SR.HeapSizeLimitExceeded, heap)); } [DoesNotReturn] internal static void PEReaderDisposed() { throw new ObjectDisposedException("PEReader"); } } [Flags] public enum MethodSemanticsAttributes { Setter = 1, Getter = 2, Other = 4, Adder = 8, Remover = 0x10, Raiser = 0x20 } public enum DeclarativeSecurityAction : short { None = 0, Demand = 2, Assert = 3, Deny = 4, PermitOnly = 5, LinkDemand = 6, InheritanceDemand = 7, RequestMinimum = 8, RequestOptional = 9, RequestRefuse = 10 } [Flags] public enum MethodImportAttributes : short { None = 0, ExactSpelling = 1, BestFitMappingDisable = 0x20, BestFitMappingEnable = 0x10, BestFitMappingMask = 0x30, CharSetAnsi = 2, CharSetUnicode = 4, CharSetAuto = 6, CharSetMask = 6, ThrowOnUnmappableCharEnable = 0x1000, ThrowOnUnmappableCharDisable = 0x2000, ThrowOnUnmappableCharMask = 0x3000, SetLastError = 0x40, CallingConventionWinApi = 0x100, CallingConventionCDecl = 0x200, CallingConventionStdCall = 0x300, CallingConventionThisCall = 0x400, CallingConventionFastCall = 0x500, CallingConventionMask = 0x700 } [Flags] public enum ManifestResourceAttributes { Public = 1, Private = 2, VisibilityMask = 7 } public enum AssemblyHashAlgorithm { None = 0, MD5 = 32771, Sha1 = 32772, Sha256 = 32780, Sha384 = 32781, Sha512 = 32782 } [Flags] public enum AssemblyFlags { PublicKey = 1, Retargetable = 0x100, WindowsRuntime = 0x200, ContentTypeMask = 0xE00, DisableJitCompileOptimizer = 0x4000, EnableJitCompileTracking = 0x8000 } internal static class TypeAttributesExtensions { private const TypeAttributes Forwarder = (TypeAttributes)2097152; private const TypeAttributes NestedMask = TypeAttributes.NestedFamANDAssem; public static bool IsForwarder(this TypeAttributes flags) { return (flags & (TypeAttributes)2097152) != 0; } public static bool IsNested(this TypeAttributes flags) { return (flags & TypeAttributes.NestedFamANDAssem) != 0; } } internal static class AssemblyNameFormatter { public static string ComputeDisplayName(string name, Version? version, string? cultureName, byte[]? pkt, AssemblyNameFlags flags = AssemblyNameFlags.None, AssemblyContentType contentType = AssemblyContentType.Default, byte[]? pk = null) { Span<char> initialBuffer = stackalloc char[256]; System.Text.ValueStringBuilder vsb = new System.Text.ValueStringBuilder(initialBuffer); vsb.AppendQuoted(name); if (version != null) { ushort num = (ushort)version.Major; if (num != ushort.MaxValue) { vsb.Append(", Version="); vsb.AppendSpanFormattable(num); ushort num2 = (ushort)version.Minor; if (num2 != ushort.MaxValue) { vsb.Append('.'); vsb.AppendSpanFormattable(num2); ushort num3 = (ushort)version.Build; if (num3 != ushort.MaxValue) { vsb.Append('.'); vsb.AppendSpanFormattable(num3); ushort num4 = (ushort)version.Revision; if (num4 != ushort.MaxValue) { vsb.Append('.'); vsb.AppendSpanFormattable(num4); } } } } } if (cultureName != null) { if (cultureName.Length == 0) { cultureName = "neutral"; } vsb.Append(", Culture="); vsb.AppendQuoted(cultureName); } byte[] array = pkt ?? pk; if (array != null) { if (pkt != null) { if (pkt.Length > 8) { throw new ArgumentException(); } vsb.Append(", PublicKeyToken="); } else { vsb.Append(", PublicKey="); } if (array.Length == 0) { vsb.Append("null"); } else { System.HexConverter.EncodeToUtf16(array, vsb.AppendSpan(array.Length * 2), System.HexConverter.Casing.Lower); } } if ((flags & AssemblyNameFlags.Retargetable) != 0) { vsb.Append(", Retargetable=Yes"); } if (contentType == AssemblyContentType.WindowsRuntime) { vsb.Append(", ContentType=WindowsRuntime"); } return vsb.ToString(); } private static void AppendQuoted(this ref System.Text.ValueStringBuilder vsb, string s) { bool flag = false; ReadOnlySpan<char> span = s.AsSpan(); if (s.Length != span.Trim().Length || span.IndexOfAny('"', '\'') >= 0) { flag = true; } if (flag) { vsb.Append('"'); } for (int i = 0; i < s.Length; i++) { switch (s[i]) { case '"': case '\'': case ',': case '=': case '\\': vsb.Append('\\'); break; case '\t': vsb.Append("\\t"); continue; case '\r': vsb.Append("\\r"); continue; case '\n': vsb.Append("\\n"); continue; } vsb.Append(s[i]); } if (flag) { vsb.Append('"'); } } private static void AppendSpanFormattable(this ref System.Text.ValueStringBuilder vsb, ushort value) { vsb.Append(value.ToString()); } } internal ref struct AssemblyNameParser { public readonly struct AssemblyNameParts { public readonly string _name; public readonly Version? _version; public readonly string? _cultureName; public readonly AssemblyNameFlags _flags; public readonly byte[]? _publicKeyOrToken; public AssemblyNameParts(string name, Version? version, string? cultureName, AssemblyNameFlags flags, byte[]? publicKeyOrToken) { _name = name; _version = version; _cultureName = cultureName; _flags = flags; _publicKeyOrToken = publicKeyOrToken; } } private enum Token { Equals = 1, Comma, String, End } private enum AttributeKind { Version = 1, Culture = 2, PublicKeyOrToken = 4, ProcessorArchitecture = 8, Retargetable = 0x10, ContentType = 0x20 } private readonly ReadOnlySpan<char> _input; private int _index; private AssemblyNameParser(ReadOnlySpan<char> input) { _input = input; _index = 0; } internal static bool TryParse(ReadOnlySpan<char> name, ref AssemblyNameParts parts) { return new AssemblyNameParser(name).TryParse(ref parts); } private static bool TryRecordNewSeen(scoped ref AttributeKind seenAttributes, AttributeKind newAttribute) { if ((seenAttributes & newAttribute) != 0) { return false; } seenAttributes |= newAttribute; return true; } private bool TryParse(ref AssemblyNameParts result) { if (!TryGetNextToken(out var tokenString, out var token) || token != Token.String || string.IsNullOrEmpty(tokenString)) { return false; } Version version = null; string result2 = null; byte[] result3 = null; AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None; AttributeKind seenAttributes = (AttributeKind)0; if (!TryGetNextToken(out var tokenString2, out token)) { return false; } do { switch (token) { default: return false; case Token.Comma: { if (!TryGetNextToken(out var tokenString3, out token) || token != Token.String) { return false; } if (!TryGetNextToken(out tokenString2, out token) || token != Token.Equals) { return false; } if (!TryGetNextToken(out var tokenString4, out token) || token != Token.String) { return false; } if (tokenString3 == string.Empty) { return false; } if (IsAttribute(tokenString3, "Version")) { if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.Version)) { return false; } if (!TryParseVersion(tokenString4, ref version)) { return false; } } else if (IsAttribute(tokenString3, "Culture")) { if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.Culture)) { return false; } if (!TryParseCulture(tokenString4, out result2)) { return false; } } else if (IsAttribute(tokenString3, "PublicKeyToken")) { if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.PublicKeyOrToken)) { return false; } if (!TryParsePKT(tokenString4, isToken: true, out result3)) { return false; } } else if (IsAttribute(tokenString3, "PublicKey")) { if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.PublicKeyOrToken)) { return false; } if (!TryParsePKT(tokenString4, isToken: false, out result3)) { return false; } assemblyNameFlags |= AssemblyNameFlags.PublicKey; } else if (IsAttribute(tokenString3, "ProcessorArchitecture")) { if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.ProcessorArchitecture)) { return false; } if (!TryParseProcessorArchitecture(tokenString4, out var result4)) { return false; } assemblyNameFlags = (AssemblyNameFlags)((int)assemblyNameFlags | ((int)result4 << 4)); } else if (IsAttribute(tokenString3, "Retargetable")) { if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.Retargetable)) { return false; } if (tokenString4.Equals("Yes", StringComparison.OrdinalIgnoreCase)) { assemblyNameFlags |= AssemblyNameFlags.Retargetable; } else if (!tokenString4.Equals("No", StringComparison.OrdinalIgnoreCase)) { return false; } } else if (IsAttribute(tokenString3, "ContentType")) { if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.ContentType)) { return false; } if (!tokenString4.Equals("WindowsRuntime", StringComparison.OrdinalIgnoreCase)) { return false; } assemblyNameFlags |= (AssemblyNameFlags)512; } break; } case Token.End: result = new AssemblyNameParts(tokenString, version, result2, assemblyNameFlags, result3); return true; } } while (TryGetNextToken(out tokenString2, out token)); return false; } private static bool IsAttribute(string candidate, string attributeKind) { return candidate.Equals(attributeKind, StringComparison.OrdinalIgnoreCase); } private static bool TryParseVersion(string attributeValue, ref Version version) { string[] array = attributeValue.Split(new char[1] { '.' }); int num = array.Length; if ((num < 2 || num > 4) ? true : false) { return false; } Span<ushort> span = new Span<ushort>(new ushort[4] { 65535, 65535, 65535, 65535 }); for (int i = 0; i < array.Length; i++) { if (!ushort.TryParse(array[i], NumberStyles.None, NumberFormatInfo.InvariantInfo, out span[i])) { return false; } } if (span[0] == ushort.MaxValue || span[1] == ushort.MaxValue) { return false; } version = ((span[2] == ushort.MaxValue) ? new Version(span[0], span[1]) : ((span[3] == ushort.MaxValue) ? new Version(span[0], span[1], span[2]) : new Version(span[0], span[1], span[2], span[3]))); return true; } private static bool TryParseCulture(string attributeValue, out string result) { if (attributeValue.Equals("Neutral", StringComparison.OrdinalIgnoreCase)) { result = ""; return true; } result = attributeValue; return true; } private static bool TryParsePKT(string attributeValue, bool isToken, out byte[] result) { if (attributeValue.Equals("null", StringComparison.OrdinalIgnoreCase) || attributeValue == string.Empty) { result = Array.Empty<byte>(); return true; } if (attributeValue.Length % 2 != 0 || (isToken && attributeValue.Length != 16)) { result = null; return false; } byte[] array = new byte[attributeValue.Length / 2]; if (!System.HexConverter.TryDecodeFromUtf16(attributeValue.AsSpan(), array, out var _)) { result = null; return false; } result = array; return true; } private static bool TryParseProcessorArchitecture(string attributeValue, out ProcessorArchitecture result) { ProcessorArchitecture processorArchitecture = (attributeValue.Equals("msil", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.MSIL : (attributeValue.Equals("x86", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.X86 : (attributeValue.Equals("ia64", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.IA64 : (attributeValue.Equals("amd64", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.Amd64 : (attributeValue.Equals("arm", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.Arm : (attributeValue.Equals("msil", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.MSIL : ProcessorArchitecture.None)))))); result = processorArchitecture; return result != ProcessorArchitecture.None; } private static bool IsWhiteSpace(char ch) { switch (ch) { case '\t': case '\n': case '\r': case ' ': return true; default: return false; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryGetNextChar(out char ch) { if (_index < _input.Length) { ch = _input[_index++]; if (ch == '\0') { return false; } } else { ch = '\0'; } return true; } private bool TryGetNextToken(out string tokenString, out Token token) { tokenString = string.Empty; char ch; do { if (!TryGetNextChar(out ch)) { token = (Token)0; return false; } switch (ch) { case ',': token = Token.Comma; return true; case '=': token = Token.Equals; return true; case '\0': token = Token.End; return true; } } while (IsWhiteSpace(ch)); Span<char> initialBuffer = stackalloc char[64]; bool flag; using (System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer)) { char c = '\0'; flag = ((ch == '"' || ch == '\'') ? true : false); if (!flag) { goto IL_0085; } c = ch; if (TryGetNextChar(out ch)) { goto IL_0085; } token = (Token)0; flag = false; goto end_IL_0056; IL_0085: while (true) { if (ch == '\0') { if (c != 0) { token = (Token)0; flag = false; break; } } else if (c == '\0' || ch != c) { bool flag2 = c == '\0'; if (flag2) { bool flag3 = ((ch == ',' || ch == '=') ? true : false); flag2 = flag3; } if (!flag2) { flag2 = c == '\0'; if (flag2) { bool flag3 = ((ch == '"' || ch == '\'') ? true : false); flag2 = flag3; } if (flag2) { token = (Token)0; flag = false; break; } if (ch == '\\') { if (!TryGetNextChar(out ch)) { token = (Token)0; flag = false; break; } switch (ch) { case '"': case '\'': case ',': case '=': case '\\': valueStringBuilder.Append(ch); goto IL_01a0; case 't': valueStringBuilder.Append('\t'); goto IL_01a0; case 'r': valueStringBuilder.Append('\r'); goto IL_01a0; case 'n': valueStringBuilder.Append('\n'); goto IL_01a0; default: token = (Token)0; flag = false; break; } break; } valueStringBuilder.Append(ch); goto IL_01a0; } _index--; } int num = valueStringBuilder.Length; if (c == '\0') { while (num > 0 && IsWhiteSpace(valueStringBuilder[num - 1])) { num--; } } tokenString = valueStringBuilder.AsSpan(0, num).ToString(); token = Token.String; flag = true; break; IL_01a0: if (!TryGetNextChar(out ch)) { token = (Token)0; flag = false; break; } } end_IL_0056:; } return flag; } } } namespace System.Reflection.PortableExecutable { public class ManagedPEBuilder : PEBuilder { public const int ManagedResourcesDataAlignment = 8; public const int MappedFieldDataAlignment = 8; private const int DefaultStrongNameSignatureSize = 128; private const string TextSectionName = ".text"; private const string ResourceSectionName = ".rsrc"; private const string RelocationSectionName = ".reloc"; private readonly PEDirectoriesBuilder _peDirectoriesBuilder; private readonly MetadataRootBuilder _metadataRootBuilder; private readonly BlobBuilder _ilStream; private readonly BlobBuilder _mappedFieldDataOpt; private readonly BlobBuilder _managedResourcesOpt; private readonly ResourceSectionBuilder _nativeResourcesOpt; private readonly int _strongNameSignatureSize; private readonly MethodDefinitionHandle _entryPointOpt; private readonly DebugDirectoryBuilder _debugDirectoryBuilderOpt; private readonly CorFlags _corFlags; private int _lazyEntryPointAddress; private Blob _lazyStrongNameSignature; public ManagedPEBuilder(PEHeaderBuilder header, MetadataRootBuilder metadataRootBuilder, BlobBuilder ilStream, BlobBuilder? mappedFieldData = null, BlobBuilder? managedResources = null, ResourceSectionBuilder? nativeResources = null, DebugDirectoryBuilder? debugDirectoryBuilder = null, int strongNameSignatureSize = 128, MethodDefinitionHandle entryPoint = default(MethodDefinitionHandle), CorFlags flags = CorFlags.ILOnly, Func<IEnumerable<Blob>, BlobContentId>? deterministicIdProvider = null) : base(header, deterministicIdProvider) { if (header == null) { Throw.ArgumentNull("header"); } if (metadataRootBuilder == null) { Throw.ArgumentNull("metadataRootBuilder"); } if (ilStream == null) { Throw.ArgumentNull("ilStream"); } if (strongNameSignatureSize < 0) { Throw.ArgumentOutOfRange("strongNameSignatureSize"); } _metadataRootBuilder = metadataRootBuilder; _ilStream = ilStream; _mappedFieldDataOpt = mappedFieldData; _managedResourcesOpt = managedResources; _nativeResourcesOpt = nativeResources; _strongNameSignatureSize = strongNameSignatureSize; _entryPointOpt = entryPoint; _debugDirectoryBuilderOpt = debugDirectoryBuilder ?? CreateDefaultDebugDirectoryBuilder(); _corFlags = flags; _peDirectoriesBuilder = new PEDirectoriesBuilder(); } private DebugDirectoryBuilder CreateDefaultDebugDirectoryBuilder() { if (base.IsDeterministic) { DebugDirectoryBuilder debugDirectoryBuilder = new DebugDirectoryBuilder(); debugDirectoryBuilder.AddReproducibleEntry(); return debugDirectoryBuilder; } return null; } protected override ImmutableArray<Section> CreateSections() { ImmutableArray<Section>.Builder builder = ImmutableArray.CreateBuilder<Section>(3); builder.Add(new Section(".text", SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead)); if (_nativeResourcesOpt != null) { builder.Add(new Section(".rsrc", SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemRead)); } if (base.Header.Machine == Machine.I386 || base.Header.Machine == Machine.Unknown) { builder.Add(new Section(".reloc", SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable | SectionCharacteristics.MemRead)); } return builder.ToImmutable(); } protected override BlobBuilder SerializeSection(string name, SectionLocation location) { return name switch { ".text" => SerializeTextSection(location), ".rsrc" => SerializeResourceSection(location), ".reloc" => SerializeRelocationSection(location), _ => throw new ArgumentException(System.SR.Format(System.SR.UnknownSectionName, name), "name"), }; } private BlobBuilder SerializeTextSection(SectionLocation location) { BlobBuilder blobBuilder = new BlobBuilder(); BlobBuilder blobBuilder2 = new BlobBuilder(); MetadataSizes sizes = _metadataRootBuilder.Sizes; ManagedTextSection managedTextSection = new ManagedTextSection(base.Header.ImageCharacteristics, base.Header.Machine, _ilStream.Count, sizes.MetadataSize, _managedResourcesOpt?.Count ?? 0, _strongNameSignatureSize, _debugDirectoryBuilderOpt?.Size ?? 0, _mappedFieldDataOpt?.Count ?? 0); int methodBodyStreamRva = location.RelativeVirtualAddress + managedTextSection.OffsetToILStream; int mappedFieldDataStreamRva = location.RelativeVirtualAddress + managedTextSection.CalculateOffsetToMappedFieldDataStream(); _metadataRootBuilder.Serialize(blobBuilder2, methodBodyStreamRva, mappedFieldDataStreamRva); BlobBuilder blobBuilder3; DirectoryEntry debugTable; if (_debugDirectoryBuilderOpt != null) { int num = managedTextSection.ComputeOffsetToDebugDirectory(); blobBuilder3 = new BlobBuilder(_debugDirectoryBuilderOpt.TableSize); _debugDirectoryBuilderOpt.Serialize(blobBuilder3, location, num); debugTable = new DirectoryEntry(location.RelativeVirtualAddress + num, _debugDirectoryBuilderOpt.TableSize); } else { blobBuilder3 = null; debugTable = default(DirectoryEntry); } _lazyEntryPointAddress = managedTextSection.GetEntryPointAddress(location.RelativeVirtualAddress); managedTextSection.Serialize(blobBuilder, location.RelativeVirtualAddress, (!_entryPointOpt.IsNil) ? MetadataTokens.GetToken(_entryPointOpt) : 0, _corFlags, base.Header.ImageBase, blobBuilder2, _ilStream, _mappedFieldDataOpt, _managedResourcesOpt, blobBuilder3, out _lazyStrongNameSignature); _peDirectoriesBuilder.AddressOfEntryPoint = _lazyEntryPointAddress; _peDirectoriesBuilder.DebugTable = debugTable; _peDirectoriesBuilder.ImportAddressTable = managedTextSection.GetImportAddressTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.ImportTable = managedTextSection.GetImportTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.CorHeaderTable = managedTextSection.GetCorHeaderDirectoryEntry(location.RelativeVirtualAddress); return blobBuilder; } private BlobBuilder SerializeResourceSection(SectionLocation location) { BlobBuilder blobBuilder = new BlobBuilder(); _nativeResourcesOpt.Serialize(blobBuilder, location); _peDirectoriesBuilder.ResourceTable = new DirectoryEntry(location.RelativeVirtualAddress, blobBuilder.Count); return blobBuilder; } private BlobBuilder SerializeRelocationSection(SectionLocation location) { BlobBuilder blobBuilder = new BlobBuilder(); WriteRelocationSection(blobBuilder, base.Header.Machine, _lazyEntryPointAddress); _peDirectoriesBuilder.BaseRelocationTable = new DirectoryEntry(location.RelativeVirtualAddress, blobBuilder.Count); return blobBuilder; } private static void WriteRelocationSection(BlobBuilder builder, Machine machine, int entryPointAddress) { builder.WriteUInt32((uint)(entryPointAddress + 2) / 4096u * 4096); builder.WriteUInt32((machine == Machine.IA64) ? 14u : 12u); uint num = (uint)(entryPointAddress + 2) % 4096u; uint num2 = ((machine == Machine.Amd64 || machine == Machine.IA64 || machine == Machine.Arm64) ? 10u : 3u); ushort value = (ushort)((num2 << 12) | num); builder.WriteUInt16(value); if (machine == Machine.IA64) { builder.WriteUInt32(num2 << 12); } builder.WriteUInt16(0); } protected internal override PEDirectoriesBuilder GetDirectories() { return _peDirectoriesBuilder; } public void Sign(BlobBuilder peImage, Func<IEnumerable<Blob>, byte[]> signatureProvider) { if (peImage == null) { Throw.ArgumentNull("peImage"); } if (signatureProvider == null) { Throw.ArgumentNull("signatureProvider"); } Sign(peImage, _lazyStrongNameSignature, signatureProvider); } } internal sealed class ManagedTextSection { public const int ManagedResourcesDataAlignment = 8; public const int MappedFieldDataAlignment = 8; private const int CorHeaderSize = 72; public Characteristics ImageCharacteristics { get; } public Machine Machine { get; } public int ILStreamSize { get; } public int MetadataSize { get; } public int ResourceDataSize { get; } public int StrongNameSignatureSize { get; } public int DebugDataSize { get; } public int MappedFieldDataSize { get; } internal bool RequiresStartupStub { get { if (Machine != Machine.I386) { return Machine == Machine.Unknown; } return true; } } internal bool Requires64bits { get { if (Machine != Machine.Amd64 && Machine != Machine.IA64) { return Machine == Machine.Arm64; } return true; } } public bool Is32Bit => !Requires64bits; private static ReadOnlySpan<byte> CorEntryPointDll => "mscoree.dll"u8; private ReadOnlySpan<byte> CorEntryPointName { get { if ((ImageCharacteristics & Characteristics.Dll) != 0) { return "_CorDllMain"u8; } return "_CorExeMain"u8; } } private int SizeOfImportAddressTable { get { if (!RequiresStartupStub) { return 0; } if (!Is32Bit) { return 16; } return 8; } } private int SizeOfImportTable => 40 + (Is32Bit ? 12 : 16) + 2 + CorEntryPointName.Length + 1; private static int SizeOfNameTable => CorEntryPointDll.Length + 1 + 2; private int SizeOfRuntimeStartupStub { get { if (!Is32Bit) { return 16; } return 8; } } public int OffsetToILStream => SizeOfImportAddressTable + 72; public ManagedTextSection(Characteristics imageCharacteristics, Machine machine, int ilStreamSize, int metadataSize, int resourceDataSize, int strongNameSignatureSize, int debugDataSize, int mappedFieldDataSize) { MetadataSize = metadataSize; ResourceDataSize = resourceDataSize; ILStreamSize = ilStreamSize; MappedFieldDataSize = mappedFieldDataSize; StrongNameSignatureSize = strongNameSignatureSize; ImageCharacteristics = imageCharacteristics; Machine = machine; DebugDataSize = debugDataSize; } internal int CalculateOffsetToMappedFieldDataStreamUnaligned() { int num = ComputeOffsetToImportTable(); if (RequiresStartupStub) { num += SizeOfImportTable + SizeOfNameTable; num = BitArithmetic.Align(num, Is32Bit ? 4 : 8); num += SizeOfRuntimeStartupStub; } return num; } public int CalculateOffsetToMappedFieldDataStream() { int num = CalculateOffsetToMappedFieldDataStreamUnaligned(); if (MappedFieldDataSize != 0) { num = BitArithmetic.Align(num, 8); } return num; } internal int ComputeOffsetToDebugDirectory() { return ComputeOffsetToMetadata() + MetadataSize + ResourceDataSize + StrongNameSignatureSize; } private int ComputeOffsetToImportTable() { return ComputeOffsetToDebugDirectory() + DebugDataSize; } private int ComputeOffsetToMetadata() { return OffsetToILStream + BitArithmetic.Align(ILStreamSize, 4); } public int ComputeSizeOfTextSection() { return CalculateOffsetToMappedFieldDataStream() + MappedFieldDataSize; } public int GetEntryPointAddress(int rva) { if (!RequiresStartupStub) { return 0; } return rva + CalculateOffsetToMappedFieldDataStreamUnaligned() - (Is32Bit ? 6 : 10); } public DirectoryEntry GetImportAddressTableDirectoryEntry(int rva) { if (!RequiresStartupStub) { return default(DirectoryEntry); } return new DirectoryEntry(rva, SizeOfImportAddressTable); } public DirectoryEntry GetImportTableDirectoryEntry(int rva) { if (!RequiresStartupStub) { return default(DirectoryEntry); } return new DirectoryEntry(rva + ComputeOffsetToImportTable(), (Is32Bit ? 66 : 70) + 13); } public DirectoryEntry GetCorHeaderDirectoryEntry(int rva) { return new DirectoryEntry(rva + SizeOfImportAddressTable, 72); } public void Serialize(BlobBuilder builder, int relativeVirtualAddess, int entryPointTokenOrRelativeVirtualAddress, CorFlags corFlags, ulong baseAddress, BlobBuilder metadataBuilder, BlobBuilder ilBuilder, BlobBuilder? mappedFieldDataBuilderOpt, BlobBuilder? resourceBuilderOpt, BlobBuilder? debugDataBuilderOpt, out Blob strongNameSignature) { int relativeVirtualAddress = GetImportTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress; int relativeVirtualAddress2 = GetImportAddressTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress; if (RequiresStartupStub) { WriteImportAddressTable(builder, relativeVirtualAddress); } WriteCorHeader(builder, relativeVirtualAddess, entryPointTokenOrRelativeVirtualAddress, corFlags); ilBuilder.Align(4); builder.LinkSuffix(ilBuilder); builder.LinkSuffix(metadataBuilder); if (resourceBuilderOpt != null) { builder.LinkSuffix(resourceBuilderOpt); } strongNameSignature = builder.ReserveBytes(StrongNameSignatureSize); new BlobWriter(strongNameSignature).WriteBytes(0, StrongNameSignatureSize); if (debugDataBuilderOpt != null) { builder.LinkSuffix(debugDataBuilderOpt); } if (RequiresStartupStub) { WriteImportTable(builder, relativeVirtualAddress, relativeVirtualAddress2); WriteNameTable(builder); WriteRuntimeStartupStub(builder, relativeVirtualAddress2, baseAddress); } if (mappedFieldDataBuilderOpt != null) { if (mappedFieldDataBuilderOpt.Count != 0) { builder.Align(8); } builder.LinkSuffix(mappedFieldDataBuilderOpt); } } private void WriteImportAddressTable(BlobBuilder builder, int importTableRva) { _ = builder.Count; int num = importTableRva + 40 + (Is32Bit ? 12 : 16); if (Is32Bit) { builder.WriteUInt32((uint)num); builder.WriteUInt32(0u); } else { builder.WriteUInt64((uint)num); builder.WriteUInt64(0uL); } } private void WriteImportTable(BlobBuilder builder, int importTableRva, int importAddressTableRva) { _ = builder.Count; int num = importTableRva + 40; int num2 = num + (Is32Bit ? 12 : 16); int value = num2 + 12 + 2; builder.WriteUInt32((uint)num); builder.WriteUInt32(0u); builder.WriteUInt32(0u); builder.WriteUInt32((uint)value); builder.WriteUInt32((uint)importAddressTableRva); builder.WriteBytes(0, 20); if (Is32Bit) { builder.WriteUInt32((uint)num2); builder.WriteUInt32(0u); builder.WriteUInt32(0u); } else { builder.WriteUInt64((uint)num2); builder.WriteUInt64(0uL); } builder.WriteUInt16(0); builder.WriteBytes(CorEntryPointName); builder.WriteByte(0); } private static void WriteNameTable(BlobBuilder builder) { _ = builder.Count; builder.WriteBytes(CorEntryPointDll); builder.WriteByte(0); builder.WriteUInt16(0); } private void WriteCorHeader(BlobBuilder builder, int textSectionRva, int entryPointTokenOrRva, CorFlags corFlags) { int num = textSectionRva + ComputeOffsetToMetadata(); int num2 = num + MetadataSize; int num3 = num2 + ResourceDataSize; _ = builder.Count; builder.WriteUInt32(72u); builder.WriteUInt16(2); builder.WriteUInt16(5); builder.WriteUInt32((uint)num); builder.WriteUInt32((uint)MetadataSize); builder.WriteUInt32((uint)corFlags); builder.WriteUInt32((uint)entryPointTokenOrRva); builder.WriteUInt32((ResourceDataSize != 0) ? ((uint)num2) : 0u); builder.WriteUInt32((uint)ResourceDataSize); builder.WriteUInt32((StrongNameSignatureSize != 0) ? ((uint)num3) : 0u); builder.WriteUInt32((uint)StrongNameSignatureSize); builder.WriteUInt32(0u); builder.WriteUInt32(0u); builder.WriteUInt32(0u); builder.WriteUInt32(0u); builder.WriteUInt32(0u); builder.WriteUInt32(0u); builder.WriteUInt32(0u); builder.WriteUInt32(0u); } private void WriteRuntimeStartupStub(BlobBuilder sectionBuilder, int importAddressTableRva, ulong baseAddress) { if (Is32Bit) { sectionBuilder.Align(4); sectionBuilder.WriteUInt16(0); sectionBuilder.WriteByte(byte.MaxValue); sectionBuilder.WriteByte(37); sectionBuilder.WriteUInt32((uint)(importAddressTableRva + (int)baseAddress)); } else { sectionBuilder.Align(8); sectionBuilder.WriteUInt32(0u); sectionBuilder.WriteUInt16(0); sectionBuilder.WriteByte(byte.MaxValue); sectionBuilder.WriteByte(37); sectionBuilder.WriteUInt64((ulong)importAddressTableRva + baseAddress); } } } public abstract class PEBuilder { protected readonly struct Section { public readonly string Name; public readonly SectionCharacteristics Characteristics; public Section(string name, SectionCharacteristics characteristics) { if (name == null) { Throw.ArgumentNull("name"); } Name = name; Characteristics = characteristics; } } private readonly struct SerializedSection { public readonly BlobBuilder Builder; public readonly string Name; public readonly SectionCharacteristics Characteristics; public readonly int RelativeVirtualAddress; public readonly int SizeOfRawData; public readonly int PointerToRawData; public int VirtualSize => Builder.Count; public SerializedSection(BlobBuilder builder, string name, SectionCharacteristics characteristics, int relativeVirtualAddress, int sizeOfRawData, int pointerToRawData) { Name = name; Characteristics = characteristics; Builder = builder; RelativeVirtualAddress = relativeVirtualAddress; SizeOfRawData = sizeOfRawData; PointerToRawData = pointerToRawData; } } private readonly Lazy<ImmutableArray<Section>> _lazySections; private Blob _lazyChecksum; internal const int DosHeaderSize = 128; public PEHeaderBuilder Header { get; } public Func<IEnumerable<Blob>, BlobContentId> IdProvider { get; } public bool IsDeterministic { get; } private static ReadOnlySpan<byte> DosHeader => new byte[128] { 77, 90, 144, 0, 3, 0, 0, 0, 4, 0, 0, 0, 255, 255, 0, 0, 184, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 14, 31, 186, 14, 0, 180, 9, 205, 33, 184, 1, 76, 205, 33, 84, 104, 105, 115, 32, 112, 114, 111, 103, 114, 97, 109, 32, 99, 97, 110, 110, 111, 116, 32, 98, 101, 32, 114, 117, 110, 32, 105, 110, 32, 68, 79, 83, 32, 109, 111, 100, 101, 46, 13, 13, 10, 36, 0, 0, 0, 0, 0, 0, 0 }; protected PEBuilder(PEHeaderBuilder header, Func<IEnumerable<Blob>, BlobContentId>? deterministicIdProvider) { if (header == null) { Throw.ArgumentNull("header"); } IdProvider = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider(); IsDeterministic = deterministicIdProvider != null; Header = header; _lazySections = new Lazy<ImmutableArray<Section>>(CreateSections); } protected ImmutableArray<Section> GetSections() { ImmutableArray<Section> value = _lazySections.Value; if (value.IsDefault) { throw new InvalidOperationException(System.SR.Format(System.SR.MustNotReturnNull, "CreateSections")); } return value; } protected abstract ImmutableArray<Section> CreateSections(); protected abstract BlobBuilder SerializeSection(string name, SectionLocation location); protected internal abstract PEDirectoriesBuilder GetDirectories(); public BlobContentId Serialize(BlobBuilder builder) { ImmutableArray<SerializedSection> immutableArray = SerializeSections(); PEDirectoriesBuilder directories = GetDirectories(); WritePESignature(builder); WriteCoffHeader(builder, immutableArray, out var stampFixup); WritePEHeader(builder, directories, immutableArray); WriteSectionHeaders(builder, immutableArray); builder.Align(Header.FileAlignment); ImmutableArray<SerializedSection>.Enumerator enumerator = immutableArray.GetEnumerator(); while (enumerator.MoveNext()) { builder.LinkSuffix(enumerator.Current.Builder); builder.Align(Header.FileAlignment); } BlobContentId result = IdProvider(builder.GetBlobs()); new BlobWriter(stampFixup).WriteUInt32(result.Stamp); return result; } private ImmutableArray<SerializedSection> SerializeSections() { ImmutableArray<Section> sections = GetSections(); ImmutableArray<SerializedSection>.Builder builder = ImmutableArray.CreateBuilder<SerializedSection>(sections.Length); int posi
deps/System.Runtime.CompilerServices.Unsafe.dll
Decompiled a day agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Microsoft.CodeAnalysis; [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: CLSCompliant(false)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0")] [assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyVersion("6.0.0.0")] namespace System.Runtime.CompilerServices { public static class Unsafe { [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T Read<T>(void* source) { return Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T ReadUnaligned<T>(void* source) { return Unsafe.ReadUnaligned<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T ReadUnaligned<T>(ref byte source) { return Unsafe.ReadUnaligned<T>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Write<T>(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void WriteUnaligned<T>(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void WriteUnaligned<T>(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(ref T destination, void* source) { destination = Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* AsPointer<T>(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void SkipInit<T>(out T value) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static int SizeOf<T>() { return Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T As<T>(object o) where T : class { return (T)o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T AsRef<T>(void* source) { return ref *(T*)source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AsRef<T>(in T source) { return ref source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref TTo As<TFrom, TTo>(ref TFrom source) { return ref Unsafe.As<TFrom, TTo>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Unbox<T>(object box) where T : struct { return ref (T)box; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Add<T>(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Subtract<T>(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static IntPtr ByteOffset<T>(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool AreSame<T>(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressLessThan<T>(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNullRef<T>(ref T source) { return Unsafe.AsPointer(ref source) == null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T NullRef<T>() { return ref *(T*)null; } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] A_0) { TransformFlags = A_0; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } }
deps/System.Runtime.Serialization.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Configuration; using System.Runtime.Serialization.Diagnostics; using System.Runtime.Serialization.Diagnostics.Application; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Json; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.XPath; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Runtime.Serialization.dll")] [assembly: AssemblyDescription("System.Runtime.Serialization.dll")] [assembly: AssemblyDefaultAlias("System.Runtime.Serialization.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../ecma.pub")] [assembly: AllowPartiallyTrustedCallers] [assembly: ComCompatibleVersion(1, 0, 3300, 0)] [assembly: SecurityCritical(SecurityCriticalScope.Explicit)] [assembly: ComVisible(false)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class SR { internal static string GetString(string name, params object[] args) { return GetString(CultureInfo.InvariantCulture, name, args); } internal static string GetString(CultureInfo culture, string name, params object[] args) { return string.Format(culture, name, args); } internal static string GetString(string name) { return name; } internal static string GetString(CultureInfo culture, string name) { return name; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2); } internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2) { return string.Format(ci, resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3); } internal static string GetResourceString(string str) { return str; } } namespace System { internal static class LocalAppContextSwitches { public static readonly bool DoNotUseTimeZoneInfo; public static readonly bool DoNotUseEcmaScriptV6EscapeControlCharacter; } internal static class NotImplemented { internal static Exception ByDesign => new NotImplementedException(); internal static Exception ByDesignWithMessage(string message) { return new NotImplementedException(message); } } } namespace System.Xml { internal abstract class ArrayHelper<TArgument, TArray> { public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, int maxArrayLength) { TArray[][] array = null; TArray[] array2 = null; int num = 0; int num2 = 0; if (reader.TryGetArrayLength(out var count)) { if (count > maxArrayLength) { XmlExceptionHelper.ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(reader, maxArrayLength); } if (count > 65535) { count = 65535; } } else { count = 32; } while (true) { array2 = new TArray[count]; int i; int num3; for (i = 0; i < array2.Length; i += num3) { num3 = ReadArray(reader, localName, namespaceUri, array2, i, array2.Length - i); if (num3 == 0) { break; } } if (num2 > maxArrayLength - i) { XmlExceptionHelper.ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(reader, maxArrayLength); } num2 += i; if (i < array2.Length || reader.NodeType == XmlNodeType.EndElement) { break; } if (array == null) { array = new TArray[32][]; } array[num++] = array2; count *= 2; } if (num2 != array2.Length || num > 0) { TArray[] array3 = new TArray[num2]; int num4 = 0; for (int j = 0; j < num; j++) { Array.Copy(array[j], 0, array3, num4, array[j].Length); num4 += array[j].Length; } Array.Copy(array2, 0, array3, num4, num2 - num4); array2 = array3; } return array2; } public void WriteArray(XmlDictionaryWriter writer, string prefix, TArgument localName, TArgument namespaceUri, XmlDictionaryReader reader) { int count = ((!reader.TryGetArrayLength(out count)) ? 256 : Math.Min(count, 256)); TArray[] array = new TArray[count]; while (true) { int num = ReadArray(reader, localName, namespaceUri, array, 0, array.Length); if (num != 0) { WriteArray(writer, prefix, localName, namespaceUri, array, 0, num); continue; } break; } } protected abstract int ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, TArray[] array, int offset, int count); protected abstract void WriteArray(XmlDictionaryWriter writer, string prefix, TArgument localName, TArgument namespaceUri, TArray[] array, int offset, int count); } internal class BooleanArrayHelperWithString : ArrayHelper<string, bool> { public static readonly BooleanArrayHelperWithString Instance = new BooleanArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, bool[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class BooleanArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, bool> { public static readonly BooleanArrayHelperWithDictionaryString Instance = new BooleanArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int16ArrayHelperWithString : ArrayHelper<string, short> { public static readonly Int16ArrayHelperWithString Instance = new Int16ArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, short[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int16ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, short> { public static readonly Int16ArrayHelperWithDictionaryString Instance = new Int16ArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int32ArrayHelperWithString : ArrayHelper<string, int> { public static readonly Int32ArrayHelperWithString Instance = new Int32ArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, int[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int32ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, int> { public static readonly Int32ArrayHelperWithDictionaryString Instance = new Int32ArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int64ArrayHelperWithString : ArrayHelper<string, long> { public static readonly Int64ArrayHelperWithString Instance = new Int64ArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, long[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int64ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, long> { public static readonly Int64ArrayHelperWithDictionaryString Instance = new Int64ArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class SingleArrayHelperWithString : ArrayHelper<string, float> { public static readonly SingleArrayHelperWithString Instance = new SingleArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, float[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class SingleArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, float> { public static readonly SingleArrayHelperWithDictionaryString Instance = new SingleArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DoubleArrayHelperWithString : ArrayHelper<string, double> { public static readonly DoubleArrayHelperWithString Instance = new DoubleArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, double[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DoubleArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, double> { public static readonly DoubleArrayHelperWithDictionaryString Instance = new DoubleArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DecimalArrayHelperWithString : ArrayHelper<string, decimal> { public static readonly DecimalArrayHelperWithString Instance = new DecimalArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, decimal[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DecimalArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, decimal> { public static readonly DecimalArrayHelperWithDictionaryString Instance = new DecimalArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DateTimeArrayHelperWithString : ArrayHelper<string, DateTime> { public static readonly DateTimeArrayHelperWithString Instance = new DateTimeArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DateTimeArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, DateTime> { public static readonly DateTimeArrayHelperWithDictionaryString Instance = new DateTimeArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class GuidArrayHelperWithString : ArrayHelper<string, Guid> { public static readonly GuidArrayHelperWithString Instance = new GuidArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, Guid[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class GuidArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, Guid> { public static readonly GuidArrayHelperWithDictionaryString Instance = new GuidArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class TimeSpanArrayHelperWithString : ArrayHelper<string, TimeSpan> { public static readonly TimeSpanArrayHelperWithString Instance = new TimeSpanArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class TimeSpanArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, TimeSpan> { public static readonly TimeSpanArrayHelperWithDictionaryString Instance = new TimeSpanArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class EncodingStreamWrapper : Stream { private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly UTF8Encoding SafeUTF8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); private static readonly UnicodeEncoding SafeUTF16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false); private static readonly UnicodeEncoding SafeBEUTF16 = new UnicodeEncoding(bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: false); private static readonly UTF8Encoding ValidatingUTF8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private static readonly UnicodeEncoding ValidatingUTF16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); private static readonly UnicodeEncoding ValidatingBEUTF16 = new UnicodeEncoding(bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: true); private const int BufferLength = 128; private static readonly byte[] encodingAttr = new byte[8] { 101, 110, 99, 111, 100, 105, 110, 103 }; private static readonly byte[] encodingUTF8 = new byte[5] { 117, 116, 102, 45, 56 }; private static readonly byte[] encodingUnicode = new byte[6] { 117, 116, 102, 45, 49, 54 }; private static readonly byte[] encodingUnicodeLE = new byte[8] { 117, 116, 102, 45, 49, 54, 108, 101 }; private static readonly byte[] encodingUnicodeBE = new byte[8] { 117, 116, 102, 45, 49, 54, 98, 101 }; private SupportedEncoding encodingCode; private Encoding encoding; private Encoder enc; private Decoder dec; private bool isReading; private Stream stream; private char[] chars; private byte[] bytes; private int byteOffset; private int byteCount; private byte[] byteBuffer = new byte[1]; public override bool CanRead { get { if (!isReading) { return false; } return stream.CanRead; } } public override bool CanSeek => false; public override bool CanWrite { get { if (isReading) { return false; } return stream.CanWrite; } } public override long Position { get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } set { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } } public override bool CanTimeout => stream.CanTimeout; public override long Length => stream.Length; public override int ReadTimeout { get { return stream.ReadTimeout; } set { stream.ReadTimeout = value; } } public override int WriteTimeout { get { return stream.WriteTimeout; } set { stream.WriteTimeout = value; } } public EncodingStreamWrapper(Stream stream, Encoding encoding) { try { isReading = true; this.stream = new BufferedStream(stream); SupportedEncoding supportedEncoding = GetSupportedEncoding(encoding); SupportedEncoding supportedEncoding2 = ReadBOMEncoding(encoding == null); if (supportedEncoding != SupportedEncoding.None && supportedEncoding != supportedEncoding2) { ThrowExpectedEncodingMismatch(supportedEncoding, supportedEncoding2); } if (supportedEncoding2 == SupportedEncoding.UTF8) { FillBuffer(2); if (bytes[byteOffset + 1] == 63 && bytes[byteOffset] == 60) { FillBuffer(128); CheckUTF8DeclarationEncoding(bytes, byteOffset, byteCount, supportedEncoding2, supportedEncoding); } return; } EnsureBuffers(); FillBuffer(254); SetReadDocumentEncoding(supportedEncoding2); CleanupCharBreak(); int charCount = this.encoding.GetChars(bytes, byteOffset, byteCount, chars, 0); byteOffset = 0; byteCount = ValidatingUTF8.GetBytes(chars, 0, charCount, bytes, 0); if (bytes[1] == 63 && bytes[0] == 60) { CheckUTF8DeclarationEncoding(bytes, 0, byteCount, supportedEncoding2, supportedEncoding); } else if (supportedEncoding == SupportedEncoding.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents."))); } } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException)); } } private void SetReadDocumentEncoding(SupportedEncoding e) { EnsureBuffers(); encodingCode = e; encoding = GetEncoding(e); } private static Encoding GetEncoding(SupportedEncoding e) { return e switch { SupportedEncoding.UTF8 => ValidatingUTF8, SupportedEncoding.UTF16LE => ValidatingUTF16, SupportedEncoding.UTF16BE => ValidatingBEUTF16, _ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), }; } private static Encoding GetSafeEncoding(SupportedEncoding e) { return e switch { SupportedEncoding.UTF8 => SafeUTF8, SupportedEncoding.UTF16LE => SafeUTF16, SupportedEncoding.UTF16BE => SafeBEUTF16, _ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), }; } private static string GetEncodingName(SupportedEncoding enc) { return enc switch { SupportedEncoding.UTF8 => "utf-8", SupportedEncoding.UTF16LE => "utf-16LE", SupportedEncoding.UTF16BE => "utf-16BE", _ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), }; } private static SupportedEncoding GetSupportedEncoding(Encoding encoding) { if (encoding == null) { return SupportedEncoding.None; } if (encoding.WebName == ValidatingUTF8.WebName) { return SupportedEncoding.UTF8; } if (encoding.WebName == ValidatingUTF16.WebName) { return SupportedEncoding.UTF16LE; } if (encoding.WebName == ValidatingBEUTF16.WebName) { return SupportedEncoding.UTF16BE; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))); } public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM) { isReading = false; this.encoding = encoding; this.stream = new BufferedStream(stream); encodingCode = GetSupportedEncoding(encoding); if (encodingCode == SupportedEncoding.UTF8) { return; } EnsureBuffers(); dec = ValidatingUTF8.GetDecoder(); enc = this.encoding.GetEncoder(); if (emitBOM) { byte[] preamble = this.encoding.GetPreamble(); if (preamble.Length != 0) { this.stream.Write(preamble, 0, preamble.Length); } } } private SupportedEncoding ReadBOMEncoding(bool notOutOfBand) { int num = stream.ReadByte(); int num2 = stream.ReadByte(); int num3 = stream.ReadByte(); int num4 = stream.ReadByte(); if (num4 == -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file."))); } int preserve; SupportedEncoding result = ReadBOMEncoding((byte)num, (byte)num2, (byte)num3, (byte)num4, notOutOfBand, out preserve); EnsureByteBuffer(); switch (preserve) { case 1: bytes[0] = (byte)num4; break; case 2: bytes[0] = (byte)num3; bytes[1] = (byte)num4; break; case 4: bytes[0] = (byte)num; bytes[1] = (byte)num2; bytes[2] = (byte)num3; bytes[3] = (byte)num4; break; } byteCount = preserve; return result; } private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve) { SupportedEncoding result = SupportedEncoding.UTF8; preserve = 0; if (b1 == 60 && b2 != 0) { result = SupportedEncoding.UTF8; preserve = 4; } else if (b1 == byte.MaxValue && b2 == 254) { result = SupportedEncoding.UTF16LE; preserve = 2; } else if (b1 == 254 && b2 == byte.MaxValue) { result = SupportedEncoding.UTF16BE; preserve = 2; } else if (b1 == 0 && b2 == 60) { result = SupportedEncoding.UTF16BE; if (notOutOfBand && (b3 != 0 || b4 != 63)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration is required for all non-UTF8 documents."))); } preserve = 4; } else if (b1 == 60 && b2 == 0) { result = SupportedEncoding.UTF16LE; if (notOutOfBand && (b3 != 63 || b4 != 0)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration is required for all non-UTF8 documents."))); } preserve = 4; } else if (b1 == 239 && b2 == 187) { if (notOutOfBand && b3 != 191) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unrecognized Byte Order Mark."))); } preserve = 1; } else { preserve = 4; } return result; } private void FillBuffer(int count) { count -= byteCount; while (count > 0) { int num = stream.Read(bytes, byteOffset + byteCount, count); if (num != 0) { byteCount += num; count -= num; continue; } break; } } private void EnsureBuffers() { EnsureByteBuffer(); if (chars == null) { chars = new char[128]; } } private void EnsureByteBuffer() { if (bytes == null) { bytes = new byte[512]; byteOffset = 0; byteCount = 0; } } private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc) { byte b = 0; int num = -1; int num2 = offset + Math.Min(count, 128); int num3 = 0; int num4 = 0; for (num3 = offset + 2; num3 < num2; num3++) { if (b != 0) { if (buffer[num3] == b) { b = 0; } } else if (buffer[num3] == 39 || buffer[num3] == 34) { b = buffer[num3]; } else if (buffer[num3] == 61) { if (num4 == 1) { num = num3; break; } num4++; } else if (buffer[num3] == 63) { break; } } if (num == -1) { if (e != 0 && expectedEnc == SupportedEncoding.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents."))); } return; } if (num < 28) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } num3 = num - 1; while (IsWhitespace(buffer[num3])) { num3--; } if (!Compare(encodingAttr, buffer, num3 - encodingAttr.Length + 1)) { if (e == SupportedEncoding.UTF8 || expectedEnc != SupportedEncoding.None) { return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents."))); } for (num3 = num + 1; num3 < num2 && IsWhitespace(buffer[num3]); num3++) { } if (buffer[num3] != 39 && buffer[num3] != 34) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } b = buffer[num3]; int num5 = num3++; for (; buffer[num3] != b && num3 < num2; num3++) { } if (buffer[num3] != b) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } int num6 = num5 + 1; int num7 = num3 - num6; SupportedEncoding supportedEncoding = e; if (num7 == encodingUTF8.Length && CompareCaseInsensitive(encodingUTF8, buffer, num6)) { supportedEncoding = SupportedEncoding.UTF8; } else if (num7 == encodingUnicodeLE.Length && CompareCaseInsensitive(encodingUnicodeLE, buffer, num6)) { supportedEncoding = SupportedEncoding.UTF16LE; } else if (num7 == encodingUnicodeBE.Length && CompareCaseInsensitive(encodingUnicodeBE, buffer, num6)) { supportedEncoding = SupportedEncoding.UTF16BE; } else if (num7 == encodingUnicode.Length && CompareCaseInsensitive(encodingUnicode, buffer, num6)) { if (e == SupportedEncoding.UTF8) { ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), SafeUTF8.GetString(encodingUTF8, 0, encodingUTF8.Length)); } } else { ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), e); } if (e != supportedEncoding) { ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), e); } } private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i] && key[i] != char.ToLower((char)buffer[offset + i], CultureInfo.InvariantCulture)) { return false; } } return true; } private static bool Compare(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i]) { return false; } } return true; } private static bool IsWhitespace(byte ch) { if (ch != 32 && ch != 10 && ch != 9) { return ch == 13; } return true; } internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) { if (count < 4) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file."))); } try { SupportedEncoding supportedEncoding = GetSupportedEncoding(encoding); int preserve; SupportedEncoding supportedEncoding2 = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve); if (supportedEncoding != SupportedEncoding.None && supportedEncoding != supportedEncoding2) { ThrowExpectedEncodingMismatch(supportedEncoding, supportedEncoding2); } offset += 4 - preserve; count -= 4 - preserve; if (supportedEncoding2 == SupportedEncoding.UTF8) { if (buffer[offset + 1] != 63 || buffer[offset] != 60) { return new ArraySegment<byte>(buffer, offset, count); } CheckUTF8DeclarationEncoding(buffer, offset, count, supportedEncoding2, supportedEncoding); return new ArraySegment<byte>(buffer, offset, count); } Encoding safeEncoding = GetSafeEncoding(supportedEncoding2); int num = Math.Min(count, 256); char[] array = new char[safeEncoding.GetMaxCharCount(num)]; int charCount = safeEncoding.GetChars(buffer, offset, num, array, 0); byte[] array2 = new byte[ValidatingUTF8.GetMaxByteCount(charCount)]; int count2 = ValidatingUTF8.GetBytes(array, 0, charCount, array2, 0); if (array2[1] == 63 && array2[0] == 60) { CheckUTF8DeclarationEncoding(array2, 0, count2, supportedEncoding2, supportedEncoding); } else if (supportedEncoding == SupportedEncoding.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents."))); } return new ArraySegment<byte>(ValidatingUTF8.GetBytes(GetEncoding(supportedEncoding2).GetChars(buffer, offset, count))); } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException)); } } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("The expected encoding '{0}' does not match the actual encoding '{1}'.", GetEncodingName(expEnc), GetEncodingName(actualEnc)))); } private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc) { ThrowEncodingMismatch(declEnc, GetEncodingName(enc)); } private static void ThrowEncodingMismatch(string declEnc, string docEnc) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("The encoding in the declaration '{0}' does not match the encoding of the document '{1}'.", declEnc, docEnc))); } public override void Close() { Flush(); base.Close(); stream.Close(); } public override void Flush() { stream.Flush(); } public override int ReadByte() { if (byteCount == 0 && encodingCode == SupportedEncoding.UTF8) { return stream.ReadByte(); } if (Read(byteBuffer, 0, 1) == 0) { return -1; } return byteBuffer[0]; } public override int Read(byte[] buffer, int offset, int count) { try { if (byteCount == 0) { if (encodingCode == SupportedEncoding.UTF8) { return stream.Read(buffer, offset, count); } byteOffset = 0; byteCount = stream.Read(bytes, byteCount, (chars.Length - 1) * 2); if (byteCount == 0) { return 0; } CleanupCharBreak(); int charCount = encoding.GetChars(bytes, 0, byteCount, chars, 0); byteCount = Encoding.UTF8.GetBytes(chars, 0, charCount, bytes, 0); } if (byteCount < count) { count = byteCount; } Buffer.BlockCopy(bytes, byteOffset, buffer, offset, count); byteOffset += count; byteCount -= count; return count; } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException)); } } private void CleanupCharBreak() { int num = byteOffset + byteCount; if (byteCount % 2 != 0) { int num2 = stream.ReadByte(); if (num2 < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file."))); } bytes[num++] = (byte)num2; byteCount++; } int num3 = ((encodingCode != SupportedEncoding.UTF16LE) ? (bytes[num - 1] + (bytes[num - 2] << 8)) : (bytes[num - 2] + (bytes[num - 1] << 8))); if ((num3 & 0xDC00) != 56320 && num3 >= 55296 && num3 <= 56319) { int num4 = stream.ReadByte(); int num5 = stream.ReadByte(); if (num5 < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file."))); } bytes[num++] = (byte)num4; bytes[num++] = (byte)num5; byteCount += 2; } } public override long Seek(long offset, SeekOrigin origin) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public override void WriteByte(byte b) { if (encodingCode == SupportedEncoding.UTF8) { stream.WriteByte(b); return; } byteBuffer[0] = b; Write(byteBuffer, 0, 1); } public override void Write(byte[] buffer, int offset, int count) { if (encodingCode == SupportedEncoding.UTF8) { stream.Write(buffer, offset, count); return; } while (count > 0) { int num = ((chars.Length < count) ? chars.Length : count); int charCount = dec.GetChars(buffer, offset, num, chars, 0, flush: false); byteCount = enc.GetBytes(chars, 0, charCount, bytes, 0, flush: false); stream.Write(bytes, 0, byteCount); offset += num; count -= num; } } public override void SetLength(long value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } } public interface IFragmentCapableXmlDictionaryWriter { bool CanFragment { get; } void StartFragment(Stream stream, bool generateSelfContainedTextFragment); void EndFragment(); void WriteFragment(byte[] buffer, int offset, int count); } public interface IStreamProvider { Stream GetStream(); void ReleaseStream(Stream stream); } public interface IXmlDictionary { bool TryLookup(string value, out XmlDictionaryString result); bool TryLookup(int key, out XmlDictionaryString result); bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result); } internal enum PrefixHandleType { Empty, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Buffer, Max } internal class PrefixHandle { private XmlBufferReader bufferReader; private PrefixHandleType type; private int offset; private int length; private static string[] prefixStrings = new string[27] { "", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; private static byte[] prefixBuffer = new byte[26] { 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122 }; public bool IsEmpty => type == PrefixHandleType.Empty; public bool IsXmlns { get { if (type != PrefixHandleType.Buffer) { return false; } if (length != 5) { return false; } byte[] buffer = bufferReader.Buffer; int num = offset; if (buffer[num] == 120 && buffer[num + 1] == 109 && buffer[num + 2] == 108 && buffer[num + 3] == 110) { return buffer[num + 4] == 115; } return false; } } public bool IsXml { get { if (type != PrefixHandleType.Buffer) { return false; } if (length != 3) { return false; } byte[] buffer = bufferReader.Buffer; int num = offset; if (buffer[num] == 120 && buffer[num + 1] == 109) { return buffer[num + 2] == 108; } return false; } } public PrefixHandle(XmlBufferReader bufferReader) { this.bufferReader = bufferReader; } public void SetValue(PrefixHandleType type) { this.type = type; } public void SetValue(PrefixHandle prefix) { type = prefix.type; offset = prefix.offset; length = prefix.length; } public void SetValue(int offset, int length) { switch (length) { case 0: SetValue(PrefixHandleType.Empty); return; case 1: { byte @byte = bufferReader.GetByte(offset); if (@byte >= 97 && @byte <= 122) { SetValue(GetAlphaPrefix(@byte - 97)); return; } break; } } type = PrefixHandleType.Buffer; this.offset = offset; this.length = length; } public bool TryGetShortPrefix(out PrefixHandleType type) { type = this.type; return type != PrefixHandleType.Buffer; } public static string GetString(PrefixHandleType type) { return prefixStrings[(int)type]; } public static PrefixHandleType GetAlphaPrefix(int index) { return (PrefixHandleType)(1 + index); } public static byte[] GetString(PrefixHandleType type, out int offset, out int length) { if (type == PrefixHandleType.Empty) { offset = 0; length = 0; } else { length = 1; offset = (int)(type - 1); } return prefixBuffer; } public string GetString(XmlNameTable nameTable) { PrefixHandleType prefixHandleType = type; if (prefixHandleType != PrefixHandleType.Buffer) { return GetString(prefixHandleType); } return bufferReader.GetString(offset, length, nameTable); } public string GetString() { PrefixHandleType prefixHandleType = type; if (prefixHandleType != PrefixHandleType.Buffer) { return GetString(prefixHandleType); } return bufferReader.GetString(offset, length); } public byte[] GetString(out int offset, out int length) { PrefixHandleType prefixHandleType = type; if (prefixHandleType != PrefixHandleType.Buffer) { return GetString(prefixHandleType, out offset, out length); } offset = this.offset; length = this.length; return bufferReader.Buffer; } public int CompareTo(PrefixHandle that) { return GetString().CompareTo(that.GetString()); } private bool Equals2(PrefixHandle prefix2) { PrefixHandleType prefixHandleType = type; PrefixHandleType prefixHandleType2 = prefix2.type; if (prefixHandleType != prefixHandleType2) { return false; } if (prefixHandleType != PrefixHandleType.Buffer) { return true; } if (bufferReader == prefix2.bufferReader) { return bufferReader.Equals2(offset, length, prefix2.offset, prefix2.length); } return bufferReader.Equals2(offset, length, prefix2.bufferReader, prefix2.offset, prefix2.length); } private bool Equals2(string prefix2) { PrefixHandleType prefixHandleType = type; if (prefixHandleType != PrefixHandleType.Buffer) { return GetString(prefixHandleType) == prefix2; } return bufferReader.Equals2(offset, length, prefix2); } private bool Equals2(XmlDictionaryString prefix2) { return Equals2(prefix2.Value); } public static bool operator ==(PrefixHandle prefix1, string prefix2) { return prefix1.Equals2(prefix2); } public static bool operator !=(PrefixHandle prefix1, string prefix2) { return !prefix1.Equals2(prefix2); } public static bool operator ==(PrefixHandle prefix1, XmlDictionaryString prefix2) { return prefix1.Equals2(prefix2); } public static bool operator !=(PrefixHandle prefix1, XmlDictionaryString prefix2) { return !prefix1.Equals2(prefix2); } public static bool operator ==(PrefixHandle prefix1, PrefixHandle prefix2) { return prefix1.Equals2(prefix2); } public static bool operator !=(PrefixHandle prefix1, PrefixHandle prefix2) { return !prefix1.Equals2(prefix2); } public override bool Equals(object obj) { if (!(obj is PrefixHandle prefixHandle)) { return false; } return this == prefixHandle; } public override string ToString() { return GetString(); } public override int GetHashCode() { return GetString().GetHashCode(); } } internal enum StringHandleConstStringType { Type, Root, Item } internal class StringHandle { private enum StringHandleType { Dictionary, UTF8, EscapedUTF8, ConstString } private XmlBufferReader bufferReader; private StringHandleType type; private int key; private int offset; private int length; private static string[] constStrings = new string[3] { "type", "root", "item" }; public bool IsEmpty { get { if (type == StringHandleType.UTF8) { return length == 0; } return Equals2(string.Empty); } } public bool IsXmlns { get { if (type == StringHandleType.UTF8) { if (length != 5) { return false; } byte[] buffer = bufferReader.Buffer; int num = offset; if (buffer[num] == 120 && buffer[num + 1] == 109 && buffer[num + 2] == 108 && buffer[num + 3] == 110) { return buffer[num + 4] == 115; } return false; } return Equals2("xmlns"); } } public StringHandle(XmlBufferReader bufferReader) { this.bufferReader = bufferReader; SetValue(0, 0); } public void SetValue(int offset, int length) { type = StringHandleType.UTF8; this.offset = offset; this.length = length; } public void SetConstantValue(StringHandleConstStringType constStringType) { type = StringHandleType.ConstString; key = (int)constStringType; } public void SetValue(int offset, int length, bool escaped) { type = ((!escaped) ? StringHandleType.UTF8 : StringHandleType.EscapedUTF8); this.offset = offset; this.length = length; } public void SetValue(int key) { type = StringHandleType.Dictionary; this.key = key; } public void SetValue(StringHandle value) { type = value.type; key = value.key; offset = value.offset; length = value.length; } public void ToPrefixHandle(PrefixHandle prefix) { prefix.SetValue(offset, length); } public string GetString(XmlNameTable nameTable) { return type switch { StringHandleType.UTF8 => bufferReader.GetString(offset, length, nameTable), StringHandleType.Dictionary => nameTable.Add(bufferReader.GetDictionaryString(key).Value), StringHandleType.ConstString => nameTable.Add(constStrings[key]), _ => bufferReader.GetEscapedString(offset, length, nameTable), }; } public string GetString() { return type switch { StringHandleType.UTF8 => bufferReader.GetString(offset, length), StringHandleType.Dictionary => bufferReader.GetDictionaryString(key).Value, StringHandleType.ConstString => constStrings[key], _ => bufferReader.GetEscapedString(offset, length), }; } public byte[] GetString(out int offset, out int length) { switch (type) { case StringHandleType.UTF8: offset = this.offset; length = this.length; return bufferReader.Buffer; case StringHandleType.Dictionary: { byte[] array3 = bufferReader.GetDictionaryString(key).ToUTF8(); offset = 0; length = array3.Length; return array3; } case StringHandleType.ConstString: { byte[] array2 = XmlConverter.ToBytes(constStrings[key]); offset = 0; length = array2.Length; return array2; } default: { byte[] array = XmlConverter.ToBytes(bufferReader.GetEscapedString(this.offset, this.length)); offset = 0; length = array.Length; return array; } } } public bool TryGetDictionaryString(out XmlDictionaryString value) { if (type == StringHandleType.Dictionary) { value = bufferReader.GetDictionaryString(key); return true; } if (IsEmpty) { value = XmlDictionaryString.Empty; return true; } value = null; return false; } public override string ToString() { return GetString(); } private bool Equals2(int key2, XmlBufferReader bufferReader2) { return type switch { StringHandleType.Dictionary => bufferReader.Equals2(key, key2, bufferReader2), StringHandleType.UTF8 => bufferReader.Equals2(offset, length, bufferReader2.GetDictionaryString(key2).Value), _ => GetString() == bufferReader.GetDictionaryString(key2).Value, }; } private bool Equals2(XmlDictionaryString xmlString2) { return type switch { StringHandleType.Dictionary => bufferReader.Equals2(key, xmlString2), StringHandleType.UTF8 => bufferReader.Equals2(offset, length, xmlString2.ToUTF8()), _ => GetString() == xmlString2.Value, }; } private bool Equals2(string s2) { return type switch { StringHandleType.Dictionary => bufferReader.GetDictionaryString(key).Value == s2, StringHandleType.UTF8 => bufferReader.Equals2(offset, length, s2), _ => GetString() == s2, }; } private bool Equals2(int offset2, int length2, XmlBufferReader bufferReader2) { return type switch { StringHandleType.Dictionary => bufferReader2.Equals2(offset2, length2, bufferReader.GetDictionaryString(key).Value), StringHandleType.UTF8 => bufferReader.Equals2(offset, length, bufferReader2, offset2, length2), _ => GetString() == bufferReader.GetString(offset2, length2), }; } private bool Equals2(StringHandle s2) { return s2.type switch { StringHandleType.Dictionary => Equals2(s2.key, s2.bufferReader), StringHandleType.UTF8 => Equals2(s2.offset, s2.length, s2.bufferReader), _ => Equals2(s2.GetString()), }; } public static bool operator ==(StringHandle s1, XmlDictionaryString xmlString2) { return s1.Equals2(xmlString2); } public static bool operator !=(StringHandle s1, XmlDictionaryString xmlString2) { return !s1.Equals2(xmlString2); } public static bool operator ==(StringHandle s1, string s2) { return s1.Equals2(s2); } public static bool operator !=(StringHandle s1, string s2) { return !s1.Equals2(s2); } public static bool operator ==(StringHandle s1, StringHandle s2) { return s1.Equals2(s2); } public static bool operator !=(StringHandle s1, StringHandle s2) { return !s1.Equals2(s2); } public int CompareTo(StringHandle that) { if (type == StringHandleType.UTF8 && that.type == StringHandleType.UTF8) { return bufferReader.Compare(offset, length, that.offset, that.length); } return string.Compare(GetString(), that.GetString(), StringComparison.Ordinal); } public override bool Equals(object obj) { if (!(obj is StringHandle stringHandle)) { return false; } return this == stringHandle; } public override int GetHashCode() { return GetString().GetHashCode(); } } public class UniqueId { private long idLow; private long idHigh; [SecurityCritical] private string s; private const int guidLength = 16; private const int uuidLength = 45; private static short[] char2val = new short[256] { 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 160, 176, 192, 208, 224, 240, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 10, 11, 12, 13, 14, 15, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256 }; private const string val2char = "0123456789abcdef"; public int CharArrayLength { [SecuritySafeCritical] get { if (s != null) { return s.Length; } return 45; } } public bool IsGuid => (idLow | idHigh) != 0; public UniqueId() : this(Guid.NewGuid()) { } public UniqueId(Guid guid) : this(guid.ToByteArray()) { } public UniqueId(byte[] guid) : this(guid, 0) { } [SecuritySafeCritical] public unsafe UniqueId(byte[] guid, int offset) { if (guid == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("guid")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > guid.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", guid.Length))); } if (16 > guid.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small. Length of available data must be at least {0}.", 16), "guid")); } fixed (byte* ptr = &guid[offset]) { idLow = UnsafeGetInt64(ptr); idHigh = UnsafeGetInt64(ptr + 8); } } [SecuritySafeCritical] public unsafe UniqueId(string value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("UniqueId cannot be zero length."))); } fixed (char* chars = value) { UnsafeParse(chars, value.Length); } s = value; } [SecuritySafeCritical] public unsafe UniqueId(char[] chars, int offset, int count) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } if (count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("UniqueId cannot be zero length."))); } fixed (char* chars2 = &chars[offset]) { UnsafeParse(chars2, count); } if (!IsGuid) { s = new string(chars, offset, count); } } [SecurityCritical] private unsafe int UnsafeDecode(short* char2val, char ch1, char ch2) { if ((ch1 | ch2) >= 128) { return 256; } return char2val[(int)ch1] | char2val[128 + ch2]; } [SecurityCritical] private unsafe void UnsafeEncode(char* val2char, byte b, char* pch) { *pch = val2char[b >> 4]; pch[1] = val2char[b & 0xF]; } [SecurityCritical] private unsafe void UnsafeParse(char* chars, int charCount) { if (charCount != 45 || *chars != 'u' || chars[1] != 'r' || chars[2] != 'n' || chars[3] != ':' || chars[4] != 'u' || chars[5] != 'u' || chars[6] != 'i' || chars[7] != 'd' || chars[8] != ':' || chars[17] != '-' || chars[22] != '-' || chars[27] != '-' || chars[32] != '-') { return; } byte* ptr = stackalloc byte[16]; int num = 0; fixed (short* ptr2 = char2val) { short* ptr3 = ptr2; num = UnsafeDecode(ptr3, chars[15], chars[16]); *ptr = (byte)num; int num2 = 0 | num; num = UnsafeDecode(ptr3, chars[13], chars[14]); ptr[1] = (byte)num; int num3 = num2 | num; num = UnsafeDecode(ptr3, chars[11], chars[12]); ptr[2] = (byte)num; int num4 = num3 | num; num = UnsafeDecode(ptr3, chars[9], chars[10]); ptr[3] = (byte)num; int num5 = num4 | num; num = UnsafeDecode(ptr3, chars[20], chars[21]); ptr[4] = (byte)num; int num6 = num5 | num; num = UnsafeDecode(ptr3, chars[18], chars[19]); ptr[5] = (byte)num; int num7 = num6 | num; num = UnsafeDecode(ptr3, chars[25], chars[26]); ptr[6] = (byte)num; int num8 = num7 | num; num = UnsafeDecode(ptr3, chars[23], chars[24]); ptr[7] = (byte)num; int num9 = num8 | num; num = UnsafeDecode(ptr3, chars[28], chars[29]); ptr[8] = (byte)num; int num10 = num9 | num; num = UnsafeDecode(ptr3, chars[30], chars[31]); ptr[9] = (byte)num; int num11 = num10 | num; num = UnsafeDecode(ptr3, chars[33], chars[34]); ptr[10] = (byte)num; int num12 = num11 | num; num = UnsafeDecode(ptr3, chars[35], chars[36]); ptr[11] = (byte)num; int num13 = num12 | num; num = UnsafeDecode(ptr3, chars[37], chars[38]); ptr[12] = (byte)num; int num14 = num13 | num; num = UnsafeDecode(ptr3, chars[39], chars[40]); ptr[13] = (byte)num; int num15 = num14 | num; num = UnsafeDecode(ptr3, chars[41], chars[42]); ptr[14] = (byte)num; int num16 = num15 | num; num = UnsafeDecode(ptr3, chars[43], chars[44]); ptr[15] = (byte)num; if ((num16 | num) >= 256) { return; } idLow = UnsafeGetInt64(ptr); idHigh = UnsafeGetInt64(ptr + 8); } } [SecuritySafeCritical] public unsafe int ToCharArray(char[] chars, int offset) { int charArrayLength = CharArrayLength; if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (charArrayLength > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("chars", System.Runtime.Serialization.SR.GetString("Array too small. Must be able to hold at least {0}.", charArrayLength))); } if (s != null) { s.CopyTo(0, chars, offset, charArrayLength); } else { byte* ptr = stackalloc byte[16]; UnsafeSetInt64(idLow, ptr); UnsafeSetInt64(idHigh, ptr + 8); fixed (char* ptr2 = &chars[offset]) { *ptr2 = 'u'; ptr2[1] = 'r'; ptr2[2] = 'n'; ptr2[3] = ':'; ptr2[4] = 'u'; ptr2[5] = 'u'; ptr2[6] = 'i'; ptr2[7] = 'd'; ptr2[8] = ':'; ptr2[17] = '-'; ptr2[22] = '-'; ptr2[27] = '-'; ptr2[32] = '-'; fixed (char* ptr3 = "0123456789abcdef") { char* ptr4 = ptr3; UnsafeEncode(ptr4, *ptr, ptr2 + 15); UnsafeEncode(ptr4, ptr[1], ptr2 + 13); UnsafeEncode(ptr4, ptr[2], ptr2 + 11); UnsafeEncode(ptr4, ptr[3], ptr2 + 9); UnsafeEncode(ptr4, ptr[4], ptr2 + 20); UnsafeEncode(ptr4, ptr[5], ptr2 + 18); UnsafeEncode(ptr4, ptr[6], ptr2 + 25); UnsafeEncode(ptr4, ptr[7], ptr2 + 23); UnsafeEncode(ptr4, ptr[8], ptr2 + 28); UnsafeEncode(ptr4, ptr[9], ptr2 + 30); UnsafeEncode(ptr4, ptr[10], ptr2 + 33); UnsafeEncode(ptr4, ptr[11], ptr2 + 35); UnsafeEncode(ptr4, ptr[12], ptr2 + 37); UnsafeEncode(ptr4, ptr[13], ptr2 + 39); UnsafeEncode(ptr4, ptr[14], ptr2 + 41); UnsafeEncode(ptr4, ptr[15], ptr2 + 43); } } } return charArrayLength; } public bool TryGetGuid(out Guid guid) { byte[] array = new byte[16]; if (!TryGetGuid(array, 0)) { guid = Guid.Empty; return false; } guid = new Guid(array); return true; } [SecuritySafeCritical] public unsafe bool TryGetGuid(byte[] buffer, int offset) { if (!IsGuid) { return false; } if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (16 > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("buffer", System.Runtime.Serialization.SR.GetString("Array too small. Must be able to hold at least {0}.", 16))); } fixed (byte* ptr = &buffer[offset]) { UnsafeSetInt64(idLow, ptr); UnsafeSetInt64(idHigh, ptr + 8); } return true; } [SecuritySafeCritical] public override string ToString() { if (s == null) { int charArrayLength = CharArrayLength; char[] array = new char[charArrayLength]; ToCharArray(array, 0); s = new string(array, 0, charArrayLength); } return s; } public static bool operator ==(UniqueId id1, UniqueId id2) { if ((object)id1 == null && (object)id2 == null) { return true; } if ((object)id1 == null || (object)id2 == null) { return false; } if (id1.IsGuid && id2.IsGuid) { if (id1.idLow == id2.idLow) { return id1.idHigh == id2.idHigh; } return false; } return id1.ToString() == id2.ToString(); } public static bool operator !=(UniqueId id1, UniqueId id2) { return !(id1 == id2); } public override bool Equals(object obj) { return this == obj as UniqueId; } public override int GetHashCode() { if (IsGuid) { long num = idLow ^ idHigh; return (int)(num >> 32) ^ (int)num; } return ToString().GetHashCode(); } [SecurityCritical] private unsafe long UnsafeGetInt64(byte* pb) { int num = UnsafeGetInt32(pb); return ((long)UnsafeGetInt32(pb + 4) << 32) | (uint)num; } [SecurityCritical] private unsafe int UnsafeGetInt32(byte* pb) { return (((((pb[3] << 8) | pb[2]) << 8) | pb[1]) << 8) | *pb; } [SecurityCritical] private unsafe void UnsafeSetInt64(long value, byte* pb) { UnsafeSetInt32((int)value, pb); UnsafeSetInt32((int)(value >> 32), pb + 4); } [SecurityCritical] private unsafe void UnsafeSetInt32(int value, byte* pb) { *pb = (byte)value; value >>= 8; pb[1] = (byte)value; value >>= 8; pb[2] = (byte)value; value >>= 8; pb[3] = (byte)value; } } internal enum ValueHandleConstStringType { String, Number, Array, Object, Boolean, Null } internal static class ValueHandleLength { public const int Int8 = 1; public const int Int16 = 2; public const int Int32 = 4; public const int Int64 = 8; public const int UInt64 = 8; public const int Single = 4; public const int Double = 8; public const int Decimal = 16; public const int DateTime = 8; public const int TimeSpan = 8; public const int Guid = 16; public const int UniqueId = 16; } internal enum ValueHandleType { Empty, True, False, Zero, One, Int8, Int16, Int32, Int64, UInt64, Single, Double, Decimal, DateTime, TimeSpan, Guid, UniqueId, UTF8, EscapedUTF8, Base64, Dictionary, List, Char, Unicode, QName, ConstString } internal class ValueHandle { private XmlBufferReader bufferReader; private ValueHandleType type; private int offset; private int length; private static Base64Encoding base64Encoding; private static string[] constStrings = new string[6] { "string", "number", "array", "object", "boolean", "null" }; private static Base64Encoding Base64Encoding { get { if (base64Encoding == null) { base64Encoding = new Base64Encoding(); } return base64Encoding; } } public ValueHandle(XmlBufferReader bufferReader) { this.bufferReader = bufferReader; type = ValueHandleType.Empty; } public void SetConstantValue(ValueHandleConstStringType constStringType) { type = ValueHandleType.ConstString; offset = (int)constStringType; } public void SetValue(ValueHandleType type) { this.type = type; } public void SetDictionaryValue(int key) { SetValue(ValueHandleType.Dictionary, key, 0); } public void SetCharValue(int ch) { SetValue(ValueHandleType.Char, ch, 0); } public void SetQNameValue(int prefix, int key) { SetValue(ValueHandleType.QName, key, prefix); } public void SetValue(ValueHandleType type, int offset, int length) { this.type = type; this.offset = offset; this.length = length; } public bool IsWhitespace() { switch (type) { case ValueHandleType.UTF8: return bufferReader.IsWhitespaceUTF8(offset, length); case ValueHandleType.Dictionary: return bufferReader.IsWhitespaceKey(offset); case ValueHandleType.Char: { int @char = GetChar(); if (@char > 65535) { return false; } return XmlConverter.IsWhitespace((char)@char); } case ValueHandleType.EscapedUTF8: return bufferReader.IsWhitespaceUTF8(offset, length); case ValueHandleType.Unicode: return bufferReader.IsWhitespaceUnicode(offset, length); case ValueHandleType.True: case ValueHandleType.False: case ValueHandleType.Zero: case ValueHandleType.One: return false; case ValueHandleType.ConstString: return constStrings[offset].Length == 0; default: return length == 0; } } public Type ToType() { switch (type) { case ValueHandleType.True: case ValueHandleType.False: return typeof(bool); case ValueHandleType.Zero: case ValueHandleType.One: case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return typeof(int); case ValueHandleType.Int64: return typeof(long); case ValueHandleType.UInt64: return typeof(ulong); case ValueHandleType.Single: return typeof(float); case ValueHandleType.Double: return typeof(double); case ValueHandleType.Decimal: return typeof(decimal); case ValueHandleType.DateTime: return typeof(DateTime); case ValueHandleType.Empty: case ValueHandleType.UTF8: case ValueHandleType.EscapedUTF8: case ValueHandleType.Dictionary: case ValueHandleType.Char: case ValueHandleType.Unicode: case ValueHandleType.QName: case ValueHandleType.ConstString: return typeof(string); case ValueHandleType.Base64: return typeof(byte[]); case ValueHandleType.List: return typeof(object[]); case ValueHandleType.UniqueId: return typeof(UniqueId); case ValueHandleType.Guid: return typeof(Guid); case ValueHandleType.TimeSpan: return typeof(TimeSpan); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } public bool ToBoolean() { switch (type) { case ValueHandleType.False: return false; case ValueHandleType.True: return true; case ValueHandleType.UTF8: return XmlConverter.ToBoolean(bufferReader.Buffer, offset, length); case ValueHandleType.Int8: switch (GetInt8()) { case 0: return false; case 1: return true; } break; } return XmlConverter.ToBoolean(GetString()); } public int ToInt() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Zero: return 0; case ValueHandleType.One: return 1; case ValueHandleType.Int8: return GetInt8(); case ValueHandleType.Int16: return GetInt16(); case ValueHandleType.Int32: return GetInt32(); case ValueHandleType.Int64: { long @int = GetInt64(); if (@int >= int.MinValue && @int <= int.MaxValue) { return (int)@int; } break; } } if (valueHandleType == ValueHandleType.UInt64) { ulong uInt = GetUInt64(); if (uInt <= int.MaxValue) { return (int)uInt; } } if (valueHandleType == ValueHandleType.UTF8) { return XmlConverter.ToInt32(bufferReader.Buffer, offset, length); } return XmlConverter.ToInt32(GetString()); } public long ToLong() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Zero: return 0L; case ValueHandleType.One: return 1L; case ValueHandleType.Int8: return GetInt8(); case ValueHandleType.Int16: return GetInt16(); case ValueHandleType.Int32: return GetInt32(); case ValueHandleType.Int64: return GetInt64(); case ValueHandleType.UInt64: { ulong uInt = GetUInt64(); if (uInt <= long.MaxValue) { return (long)uInt; } break; } } if (valueHandleType == ValueHandleType.UTF8) { return XmlConverter.ToInt64(bufferReader.Buffer, offset, length); } return XmlConverter.ToInt64(GetString()); } public ulong ToULong() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Zero: return 0uL; case ValueHandleType.One: return 1uL; case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: case ValueHandleType.Int64: { long num = ToLong(); if (num >= 0) { return (ulong)num; } break; } } return valueHandleType switch { ValueHandleType.UInt64 => GetUInt64(), ValueHandleType.UTF8 => XmlConverter.ToUInt64(bufferReader.Buffer, offset, length), _ => XmlConverter.ToUInt64(GetString()), }; } public float ToSingle() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Single: return GetSingle(); case ValueHandleType.Double: { double @double = GetDouble(); if ((@double >= -3.4028234663852886E+38 && @double <= 3.4028234663852886E+38) || double.IsInfinity(@double) || double.IsNaN(@double)) { return (float)@double; } break; } } return valueHandleType switch { ValueHandleType.Zero => 0f, ValueHandleType.One => 1f, ValueHandleType.Int8 => GetInt8(), ValueHandleType.Int16 => GetInt16(), ValueHandleType.UTF8 => XmlConverter.ToSingle(bufferReader.Buffer, offset, length), _ => XmlConverter.ToSingle(GetString()), }; } public double ToDouble() { return type switch { ValueHandleType.Double => GetDouble(), ValueHandleType.Single => GetSingle(), ValueHandleType.Zero => 0.0, ValueHandleType.One => 1.0, ValueHandleType.Int8 => GetInt8(), ValueHandleType.Int16 => GetInt16(), ValueHandleType.Int32 => GetInt32(), ValueHandleType.UTF8 => XmlConverter.ToDouble(bufferReader.Buffer, offset, length), _ => XmlConverter.ToDouble(GetString()), }; } public decimal ToDecimal() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Decimal: return GetDecimal(); case ValueHandleType.Zero: return 0m; case ValueHandleType.One: return 1m; case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: case ValueHandleType.Int64: return ToLong(); default: return valueHandleType switch { ValueHandleType.UInt64 => GetUInt64(), ValueHandleType.UTF8 => XmlConverter.ToDecimal(bufferReader.Buffer, offset, length), _ => XmlConverter.ToDecimal(GetString()), }; } } public DateTime ToDateTime() { if (type == ValueHandleType.DateTime) { return XmlConverter.ToDateTime(GetInt64()); } if (type == ValueHandleType.UTF8) { return XmlConverter.ToDateTime(bufferReader.Buffer, offset, length); } return XmlConverter.ToDateTime(GetString()); } public UniqueId ToUniqueId() { if (type == ValueHandleType.UniqueId) { return GetUniqueId(); } if (type == ValueHandleType.UTF8) { return XmlConverter.ToUniqueId(bufferReader.Buffer, offset, length); } return XmlConverter.ToUniqueId(GetString()); } public TimeSpan ToTimeSpan() { if (type == ValueHandleType.TimeSpan) { return new TimeSpan(GetInt64()); } if (type == ValueHandleType.UTF8) { return XmlConverter.ToTimeSpan(bufferReader.Buffer, offset, length); } return XmlConverter.ToTimeSpan(GetString()); } public Guid ToGuid() { if (type == ValueHandleType.Guid) { return GetGuid(); } if (type == ValueHandleType.UTF8) { return XmlConverter.ToGuid(bufferReader.Buffer, offset, length); } return XmlConverter.ToGuid(GetString()); } public override string ToString() { return GetString(); } public byte[] ToByteArray() { if (type == ValueHandleType.Base64) { byte[] array = new byte[length]; GetBase64(array, 0, length); return array; } if (type == ValueHandleType.UTF8 && length % 4 == 0) { try { int num = length / 4 * 3; if (length > 0 && bufferReader.Buffer[offset + length - 1] == 61) { num--; if (bufferReader.Buffer[offset + length - 2] == 61) { num--; } } byte[] array2 = new byte[num]; int bytes = Base64Encoding.GetBytes(bufferReader.Buffer, offset, length, array2, 0); if (bytes != array2.Length) { byte[] array3 = new byte[bytes]; Buffer.BlockCopy(array2, 0, array3, 0, bytes); array2 = array3; } return array2; } catch (FormatException) { } } try { return Base64Encoding.GetBytes(XmlConverter.StripWhitespace(GetString())); } catch (FormatException ex2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(ex2.Message, ex2.InnerException)); } } public string GetString() { ValueHandleType valueHandleType = type; if (valueHandleType == ValueHandleType.UTF8) { return GetCharsText(); } switch (valueHandleType) { case ValueHandleType.False: return "false"; case ValueHandleType.True: return "true"; case ValueHandleType.Zero: return "0"; case ValueHandleType.One: return "1"; case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return XmlConverter.ToString(ToInt()); case ValueHandleType.Int64: return XmlConverter.ToString(GetInt64()); case ValueHandleType.UInt64: return XmlConverter.ToString(GetUInt64()); case ValueHandleType.Single: return XmlConverter.ToString(GetSingle()); case ValueHandleType.Double: return XmlConverter.ToString(GetDouble()); case ValueHandleType.Decimal: return XmlConverter.ToString(GetDecimal()); case ValueHandleType.DateTime: return XmlConverter.ToString(ToDateTime()); case ValueHandleType.Empty: return string.Empty; case ValueHandleType.UTF8: return GetCharsText(); case ValueHandleType.Unicode: return GetUnicodeCharsText(); case ValueHandleType.EscapedUTF8: return GetEscapedCharsText(); case ValueHandleType.Char: return GetCharText(); case ValueHandleType.Dictionary: return GetDictionaryString().Value; case ValueHandleType.Base64: return Base64Encoding.GetString(ToByteArray()); case ValueHandleType.List: return XmlConverter.ToString(ToList()); case ValueHandleType.UniqueId: return XmlConverter.ToString(ToUniqueId()); case ValueHandleType.Guid: return XmlConverter.ToString(ToGuid()); case ValueHandleType.TimeSpan: return XmlConverter.ToString(ToTimeSpan()); case ValueHandleType.QName: return GetQNameDictionaryText(); case ValueHandleType.ConstString: return constStrings[offset]; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } public bool Equals2(string str, bool checkLower) { if (type != ValueHandleType.UTF8) { return GetString() == str; } if (length != str.Length) { return false; } byte[] buffer = bufferReader.Buffer; for (int i = 0; i < length; i++) { byte b = buffer[i + offset]; if (b != str[i] && (!checkLower || char.ToLowerInvariant((char)b) != str[i])) { return false; } } return true; } public void Sign(XmlSigningNodeWriter writer) { switch (type) { case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: writer.WriteInt32Text(ToInt()); break; case ValueHandleType.Int64: writer.WriteInt64Text(GetInt64()); break; case ValueHandleType.UInt64: writer.WriteUInt64Text(GetUInt64()); break; case ValueHandleType.Single: writer.WriteFloatText(GetSingle()); break; case ValueHandleType.Double: writer.WriteDoubleText(GetDouble()); break; case ValueHandleType.Decimal: writer.WriteDecimalText(GetDecimal()); break; case ValueHandleType.DateTime: writer.WriteDateTimeText(ToDateTime()); break; case ValueHandleType.UTF8: writer.WriteEscapedText(bufferReader.Buffer, offset, length); break; case ValueHandleType.Base64: writer.WriteBase64Text(bufferReader.Buffer, 0, bufferReader.Buffer, offset, length); break; case ValueHandleType.UniqueId: writer.WriteUniqueIdText(ToUniqueId()); break; case ValueHandleType.Guid: writer.WriteGuidText(ToGuid()); break; case ValueHandleType.TimeSpan: writer.WriteTimeSpanText(ToTimeSpan()); break; default: writer.WriteEscapedText(GetString()); break; case ValueHandleType.Empty: break; } } public object[] ToList() { return bufferReader.GetList(offset, length); } public object ToObject() { switch (type) { case ValueHandleType.True: case ValueHandleType.False: return ToBoolean(); case ValueHandleType.Zero: case ValueHandleType.One: case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return ToInt(); case ValueHandleType.Int64: return ToLong(); case ValueHandleType.UInt64: return GetUInt64(); case ValueHandleType.Single: return ToSingle(); case ValueHandleType.Double: return ToDouble(); case ValueHandleType.Decimal: return ToDecimal(); case ValueHandleType.DateTime: return ToDateTime(); case ValueHandleType.Empty: case ValueHandleType.UTF8: case ValueHandleType.EscapedUTF8: case ValueHandleType.Dictionary: case ValueHandleType.Char: case ValueHandleType.Unicode: case ValueHandleType.ConstString: return ToString(); case ValueHandleType.Base64: return ToByteArray(); case ValueHandleType.List: return ToList(); case ValueHandleType.UniqueId: return ToUniqueId(); case ValueHandleType.Guid: return ToGuid(); case ValueHandleType.TimeSpan: return ToTimeSpan(); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } public bool TryReadBase64(byte[] buffer, int offset, int count, out int actual) { if (type == ValueHandleType.Base64) { actual = Math.Min(length, count); GetBase64(buffer, offset, actual); this.offset += actual; length -= actual; return true; } if (type == ValueHandleType.UTF8 && count >= 3 && length % 4 == 0) { try { int num = Math.Min(count / 3 * 4, length); actual = Base64Encoding.GetBytes(bufferReader.Buffer, this.offset, num, buffer, offset); this.offset += num; length -= num; return true; } catch (FormatException) { } } actual = 0; return false; } public bool TryReadChars(char[] chars, int offset, int count, out int actual) { if (type == ValueHandleType.Unicode) { return TryReadUnicodeChars(chars, offset, count, out actual); } if (type != ValueHandleType.UTF8) { actual = 0; return false; } int num = offset; int num2 = count; byte[] buffer = bufferReader.Buffer; int num3 = this.offset; int num4 = length; bool flag = false; while (true) { if (num2 > 0 && num4 > 0) { byte b = buffer[num3]; if (b < 128) { chars[num] = (char)b; num3++; num4--; num++; num2--; continue; } } if (num2 == 0 || num4 == 0 || flag) { break; } UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); int chars2; int num5; try { if (num2 >= uTF8Encoding.GetMaxCharCount(num4) || num2 >= uTF8Encoding.GetCharCount(buffer, num3, num4)) { chars2 = uTF8Encoding.GetChars(buffer, num3, num4, chars, num); num5 = num4; } else { Decoder decoder = uTF8Encoding.GetDecoder(); num5 = Math.Min(num2, num4); chars2 = decoder.GetChars(buffer, num3, num5, chars, num); while (chars2 == 0) { if (num5 >= 3 && num2 < 2) { flag = true; break; } chars2 = decoder.GetChars(buffer, num3 + num5, 1, chars, num); num5++; } num5 = uTF8Encoding.GetByteCount(chars, num, chars2); } } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, num3, num4, exception)); } num3 += num5; num4 -= num5; num += chars2; num2 -= chars2; } this.offset = num3; length = num4; actual = count - num2; return true; } private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int actual) { int num = Math.Min(count, length / 2); for (int i = 0; i < num; i++) { chars[offset + i] = (char)bufferReader.GetInt16(this.offset + i * 2); } this.offset += num * 2; length -= num * 2; actual = num; return true; } public bool TryGetDictionaryString(out XmlDictionaryString value) { if (type == ValueHandleType.Dictionary) { value = GetDictionaryString(); return true; } value = null; return false; } public bool TryGetByteArrayLength(out int length) { if (type == ValueHandleType.Base64) { length = this.length; return true; } length = 0; return false; } private string GetCharsText() { if (length == 1 && bufferReader.GetByte(offset) == 49) { return "1"; } return bufferReader.GetString(offset, length); } private string GetUnicodeCharsText() { return bufferReader.GetUnicodeString(offset, length); } private string GetEscapedCharsText() { return bufferReader.GetEscapedString(offset, length); } private string GetCharText() { int @char = GetChar(); if (@char > 65535) { SurrogateChar surrogateChar = new SurrogateChar(@char); return new string(new char[2] { surrogateChar.HighChar, surrogateChar.LowChar }, 0, 2); } return ((char)@char).ToString(); } private int GetChar() { return offset; } private int GetInt8() { return bufferReader.GetInt8(offset); } private int GetInt16() { return bufferReader.GetInt16(offset); } private int GetInt32() { return bufferReader.GetInt32(offset); } private long GetInt64() { return bufferReader.GetInt64(offset); } private ulong GetUInt64() { return bufferReader.GetUInt64(offset); } private float GetSingle() { return bufferReader.GetSingle(offset); } private double GetDouble() { return bufferReader.GetDouble(offset); } private decimal GetDecimal() { return bufferReader.GetDecimal(offset); } private UniqueId GetUniqueId() { return bufferReader.GetUniqueId(offset); } private Guid GetGuid() { return bufferReader.GetGuid(offset); } private void GetBase64(byte[] buffer, int offset, int count) { bufferReader.GetBase64(this.offset, buffer, offset, count); } private XmlDictionaryString GetDictionaryString() { return bufferReader.GetDictionaryString(offset); } private string GetQNameDictionaryText() { return PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(length)) + ":" + bufferReader.GetDictionaryString(offset); } } internal abstract class XmlBaseReader : XmlDictionaryReader { protected enum QNameType { Normal, Xmlns } protected class XmlNode { protected enum XmlNodeFlags { None = 0, CanGetAttribute = 1, CanMoveToElement = 2, HasValue = 4, AtomicValue = 8, SkipValue = 0x10, HasContent = 0x20 } private XmlNodeType nodeType; private PrefixHandle prefix; private StringHandle localName; private ValueHandle value; private Namespace ns; private bool hasValue; private bool canGetAttribute; private bool canMoveToElement; private ReadState readState; private XmlAttributeTextNode attributeTextNode; private bool exitScope; private int depthDelta; private bool isAtomicValue; private bool skipValue; private QNameType qnameType; private bool hasContent; private bool isEmptyElement; private char quoteChar; public bool HasValue => hasValue; public ReadState ReadState => readState; public StringHandle LocalName => localName; public PrefixHandle Prefix => prefix; public bool CanGetAttribute => canGetAttribute; public bool CanMoveToElement => canMoveToElement; public XmlAttributeTextNode AttributeText => attributeTextNode; public bool SkipValue => skipValue; public ValueHandle Value => value; public int DepthDelta => depthDelta; public bool HasContent => hasContent; public XmlNodeType NodeType { get { return nodeType; } set { nodeType = value; } } public QNameType QNameType { get { return qnameType; } set { qnameType = value; } } public Namespace Namespace { get { return ns; } set { ns = value; } } public bool IsAtomicValue { get { return isAtomicValue; } set { isAtomicValue = value; } } public bool ExitScope { get { return exitScope; } set { exitScope = value; } } public bool IsEmptyElement { get { return isEmptyElement; } set { isEmptyElement = value; } } public char QuoteChar { get { return quoteChar; } set { quoteChar = value; } } public string ValueAsString { get { if (qnameType == QNameType.Normal) { return Value.GetString(); } return Namespace.Uri.GetString(); } } protected XmlNode(XmlNodeType nodeType, PrefixHandle prefix, StringHandle localName, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, XmlAttributeTextNode attributeTextNode, int depthDelta) { this.nodeType = nodeType; this.prefix = prefix; this.localName = localName; this.value = value; ns = NamespaceManager.EmptyNamespace; hasValue = (nodeFlags & XmlNodeFlags.HasValue) != 0; canGetAttribute = (nodeFlags & XmlNodeFlags.CanGetAttribute) != 0; canMoveToElement = (nodeFlags & XmlNodeFlags.CanMoveToElement) != 0; isAtomicValue = (nodeFlags & XmlNodeFlags.AtomicValue) != 0; skipValue = (nodeFlags & XmlNodeFlags.SkipValue) != 0; hasContent = (nodeFlags & XmlNodeFlags.HasContent) != 0; this.readState = readState; this.attributeTextNode = attributeTextNode; exitScope = nodeType == XmlNodeType.EndElement; this.depthDelta = depthDelta; isEmptyElement = false; quoteChar = '"'; qnameType = QNameType.Normal; } public bool IsLocalName(string localName) { if (qnameType == QNameType.Normal) { return LocalName == localName; } return Namespace.Prefix == localName; } public bool IsLocalName(XmlDictionaryString localName) { if (qnameType == QNameType.Normal) { return LocalName == localName; } return Namespace.Prefix == localName; } public bool IsNamespaceUri(string ns) { if (qnameType == QNameType.Normal) { return Namespace.IsUri(ns); } return ns == "http://www.w3.org/2000/xmlns/"; } public bool IsNamespaceUri(XmlDictionaryString ns) { if (qnameType == QNameType.Normal) { return Namespace.IsUri(ns); } return ns.Value == "http://www.w3.org/2000/xmlns/"; } public bool IsLocalNameAndNamespaceUri(string localName, string ns) { if (qnameType == QNameType.Normal) { if (LocalName == localName) { return Namespace.IsUri(ns); } return false; } if (Namespace.Prefix == localName) { return ns == "http://www.w3.org/2000/xmlns/"; } return false; } public bool IsLocalNameAndNamespaceUri(XmlDictionaryString localName, XmlDictionaryString ns) { if (qnameType == QNameType.Normal) { if (LocalName == localName) { return Namespace.IsUri(ns); } return false; } if (Namespace.Prefix == localName) { return ns.Value == "http://www.w3.org/2000/xmlns/"; } return false; } public bool IsPrefixAndLocalName(string prefix, string localName) { if (qnameType == QNameType.Normal) { if (Prefix == prefix) { return LocalName == localName; } return false; } if (prefix == "xmlns") { return Namespace.Prefix == localName; } return false; } public bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName) { if (qnameType == QNameType.Normal) { return LocalName.TryGetDictionaryString(out localName); } localName = null; return false; } public bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString ns) { if (qnameType == QNameType.Normal) { return Namespace.Uri.TryGetDictionaryString(out ns); } ns = null; return false; } public bool TryGetValueAsDictionaryString(out XmlDictionaryString value) { if (qnameType == QNameType.Normal) { return Value.TryGetDictionaryString(out value); } value = null; return false; } } protected class XmlElementNode : XmlNode { private XmlEndElementNode endElementNode; private int bufferOffset; public int NameOffset; public int NameLength; public XmlEndElementNode EndElement => endElementNode; public int BufferOffset { get { return bufferOffset; } set { bufferOffset = value; } } public XmlElementNode(XmlBufferReader bufferReader) : this(new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader)) { } private XmlElementNode(PrefixHandle prefix, StringHandle localName, ValueHandle value) : base(XmlNodeType.Element, prefix, localName, value, (XmlNodeFlags)33, ReadState.Interactive, null, -1) { endElementNode = new XmlEndElementNode(prefix, localName, value); } } protected class XmlAttributeNode : XmlNode { public XmlAttributeNode(XmlBufferReader bufferReader) : this(new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader)) { } private XmlAttributeNode(PrefixHandle prefix, StringHandle localName, ValueHandle value) : base(XmlNodeType.Attribute, prefix, localName, value, (XmlNodeFlags)15, ReadState.Interactive, new XmlAttributeTextNode(prefix, localName, value), 0) { } } protected class XmlEndElementNode : XmlNode { public XmlEndElementNode(PrefixHandle prefix, StringHandle localName, ValueHandle value) : base(XmlNodeType.EndElement, prefix, localName, value, XmlNodeFlags.HasContent, ReadState.Interactive, null, -1) { } } protected class XmlTextNode : XmlNode { protected XmlTextNode(XmlNodeType nodeType, PrefixHandle prefix, StringHandle localName, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, XmlAttributeTextNode attributeTextNode, int depthDelta) : base(nodeType, prefix, localName, value, nodeFlags, readState, attributeTextNode, depthDelta) { } } protected class XmlAtomicTextNode : XmlTextNode { public XmlAtomicTextNode(XmlBufferReader bufferReader) : base(XmlNodeType.Text, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)60, ReadState.Interactive, null, 0) { } } protected class XmlComplexTextNode : XmlTextNode { public XmlComplexTextNode(XmlBufferReader bufferReader) : base(XmlNodeType.Text, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)36, ReadState.Interactive, null, 0) { } } protected class XmlWhitespaceTextNode : XmlTextNode { public XmlWhitespaceTextNode(XmlBufferReader bufferReader) : base(XmlNodeType.Whitespace, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.HasValue, ReadState.Interactive, null, 0) { } } protected class XmlCDataNode : XmlTextNode { public XmlCDataNode(XmlBufferReader bufferReader) : base(XmlNodeType.CDATA, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)36, ReadState.Interactive, null, 0) { } } protected class XmlAttributeTextNode : XmlTextNode { public XmlAttributeTextNode(PrefixHandle prefix, StringHandle localName, ValueHandle value) : base(XmlNodeType.Text, prefix, localName, value, (XmlNodeFlags)47, ReadState.Interactive, null, 1) { } } protected class XmlInitialNode : XmlNode { public XmlInitialNode(XmlBufferReader bufferReader) : base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.Initial, null, 0) { } } protected class XmlDeclarationNode : XmlNode { public XmlDeclarationNode(XmlBufferReader bufferReader) : base(XmlNodeType.XmlDeclaration, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.CanGetAttribute, ReadState.Interactive, null, 0) { } } protected class XmlCommentNode : XmlNode { public XmlCommentNode(XmlBufferReader bufferReader) : base(XmlNodeType.Comment, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.HasValue, ReadState.Interactive, null, 0) { } } protected class XmlEndOfFileNode : XmlNode { public XmlEndOfFileNode(XmlBufferReader bufferReader) : base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.EndOfFile, null, 0) { } } protected class XmlClosedNode : XmlNode { public XmlClosedNode(XmlBufferReader bufferReader) : base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.Closed, null, 0) { } } private class AttributeSorter : IComparer { private object[] indeces; private XmlAttributeNode[] attributeNodes; private int attributeCount; private int attributeIndex1; private int attributeIndex2; public bool Sort(XmlAttributeNode[] attributeNodes, int attributeCount) { attributeIndex1 = -1; attributeIndex2 = -1; this.attributeNodes = attributeNodes; this.attributeCount = attributeCount; bool result = Sort(); this.attributeNodes = null; this.attributeCount = 0; return result; } public void GetIndeces(out int attributeIndex1, out int attributeIndex2) { attributeIndex1 = this.attributeIndex1; attributeIndex2 = this.attributeIndex2; } public void Close() { if (indeces != null && indeces.Length > 32) { indeces = null; } } private bool Sort() { if (indeces != null && indeces.Length == attributeCount && IsSorted()) { return true; } object[] array = new object[attributeCount]; for (int i = 0; i < array.Length; i++) { array[i] = i; } indeces = array; Array.Sort(indeces, 0, attributeCount, this); return IsSorted(); } private bool IsSorted() { for (int i = 0; i < indeces.Length - 1; i++) { if (Compare(indeces[i], indeces[i + 1]) >= 0) { attributeIndex1 = (int)indeces[i]; attributeIndex2 = (int)indeces[i + 1]; return false; } } return true; } public int Compare(object obj1, object obj2) { int num = (int)obj1; int num2 = (int)obj2; XmlAttributeNode xmlAttributeNode = attributeNodes[num]; XmlAttributeNode xmlAttributeNode2 = attributeNodes[num2]; int num3 = CompareQNameType(xmlAttributeNode.QNameType, xmlAttributeNode2.QNameType); if (num3 == 0) { if (xmlAttributeNode.QNameType == QNameType.Normal) { num3 = xmlAttributeNode.LocalName.CompareTo(xmlAttributeNode2.LocalName); if (num3 == 0) { num3 = xmlAttributeNode.Namespace.Uri.CompareTo(xmlAttributeNode2.Namespace.Uri); } } else { num3 = xmlAttributeNode.Namespace.Prefix.CompareTo(xmlAttributeNode2.Namespace.Prefix); } } return num3; } public int CompareQNameType(QNameType type1, QNameType type2) { return type1 - type2; } } private class NamespaceManager { private class XmlAttribute { private XmlSpace space; private string lang; private int depth; public int Depth { get { return depth; } set { depth = value; } } public string XmlLang { get { return lang;
deps/System.Runtime.Serialization.Formatters.Soap.dll
Decompiled a day agousing System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Metadata; using System.Runtime.Remoting.Metadata.W3cXsd2001; using System.Text; using System.Threading; using System.Xml; [assembly: AssemblyDefaultAlias("System.Runtime.Serialization.Formatters.Soap.dll")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: AssemblyDelaySign(true)] [assembly: CLSCompliant(true)] [assembly: ComCompatibleVersion(1, 0, 3300, 0)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCompany("Mono development team")] [assembly: ComVisible(true)] [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] [assembly: AssemblyTitle("System.Runtime.Serialization.Formatters.Soap.dll")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyDescription("System.Runtime.Serialization.Formatters.Soap.dll")] [assembly: AssemblyVersion("4.0.0.0")] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal sealed class Locale { private Locale() { } public static string GetText(string msg) { return msg; } public static string GetText(string fmt, params object[] args) { return string.Format(fmt, args); } } namespace System { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoTODOAttribute : Attribute { private string comment; public string Comment => comment; public MonoTODOAttribute() { } public MonoTODOAttribute(string comment) { this.comment = comment; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoDocumentationNoteAttribute : MonoTODOAttribute { public MonoDocumentationNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoExtensionAttribute : MonoTODOAttribute { public MonoExtensionAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoInternalNoteAttribute : MonoTODOAttribute { public MonoInternalNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoLimitationAttribute : MonoTODOAttribute { public MonoLimitationAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoNotSupportedAttribute : MonoTODOAttribute { public MonoNotSupportedAttribute(string comment) : base(comment) { } } } namespace System.Runtime.Serialization.Formatters.Soap { internal enum RemMessageType { MethodCall, MethodResponse, ServerFault, NotRecognize } public sealed class SoapFormatter : IRemotingFormatter, IFormatter { private SerializationBinder _binder; private StreamingContext _context; private ISurrogateSelector _selector; private FormatterAssemblyStyle _assemblyFormat = FormatterAssemblyStyle.Full; private FormatterTypeStyle _typeFormat; private ISoapMessage _topObject; private TypeFilterLevel _filterLevel = TypeFilterLevel.Low; public ISurrogateSelector SurrogateSelector { get { return _selector; } set { _selector = value; } } public SerializationBinder Binder { get { return _binder; } set { _binder = value; } } public StreamingContext Context { get { return _context; } set { _context = value; } } public ISoapMessage TopObject { get { return _topObject; } set { _topObject = value; } } [MonoTODO("Interpret this")] public TypeFilterLevel FilterLevel { get { return _filterLevel; } set { _filterLevel = value; } } public FormatterAssemblyStyle AssemblyFormat { get { return _assemblyFormat; } set { _assemblyFormat = value; } } public FormatterTypeStyle TypeFormat { get { return _typeFormat; } set { _typeFormat = value; } } public SoapFormatter() { _selector = null; _context = new StreamingContext(StreamingContextStates.All); } public SoapFormatter(ISurrogateSelector selector, StreamingContext context) { _selector = selector; _context = context; } public object Deserialize(Stream serializationStream) { return Deserialize(serializationStream, null); } public object Deserialize(Stream serializationStream, HeaderHandler handler) { return new SoapReader(_binder, _selector, _context).Deserialize(serializationStream, _topObject); } public void Serialize(Stream serializationStream, object graph) { Serialize(serializationStream, graph, null); } public void Serialize(Stream serializationStream, object graph, Header[] headers) { if (serializationStream == null) { throw new ArgumentNullException("serializationStream"); } if (!serializationStream.CanWrite) { throw new SerializationException("Can't write in the serialization stream"); } if (graph == null) { throw new ArgumentNullException("graph"); } new SoapWriter(serializationStream, _selector, _context, _topObject).Serialize(graph, headers, _typeFormat, _assemblyFormat); } } internal sealed class SoapReader { private class TypeMetadata { public MemberInfo[] MemberInfos; public Hashtable Indices; } private SerializationBinder _binder; private SoapTypeMapper mapper; private ObjectManager objMgr; private StreamingContext _context; private long _nextAvailableId = long.MaxValue; private ISurrogateSelector _surrogateSelector; private XmlTextReader xmlReader; private Hashtable _fieldIndices; private long _topObjectId = 1L; private long NextAvailableId { get { _nextAvailableId--; return _nextAvailableId; } } public SoapTypeMapper Mapper => mapper; public XmlTextReader XmlReader => xmlReader; private object TopObject { get { objMgr.DoFixups(); objMgr.RaiseDeserializationEvent(); return objMgr.GetObject(_topObjectId); } } public SoapReader(SerializationBinder binder, ISurrogateSelector selector, StreamingContext context) { _binder = binder; objMgr = new ObjectManager(selector, context); _context = context; _surrogateSelector = selector; _fieldIndices = new Hashtable(); } public object Deserialize(Stream inStream, ISoapMessage soapMessage) { CultureInfo currentCulture = CultureInfo.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); Deserialize_inner(inStream, soapMessage); } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } return TopObject; } private void Deserialize_inner(Stream inStream, ISoapMessage soapMessage) { ArrayList arrayList = null; xmlReader = new XmlTextReader(inStream); xmlReader.WhitespaceHandling = WhitespaceHandling.None; mapper = new SoapTypeMapper(_binder); try { xmlReader.MoveToContent(); xmlReader.ReadStartElement(); xmlReader.MoveToContent(); while (xmlReader.NodeType != XmlNodeType.Element || !(xmlReader.LocalName == "Body") || !(xmlReader.NamespaceURI == SoapTypeMapper.SoapEnvelopeNamespace)) { if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Header" && xmlReader.NamespaceURI == SoapTypeMapper.SoapEnvelopeNamespace) { if (arrayList == null) { arrayList = new ArrayList(); } DeserializeHeaders(arrayList); } else { xmlReader.Skip(); } xmlReader.MoveToContent(); } xmlReader.ReadStartElement(); xmlReader.MoveToContent(); if (soapMessage != null) { if (DeserializeMessage(soapMessage)) { _topObjectId = NextAvailableId; RegisterObject(_topObjectId, soapMessage, null, 0L, null, null); } xmlReader.MoveToContent(); if (arrayList != null) { soapMessage.Headers = (Header[])arrayList.ToArray(typeof(Header)); } } while (xmlReader.NodeType != XmlNodeType.EndElement) { Deserialize(); } xmlReader.ReadEndElement(); xmlReader.MoveToContent(); xmlReader.ReadEndElement(); } finally { if (xmlReader != null) { xmlReader.Close(); } } } private bool IsNull() { string text = xmlReader["null", "http://www.w3.org/2001/XMLSchema-instance"]; if (text != null && !(text == string.Empty)) { return true; } return false; } private long GetId() { string text = xmlReader["id"]; if (text == null || text == string.Empty) { return 0L; } return Convert.ToInt64(text.Substring(4)); } private long GetHref() { string text = xmlReader["href"]; if (text == null || text == string.Empty) { return 0L; } return Convert.ToInt64(text.Substring(5)); } private Type GetComponentType() { string text = xmlReader["type", "http://www.w3.org/2001/XMLSchema-instance"]; if (text == null) { if (GetId() != 0L) { return typeof(string); } return null; } return GetTypeFromQName(text); } private bool DeserializeMessage(ISoapMessage message) { if (xmlReader.Name == SoapTypeMapper.SoapEnvelopePrefix + ":Fault") { Deserialize(); return false; } string text = default(string); string text2 = default(string); SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlReader.NamespaceURI, ref text, ref text2); message.MethodName = xmlReader.LocalName; message.XmlNameSpace = xmlReader.NamespaceURI; ArrayList arrayList = new ArrayList(); ArrayList arrayList2 = new ArrayList(); long nextAvailableId = NextAvailableId; int[] array = new int[1]; if (!xmlReader.IsEmptyElement) { int depth = xmlReader.Depth; xmlReader.Read(); int num = 0; while (xmlReader.Depth > depth) { object obj = null; arrayList.Add(xmlReader.Name); Type componentType = null; if (message.ParamTypes != null) { if (num >= message.ParamTypes.Length) { throw new SerializationException("Not enough parameter types in SoapMessages"); } componentType = message.ParamTypes[num]; } array[0] = num; obj = DeserializeComponent(componentType, out var _, out var componentHref, nextAvailableId, null, array); array[0] = arrayList2.Add(obj); if (componentHref != 0L) { RecordFixup(nextAvailableId, componentHref, arrayList2.ToArray(), null, null, null, array); } num++; } xmlReader.ReadEndElement(); } else { xmlReader.Read(); } message.ParamNames = (string[])arrayList.ToArray(typeof(string)); message.ParamValues = arrayList2.ToArray(); RegisterObject(nextAvailableId, message.ParamValues, null, 0L, null, null); return true; } private void DeserializeHeaders(ArrayList headers) { xmlReader.ReadStartElement(); xmlReader.MoveToContent(); while (xmlReader.NodeType != XmlNodeType.EndElement) { if (xmlReader.NodeType != XmlNodeType.Element) { xmlReader.Skip(); continue; } if (xmlReader.GetAttribute("root", SoapTypeMapper.SoapEncodingNamespace) == "1") { headers.Add(DeserializeHeader()); } else { Deserialize(); } xmlReader.MoveToContent(); } xmlReader.ReadEndElement(); } private Header DeserializeHeader() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown Header val = new Header(xmlReader.LocalName, (object)null); val.HeaderNamespace = xmlReader.NamespaceURI; val.MustUnderstand = xmlReader.GetAttribute("mustUnderstand", SoapTypeMapper.SoapEnvelopeNamespace) == "1"; long nextAvailableId = NextAvailableId; FieldInfo field = typeof(Header).GetField("Value"); long componentId; long componentHref; object obj = (val.Value = DeserializeComponent(null, out componentId, out componentHref, nextAvailableId, field, null)); if (componentHref != 0L && obj == null) { RecordFixup(nextAvailableId, componentHref, val, null, null, field, null); } else if (obj != null && obj.GetType().IsValueType && componentId != 0L) { RecordFixup(nextAvailableId, componentId, val, null, null, field, null); } else if (componentId != 0L) { RegisterObject(componentId, obj, null, nextAvailableId, field, null); } RegisterObject(nextAvailableId, val, null, 0L, null, null); return val; } private object DeserializeArray(long id) { if (GetComponentType() == typeof(byte[])) { byte[] array = Convert.FromBase64String(xmlReader.ReadElementString()); RegisterObject(id, array, null, 0L, null, null); return array; } string[] array2 = xmlReader["arrayType", SoapTypeMapper.SoapEncodingNamespace].Split(':'); int num = array2[1].LastIndexOf('['); string xmlName = array2[1].Substring(0, num); string text = array2[1].Substring(num); string[] array3 = text.Substring(1, text.Length - 2).Trim().Split(','); int num2 = array3.Length; int[] array4 = new int[num2]; for (int i = 0; i < num2; i++) { array4[i] = Convert.ToInt32(array3[i]); } int[] array5 = new int[num2]; Array array6 = Array.CreateInstance(mapper.GetType(xmlName, xmlReader.LookupNamespace(array2[0])), array4); for (int j = 0; j < num2; j++) { array5[j] = array6.GetLowerBound(j); } int depth = xmlReader.Depth; xmlReader.Read(); while (xmlReader.Depth > depth) { Type type = GetComponentType(); if (type == null) { type = array6.GetType().GetElementType(); } long componentId; long componentHref; object obj = DeserializeComponent(type, out componentId, out componentHref, id, null, array5); if (componentHref != 0L) { object @object = objMgr.GetObject(componentHref); if (@object != null) { array6.SetValue(@object, array5); } else { RecordFixup(id, componentHref, array6, null, null, null, array5); } } else if (obj != null && obj.GetType().IsValueType && componentId != 0L) { RecordFixup(id, componentId, array6, null, null, null, array5); } else if (componentId != 0L) { RegisterObject(componentId, obj, null, id, null, array5); array6.SetValue(obj, array5); } else { array6.SetValue(obj, array5); } for (int num3 = array6.Rank - 1; num3 >= 0; num3--) { array5[num3]++; if (array5[num3] <= array6.GetUpperBound(num3) || num3 <= 0) { break; } array5[num3] = array6.GetLowerBound(num3); } } RegisterObject(id, array6, null, 0L, null, null); xmlReader.ReadEndElement(); return array6; } private object Deserialize() { object obj = null; Type type = mapper.GetType(xmlReader.LocalName, xmlReader.NamespaceURI); long id = GetId(); id = ((id == 0L) ? 1 : id); if (type == typeof(Array)) { return DeserializeArray(id); } return DeserializeObject(type, id, 0L, null, null); } private object DeserializeObject(Type type, long id, long parentId, MemberInfo parentMemberInfo, int[] indices) { SerializationInfo info = null; bool flag = false; if (type == typeof(string) || type == typeof(TimeSpan) || (mapper.IsInternalSoapType(type) && (indices != null || parentMemberInfo != null))) { object obj = mapper.ReadInternalSoapValue(this, type); if (id != 0L) { RegisterObject(id, obj, info, parentId, parentMemberInfo, indices); } return obj; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); objMgr.RaiseOnDeserializingEvent(uninitializedObject); if (uninitializedObject is ISerializable) { flag = true; } if (_surrogateSelector != null && !flag) { ISurrogateSelector selector; ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate(type, _context, out selector); flag = flag || surrogate != null; } bool hasFixup; if (flag) { uninitializedObject = DeserializeISerializableObject(uninitializedObject, id, out info, out hasFixup); } else { uninitializedObject = DeserializeSimpleObject(uninitializedObject, id, out hasFixup); if (!hasFixup && uninitializedObject is IObjectReference) { uninitializedObject = ((IObjectReference)uninitializedObject).GetRealObject(_context); } } RegisterObject(id, uninitializedObject, info, parentId, parentMemberInfo, indices); xmlReader.ReadEndElement(); return uninitializedObject; } private object DeserializeSimpleObject(object obj, long id, out bool hasFixup) { hasFixup = false; Type type = obj.GetType(); TypeMetadata typeMetadata = GetTypeMetadata(type); object[] array = new object[typeMetadata.MemberInfos.Length]; xmlReader.Read(); xmlReader.MoveToContent(); while (xmlReader.NodeType != XmlNodeType.EndElement) { if (xmlReader.NodeType != XmlNodeType.Element) { xmlReader.Skip(); continue; } int num = (int)(typeMetadata.Indices[xmlReader.LocalName] ?? throw new SerializationException("Field \"" + xmlReader.LocalName + "\" not found in class " + type.FullName)); FieldInfo fieldInfo = typeMetadata.MemberInfos[num] as FieldInfo; long componentId; long componentHref; object obj2 = (array[num] = DeserializeComponent(fieldInfo.FieldType, out componentId, out componentHref, id, fieldInfo, null)); if (componentHref != 0L && obj2 == null) { RecordFixup(id, componentHref, obj, null, null, fieldInfo, null); hasFixup = true; } else if (obj2 != null && obj2.GetType().IsValueType && componentId != 0L) { RecordFixup(id, componentId, obj, null, null, fieldInfo, null); hasFixup = true; } else if (componentId != 0L) { RegisterObject(componentId, obj2, null, id, fieldInfo, null); } } FormatterServices.PopulateObjectMembers(obj, typeMetadata.MemberInfos, array); return obj; } private object DeserializeISerializableObject(object obj, long id, out SerializationInfo info, out bool hasFixup) { info = new SerializationInfo(obj.GetType(), new FormatterConverter()); hasFixup = false; int depth = xmlReader.Depth; xmlReader.Read(); while (xmlReader.Depth > depth) { Type componentType = GetComponentType(); string text = XmlConvert.DecodeName(xmlReader.LocalName); long componentId; long componentHref; object obj2 = DeserializeComponent(componentType, out componentId, out componentHref, id, null, null); if (componentHref != 0L && obj2 == null) { RecordFixup(id, componentHref, obj, info, text, null, null); hasFixup = true; continue; } if (componentId != 0L && obj2.GetType().IsValueType) { RecordFixup(id, componentId, obj, info, text, null, null); hasFixup = true; continue; } if (componentId != 0L) { RegisterObject(componentId, obj2, null, id, null, null); } info.AddValue(text, obj2, (componentType != null) ? componentType : typeof(object)); } return obj; } private object DeserializeComponent(Type componentType, out long componentId, out long componentHref, long parentId, MemberInfo parentMemberInfo, int[] indices) { componentId = 0L; componentHref = 0L; if (IsNull()) { xmlReader.Read(); return null; } Type componentType2 = GetComponentType(); if (componentType2 != null) { componentType = componentType2; } if (xmlReader.HasAttributes) { componentId = GetId(); componentHref = GetHref(); } if (componentId != 0L) { string text = xmlReader.ReadElementString(); objMgr.RegisterObject(text, componentId); return text; } if (componentHref != 0L) { xmlReader.Read(); return objMgr.GetObject(componentHref); } if (componentType == null) { return xmlReader.ReadElementString(); } componentId = NextAvailableId; return DeserializeObject(componentType, componentId, parentId, parentMemberInfo, indices); } public void RecordFixup(long parentObjectId, long childObjectId, object parentObject, SerializationInfo info, string fieldName, MemberInfo memberInfo, int[] indices) { if (info != null) { objMgr.RecordDelayedFixup(parentObjectId, fieldName, childObjectId); } else if (parentObject is Array) { if (indices.Length == 1) { objMgr.RecordArrayElementFixup(parentObjectId, indices[0], childObjectId); } else { objMgr.RecordArrayElementFixup(parentObjectId, (int[])indices.Clone(), childObjectId); } } else { objMgr.RecordFixup(parentObjectId, memberInfo, childObjectId); } } private void RegisterObject(long objectId, object objectInstance, SerializationInfo info, long parentObjectId, MemberInfo parentObjectMember, int[] indices) { if (parentObjectId == 0L) { indices = null; } if (!objectInstance.GetType().IsValueType || parentObjectId == 0L) { if (objMgr.GetObject(objectId) != objectInstance) { objMgr.RegisterObject(objectInstance, objectId, info, 0L, null, null); } return; } if (objMgr.GetObject(objectId) != null) { throw new SerializationException("Object already registered"); } if (indices != null) { indices = (int[])indices.Clone(); } objMgr.RegisterObject(objectInstance, objectId, info, parentObjectId, parentObjectMember, indices); } private TypeMetadata GetTypeMetadata(Type type) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown if (_fieldIndices[type] is TypeMetadata result) { return result; } TypeMetadata typeMetadata = new TypeMetadata(); typeMetadata.MemberInfos = FormatterServices.GetSerializableMembers(type, _context); typeMetadata.Indices = new Hashtable(); for (int i = 0; i < typeMetadata.MemberInfos.Length; i++) { SoapFieldAttribute val = (SoapFieldAttribute)InternalRemotingServices.GetCachedSoapAttribute((object)typeMetadata.MemberInfos[i]); typeMetadata.Indices[XmlConvert.EncodeLocalName(val.XmlElementName)] = i; } _fieldIndices[type] = typeMetadata; return typeMetadata; } public Type GetTypeFromQName(string qname) { string[] array = qname.Split(':'); string xmlNamespace = xmlReader.LookupNamespace(array[0]); return mapper.GetType(array[1], xmlNamespace); } } internal class Element { private string _prefix; private string _localName; private string _namespaceURI; private MethodInfo _parseMethod; public string Prefix => _prefix; public string LocalName => _localName; public string NamespaceURI => _namespaceURI; public MethodInfo ParseMethod { get { return _parseMethod; } set { _parseMethod = value; } } public Element(string prefix, string localName, string namespaceURI) { _prefix = prefix; _localName = localName; _namespaceURI = namespaceURI; } public Element(string localName, string namespaceURI) : this(null, localName, namespaceURI) { } public override bool Equals(object obj) { Element element = obj as Element; if (!(_localName == XmlConvert.DecodeName(element._localName)) || !(_namespaceURI == XmlConvert.DecodeName(element._namespaceURI))) { return false; } return true; } public override int GetHashCode() { return $"{XmlConvert.DecodeName(_localName)} {XmlConvert.DecodeName(_namespaceURI)}".GetHashCode(); } public override string ToString() { return $"Element.Prefix = {Prefix}, Element.LocalName = {LocalName}, Element.NamespaceURI = {NamespaceURI}"; } } internal class SoapTypeMapper { private static Hashtable xmlNodeToTypeTable; private static Hashtable typeToXmlNodeTable; public static readonly string SoapEncodingNamespace; public static readonly string SoapEncodingPrefix; public static readonly string SoapEnvelopeNamespace; public static readonly string SoapEnvelopePrefix; private XmlTextWriter _xmlWriter; private long _prefixNumber; private Hashtable namespaceToPrefixTable = new Hashtable(); private SerializationBinder _binder; private static ArrayList _canBeValueTypeList; private FormatterAssemblyStyle _assemblyFormat = FormatterAssemblyStyle.Full; private Element elementString; public SoapTypeMapper(SerializationBinder binder) { _binder = binder; } public SoapTypeMapper(XmlTextWriter xmlWriter, FormatterAssemblyStyle assemblyFormat, FormatterTypeStyle typeFormat) { _xmlWriter = xmlWriter; _assemblyFormat = assemblyFormat; _prefixNumber = 1L; if (typeFormat == FormatterTypeStyle.XsdString) { elementString = new Element("xsd", "string", "http://www.w3.org/2001/XMLSchema"); } else { elementString = new Element(SoapEncodingPrefix, "string", SoapEncodingNamespace); } } static SoapTypeMapper() { xmlNodeToTypeTable = new Hashtable(); typeToXmlNodeTable = new Hashtable(); SoapEncodingNamespace = "http://schemas.xmlsoap.org/soap/encoding/"; SoapEncodingPrefix = "SOAP-ENC"; SoapEnvelopeNamespace = "http://schemas.xmlsoap.org/soap/envelope/"; SoapEnvelopePrefix = "SOAP-ENV"; _canBeValueTypeList = new ArrayList(); _canBeValueTypeList.Add(typeof(DateTime).ToString()); _canBeValueTypeList.Add(typeof(TimeSpan).ToString()); _canBeValueTypeList.Add(typeof(string).ToString()); _canBeValueTypeList.Add(typeof(decimal).ToString()); _canBeValueTypeList.Sort(); InitMappingTables(); } private static string GetKey(string localName, string namespaceUri) { return localName + " " + namespaceUri; } public Type GetType(string xmlName, string xmlNamespace) { Type type = null; string text = XmlConvert.DecodeName(xmlName); string arg = XmlConvert.DecodeName(xmlNamespace); string text2 = default(string); string text3 = default(string); SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlNamespace, ref text2, ref text3); string text4 = ((text2 == null || text2 == string.Empty) ? text : (text2 + Type.Delimiter + text)); if (text3 != null && text3 != string.Empty && _binder != null) { type = _binder.BindToType(text3, text4); } if (type == null) { string text5 = (string)xmlNodeToTypeTable[GetKey(xmlName, xmlNamespace)]; if (text5 != null) { type = Type.GetType(text5); } else { type = Type.GetType(text4); if (type == null) { if (text3 == null || text3 == string.Empty) { throw new SerializationException($"Parse Error, no assembly associated with XML key {text} {arg}"); } type = FormatterServices.GetTypeFromAssembly(Assembly.Load(text3), text4); } } if (type == null) { throw new SerializationException(); } } return type; } public Element GetXmlElement(string typeFullName, string assemblyName) { string text = string.Empty; string text2 = typeFullName; if (_assemblyFormat == FormatterAssemblyStyle.Simple) { assemblyName = assemblyName.Split(',')[0]; } string key = typeFullName + ", " + assemblyName; Element element = (Element)typeToXmlNodeTable[key]; if (element == null) { int num = typeFullName.LastIndexOf('.'); if (num != -1) { text = typeFullName.Substring(0, num); text2 = typeFullName.Substring(text.Length + 1); } string text3 = SoapServices.CodeXmlNamespaceForClrTypeNamespace(text, (!assemblyName.StartsWith("mscorlib")) ? assemblyName : string.Empty); string text4 = (string)namespaceToPrefixTable[text3]; if (text4 == null || text4 == string.Empty) { text4 = "a" + _prefixNumber++; namespaceToPrefixTable[text3] = text4; } int num2 = text2.IndexOf("["); if (num2 != -1) { text2 = XmlConvert.EncodeName(text2.Substring(0, num2)) + text2.Substring(num2); } else { int num3 = text2.IndexOf("&"); text2 = ((num3 == -1) ? XmlConvert.EncodeName(text2) : (XmlConvert.EncodeName(text2.Substring(0, num3)) + text2.Substring(num3))); } element = new Element(text4, text2, text3); } return element; } public Element GetXmlElement(Type type) { if (type == typeof(string)) { return elementString; } Element element = (Element)typeToXmlNodeTable[type.AssemblyQualifiedName]; if (element == null) { element = GetXmlElement(type.FullName, type.Assembly.FullName); } else if (_xmlWriter != null) { element = new Element((element.Prefix == null) ? _xmlWriter.LookupPrefix(element.NamespaceURI) : element.Prefix, element.LocalName, element.NamespaceURI); } if (element == null) { throw new SerializationException("Oooops"); } return element; } private static void RegisterType(Type type, string name, string namspace) { RegisterType(type, name, namspace, reverseMap: true); } private static Element RegisterType(Type type, string name, string namspace, bool reverseMap) { Element element = new Element(name, namspace); xmlNodeToTypeTable.Add(GetKey(name, namspace), type.AssemblyQualifiedName); if (reverseMap) { typeToXmlNodeTable.Add(type.AssemblyQualifiedName, element); } return element; } private static void RegisterType(Type type) { string name = (string)type.GetProperty("XsdType", BindingFlags.Static | BindingFlags.Public).GetValue(null, null); Element element = RegisterType(type, name, "http://www.w3.org/2001/XMLSchema", reverseMap: true); element.ParseMethod = type.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public); if (element.ParseMethod == null) { throw new InvalidOperationException("Parse method not found in class " + type); } } private static void InitMappingTables() { RegisterType(typeof(Array), "Array", SoapEncodingNamespace); RegisterType(typeof(string), "string", "http://www.w3.org/2001/XMLSchema", reverseMap: false); RegisterType(typeof(string), "string", SoapEncodingNamespace, reverseMap: false); RegisterType(typeof(bool), "boolean", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(sbyte), "byte", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(byte), "unsignedByte", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(long), "long", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(ulong), "unsignedLong", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(int), "int", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(uint), "unsignedInt", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(float), "float", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(double), "double", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(decimal), "decimal", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(short), "short", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(ushort), "unsignedShort", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(object), "anyType", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(DateTime), "dateTime", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(TimeSpan), "duration", "http://www.w3.org/2001/XMLSchema"); RegisterType(typeof(SoapFault), "Fault", SoapEnvelopeNamespace); RegisterType(typeof(byte[]), "base64", SoapEncodingNamespace); RegisterType(typeof(MethodSignature), "methodSignature", SoapEncodingNamespace); RegisterType(typeof(SoapAnyUri)); RegisterType(typeof(SoapEntity)); RegisterType(typeof(SoapMonth)); RegisterType(typeof(SoapNonNegativeInteger)); RegisterType(typeof(SoapToken)); RegisterType(typeof(SoapBase64Binary)); RegisterType(typeof(SoapHexBinary)); RegisterType(typeof(SoapMonthDay)); RegisterType(typeof(SoapNonPositiveInteger)); RegisterType(typeof(SoapYear)); RegisterType(typeof(SoapDate)); RegisterType(typeof(SoapId)); RegisterType(typeof(SoapName)); RegisterType(typeof(SoapNormalizedString)); RegisterType(typeof(SoapYearMonth)); RegisterType(typeof(SoapIdref)); RegisterType(typeof(SoapNcName)); RegisterType(typeof(SoapNotation)); RegisterType(typeof(SoapDay)); RegisterType(typeof(SoapIdrefs)); RegisterType(typeof(SoapNegativeInteger)); RegisterType(typeof(SoapPositiveInteger)); RegisterType(typeof(SoapInteger)); RegisterType(typeof(SoapNmtoken)); RegisterType(typeof(SoapQName)); RegisterType(typeof(SoapEntities)); RegisterType(typeof(SoapLanguage)); RegisterType(typeof(SoapNmtokens)); RegisterType(typeof(SoapTime)); } public static string GetXsdValue(object value) { if (value is DateTime) { return SoapDateTime.ToString((DateTime)value); } if (value is decimal num) { return num.ToString(CultureInfo.InvariantCulture); } if (value is double num2) { return num2.ToString("G17", CultureInfo.InvariantCulture); } if (value is float num3) { return num3.ToString("G9", CultureInfo.InvariantCulture); } if (value is TimeSpan) { return SoapDuration.ToString((TimeSpan)value); } if (value is bool) { if (!(bool)value) { return "false"; } return "true"; } if (value is MethodSignature) { return null; } return value.ToString(); } public static object ParseXsdValue(string value, Type type) { if (type == typeof(DateTime)) { return SoapDateTime.Parse(value); } if (type == typeof(decimal)) { return decimal.Parse(value, CultureInfo.InvariantCulture); } if (type == typeof(double)) { return double.Parse(value, CultureInfo.InvariantCulture); } if (type == typeof(float)) { return float.Parse(value, CultureInfo.InvariantCulture); } if (type == typeof(TimeSpan)) { return SoapDuration.Parse(value); } if (type.IsEnum) { return Enum.Parse(type, value); } return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } public static bool CanBeValue(Type type) { if (type.IsPrimitive) { return true; } if (type.IsEnum) { return true; } if (_canBeValueTypeList.BinarySearch(type.ToString()) >= 0) { return true; } return false; } public bool IsInternalSoapType(Type type) { if (CanBeValue(type)) { return true; } if (typeof(ISoapXsd).IsAssignableFrom(type)) { return true; } if (type == typeof(MethodSignature)) { return true; } return false; } public object ReadInternalSoapValue(SoapReader reader, Type type) { if (CanBeValue(type)) { return ParseXsdValue(reader.XmlReader.ReadElementString(), type); } if (type == typeof(MethodSignature)) { return MethodSignature.ReadXmlValue(reader); } string text = reader.XmlReader.ReadElementString(); Element xmlElement = GetXmlElement(type); if (xmlElement.ParseMethod != null) { return xmlElement.ParseMethod.Invoke(null, new object[1] { text }); } throw new SerializationException("Can't parse type " + type); } public string GetInternalSoapValue(SoapWriter writer, object value) { if (CanBeValue(value.GetType())) { return GetXsdValue(value); } if (value is MethodSignature) { return ((MethodSignature)value).GetXmlValue(writer); } return value.ToString(); } } internal class MethodSignature { private Type[] types; public MethodSignature(Type[] types) { this.types = types; } public static object ReadXmlValue(SoapReader reader) { reader.XmlReader.MoveToElement(); if (reader.XmlReader.IsEmptyElement) { reader.XmlReader.Skip(); return new Type[0]; } reader.XmlReader.ReadStartElement(); string text = reader.XmlReader.ReadString(); while (reader.XmlReader.NodeType != XmlNodeType.EndElement) { reader.XmlReader.Skip(); } ArrayList arrayList = new ArrayList(); string[] array = text.Split(' '); foreach (string text2 in array) { if (text2.Length != 0) { arrayList.Add(reader.GetTypeFromQName(text2)); } } reader.XmlReader.ReadEndElement(); return (Type[])arrayList.ToArray(typeof(Type)); } public string GetXmlValue(SoapWriter writer) { StringBuilder stringBuilder = new StringBuilder(); Type[] array = types; foreach (Type type in array) { Element xmlElement = writer.Mapper.GetXmlElement(type); if (stringBuilder.Length > 0) { stringBuilder.Append(' '); } string namespacePrefix = writer.GetNamespacePrefix(xmlElement); stringBuilder.Append(namespacePrefix).Append(':').Append(xmlElement.LocalName); } return stringBuilder.ToString(); } } internal class SoapWriter : IComparer { private struct EnqueuedObject { public long _id; public object _object; public long Id => _id; public object Object => _object; public EnqueuedObject(object currentObject, long id) { _id = id; _object = currentObject; } } private XmlTextWriter _xmlWriter; private Queue _objectQueue = new Queue(); private Hashtable _objectToIdTable = new Hashtable(); private ISurrogateSelector _surrogateSelector; private SoapTypeMapper _mapper; private StreamingContext _context; private ObjectIDGenerator idGen = new ObjectIDGenerator(); private FormatterAssemblyStyle _assemblyFormat = FormatterAssemblyStyle.Full; private FormatterTypeStyle _typeFormat; private static string defaultMessageNamespace; private SerializationObjectManager _manager; public SoapTypeMapper Mapper => _mapper; public XmlTextWriter XmlWriter => _xmlWriter; internal FormatterAssemblyStyle AssemblyFormat { get { return _assemblyFormat; } set { _assemblyFormat = value; } } internal FormatterTypeStyle TypeFormat { get { return _typeFormat; } set { _typeFormat = value; } } ~SoapWriter() { } internal SoapWriter(Stream outStream, ISurrogateSelector selector, StreamingContext context, ISoapMessage soapMessage) { _xmlWriter = new XmlTextWriter(outStream, null); _xmlWriter.Formatting = Formatting.Indented; _surrogateSelector = selector; _context = context; _manager = new SerializationObjectManager(_context); } static SoapWriter() { defaultMessageNamespace = typeof(SoapWriter).Assembly.GetName().FullName; } private void Id(long id) { _xmlWriter.WriteAttributeString(null, "id", null, "ref-" + id); } private void Href(long href) { _xmlWriter.WriteAttributeString(null, "href", null, "#ref-" + href); } private void Null() { _xmlWriter.WriteAttributeString("xsi", "null", "http://www.w3.org/2001/XMLSchema-instance", "1"); } private bool IsEncodingNeeded(object componentObject, Type componentType) { if (componentObject == null) { return false; } if (_typeFormat == FormatterTypeStyle.TypesAlways) { return true; } if (componentType == null) { componentType = componentObject.GetType(); if (componentType.IsPrimitive || componentType == typeof(string)) { return false; } return true; } if (componentType == typeof(object) || componentType != componentObject.GetType()) { return true; } return false; } internal void Serialize(object objGraph, Header[] headers, FormatterTypeStyle typeFormat, FormatterAssemblyStyle assemblyFormat) { CultureInfo currentCulture = CultureInfo.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); Serialize_inner(objGraph, headers, typeFormat, assemblyFormat); } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } _manager.RaiseOnSerializedEvent(); } private void Serialize_inner(object objGraph, Header[] headers, FormatterTypeStyle typeFormat, FormatterAssemblyStyle assemblyFormat) { _typeFormat = typeFormat; _assemblyFormat = assemblyFormat; _mapper = new SoapTypeMapper(_xmlWriter, assemblyFormat, typeFormat); _xmlWriter.WriteStartElement(SoapTypeMapper.SoapEnvelopePrefix, "Envelope", SoapTypeMapper.SoapEnvelopeNamespace); _xmlWriter.WriteAttributeString("xmlns", "xsi", "http://www.w3.org/2000/xmlns/", "http://www.w3.org/2001/XMLSchema-instance"); _xmlWriter.WriteAttributeString("xmlns", "xsd", "http://www.w3.org/2000/xmlns/", "http://www.w3.org/2001/XMLSchema"); _xmlWriter.WriteAttributeString("xmlns", SoapTypeMapper.SoapEncodingPrefix, "http://www.w3.org/2000/xmlns/", SoapTypeMapper.SoapEncodingNamespace); _xmlWriter.WriteAttributeString("xmlns", SoapTypeMapper.SoapEnvelopePrefix, "http://www.w3.org/2000/xmlns/", SoapTypeMapper.SoapEnvelopeNamespace); _xmlWriter.WriteAttributeString("xmlns", "clr", "http://www.w3.org/2000/xmlns/", SoapServices.XmlNsForClrType); _xmlWriter.WriteAttributeString(SoapTypeMapper.SoapEnvelopePrefix, "encodingStyle", SoapTypeMapper.SoapEnvelopeNamespace, "http://schemas.xmlsoap.org/soap/encoding/"); ISoapMessage val = (ISoapMessage)((objGraph is ISoapMessage) ? objGraph : null); if (val != null) { headers = val.Headers; } if (headers != null && headers.Length != 0) { _xmlWriter.WriteStartElement(SoapTypeMapper.SoapEnvelopePrefix, "Header", SoapTypeMapper.SoapEnvelopeNamespace); Header[] array = headers; foreach (Header header in array) { SerializeHeader(header); } WriteObjectQueue(); _xmlWriter.WriteEndElement(); } _xmlWriter.WriteStartElement(SoapTypeMapper.SoapEnvelopePrefix, "Body", SoapTypeMapper.SoapEnvelopeNamespace); bool firstTime = false; if (val != null) { SerializeMessage(val); } else { _objectQueue.Enqueue(new EnqueuedObject(objGraph, idGen.GetId(objGraph, out firstTime))); } WriteObjectQueue(); _xmlWriter.WriteFullEndElement(); _xmlWriter.WriteFullEndElement(); _xmlWriter.Flush(); } private void WriteObjectQueue() { while (_objectQueue.Count > 0) { EnqueuedObject enqueuedObject = (EnqueuedObject)_objectQueue.Dequeue(); object @object = enqueuedObject.Object; Type type = @object.GetType(); if (!type.IsValueType) { _objectToIdTable[@object] = enqueuedObject.Id; } if (type.IsArray) { SerializeArray((Array)@object, enqueuedObject.Id); } else { SerializeObject(@object, enqueuedObject.Id); } } } private void SerializeMessage(ISoapMessage message) { string ns = ((message.XmlNameSpace != null) ? message.XmlNameSpace : defaultMessageNamespace); _xmlWriter.WriteStartElement("i2", message.MethodName, ns); Id(idGen.GetId(message, out var _)); string[] paramNames = message.ParamNames; object[] paramValues = message.ParamValues; int num = ((paramNames != null) ? paramNames.Length : 0); for (int i = 0; i < num; i++) { _xmlWriter.WriteStartElement(paramNames[i]); SerializeComponent(paramValues[i], specifyEncoding: true); _xmlWriter.WriteEndElement(); } _xmlWriter.WriteFullEndElement(); } private void SerializeHeader(Header header) { string ns = ((header.HeaderNamespace != null) ? header.HeaderNamespace : "http://schemas.microsoft.com/clr/soap"); _xmlWriter.WriteStartElement("h4", header.Name, ns); if (header.MustUnderstand) { _xmlWriter.WriteAttributeString("mustUnderstand", SoapTypeMapper.SoapEnvelopeNamespace, "1"); } _xmlWriter.WriteAttributeString("root", SoapTypeMapper.SoapEncodingNamespace, "1"); if (header.Name == "__MethodSignature") { if (!(header.Value is Type[] types)) { throw new SerializationException("Invalid method signature."); } SerializeComponent(new MethodSignature(types), specifyEncoding: true); } else { SerializeComponent(header.Value, specifyEncoding: true); } _xmlWriter.WriteEndElement(); } private void SerializeObject(object currentObject, long currentObjectId) { bool flag = false; ISerializationSurrogate serializationSurrogate = null; if (_surrogateSelector != null) { serializationSurrogate = _surrogateSelector.GetSurrogate(currentObject.GetType(), _context, out ISurrogateSelector _); } if (currentObject is ISerializable || serializationSurrogate != null) { flag = true; } _manager.RegisterObject(currentObject); if (flag) { SerializeISerializableObject(currentObject, currentObjectId, serializationSurrogate); return; } if (!currentObject.GetType().IsSerializable) { throw new SerializationException($"Type {currentObject.GetType()} in assembly {currentObject.GetType().Assembly.FullName} is not marked as serializable."); } SerializeSimpleObject(currentObject, currentObjectId); } public int Compare(object x, object y) { MemberInfo obj = x as MemberInfo; MemberInfo memberInfo = y as MemberInfo; return string.Compare(obj.Name, memberInfo.Name); } private void SerializeSimpleObject(object currentObject, long currentObjectId) { //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown Type type = currentObject.GetType(); if (currentObjectId > 0) { Element xmlElement = _mapper.GetXmlElement(type); _xmlWriter.WriteStartElement(xmlElement.Prefix, xmlElement.LocalName, xmlElement.NamespaceURI); Id(currentObjectId); } if (type == typeof(TimeSpan)) { _xmlWriter.WriteString(SoapTypeMapper.GetXsdValue(currentObject)); } else if (type == typeof(string)) { _xmlWriter.WriteString(currentObject.ToString()); } else { MemberInfo[] serializableMembers = FormatterServices.GetSerializableMembers(type, _context); object[] objectData = FormatterServices.GetObjectData(currentObject, serializableMembers); for (int i = 0; i < serializableMembers.Length; i++) { FieldInfo fieldInfo = (FieldInfo)serializableMembers[i]; SoapFieldAttribute val = (SoapFieldAttribute)InternalRemotingServices.GetCachedSoapAttribute((object)fieldInfo); _xmlWriter.WriteStartElement(XmlConvert.EncodeLocalName(val.XmlElementName)); SerializeComponent(objectData[i], IsEncodingNeeded(objectData[i], fieldInfo.FieldType)); _xmlWriter.WriteEndElement(); } } if (currentObjectId > 0) { _xmlWriter.WriteFullEndElement(); } } private void SerializeISerializableObject(object currentObject, long currentObjectId, ISerializationSurrogate surrogate) { SerializationInfo serializationInfo = new SerializationInfo(currentObject.GetType(), new FormatterConverter()); ISerializable serializable = currentObject as ISerializable; if (surrogate != null) { surrogate.GetObjectData(currentObject, serializationInfo, _context); } else { serializable.GetObjectData(serializationInfo, _context); } if (currentObjectId > 0) { Element xmlElement = _mapper.GetXmlElement(serializationInfo.FullTypeName, serializationInfo.AssemblyName); _xmlWriter.WriteStartElement(xmlElement.Prefix, xmlElement.LocalName, xmlElement.NamespaceURI); Id(currentObjectId); } SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; _xmlWriter.WriteStartElement(XmlConvert.EncodeLocalName(current.Name)); SerializeComponent(current.Value, IsEncodingNeeded(current.Value, null)); _xmlWriter.WriteEndElement(); } if (currentObjectId > 0) { _xmlWriter.WriteFullEndElement(); } } private void SerializeArray(Array currentArray, long currentArrayId) { Element xmlElement = _mapper.GetXmlElement(typeof(Array)); Type elementType = currentArray.GetType().GetElementType(); Element xmlElement2 = _mapper.GetXmlElement(elementType); _xmlWriter.WriteStartElement(xmlElement.Prefix, xmlElement.LocalName, xmlElement.NamespaceURI); if (currentArrayId > 0) { Id(currentArrayId); } if (elementType == typeof(byte)) { EncodeType(currentArray.GetType()); _xmlWriter.WriteString(Convert.ToBase64String((byte[])currentArray)); _xmlWriter.WriteFullEndElement(); return; } string namespacePrefix = GetNamespacePrefix(xmlElement2); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("{0}:{1}[", namespacePrefix, xmlElement2.LocalName); for (int i = 0; i < currentArray.Rank; i++) { stringBuilder.AppendFormat("{0},", currentArray.GetUpperBound(i) + 1); } stringBuilder.Replace(',', ']', stringBuilder.Length - 1, 1); _xmlWriter.WriteAttributeString(SoapTypeMapper.SoapEncodingPrefix, "arrayType", SoapTypeMapper.SoapEncodingNamespace, stringBuilder.ToString()); int num = 0; int num2 = 0; foreach (object item in currentArray) { if (item != null) { for (int j = num; j < num2; j++) { _xmlWriter.WriteStartElement("item"); Null(); _xmlWriter.WriteEndElement(); } num = num2 + 1; _xmlWriter.WriteStartElement("item"); SerializeComponent(item, IsEncodingNeeded(item, elementType)); _xmlWriter.WriteEndElement(); } num2++; } _xmlWriter.WriteFullEndElement(); } private void SerializeComponent(object obj, bool specifyEncoding) { if (_typeFormat == FormatterTypeStyle.TypesAlways) { specifyEncoding = true; } if (obj == null) { Null(); return; } Type type = obj.GetType(); bool flag = _mapper.IsInternalSoapType(type); long num = 0L; if ((num = idGen.HasId(obj, out var firstTime)) != 0L) { Href(idGen.GetId(obj, out firstTime)); return; } if (type == typeof(string) && _typeFormat != FormatterTypeStyle.XsdString) { num = idGen.GetId(obj, out firstTime); Id(num); } if (!flag && !type.IsValueType) { long id = idGen.GetId(obj, out firstTime); Href(id); _objectQueue.Enqueue(new EnqueuedObject(obj, id)); return; } if (specifyEncoding) { EncodeType(type); } if (!flag && type.IsValueType) { SerializeObject(obj, 0L); } else { _xmlWriter.WriteString(_mapper.GetInternalSoapValue(this, obj)); } } private void EncodeType(Type type) { if (type == null) { throw new SerializationException("Oooops"); } Element xmlElement = _mapper.GetXmlElement(type); string namespacePrefix = GetNamespacePrefix(xmlElement); _xmlWriter.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", namespacePrefix + ":" + xmlElement.LocalName); } public string GetNamespacePrefix(Element xmlType) { string text = _xmlWriter.LookupPrefix(xmlType.NamespaceURI); if (text == null || text == string.Empty) { _xmlWriter.WriteAttributeString("xmlns", xmlType.Prefix, "http://www.w3.org/2000/xmlns/", xmlType.NamespaceURI); return xmlType.Prefix; } return text; } } }
deps/System.Security.AccessControl.dll
Decompiled a day agousing System; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Security.Principal; using FxResources.System.Security.AccessControl; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyDefaultAlias("System.Security.AccessControl")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("NotSupported", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("System.Security.AccessControl")] [assembly: AssemblyFileVersion("4.700.19.56404")] [assembly: AssemblyInformationalVersion("3.1.0+0f7f38c4fd323b26da10cce95f857f77f0f09b48")] [assembly: AssemblyProduct("Microsoft® .NET Core")] [assembly: AssemblyTitle("System.Security.AccessControl")] [assembly: CLSCompliant(true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.1.3.0")] [module: UnverifiableCode] namespace FxResources.System.Security.AccessControl { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string AccessControl_AclTooLong => GetResourceString("AccessControl_AclTooLong"); internal static string AccessControl_InvalidAccessRuleType => GetResourceString("AccessControl_InvalidAccessRuleType"); internal static string AccessControl_InvalidAuditRuleType => GetResourceString("AccessControl_InvalidAuditRuleType"); internal static string AccessControl_InvalidOwner => GetResourceString("AccessControl_InvalidOwner"); internal static string AccessControl_InvalidGroup => GetResourceString("AccessControl_InvalidGroup"); internal static string AccessControl_InvalidHandle => GetResourceString("AccessControl_InvalidHandle"); internal static string AccessControl_InvalidSecurityDescriptorRevision => GetResourceString("AccessControl_InvalidSecurityDescriptorRevision"); internal static string AccessControl_InvalidSecurityDescriptorSelfRelativeForm => GetResourceString("AccessControl_InvalidSecurityDescriptorSelfRelativeForm"); internal static string AccessControl_InvalidSidInSDDLString => GetResourceString("AccessControl_InvalidSidInSDDLString"); internal static string AccessControl_MustSpecifyContainerAcl => GetResourceString("AccessControl_MustSpecifyContainerAcl"); internal static string AccessControl_MustSpecifyDirectoryObjectAcl => GetResourceString("AccessControl_MustSpecifyDirectoryObjectAcl"); internal static string AccessControl_MustSpecifyLeafObjectAcl => GetResourceString("AccessControl_MustSpecifyLeafObjectAcl"); internal static string AccessControl_MustSpecifyNonDirectoryObjectAcl => GetResourceString("AccessControl_MustSpecifyNonDirectoryObjectAcl"); internal static string AccessControl_NoAssociatedSecurity => GetResourceString("AccessControl_NoAssociatedSecurity"); internal static string AccessControl_UnexpectedError => GetResourceString("AccessControl_UnexpectedError"); internal static string Arg_EnumAtLeastOneFlag => GetResourceString("Arg_EnumAtLeastOneFlag"); internal static string Arg_EnumIllegalVal => GetResourceString("Arg_EnumIllegalVal"); internal static string Arg_InvalidOperationException => GetResourceString("Arg_InvalidOperationException"); internal static string Arg_MustBeIdentityReferenceType => GetResourceString("Arg_MustBeIdentityReferenceType"); internal static string Argument_ArgumentZero => GetResourceString("Argument_ArgumentZero"); internal static string Argument_InvalidAnyFlag => GetResourceString("Argument_InvalidAnyFlag"); internal static string Argument_InvalidEnumValue => GetResourceString("Argument_InvalidEnumValue"); internal static string Argument_InvalidName => GetResourceString("Argument_InvalidName"); internal static string Argument_InvalidPrivilegeName => GetResourceString("Argument_InvalidPrivilegeName"); internal static string Argument_InvalidSafeHandle => GetResourceString("Argument_InvalidSafeHandle"); internal static string ArgumentException_InvalidAceBinaryForm => GetResourceString("ArgumentException_InvalidAceBinaryForm"); internal static string ArgumentException_InvalidAclBinaryForm => GetResourceString("ArgumentException_InvalidAclBinaryForm"); internal static string ArgumentException_InvalidSDSddlForm => GetResourceString("ArgumentException_InvalidSDSddlForm"); internal static string ArgumentOutOfRange_ArrayLength => GetResourceString("ArgumentOutOfRange_ArrayLength"); internal static string ArgumentOutOfRange_ArrayLengthMultiple => GetResourceString("ArgumentOutOfRange_ArrayLengthMultiple"); internal static string ArgumentOutOfRange_ArrayTooSmall => GetResourceString("ArgumentOutOfRange_ArrayTooSmall"); internal static string ArgumentOutOfRange_Enum => GetResourceString("ArgumentOutOfRange_Enum"); internal static string ArgumentOutOfRange_InvalidUserDefinedAceType => GetResourceString("ArgumentOutOfRange_InvalidUserDefinedAceType"); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); internal static string InvalidOperation_ModificationOfNonCanonicalAcl => GetResourceString("InvalidOperation_ModificationOfNonCanonicalAcl"); internal static string InvalidOperation_MustBeSameThread => GetResourceString("InvalidOperation_MustBeSameThread"); internal static string InvalidOperation_MustLockForReadOrWrite => GetResourceString("InvalidOperation_MustLockForReadOrWrite"); internal static string InvalidOperation_MustLockForWrite => GetResourceString("InvalidOperation_MustLockForWrite"); internal static string InvalidOperation_MustRevertPrivilege => GetResourceString("InvalidOperation_MustRevertPrivilege"); internal static string InvalidOperation_NoSecurityDescriptor => GetResourceString("InvalidOperation_NoSecurityDescriptor"); internal static string InvalidOperation_OnlyValidForDS => GetResourceString("InvalidOperation_OnlyValidForDS"); internal static string InvalidOperation_DisconnectedPipe => GetResourceString("InvalidOperation_DisconnectedPipe"); internal static string NotSupported_SetMethod => GetResourceString("NotSupported_SetMethod"); internal static string PrivilegeNotHeld_Default => GetResourceString("PrivilegeNotHeld_Default"); internal static string PrivilegeNotHeld_Named => GetResourceString("PrivilegeNotHeld_Named"); internal static string Rank_MultiDimNotSupported => GetResourceString("Rank_MultiDimNotSupported"); internal static string PlatformNotSupported_AccessControl => GetResourceString("PlatformNotSupported_AccessControl"); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString = null) { if (UsingResourceKeys()) { return defaultString ?? resourceKey; } string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text)) { return defaultString; } return text; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Security.AccessControl { [Flags] public enum AccessControlActions { None = 0, View = 1, Change = 2 } public enum AccessControlModification { Add, Set, Reset, Remove, RemoveAll, RemoveSpecific } [Flags] public enum AccessControlSections { None = 0, Audit = 1, Access = 2, Owner = 4, Group = 8, All = 0xF } public enum AccessControlType { Allow, Deny } public abstract class AccessRule : AuthorizationRule { public AccessControlType AccessControlType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected AccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public class AccessRule<T> : AccessRule where T : struct { public T Rights { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public AccessRule(IdentityReference identity, T rights, AccessControlType type) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public AccessRule(IdentityReference identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public AccessRule(string identity, T rights, AccessControlType type) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public AccessRule(string identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class AceEnumerator : IEnumerator { public GenericAce Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } object IEnumerator.Current { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } internal AceEnumerator() { } public bool MoveNext() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void Reset() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } [Flags] public enum AceFlags : byte { None = 0, ObjectInherit = 1, ContainerInherit = 2, NoPropagateInherit = 4, InheritOnly = 8, InheritanceFlags = 0xF, Inherited = 0x10, SuccessfulAccess = 0x40, FailedAccess = 0x80, AuditFlags = 0xC0 } public enum AceQualifier { AccessAllowed, AccessDenied, SystemAudit, SystemAlarm } public enum AceType : byte { AccessAllowed = 0, AccessDenied = 1, SystemAudit = 2, SystemAlarm = 3, AccessAllowedCompound = 4, AccessAllowedObject = 5, AccessDeniedObject = 6, SystemAuditObject = 7, SystemAlarmObject = 8, AccessAllowedCallback = 9, AccessDeniedCallback = 10, AccessAllowedCallbackObject = 11, AccessDeniedCallbackObject = 12, SystemAuditCallback = 13, SystemAlarmCallback = 14, SystemAuditCallbackObject = 15, MaxDefinedAceType = 16, SystemAlarmCallbackObject = 16 } [Flags] public enum AuditFlags { None = 0, Success = 1, Failure = 2 } public abstract class AuditRule : AuthorizationRule { public AuditFlags AuditFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected AuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags auditFlags) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public class AuditRule<T> : AuditRule where T : struct { public T Rights { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public AuditRule(IdentityReference identity, T rights, AuditFlags flags) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public AuditRule(IdentityReference identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public AuditRule(string identity, T rights, AuditFlags flags) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public AuditRule(string identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class AuthorizationRule { protected internal int AccessMask { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public IdentityReference IdentityReference { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public InheritanceFlags InheritanceFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsInherited { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public PropagationFlags PropagationFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected internal AuthorizationRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class AuthorizationRuleCollection : ReadOnlyCollectionBase { public AuthorizationRule this[int index] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public AuthorizationRuleCollection() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddRule(AuthorizationRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void CopyTo(AuthorizationRule[] rules, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class CommonAce : QualifiedAce { public override int BinaryLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public CommonAce(AceFlags flags, AceQualifier qualifier, int accessMask, SecurityIdentifier sid, bool isCallback, byte[] opaque) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public override void GetBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public static int MaxOpaqueLength(bool isCallback) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class CommonAcl : GenericAcl { public sealed override int BinaryLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed override int Count { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsCanonical { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsContainer { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsDS { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed override GenericAce this[int index] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed override byte Revision { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } internal CommonAcl() { } public sealed override void GetBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void Purge(SecurityIdentifier sid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void RemoveInheritedAces() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class CommonObjectSecurity : ObjectSecurity { protected CommonObjectSecurity(bool isContainer) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void AddAccessRule(AccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void AddAuditRule(AuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public AuthorizationRuleCollection GetAccessRules(bool includeExplicit, bool includeInherited, Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public AuthorizationRuleCollection GetAuditRules(bool includeExplicit, bool includeInherited, Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected override bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected override bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected bool RemoveAccessRule(AccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void RemoveAccessRuleAll(AccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void RemoveAccessRuleSpecific(AccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected bool RemoveAuditRule(AuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void RemoveAuditRuleAll(AuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void RemoveAuditRuleSpecific(AuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void ResetAccessRule(AccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void SetAccessRule(AccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void SetAuditRule(AuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class CommonSecurityDescriptor : GenericSecurityDescriptor { public override ControlFlags ControlFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public DiscretionaryAcl DiscretionaryAcl { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override SecurityIdentifier Group { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsContainer { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsDiscretionaryAclCanonical { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsDS { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsSystemAclCanonical { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override SecurityIdentifier Owner { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public SystemAcl SystemAcl { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public CommonSecurityDescriptor(bool isContainer, bool isDS, byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public CommonSecurityDescriptor(bool isContainer, bool isDS, string sddlForm) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddDiscretionaryAcl(byte revision, int trusted) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddSystemAcl(byte revision, int trusted) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void PurgeAccessControl(SecurityIdentifier sid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void PurgeAudit(SecurityIdentifier sid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInheritance) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetSystemAclProtection(bool isProtected, bool preserveInheritance) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class CompoundAce : KnownAce { public override int BinaryLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public CompoundAceType CompoundAceType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public CompoundAce(AceFlags flags, int accessMask, CompoundAceType compoundAceType, SecurityIdentifier sid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public override void GetBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public enum CompoundAceType { Impersonation = 1 } [Flags] public enum ControlFlags { None = 0, OwnerDefaulted = 1, GroupDefaulted = 2, DiscretionaryAclPresent = 4, DiscretionaryAclDefaulted = 8, SystemAclPresent = 0x10, SystemAclDefaulted = 0x20, DiscretionaryAclUntrusted = 0x40, ServerSecurity = 0x80, DiscretionaryAclAutoInheritRequired = 0x100, SystemAclAutoInheritRequired = 0x200, DiscretionaryAclAutoInherited = 0x400, SystemAclAutoInherited = 0x800, DiscretionaryAclProtected = 0x1000, SystemAclProtected = 0x2000, RMControlValid = 0x4000, SelfRelative = 0x8000 } public sealed class CustomAce : GenericAce { public static readonly int MaxOpaqueLength; public override int BinaryLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public int OpaqueLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public CustomAce(AceType type, AceFlags flags, byte[] opaque) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public override void GetBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public byte[] GetOpaque() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetOpaque(byte[] opaque) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class DiscretionaryAcl : CommonAcl { public DiscretionaryAcl(bool isContainer, bool isDS, byte revision, int capacity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public DiscretionaryAcl(bool isContainer, bool isDS, int capacity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public DiscretionaryAcl(bool isContainer, bool isDS, RawAcl rawAcl) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class GenericAce { public AceFlags AceFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public AceType AceType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public AuditFlags AuditFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract int BinaryLength { get; } public InheritanceFlags InheritanceFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsInherited { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public PropagationFlags PropagationFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } internal GenericAce() { } public GenericAce Copy() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public static GenericAce CreateFromBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public sealed override bool Equals(object o) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public abstract void GetBinaryForm(byte[] binaryForm, int offset); public sealed override int GetHashCode() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public static bool operator ==(GenericAce left, GenericAce right) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public static bool operator !=(GenericAce left, GenericAce right) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class GenericAcl : ICollection, IEnumerable { public static readonly byte AclRevision; public static readonly byte AclRevisionDS; public static readonly int MaxBinaryLength; public abstract int BinaryLength { get; } public abstract int Count { get; } public bool IsSynchronized { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract GenericAce this[int index] { get; set; } public abstract byte Revision { get; } public virtual object SyncRoot { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected GenericAcl() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void CopyTo(GenericAce[] array, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public abstract void GetBinaryForm(byte[] binaryForm, int offset); public AceEnumerator GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } void ICollection.CopyTo(Array array, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } IEnumerator IEnumerable.GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class GenericSecurityDescriptor { public int BinaryLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract ControlFlags ControlFlags { get; } public abstract SecurityIdentifier Group { get; set; } public abstract SecurityIdentifier Owner { get; set; } public static byte Revision { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } internal GenericSecurityDescriptor() { } public void GetBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public string GetSddlForm(AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public static bool IsSddlConversionSupported() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } [Flags] public enum InheritanceFlags { None = 0, ContainerInherit = 1, ObjectInherit = 2 } public abstract class KnownAce : GenericAce { public int AccessMask { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public SecurityIdentifier SecurityIdentifier { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } internal KnownAce() { } } public abstract class NativeObjectSecurity : CommonObjectSecurity { protected internal delegate Exception ExceptionFromErrorCode(int errorCode, string name, SafeHandle handle, object context); protected NativeObjectSecurity(bool isContainer, ResourceType resourceType) : base(isContainer: false) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections) : base(isContainer: false) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(isContainer: false) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(isContainer: false) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections) : base(isContainer: false) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(isContainer: false) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected sealed override void Persist(SafeHandle handle, AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void Persist(SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected sealed override void Persist(string name, AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void Persist(string name, AccessControlSections includeSections, object exceptionContext) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class ObjectAccessRule : AccessRule { public Guid InheritedObjectType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public ObjectAceFlags ObjectFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public Guid ObjectType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected ObjectAccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AccessControlType type) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class ObjectAce : QualifiedAce { public override int BinaryLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public Guid InheritedObjectAceType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public ObjectAceFlags ObjectAceFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public Guid ObjectAceType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public ObjectAce(AceFlags aceFlags, AceQualifier qualifier, int accessMask, SecurityIdentifier sid, ObjectAceFlags flags, Guid type, Guid inheritedType, bool isCallback, byte[] opaque) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public override void GetBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public static int MaxOpaqueLength(bool isCallback) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } [Flags] public enum ObjectAceFlags { None = 0, ObjectAceTypePresent = 1, InheritedObjectAceTypePresent = 2 } public abstract class ObjectAuditRule : AuditRule { public Guid InheritedObjectType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public ObjectAceFlags ObjectFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public Guid ObjectType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected ObjectAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AuditFlags auditFlags) : base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class ObjectSecurity { public abstract Type AccessRightType { get; } protected bool AccessRulesModified { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract Type AccessRuleType { get; } public bool AreAccessRulesCanonical { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool AreAccessRulesProtected { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool AreAuditRulesCanonical { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool AreAuditRulesProtected { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected bool AuditRulesModified { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract Type AuditRuleType { get; } protected bool GroupModified { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected bool IsContainer { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected bool IsDS { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected bool OwnerModified { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected CommonSecurityDescriptor SecurityDescriptor { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected ObjectSecurity() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected ObjectSecurity(bool isContainer, bool isDS) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public abstract AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type); public abstract AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags); public IdentityReference GetGroup(Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public IdentityReference GetOwner(Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public byte[] GetSecurityDescriptorBinaryForm() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public string GetSecurityDescriptorSddlForm(AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public static bool IsSddlConversionSupported() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected abstract bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified); public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected abstract bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified); public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected virtual void Persist(SafeHandle handle, AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected virtual void Persist(string name, AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void PurgeAccessRules(IdentityReference identity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void PurgeAuditRules(IdentityReference identity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void ReadLock() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void ReadUnlock() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetAccessRuleProtection(bool isProtected, bool preserveInheritance) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetAuditRuleProtection(bool isProtected, bool preserveInheritance) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetGroup(IdentityReference identity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetOwner(IdentityReference identity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetSecurityDescriptorBinaryForm(byte[] binaryForm) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetSecurityDescriptorSddlForm(string sddlForm) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetSecurityDescriptorSddlForm(string sddlForm, AccessControlSections includeSections) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void WriteLock() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected void WriteUnlock() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public abstract class ObjectSecurity<T> : NativeObjectSecurity where T : struct { public override Type AccessRightType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override Type AccessRuleType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override Type AuditRuleType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } protected ObjectSecurity(bool isContainer, ResourceType resourceType) : base(isContainer: false, ResourceType.Unknown) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle safeHandle, AccessControlSections includeSections) : base(isContainer: false, ResourceType.Unknown) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle safeHandle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(isContainer: false, ResourceType.Unknown) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected ObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections) : base(isContainer: false, ResourceType.Unknown) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected ObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(isContainer: false, ResourceType.Unknown) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void AddAccessRule(AccessRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void AddAuditRule(AuditRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected internal void Persist(SafeHandle handle) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } protected internal void Persist(string name) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual bool RemoveAccessRule(AccessRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void RemoveAccessRuleAll(AccessRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void RemoveAccessRuleSpecific(AccessRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual bool RemoveAuditRule(AuditRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void RemoveAuditRuleAll(AuditRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void RemoveAuditRuleSpecific(AuditRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void ResetAccessRule(AccessRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void SetAccessRule(AccessRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public virtual void SetAuditRule(AuditRule<T> rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class PrivilegeNotHeldException : UnauthorizedAccessException, ISerializable { public string PrivilegeName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public PrivilegeNotHeldException() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public PrivilegeNotHeldException(string privilege) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public PrivilegeNotHeldException(string privilege, Exception inner) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } [Flags] public enum PropagationFlags { None = 0, NoPropagateInherit = 1, InheritOnly = 2 } public abstract class QualifiedAce : KnownAce { public AceQualifier AceQualifier { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public bool IsCallback { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public int OpaqueLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } internal QualifiedAce() { } public byte[] GetOpaque() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetOpaque(byte[] opaque) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class RawAcl : GenericAcl { public override int BinaryLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override int Count { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override GenericAce this[int index] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override byte Revision { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public RawAcl(byte revision, int capacity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public RawAcl(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public override void GetBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void InsertAce(int index, GenericAce ace) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void RemoveAce(int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public sealed class RawSecurityDescriptor : GenericSecurityDescriptor { public override ControlFlags ControlFlags { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public RawAcl DiscretionaryAcl { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override SecurityIdentifier Group { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public override SecurityIdentifier Owner { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public byte ResourceManagerControl { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public RawAcl SystemAcl { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public RawSecurityDescriptor(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public RawSecurityDescriptor(ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public RawSecurityDescriptor(string sddlForm) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetFlags(ControlFlags flags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } public enum ResourceType { Unknown, FileObject, Service, Printer, RegistryKey, LMShare, KernelObject, WindowObject, DSObject, DSObjectAll, ProviderDefined, WmiGuidObject, RegistryWow6432Key } [Flags] public enum SecurityInfos { Owner = 1, Group = 2, DiscretionaryAcl = 4, SystemAcl = 8 } public sealed class SystemAcl : CommonAcl { public SystemAcl(bool isContainer, bool isDS, byte revision, int capacity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public SystemAcl(bool isContainer, bool isDS, int capacity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public SystemAcl(bool isContainer, bool isDS, RawAcl rawAcl) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void AddAudit(SecurityIdentifier sid, ObjectAuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public bool RemoveAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public bool RemoveAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public bool RemoveAudit(SecurityIdentifier sid, ObjectAuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void RemoveAuditSpecific(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void RemoveAuditSpecific(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void RemoveAuditSpecific(SecurityIdentifier sid, ObjectAuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } public void SetAudit(SecurityIdentifier sid, ObjectAuditRule rule) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl); } } }
deps/System.Security.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Pkcs.Asn1; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using System.Security.Permissions; using System.Security.Policy; using System.Text; using System.Threading; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using Internal.Cryptography; using Internal.Cryptography.Pal.AnyOS; using Unity; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyDescription("System.Security.dll")] [assembly: AssemblyTitle("System.Security.dll")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyDefaultAlias("System.Security.dll")] [assembly: AllowPartiallyTrustedCallers] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class Interop { internal class Kernel32 { private const int FORMAT_MESSAGE_IGNORE_INSERTS = 512; private const int FORMAT_MESSAGE_FROM_HMODULE = 2048; private const int FORMAT_MESSAGE_FROM_SYSTEM = 4096; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192; private const int ERROR_INSUFFICIENT_BUFFER = 122; private const int InitialBufferSize = 256; private const int BufferSizeIncreaseFactor = 4; private const int MaxAllowedBufferSize = 66560; [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", SetLastError = true)] private static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, [Out] StringBuilder lpBuffer, int nSize, IntPtr[] arguments); internal static string GetMessage(int errorCode) { return GetMessage(IntPtr.Zero, errorCode); } internal static string GetMessage(IntPtr moduleHandle, int errorCode) { StringBuilder stringBuilder = new StringBuilder(256); do { if (TryGetErrorMessage(moduleHandle, errorCode, stringBuilder, out var errorMsg)) { return errorMsg; } stringBuilder.Capacity *= 4; } while (stringBuilder.Capacity < 66560); return $"Unknown error (0x{errorCode:x})"; } private static bool TryGetErrorMessage(IntPtr moduleHandle, int errorCode, StringBuilder sb, out string errorMsg) { errorMsg = ""; int num = 12800; if (moduleHandle != IntPtr.Zero) { num |= 0x800; } if (FormatMessage(num, moduleHandle, (uint)errorCode, 0, sb, sb.Capacity, null) != 0) { int num2; for (num2 = sb.Length; num2 > 0; num2--) { char c = sb[num2 - 1]; if (c > ' ' && c != '.') { break; } } errorMsg = sb.ToString(0, num2); } else { if (Marshal.GetLastWin32Error() == 122) { return false; } errorMsg = $"Unknown error (0x{errorCode:x})"; } return true; } } internal class Crypt32 { [Flags] internal enum CryptProtectDataFlags { CRYPTPROTECT_UI_FORBIDDEN = 1, CRYPTPROTECT_LOCAL_MACHINE = 4, CRYPTPROTECT_CRED_SYNC = 8, CRYPTPROTECT_AUDIT = 0x10, CRYPTPROTECT_NO_RECOVERY = 0x20, CRYPTPROTECT_VERIFY_PROTECTION = 0x40 } internal struct DATA_BLOB { internal uint cbData; internal IntPtr pbData; internal DATA_BLOB(IntPtr handle, uint size) { cbData = size; pbData = handle; } } [DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CryptProtectData([In] ref DATA_BLOB pDataIn, [In] string szDataDescr, [In] ref DATA_BLOB pOptionalEntropy, [In] IntPtr pvReserved, [In] IntPtr pPromptStruct, [In] CryptProtectDataFlags dwFlags, out DATA_BLOB pDataOut); [DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CryptUnprotectData([In] ref DATA_BLOB pDataIn, [In] IntPtr ppszDataDescr, [In] ref DATA_BLOB pOptionalEntropy, [In] IntPtr pvReserved, [In] IntPtr pPromptStruct, [In] CryptProtectDataFlags dwFlags, out DATA_BLOB pDataOut); } internal class Errors { internal const int ERROR_SUCCESS = 0; internal const int ERROR_INVALID_FUNCTION = 1; internal const int ERROR_FILE_NOT_FOUND = 2; internal const int ERROR_PATH_NOT_FOUND = 3; internal const int ERROR_ACCESS_DENIED = 5; internal const int ERROR_INVALID_HANDLE = 6; internal const int ERROR_NOT_ENOUGH_MEMORY = 8; internal const int ERROR_INVALID_DATA = 13; internal const int ERROR_INVALID_DRIVE = 15; internal const int ERROR_NO_MORE_FILES = 18; internal const int ERROR_NOT_READY = 21; internal const int ERROR_BAD_COMMAND = 22; internal const int ERROR_BAD_LENGTH = 24; internal const int ERROR_SHARING_VIOLATION = 32; internal const int ERROR_LOCK_VIOLATION = 33; internal const int ERROR_HANDLE_EOF = 38; internal const int ERROR_BAD_NETPATH = 53; internal const int ERROR_BAD_NET_NAME = 67; internal const int ERROR_FILE_EXISTS = 80; internal const int ERROR_INVALID_PARAMETER = 87; internal const int ERROR_BROKEN_PIPE = 109; internal const int ERROR_SEM_TIMEOUT = 121; internal const int ERROR_CALL_NOT_IMPLEMENTED = 120; internal const int ERROR_INSUFFICIENT_BUFFER = 122; internal const int ERROR_INVALID_NAME = 123; internal const int ERROR_NEGATIVE_SEEK = 131; internal const int ERROR_DIR_NOT_EMPTY = 145; internal const int ERROR_BAD_PATHNAME = 161; internal const int ERROR_LOCK_FAILED = 167; internal const int ERROR_BUSY = 170; internal const int ERROR_ALREADY_EXISTS = 183; internal const int ERROR_BAD_EXE_FORMAT = 193; internal const int ERROR_ENVVAR_NOT_FOUND = 203; internal const int ERROR_FILENAME_EXCED_RANGE = 206; internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216; internal const int ERROR_PIPE_BUSY = 231; internal const int ERROR_NO_DATA = 232; internal const int ERROR_PIPE_NOT_CONNECTED = 233; internal const int ERROR_MORE_DATA = 234; internal const int ERROR_NO_MORE_ITEMS = 259; internal const int ERROR_DIRECTORY = 267; internal const int ERROR_PARTIAL_COPY = 299; internal const int ERROR_ARITHMETIC_OVERFLOW = 534; internal const int ERROR_PIPE_CONNECTED = 535; internal const int ERROR_PIPE_LISTENING = 536; internal const int ERROR_OPERATION_ABORTED = 995; internal const int ERROR_IO_INCOMPLETE = 996; internal const int ERROR_IO_PENDING = 997; internal const int ERROR_NO_TOKEN = 1008; internal const int ERROR_DLL_INIT_FAILED = 1114; internal const int ERROR_COUNTER_TIMEOUT = 1121; internal const int ERROR_NO_ASSOCIATION = 1155; internal const int ERROR_DDE_FAIL = 1156; internal const int ERROR_DLL_NOT_FOUND = 1157; internal const int ERROR_NOT_FOUND = 1168; internal const int ERROR_NETWORK_UNREACHABLE = 1231; internal const int ERROR_NON_ACCOUNT_SID = 1257; internal const int ERROR_NOT_ALL_ASSIGNED = 1300; internal const int ERROR_UNKNOWN_REVISION = 1305; internal const int ERROR_INVALID_OWNER = 1307; internal const int ERROR_INVALID_PRIMARY_GROUP = 1308; internal const int ERROR_NO_SUCH_PRIVILEGE = 1313; internal const int ERROR_PRIVILEGE_NOT_HELD = 1314; internal const int ERROR_INVALID_ACL = 1336; internal const int ERROR_INVALID_SECURITY_DESCR = 1338; internal const int ERROR_INVALID_SID = 1337; internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346; internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347; internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350; internal const int ERROR_CLASS_ALREADY_EXISTS = 1410; internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789; internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815; internal const int EFail = -2147467259; internal const int E_FILENOTFOUND = -2147024894; } internal static class Libraries { internal const string Advapi32 = "advapi32.dll"; internal const string BCrypt = "BCrypt.dll"; internal const string CoreComm_L1_1_1 = "api-ms-win-core-comm-l1-1-1.dll"; internal const string Crypt32 = "crypt32.dll"; internal const string Error_L1 = "api-ms-win-core-winrt-error-l1-1-0.dll"; internal const string HttpApi = "httpapi.dll"; internal const string IpHlpApi = "iphlpapi.dll"; internal const string Kernel32 = "kernel32.dll"; internal const string Memory_L1_3 = "api-ms-win-core-memory-l1-1-3.dll"; internal const string Mswsock = "mswsock.dll"; internal const string NCrypt = "ncrypt.dll"; internal const string NtDll = "ntdll.dll"; internal const string Odbc32 = "odbc32.dll"; internal const string OleAut32 = "oleaut32.dll"; internal const string PerfCounter = "perfcounter.dll"; internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll"; internal const string Secur32 = "secur32.dll"; internal const string Shell32 = "shell32.dll"; internal const string SspiCli = "sspicli.dll"; internal const string User32 = "user32.dll"; internal const string Version = "version.dll"; internal const string WebSocket = "websocket.dll"; internal const string WinHttp = "winhttp.dll"; internal const string Ws2_32 = "ws2_32.dll"; internal const string Wtsapi32 = "wtsapi32.dll"; internal const string CompressionNative = "clrcompression.dll"; } } namespace System.Security.Permissions { [Serializable] public sealed class DataProtectionPermission : CodeAccessPermission, IUnrestrictedPermission { private const int version = 1; private DataProtectionPermissionFlags _flags; public DataProtectionPermissionFlags Flags { get { return _flags; } set { if (((uint)value & 0xFFFFFFF0u) != 0) { throw new ArgumentException(string.Format(Locale.GetText("Invalid enum {0}"), value), "DataProtectionPermissionFlags"); } _flags = value; } } public DataProtectionPermission(PermissionState state) { if (PermissionHelper.CheckPermissionState(state, allowUnrestricted: true) == PermissionState.Unrestricted) { _flags = DataProtectionPermissionFlags.AllFlags; } } public DataProtectionPermission(DataProtectionPermissionFlags flag) { Flags = flag; } public bool IsUnrestricted() { return _flags == DataProtectionPermissionFlags.AllFlags; } public override IPermission Copy() { return (IPermission)(object)new DataProtectionPermission(_flags); } public override IPermission Intersect(IPermission target) { DataProtectionPermission dataProtectionPermission = Cast(target); if (dataProtectionPermission == null) { return null; } if (IsUnrestricted() && dataProtectionPermission.IsUnrestricted()) { return (IPermission)(object)new DataProtectionPermission(PermissionState.Unrestricted); } if (IsUnrestricted()) { return ((CodeAccessPermission)dataProtectionPermission).Copy(); } if (dataProtectionPermission.IsUnrestricted()) { return ((CodeAccessPermission)this).Copy(); } return (IPermission)(object)new DataProtectionPermission(_flags & dataProtectionPermission._flags); } public override IPermission Union(IPermission target) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown DataProtectionPermission dataProtectionPermission = Cast(target); if (dataProtectionPermission == null) { return ((CodeAccessPermission)this).Copy(); } if (IsUnrestricted() || dataProtectionPermission.IsUnrestricted()) { return (IPermission)new SecurityPermission(PermissionState.Unrestricted); } return (IPermission)(object)new DataProtectionPermission(_flags | dataProtectionPermission._flags); } public override bool IsSubsetOf(IPermission target) { DataProtectionPermission dataProtectionPermission = Cast(target); if (dataProtectionPermission == null) { return _flags == DataProtectionPermissionFlags.NoFlags; } if (dataProtectionPermission.IsUnrestricted()) { return true; } if (IsUnrestricted()) { return false; } return (_flags & ~dataProtectionPermission._flags) == 0; } public override void FromXml(SecurityElement securityElement) { PermissionHelper.CheckSecurityElement(securityElement, "securityElement", 1, 1); _flags = (DataProtectionPermissionFlags)Enum.Parse(typeof(DataProtectionPermissionFlags), securityElement.Attribute("Flags")); } public override SecurityElement ToXml() { SecurityElement securityElement = PermissionHelper.Element(typeof(DataProtectionPermission), 1); securityElement.AddAttribute("Flags", _flags.ToString()); return securityElement; } private DataProtectionPermission Cast(IPermission target) { if (target == null) { return null; } DataProtectionPermission obj = target as DataProtectionPermission; if (obj == null) { PermissionHelper.ThrowInvalidPermission(target, typeof(DataProtectionPermission)); } return obj; } } [Serializable] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public sealed class DataProtectionPermissionAttribute : CodeAccessSecurityAttribute { private DataProtectionPermissionFlags _flags; public DataProtectionPermissionFlags Flags { get { return _flags; } set { if ((value & DataProtectionPermissionFlags.AllFlags) != value) { throw new ArgumentException(string.Format(Locale.GetText("Invalid flags {0}"), value), "DataProtectionPermissionFlags"); } _flags = value; } } public bool ProtectData { get { return (_flags & DataProtectionPermissionFlags.ProtectData) != 0; } set { if (value) { _flags |= DataProtectionPermissionFlags.ProtectData; } else { _flags &= ~DataProtectionPermissionFlags.ProtectData; } } } public bool UnprotectData { get { return (_flags & DataProtectionPermissionFlags.UnprotectData) != 0; } set { if (value) { _flags |= DataProtectionPermissionFlags.UnprotectData; } else { _flags &= ~DataProtectionPermissionFlags.UnprotectData; } } } public bool ProtectMemory { get { return (_flags & DataProtectionPermissionFlags.ProtectMemory) != 0; } set { if (value) { _flags |= DataProtectionPermissionFlags.ProtectMemory; } else { _flags &= ~DataProtectionPermissionFlags.ProtectMemory; } } } public bool UnprotectMemory { get { return (_flags & DataProtectionPermissionFlags.UnprotectMemory) != 0; } set { if (value) { _flags |= DataProtectionPermissionFlags.UnprotectMemory; } else { _flags &= ~DataProtectionPermissionFlags.UnprotectMemory; } } } public DataProtectionPermissionAttribute(SecurityAction action) : base(action) { } public override IPermission CreatePermission() { DataProtectionPermission dataProtectionPermission = null; if (base.Unrestricted) { return (IPermission)(object)new DataProtectionPermission(PermissionState.Unrestricted); } return (IPermission)(object)new DataProtectionPermission(_flags); } } [Serializable] [Flags] public enum DataProtectionPermissionFlags { NoFlags = 0, ProtectData = 1, UnprotectData = 2, ProtectMemory = 4, UnprotectMemory = 8, AllFlags = 0xF } internal sealed class PermissionHelper { internal static SecurityElement Element(Type type, int version) { SecurityElement securityElement = new SecurityElement("IPermission"); securityElement.AddAttribute("class", type.FullName + ", " + type.Assembly.ToString().Replace('"', '\'')); securityElement.AddAttribute("version", version.ToString()); return securityElement; } internal static PermissionState CheckPermissionState(PermissionState state, bool allowUnrestricted) { switch (state) { case PermissionState.Unrestricted: if (!allowUnrestricted) { throw new ArgumentException(Locale.GetText("Unrestricted isn't not allowed for identity permissions."), "state"); } break; default: throw new ArgumentException(string.Format(Locale.GetText("Invalid enum {0}"), state), "state"); case PermissionState.None: break; } return state; } internal static int CheckSecurityElement(SecurityElement se, string parameterName, int minimumVersion, int maximumVersion) { if (se == null) { throw new ArgumentNullException(parameterName); } if (se.Attribute("class") == null) { throw new ArgumentException(Locale.GetText("Missing 'class' attribute."), parameterName); } int num = minimumVersion; string text = se.Attribute("version"); if (text != null) { try { num = int.Parse(text); } catch (Exception innerException) { throw new ArgumentException(string.Format(Locale.GetText("Couldn't parse version from '{0}'."), text), parameterName, innerException); } } if (num < minimumVersion || num > maximumVersion) { throw new ArgumentException(string.Format(Locale.GetText("Unknown version '{0}', expected versions between ['{1}','{2}']."), num, minimumVersion, maximumVersion), parameterName); } return num; } internal static bool IsUnrestricted(SecurityElement se) { string text = se.Attribute("Unrestricted"); if (text == null) { return false; } return string.Compare(text, bool.TrueString, ignoreCase: true, CultureInfo.InvariantCulture) == 0; } internal static void ThrowInvalidPermission(IPermission target, Type expected) { throw new ArgumentException(string.Format(Locale.GetText("Invalid permission type '{0}', expected type '{1}'."), target.GetType(), expected), "target"); } } } namespace System.Security.Cryptography { public sealed class CryptographicAttributeObject { private readonly Oid _oid; public Oid Oid => new Oid(_oid); public AsnEncodedDataCollection Values { get; } public CryptographicAttributeObject(Oid oid) : this(oid, new AsnEncodedDataCollection()) { } public CryptographicAttributeObject(Oid oid, AsnEncodedDataCollection values) { _oid = new Oid(oid); if (values == null) { Values = new AsnEncodedDataCollection(); return; } AsnEncodedDataEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { AsnEncodedData current = enumerator.Current; if (!string.Equals(current.Oid.Value, oid.Value, StringComparison.Ordinal)) { throw new InvalidOperationException(SR.Format("AsnEncodedData element in the collection has wrong Oid value: expected = '{0}', actual = '{1}'.", (object)oid.Value, (object)current.Oid.Value)); } } Values = values; } } public sealed class CryptographicAttributeObjectCollection : ICollection, IEnumerable { private readonly List<CryptographicAttributeObject> _list; public CryptographicAttributeObject this[int index] => _list[index]; public int Count => _list.Count; public bool IsSynchronized => false; public object SyncRoot => this; public CryptographicAttributeObjectCollection() { _list = new List<CryptographicAttributeObject>(); } public CryptographicAttributeObjectCollection(CryptographicAttributeObject attribute) { _list = new List<CryptographicAttributeObject>(); _list.Add(attribute); } public int Add(AsnEncodedData asnEncodedData) { if (asnEncodedData == null) { throw new ArgumentNullException("asnEncodedData"); } return Add(new CryptographicAttributeObject(asnEncodedData.Oid, new AsnEncodedDataCollection(asnEncodedData))); } public int Add(CryptographicAttributeObject attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } string value = attribute.Oid.Value; for (int i = 0; i < _list.Count; i++) { CryptographicAttributeObject cryptographicAttributeObject = _list[i]; if (cryptographicAttributeObject.Values == attribute.Values) { throw new InvalidOperationException("Duplicate items are not allowed in the collection."); } string value2 = cryptographicAttributeObject.Oid.Value; if (string.Equals(value, value2, StringComparison.OrdinalIgnoreCase)) { if (string.Equals(value, "1.2.840.113549.1.9.5", StringComparison.OrdinalIgnoreCase)) { throw new CryptographicException("Cannot add multiple PKCS 9 signing time attributes."); } AsnEncodedDataEnumerator enumerator = attribute.Values.GetEnumerator(); while (enumerator.MoveNext()) { AsnEncodedData current = enumerator.Current; cryptographicAttributeObject.Values.Add(current); } return i; } } int count = _list.Count; _list.Add(attribute); return count; } internal void AddWithoutMerge(CryptographicAttributeObject attribute) { _list.Add(attribute); } public void Remove(CryptographicAttributeObject attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } _list.Remove(attribute); } public CryptographicAttributeObjectEnumerator GetEnumerator() { return new CryptographicAttributeObjectEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new CryptographicAttributeObjectEnumerator(this); } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException("Only single dimensional arrays are supported for the requested action."); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", "Index was out of range. Must be non-negative and less than the size of the collection."); } if (index > array.Length - Count) { throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); } for (int i = 0; i < Count; i++) { array.SetValue(this[i], index); index++; } } public void CopyTo(CryptographicAttributeObject[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", "Index was out of range. Must be non-negative and less than the size of the collection."); } if (index > array.Length - Count) { throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); } _list.CopyTo(array, index); } } public sealed class CryptographicAttributeObjectEnumerator : IEnumerator { private readonly CryptographicAttributeObjectCollection _attributes; private int _current; public CryptographicAttributeObject Current => _attributes[_current]; object IEnumerator.Current => _attributes[_current]; internal CryptographicAttributeObjectEnumerator(CryptographicAttributeObjectCollection attributes) { _attributes = attributes; _current = -1; } public bool MoveNext() { if (_current >= _attributes.Count - 1) { return false; } _current++; return true; } public void Reset() { _current = -1; } internal CryptographicAttributeObjectEnumerator() { ThrowStub.ThrowNotSupportedException(); } } public enum DataProtectionScope { CurrentUser, LocalMachine } public static class ProtectedData { private static readonly byte[] s_nonEmpty = new byte[1]; public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) { if (userData == null) { throw new ArgumentNullException("userData"); } return ProtectOrUnprotect(userData, optionalEntropy, scope, protect: true); } public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) { if (encryptedData == null) { throw new ArgumentNullException("encryptedData"); } return ProtectOrUnprotect(encryptedData, optionalEntropy, scope, protect: false); } private unsafe static byte[] ProtectOrUnprotect(byte[] inputData, byte[] optionalEntropy, DataProtectionScope scope, bool protect) { fixed (byte* ptr = ((inputData.Length == 0) ? s_nonEmpty : inputData)) { fixed (byte* ptr2 = optionalEntropy) { global::Interop.Crypt32.DATA_BLOB pDataIn = new global::Interop.Crypt32.DATA_BLOB((IntPtr)ptr, (uint)inputData.Length); global::Interop.Crypt32.DATA_BLOB pOptionalEntropy = default(global::Interop.Crypt32.DATA_BLOB); if (optionalEntropy != null) { pOptionalEntropy = new global::Interop.Crypt32.DATA_BLOB((IntPtr)ptr2, (uint)optionalEntropy.Length); } global::Interop.Crypt32.CryptProtectDataFlags cryptProtectDataFlags = global::Interop.Crypt32.CryptProtectDataFlags.CRYPTPROTECT_UI_FORBIDDEN; if (scope == DataProtectionScope.LocalMachine) { cryptProtectDataFlags |= global::Interop.Crypt32.CryptProtectDataFlags.CRYPTPROTECT_LOCAL_MACHINE; } global::Interop.Crypt32.DATA_BLOB pDataOut = default(global::Interop.Crypt32.DATA_BLOB); try { if (!(protect ? global::Interop.Crypt32.CryptProtectData(ref pDataIn, null, ref pOptionalEntropy, IntPtr.Zero, IntPtr.Zero, cryptProtectDataFlags, out pDataOut) : global::Interop.Crypt32.CryptUnprotectData(ref pDataIn, IntPtr.Zero, ref pOptionalEntropy, IntPtr.Zero, IntPtr.Zero, cryptProtectDataFlags, out pDataOut))) { int lastWin32Error = Marshal.GetLastWin32Error(); if (protect && ErrorMayBeCausedByUnloadedProfile(lastWin32Error)) { throw new CryptographicException("The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread's user context, which may be the case when the thread is impersonating."); } throw lastWin32Error.ToCryptographicException(); } if (pDataOut.pbData == IntPtr.Zero) { throw new OutOfMemoryException(); } int cbData = (int)pDataOut.cbData; byte[] array = new byte[cbData]; Marshal.Copy(pDataOut.pbData, array, 0, cbData); return array; } finally { if (pDataOut.pbData != IntPtr.Zero) { int cbData2 = (int)pDataOut.cbData; byte* ptr3 = (byte*)(void*)pDataOut.pbData; for (int i = 0; i < cbData2; i++) { ptr3[i] = 0; } Marshal.FreeHGlobal(pDataOut.pbData); } } } } } private static bool ErrorMayBeCausedByUnloadedProfile(int errorCode) { if (errorCode != -2147024894) { return errorCode == 2; } return true; } } public abstract class DataProtector { private string m_applicationName; private string m_primaryPurpose; private IEnumerable<string> m_specificPurposes; private volatile byte[] m_hashedPurpose; protected string ApplicationName => m_applicationName; protected virtual bool PrependHashedPurposeToPlaintext => true; protected string PrimaryPurpose => m_primaryPurpose; protected IEnumerable<string> SpecificPurposes => m_specificPurposes; protected DataProtector(string applicationName, string primaryPurpose, string[] specificPurposes) { if (string.IsNullOrWhiteSpace(applicationName)) { throw new ArgumentException("Invalid application name and/or purpose", "applicationName"); } if (string.IsNullOrWhiteSpace(primaryPurpose)) { throw new ArgumentException("Invalid application name and/or purpose", "primaryPurpose"); } if (specificPurposes != null) { for (int i = 0; i < specificPurposes.Length; i++) { if (string.IsNullOrWhiteSpace(specificPurposes[i])) { throw new ArgumentException("Invalid application name and/or purpose", "specificPurposes"); } } } m_applicationName = applicationName; m_primaryPurpose = primaryPurpose; List<string> list = new List<string>(); if (specificPurposes != null) { list.AddRange(specificPurposes); } m_specificPurposes = list; } protected virtual byte[] GetHashedPurpose() { if (m_hashedPurpose == null) { using HashAlgorithm hashAlgorithm = HashAlgorithm.Create("System.Security.Cryptography.Sha256Cng"); using (BinaryWriter binaryWriter = new BinaryWriter(new CryptoStream(new MemoryStream(), hashAlgorithm, CryptoStreamMode.Write), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true))) { binaryWriter.Write(ApplicationName); binaryWriter.Write(PrimaryPurpose); foreach (string specificPurpose in SpecificPurposes) { binaryWriter.Write(specificPurpose); } } m_hashedPurpose = hashAlgorithm.Hash; } return m_hashedPurpose; } public abstract bool IsReprotectRequired(byte[] encryptedData); public static DataProtector Create(string providerClass, string applicationName, string primaryPurpose, params string[] specificPurposes) { if (providerClass == null) { throw new ArgumentNullException("providerClass"); } return (DataProtector)CryptoConfig.CreateFromName(providerClass, applicationName, primaryPurpose, specificPurposes); } public byte[] Protect(byte[] userData) { if (userData == null) { throw new ArgumentNullException("userData"); } if (PrependHashedPurposeToPlaintext) { byte[] hashedPurpose = GetHashedPurpose(); byte[] array = new byte[userData.Length + hashedPurpose.Length]; Array.Copy(hashedPurpose, 0, array, 0, hashedPurpose.Length); Array.Copy(userData, 0, array, hashedPurpose.Length, userData.Length); userData = array; } return ProviderProtect(userData); } protected abstract byte[] ProviderProtect(byte[] userData); protected abstract byte[] ProviderUnprotect(byte[] encryptedData); [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public byte[] Unprotect(byte[] encryptedData) { if (encryptedData == null) { throw new ArgumentNullException("encryptedData"); } if (PrependHashedPurposeToPlaintext) { byte[] array = ProviderUnprotect(encryptedData); byte[] hashedPurpose = GetHashedPurpose(); bool flag = array.Length >= hashedPurpose.Length; for (int i = 0; i < hashedPurpose.Length; i++) { if (hashedPurpose[i] != array[i % array.Length]) { flag = false; } } if (!flag) { throw new CryptographicException("Invalid data protection purpose"); } byte[] array2 = new byte[array.Length - hashedPurpose.Length]; Array.Copy(array, hashedPurpose.Length, array2, 0, array2.Length); return array2; } return ProviderUnprotect(encryptedData); } } public enum MemoryProtectionScope { SameProcess, CrossProcess, SameLogon } public sealed class ProtectedMemory { private enum MemoryProtectionImplementation { Unknown = 0, Win32RtlEncryptMemory = 1, Win32CryptoProtect = 2, Unsupported = int.MinValue } private const int BlockSize = 16; private static MemoryProtectionImplementation impl; private ProtectedMemory() { } [MonoTODO("only supported on Windows 2000 SP3 and later")] public static void Protect(byte[] userData, MemoryProtectionScope scope) { if (userData == null) { throw new ArgumentNullException("userData"); } Check(userData.Length, scope); try { uint cbData = (uint)userData.Length; switch (impl) { case MemoryProtectionImplementation.Win32RtlEncryptMemory: { int num = RtlEncryptMemory(userData, cbData, (uint)scope); if (num < 0) { throw new CryptographicException(Locale.GetText("Error. NTSTATUS = {0}.", new object[1] { num })); } break; } case MemoryProtectionImplementation.Win32CryptoProtect: if (!CryptProtectMemory(userData, cbData, (uint)scope)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } break; default: throw new PlatformNotSupportedException(); } } catch { impl = MemoryProtectionImplementation.Unsupported; throw new PlatformNotSupportedException(); } } [MonoTODO("only supported on Windows 2000 SP3 and later")] public static void Unprotect(byte[] encryptedData, MemoryProtectionScope scope) { if (encryptedData == null) { throw new ArgumentNullException("encryptedData"); } Check(encryptedData.Length, scope); try { uint cbData = (uint)encryptedData.Length; switch (impl) { case MemoryProtectionImplementation.Win32RtlEncryptMemory: { int num = RtlDecryptMemory(encryptedData, cbData, (uint)scope); if (num < 0) { throw new CryptographicException(Locale.GetText("Error. NTSTATUS = {0}.", new object[1] { num })); } break; } case MemoryProtectionImplementation.Win32CryptoProtect: if (!CryptUnprotectMemory(encryptedData, cbData, (uint)scope)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } break; default: throw new PlatformNotSupportedException(); } } catch { impl = MemoryProtectionImplementation.Unsupported; throw new PlatformNotSupportedException(); } } private static void Detect() { OperatingSystem oSVersion = Environment.OSVersion; if (oSVersion.Platform == PlatformID.Win32NT) { Version version = oSVersion.Version; if (version.Major < 5) { impl = MemoryProtectionImplementation.Unsupported; } else if (version.Major == 5) { if (version.Minor < 2) { impl = MemoryProtectionImplementation.Win32RtlEncryptMemory; } else { impl = MemoryProtectionImplementation.Win32CryptoProtect; } } else { impl = MemoryProtectionImplementation.Win32CryptoProtect; } } else { impl = MemoryProtectionImplementation.Unsupported; } } private static void Check(int size, MemoryProtectionScope scope) { if (size % 16 != 0) { throw new CryptographicException(Locale.GetText("Not a multiple of {0} bytes.", new object[1] { 16 })); } if (scope < MemoryProtectionScope.SameProcess || scope > MemoryProtectionScope.SameLogon) { throw new ArgumentException(Locale.GetText("Invalid enum value for '{0}'.", new object[1] { "MemoryProtectionScope" }), "scope"); } switch (impl) { case MemoryProtectionImplementation.Unknown: Detect(); break; case MemoryProtectionImplementation.Unsupported: throw new PlatformNotSupportedException(); } } [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, EntryPoint = "SystemFunction040", SetLastError = true)] [SuppressUnmanagedCodeSecurity] private static extern int RtlEncryptMemory(byte[] pData, uint cbData, uint dwFlags); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, EntryPoint = "SystemFunction041", SetLastError = true)] [SuppressUnmanagedCodeSecurity] private static extern int RtlDecryptMemory(byte[] pData, uint cbData, uint dwFlags); [DllImport("crypt32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)] [SuppressUnmanagedCodeSecurity] private static extern bool CryptProtectMemory(byte[] pData, uint cbData, uint dwFlags); [DllImport("crypt32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)] [SuppressUnmanagedCodeSecurity] private static extern bool CryptUnprotectMemory(byte[] pData, uint cbData, uint dwFlags); } } namespace System.Security.Cryptography.Translation { internal class SR { public const string Cryptography_DataProtector_InvalidAppNameOrPurpose = "Invalid application name and/or purpose"; public const string Cryptography_DataProtector_InvalidPurpose = "Invalid data protection purpose"; public const string ArgumentOutOfRange_Index = "Index was out of range. Must be non-negative and less than the size of the collection."; public const string Arg_EmptyOrNullString = "String cannot be empty or null."; public const string Cryptography_Partial_Chain = "A certificate chain could not be built to a trusted root authority."; public const string Cryptography_Xml_BadWrappedKeySize = "Bad wrapped key size."; public const string Cryptography_Xml_CipherValueElementRequired = "A Cipher Data element should have either a CipherValue or a CipherReference element."; public const string Cryptography_Xml_CreateHashAlgorithmFailed = "Could not create hash algorithm object."; public const string Cryptography_Xml_CreateTransformFailed = "Could not create the XML transformation identified by the URI {0}."; public const string Cryptography_Xml_CreatedKeyFailed = "Failed to create signing key."; public const string Cryptography_Xml_DigestMethodRequired = "A DigestMethod must be specified on a Reference prior to generating XML."; public const string Cryptography_Xml_DigestValueRequired = "A Reference must contain a DigestValue."; public const string Cryptography_Xml_EnvelopedSignatureRequiresContext = "An XmlDocument context is required for enveloped transforms."; public const string Cryptography_Xml_InvalidElement = "Malformed element {0}."; public const string Cryptography_Xml_InvalidEncryptionProperty = "Malformed encryption property element."; public const string Cryptography_Xml_InvalidKeySize = "The key size should be a non negative integer."; public const string Cryptography_Xml_InvalidReference = "Malformed reference element."; public const string Cryptography_Xml_InvalidSignatureLength = "The length of the signature with a MAC should be less than the hash output length."; public const string Cryptography_Xml_InvalidSignatureLength2 = "The length in bits of the signature with a MAC should be a multiple of 8."; public const string Cryptography_Xml_InvalidX509IssuerSerialNumber = "X509 issuer serial number is invalid."; public const string Cryptography_Xml_KeyInfoRequired = "A KeyInfo element is required to check the signature."; public const string Cryptography_Xml_KW_BadKeySize = "The length of the encrypted data in Key Wrap is either 32, 40 or 48 bytes."; public const string Cryptography_Xml_LoadKeyFailed = "Signing key is not loaded."; public const string Cryptography_Xml_MissingAlgorithm = "Symmetric algorithm is not specified."; public const string Cryptography_Xml_MissingCipherData = "Cipher data is not specified."; public const string Cryptography_Xml_MissingDecryptionKey = "Unable to retrieve the decryption key."; public const string Cryptography_Xml_MissingEncryptionKey = "Unable to retrieve the encryption key."; public const string Cryptography_Xml_NotSupportedCryptographicTransform = "The specified cryptographic transform is not supported."; public const string Cryptography_Xml_ReferenceElementRequired = "At least one Reference element is required."; public const string Cryptography_Xml_ReferenceTypeRequired = "The Reference type must be set in an EncryptedReference object."; public const string Cryptography_Xml_SelfReferenceRequiresContext = "An XmlDocument context is required to resolve the Reference Uri {0}."; public const string Cryptography_Xml_SignatureDescriptionNotCreated = "SignatureDescription could not be created for the signature algorithm supplied."; public const string Cryptography_Xml_SignatureMethodKeyMismatch = "The key does not fit the SignatureMethod."; public const string Cryptography_Xml_SignatureMethodRequired = "A signature method is required."; public const string Cryptography_Xml_SignatureValueRequired = "Signature requires a SignatureValue."; public const string Cryptography_Xml_SignedInfoRequired = "Signature requires a SignedInfo."; public const string Cryptography_Xml_TransformIncorrectInputType = "The input type was invalid for this transform."; public const string Cryptography_Xml_IncorrectObjectType = "Type of input object is invalid."; public const string Cryptography_Xml_UnknownTransform = "Unknown transform has been encountered."; public const string Cryptography_Xml_UriNotResolved = "Unable to resolve Uri {0}."; public const string Cryptography_Xml_UriNotSupported = " The specified Uri is not supported."; public const string Cryptography_Xml_UriRequired = "A Uri attribute is required for a CipherReference element."; public const string Cryptography_Xml_XrmlMissingContext = "Null Context property encountered."; public const string Cryptography_Xml_XrmlMissingIRelDecryptor = "IRelDecryptor is required."; public const string Cryptography_Xml_XrmlMissingIssuer = "Issuer node is required."; public const string Cryptography_Xml_XrmlMissingLicence = "License node is required."; public const string Cryptography_Xml_XrmlUnableToDecryptGrant = "Unable to decrypt grant content."; public const string NotSupported_KeyAlgorithm = "The certificate key algorithm is not supported."; public const string Log_ActualHashValue = "Actual hash value: {0}"; public const string Log_BeginCanonicalization = "Beginning canonicalization using \"{0}\" ({1})."; public const string Log_BeginSignatureComputation = "Beginning signature computation."; public const string Log_BeginSignatureVerification = "Beginning signature verification."; public const string Log_BuildX509Chain = "Building and verifying the X509 chain for certificate {0}."; public const string Log_CanonicalizationSettings = "Canonicalization transform is using resolver {0} and base URI \"{1}\"."; public const string Log_CanonicalizedOutput = "Output of canonicalization transform: {0}"; public const string Log_CertificateChain = "Certificate chain:"; public const string Log_CheckSignatureFormat = "Checking signature format using format validator \"[{0}] {1}.{2}\"."; public const string Log_CheckSignedInfo = "Checking signature on SignedInfo with id \"{0}\"."; public const string Log_FormatValidationSuccessful = "Signature format validation was successful."; public const string Log_FormatValidationNotSuccessful = "Signature format validation failed."; public const string Log_KeyUsages = "Found key usages \"{0}\" in extension {1} on certificate {2}."; public const string Log_NoNamespacesPropagated = "No namespaces are being propagated."; public const string Log_PropagatingNamespace = "Propagating namespace {0}=\"{1}\"."; public const string Log_RawSignatureValue = "Raw signature: {0}"; public const string Log_ReferenceHash = "Reference {0} hashed with \"{1}\" ({2}) has hash value {3}, expected hash value {4}."; public const string Log_RevocationMode = "Revocation mode for chain building: {0}."; public const string Log_RevocationFlag = "Revocation flag for chain building: {0}."; public const string Log_SigningAsymmetric = "Calculating signature with key {0} using signature description {1}, hash algorithm {2}, and asymmetric signature formatter {3}."; public const string Log_SigningHmac = "Calculating signature using keyed hash algorithm {0}."; public const string Log_SigningReference = "Hashing reference {0}, Uri \"{1}\", Id \"{2}\", Type \"{3}\" with hash algorithm \"{4}\" ({5})."; public const string Log_TransformedReferenceContents = "Transformed reference contents: {0}"; public const string Log_UnsafeCanonicalizationMethod = "Canonicalization method \"{0}\" is not on the safe list. Safe canonicalization methods are: {1}."; public const string Log_UrlTimeout = "URL retrieval timeout for chain building: {0}."; public const string Log_VerificationFailed = "Verification failed checking {0}."; public const string Log_VerificationFailed_References = "references"; public const string Log_VerificationFailed_SignedInfo = "SignedInfo"; public const string Log_VerificationFailed_X509Chain = "X509 chain verification"; public const string Log_VerificationFailed_X509KeyUsage = "X509 key usage verification"; public const string Log_VerificationFlag = "Verification flags for chain building: {0}."; public const string Log_VerificationTime = "Verification time for chain building: {0}."; public const string Log_VerificationWithKeySuccessful = "Verification with key {0} was successful."; public const string Log_VerificationWithKeyNotSuccessful = "Verification with key {0} was not successful."; public const string Log_VerifyReference = "Processing reference {0}, Uri \"{1}\", Id \"{2}\", Type \"{3}\"."; public const string Log_VerifySignedInfoAsymmetric = "Verifying SignedInfo using key {0}, signature description {1}, hash algorithm {2}, and asymmetric signature deformatter {3}."; public const string Log_VerifySignedInfoHmac = "Verifying SignedInfo using keyed hash algorithm {0}."; public const string Log_X509ChainError = "Error building X509 chain: {0}: {1}."; public const string Log_XmlContext = "Using context: {0}"; public const string Log_SignedXmlRecursionLimit = "Signed xml recursion limit hit while trying to decrypt the key. Reference {0} hashed with \"{1}\" and ({2})."; public const string Log_UnsafeTransformMethod = "Transform method \"{0}\" is not on the safe list. Safe transform methods are: {1}."; public const string Arg_RankMultiDimNotSupported = "Only single dimensional arrays are supported for the requested action."; public const string Argument_InvalidOffLen = "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."; public const string Argument_InvalidOidValue = "The OID value was invalid."; public const string Cryptography_Asn_EnumeratedValueRequiresNonFlagsEnum = "ASN.1 Enumerated values only apply to enum types without the [Flags] attribute."; public const string Cryptography_Asn_NamedBitListRequiresFlagsEnum = "Named bit list operations require an enum with the [Flags] attribute."; public const string Cryptography_Asn_NamedBitListValueTooBig = "The encoded named bit list value is larger than the value size of the '{0}' enum."; public const string Cryptography_Asn_UniversalValueIsFixed = "Tags with TagClass Universal must have the appropriate TagValue value for the data type being read or written."; public const string Cryptography_Asn_UnusedBitCountRange = "Unused bit count must be between 0 and 7, inclusive."; public const string Cryptography_AsnSerializer_AmbiguousFieldType = "Field '{0}' of type '{1}' has ambiguous type '{2}', an attribute derived from AsnTypeAttribute is required."; public const string Cryptography_AsnSerializer_Choice_AllowNullNonNullable = "[Choice].AllowNull=true is not valid because type '{0}' cannot have a null value."; public const string Cryptography_AsnSerializer_Choice_ConflictingTagMapping = "The tag ({0} {1}) for field '{2}' on type '{3}' already is associated in this context with field '{4}' on type '{5}'."; public const string Cryptography_AsnSerializer_Choice_DefaultValueDisallowed = "Field '{0}' on [Choice] type '{1}' has a default value, which is not permitted."; public const string Cryptography_AsnSerializer_Choice_NoChoiceWasMade = "An instance of [Choice] type '{0}' has no non-null fields."; public const string Cryptography_AsnSerializer_Choice_NonNullableField = "Field '{0}' on [Choice] type '{1}' can not be assigned a null value."; public const string Cryptography_AsnSerializer_Choice_TooManyValues = "Fields '{0}' and '{1}' on type '{2}' are both non-null when only one value is permitted."; public const string Cryptography_AsnSerializer_Choice_TypeCycle = "Field '{0}' on [Choice] type '{1}' has introduced a type chain cycle."; public const string Cryptography_AsnSerializer_MultipleAsnTypeAttributes = "Field '{0}' on type '{1}' has multiple attributes deriving from '{2}' when at most one is permitted."; public const string Cryptography_AsnSerializer_NoJaggedArrays = "Type '{0}' cannot be serialized or deserialized because it is an array of arrays."; public const string Cryptography_AsnSerializer_NoMultiDimensionalArrays = "Type '{0}' cannot be serialized or deserialized because it is a multi-dimensional array."; public const string Cryptography_AsnSerializer_NoOpenTypes = "Type '{0}' cannot be serialized or deserialized because it is not sealed or has unbound generic parameters."; public const string Cryptography_AsnSerializer_Optional_NonNullableField = "Field '{0}' on type '{1}' is declared [OptionalValue], but it can not be assigned a null value."; public const string Cryptography_AsnSerializer_PopulateFriendlyNameOnString = "Field '{0}' on type '{1}' has [ObjectIdentifier].PopulateFriendlyName set to true, which is not applicable to a string. Change the field to '{2}' or set PopulateFriendlyName to false."; public const string Cryptography_AsnSerializer_SetValueException = "Unable to set field {0} on type {1}."; public const string Cryptography_AsnSerializer_SpecificTagChoice = "Field '{0}' on type '{1}' has specified an implicit tag value via [ExpectedTag] for [Choice] type '{2}'. ExplicitTag must be true, or the [ExpectedTag] attribute removed."; public const string Cryptography_AsnSerializer_UnexpectedTypeForAttribute = "Field '{0}' of type '{1}' has an effective type of '{2}' when one of ({3}) was expected."; public const string Cryptography_AsnSerializer_UtcTimeTwoDigitYearMaxTooSmall = "Field '{0}' on type '{1}' has a [UtcTime] TwoDigitYearMax value ({2}) smaller than the minimum (99)."; public const string Cryptography_AsnSerializer_UnhandledType = "Could not determine how to serialize or deserialize type '{0}'."; public const string Cryptography_AsnWriter_EncodeUnbalancedStack = "Encode cannot be called while a Sequence or SetOf is still open."; public const string Cryptography_AsnWriter_PopWrongTag = "Cannot pop the requested tag as it is not currently in progress."; public const string Cryptography_BadHashValue = "The hash value is not correct."; public const string Cryptography_BadSignature = "Invalid signature."; public const string Cryptography_Cms_CannotDetermineSignatureAlgorithm = "Could not determine signature algorithm for the signer certificate."; public const string Cryptography_Cms_IncompleteCertChain = "The certificate chain is incomplete, the self-signed root authority could not be determined."; public const string Cryptography_Cms_Invalid_Originator_Identifier_Choice = "Invalid originator identifier choice {0} found in decoded CMS."; public const string Cryptography_Cms_Invalid_Subject_Identifier_Type = "The subject identifier type {0} is not valid."; public const string Cryptography_Cms_InvalidMessageType = "Invalid cryptographic message type."; public const string Cryptography_Cms_InvalidSignerHashForSignatureAlg = "SignerInfo digest algorithm '{0}' is not valid for signature algorithm '{1}'."; public const string Cryptography_Cms_Key_Agree_Date_Not_Available = "The Date property is not available for none KID key agree recipient."; public const string Cryptography_Cms_MessageNotEncrypted = "The CMS message is not encrypted."; public const string Cryptography_Cms_MessageNotSigned = "The CMS message is not signed."; public const string Cryptography_Cms_MissingAuthenticatedAttribute = "The cryptographic message does not contain an expected authenticated attribute."; public const string Cryptography_Cms_NoCounterCounterSigner = "Only one level of counter-signatures are supported on this platform."; public const string Cryptography_Cms_NoRecipients = "The recipients collection is empty. You must specify at least one recipient. This platform does not implement the certificate picker UI."; public const string Cryptography_Cms_NoSignerCert = "No signer certificate was provided. This platform does not implement the certificate picker UI."; public const string Cryptography_Cms_NoSignerAtIndex = "The signed cryptographic message does not have a signer for the specified signer index."; public const string Cryptography_Cms_RecipientNotFound = "The enveloped-data message does not contain the specified recipient."; public const string Cryptography_Cms_RecipientType_NotSupported = "The recipient type '{0}' is not supported for encryption or decryption on this platform."; public const string Cryptography_Cms_Sign_Empty_Content = "Cannot create CMS signature for empty content."; public const string Cryptography_Cms_SignerNotFound = "Cannot find the original signer."; public const string Cryptography_Cms_Signing_RequiresPrivateKey = "A certificate with a private key is required."; public const string Cryptography_Cms_TrustFailure = "Certificate trust could not be established. The first reported error is: {0}"; public const string Cryptography_Cms_UnknownAlgorithm = "Unknown algorithm '{0}'."; public const string Cryptography_Cms_UnknownKeySpec = "Unable to determine the type of key handle from this keyspec {0}."; public const string Cryptography_Cms_WrongKeyUsage = "The certificate is not valid for the requested usage."; public const string Cryptography_Pkcs_InvalidSignatureParameters = "Invalid signature paramters."; public const string Cryptography_Pkcs9_AttributeMismatch = "The parameter should be a PKCS 9 attribute."; public const string Cryptography_Pkcs9_MultipleSigningTimeNotAllowed = "Cannot add multiple PKCS 9 signing time attributes."; public const string Cryptography_Pkcs_PssParametersMissing = "PSS parameters were not present."; public const string Cryptography_Pkcs_PssParametersHashMismatch = "This platform requires that the PSS hash algorithm ({0}) match the data digest algorithm ({1})."; public const string Cryptography_Pkcs_PssParametersMgfHashMismatch = "This platform does not support the MGF hash algorithm ({0}) being different from the signature hash algorithm ({1})."; public const string Cryptography_Pkcs_PssParametersMgfNotSupported = "Mask generation function '{0}' is not supported by this platform."; public const string Cryptography_Pkcs_PssParametersSaltMismatch = "PSS salt size {0} is not supported by this platform with hash algorithm {1}."; public const string Cryptography_TimestampReq_BadNonce = "The response from the timestamping server did not match the request nonce."; public const string Cryptography_TimestampReq_BadResponse = "The response from the timestamping server was not understood."; public const string Cryptography_TimestampReq_Failure = "The timestamping server did not grant the request. The request status is '{0}' with failure info '{1}'."; public const string Cryptography_TimestampReq_NoCertFound = "The timestamping request required the TSA certificate in the response, but it was not found."; public const string Cryptography_TimestampReq_UnexpectedCertFound = "The timestamping request required the TSA certificate not be included in the response, but certificates were present."; public const string InvalidOperation_DuplicateItemNotAllowed = "Duplicate items are not allowed in the collection."; public const string InvalidOperation_WrongOidInAsnCollection = "AsnEncodedData element in the collection has wrong Oid value: expected = '{0}', actual = '{1}'."; public const string PlatformNotSupported_CryptographyPkcs = "System.Security.Cryptography.Pkcs is only supported on Windows platforms."; public const string Cryptography_Der_Invalid_Encoding = "ASN1 corrupted data."; public const string Cryptography_Invalid_IA5String = "The string contains a character not in the 7 bit ASCII character set."; public const string Cryptography_UnknownHashAlgorithm = "'{0}' is not a known hash algorithm."; public const string Cryptography_WriteEncodedValue_OneValueAtATime = "The input to WriteEncodedValue must represent a single encoded value with no trailing data."; } } namespace System.Security.Cryptography.X509Certificates { public static class X509Certificate2UI { [MonoTODO] public static void DisplayCertificate(X509Certificate2 certificate) { DisplayCertificate(certificate, IntPtr.Zero); } [MonoTODO] [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public static void DisplayCertificate(X509Certificate2 certificate, IntPtr hwndParent) { if (certificate == null) { throw new ArgumentNullException("certificate"); } certificate.GetRawCertData(); throw new NotImplementedException(); } [MonoTODO] public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag) { return SelectFromCollection(certificates, title, message, selectionFlag, IntPtr.Zero); } [MonoTODO] [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag, IntPtr hwndParent) { if (certificates == null) { throw new ArgumentNullException("certificates"); } if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection) { throw new ArgumentException("selectionFlag"); } throw new NotImplementedException(); } } public enum X509SelectionFlag { SingleSelection, MultiSelection } } namespace System.Security.Cryptography.Xml { public struct X509IssuerSerial { public string IssuerName { get; set; } public string SerialNumber { get; set; } internal X509IssuerSerial(string issuerName, string serialNumber) { this = default(X509IssuerSerial); IssuerName = issuerName; SerialNumber = serialNumber; } } internal abstract class AncestralNamespaceContextManager { internal ArrayList _ancestorStack = new ArrayList(); internal NamespaceFrame GetScopeAt(int i) { return (NamespaceFrame)_ancestorStack[i]; } internal NamespaceFrame GetCurrentScope() { return GetScopeAt(_ancestorStack.Count - 1); } protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) { XmlAttribute xmlAttribute = null; depth = -1; for (int num = _ancestorStack.Count - 1; num >= 0; num--) { if ((xmlAttribute = GetScopeAt(num).GetRendered(nsPrefix)) != null) { depth = num; return xmlAttribute; } } return null; } protected XmlAttribute GetNearestUnrenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) { XmlAttribute xmlAttribute = null; depth = -1; for (int num = _ancestorStack.Count - 1; num >= 0; num--) { if ((xmlAttribute = GetScopeAt(num).GetUnrendered(nsPrefix)) != null) { depth = num; return xmlAttribute; } } return null; } internal void EnterElementContext() { _ancestorStack.Add(new NamespaceFrame()); } internal void ExitElementContext() { _ancestorStack.RemoveAt(_ancestorStack.Count - 1); } internal abstract void TrackNamespaceNode(XmlAttribute attr, SortedList nsListToRender, Hashtable nsLocallyDeclared); internal abstract void TrackXmlNamespaceNode(XmlAttribute attr, SortedList nsListToRender, SortedList attrListToRender, Hashtable nsLocallyDeclared); internal abstract void GetNamespacesToRender(XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared); internal void LoadUnrenderedNamespaces(Hashtable nsLocallyDeclared) { object[] array = new object[nsLocallyDeclared.Count]; nsLocallyDeclared.Values.CopyTo(array, 0); object[] array2 = array; foreach (object obj in array2) { AddUnrendered((XmlAttribute)obj); } } internal void LoadRenderedNamespaces(SortedList nsRenderedList) { foreach (object key in nsRenderedList.GetKeyList()) { AddRendered((XmlAttribute)key); } } internal void AddRendered(XmlAttribute attr) { GetCurrentScope().AddRendered(attr); } internal void AddUnrendered(XmlAttribute attr) { GetCurrentScope().AddUnrendered(attr); } } internal class AttributeSortOrder : IComparer { internal AttributeSortOrder() { } public int Compare(object a, object b) { XmlNode xmlNode = a as XmlNode; XmlNode xmlNode2 = b as XmlNode; if (xmlNode == null || xmlNode2 == null) { throw new ArgumentException(); } int num = string.CompareOrdinal(xmlNode.NamespaceURI, xmlNode2.NamespaceURI); if (num != 0) { return num; } return string.CompareOrdinal(xmlNode.LocalName, xmlNode2.LocalName); } } internal class C14NAncestralNamespaceContextManager : AncestralNamespaceContextManager { internal C14NAncestralNamespaceContextManager() { } private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared) { foreach (XmlAttribute key in nsListToRender.GetKeyList()) { if (Utils.HasNamespacePrefix(key, nsPrefix)) { return; } } foreach (XmlAttribute key2 in attrListToRender.GetKeyList()) { if (key2.LocalName.Equals(nsPrefix)) { return; } } XmlAttribute xmlAttribute = (XmlAttribute)nsLocallyDeclared[nsPrefix]; int depth; XmlAttribute nearestRenderedNamespaceWithMatchingPrefix = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out depth); if (xmlAttribute != null) { if (Utils.IsNonRedundantNamespaceDecl(xmlAttribute, nearestRenderedNamespaceWithMatchingPrefix)) { nsLocallyDeclared.Remove(nsPrefix); if (Utils.IsXmlNamespaceNode(xmlAttribute)) { attrListToRender.Add(xmlAttribute, null); } else { nsListToRender.Add(xmlAttribute, null); } } return; } int depth2; XmlAttribute nearestUnrenderedNamespaceWithMatchingPrefix = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out depth2); if (nearestUnrenderedNamespaceWithMatchingPrefix != null && depth2 > depth && Utils.IsNonRedundantNamespaceDecl(nearestUnrenderedNamespaceWithMatchingPrefix, nearestRenderedNamespaceWithMatchingPrefix)) { if (Utils.IsXmlNamespaceNode(nearestUnrenderedNamespaceWithMatchingPrefix)) { attrListToRender.Add(nearestUnrenderedNamespaceWithMatchingPrefix, null); } else { nsListToRender.Add(nearestUnrenderedNamespaceWithMatchingPrefix, null); } } } internal override void GetNamespacesToRender(XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared) { XmlAttribute xmlAttribute = null; object[] array = new object[nsLocallyDeclared.Count]; nsLocallyDeclared.Values.CopyTo(array, 0); object[] array2 = array; for (int i = 0; i < array2.Length; i++) { xmlAttribute = (XmlAttribute)array2[i]; int depth; XmlAttribute nearestRenderedNamespaceWithMatchingPrefix = GetNearestRenderedNamespaceWithMatchingPrefix(Utils.GetNamespacePrefix(xmlAttribute), out depth); if (Utils.IsNonRedundantNamespaceDecl(xmlAttribute, nearestRenderedNamespaceWithMatchingPrefix)) { nsLocallyDeclared.Remove(Utils.GetNamespacePrefix(xmlAttribute)); if (Utils.IsXmlNamespaceNode(xmlAttribute)) { attrListToRender.Add(xmlAttribute, null); } else { nsListToRender.Add(xmlAttribute, null); } } } for (int num = _ancestorStack.Count - 1; num >= 0; num--) { foreach (XmlAttribute value in GetScopeAt(num).GetUnrendered().Values) { if (value != null) { GetNamespaceToRender(Utils.GetNamespacePrefix(value), attrListToRender, nsListToRender, nsLocallyDeclared); } } } } internal override void TrackNamespaceNode(XmlAttribute attr, SortedList nsListToRender, Hashtable nsLocallyDeclared) { nsLocallyDeclared.Add(Utils.GetNamespacePrefix(attr), attr); } internal override void TrackXmlNamespaceNode(XmlAttribute attr, SortedList nsListToRender, SortedList attrListToRender, Hashtable nsLocallyDeclared) { nsLocallyDeclared.Add(Utils.GetNamespacePrefix(attr), attr); } } internal class CanonicalXml { private CanonicalXmlDocument _c14nDoc; private C14NAncestralNamespaceContextManager _ancMgr; internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver resolver, string strBaseUri) { if (inputStream == null) { throw new ArgumentNullException("inputStream"); } _c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(Utils.PreProcessStreamInput(inputStream, resolver, strBaseUri)); _ancMgr = new C14NAncestralNamespaceContextManager(); } internal CanonicalXml(XmlDocument document, XmlResolver resolver) : this(document, resolver, includeComments: false) { } internal CanonicalXml(XmlDocument document, XmlResolver resolver, bool includeComments) { if (document == null) { throw new ArgumentNullException("document"); } _c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(new XmlNodeReader(document)); _ancMgr = new C14NAncestralNamespaceContextManager(); } internal CanonicalXml(XmlNodeList nodeList, XmlResolver resolver, bool includeComments) { if (nodeList == null) { throw new ArgumentNullException("nodeList"); } XmlDocument ownerDocument = Utils.GetOwnerDocument(nodeList); if (ownerDocument == null) { throw new ArgumentException("nodeList"); } _c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: false, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(new XmlNodeReader(ownerDocument)); _ancMgr = new C14NAncestralNamespaceContextManager(); MarkInclusionStateForNodes(nodeList, ownerDocument, _c14nDoc); } private static void MarkNodeAsIncluded(XmlNode node) { if (node is ICanonicalizableNode) { ((ICanonicalizableNode)node).IsInNodeSet = true; } } private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument inputRoot, XmlDocument root) { CanonicalXmlNodeList canonicalXmlNodeList = new CanonicalXmlNodeList(); CanonicalXmlNodeList canonicalXmlNodeList2 = new CanonicalXmlNodeList(); canonicalXmlNodeList.Add(inputRoot); canonicalXmlNodeList2.Add(root); int num = 0; do { XmlNode xmlNode = canonicalXmlNodeList[num]; XmlNode? xmlNode2 = canonicalXmlNodeList2[num]; XmlNodeList childNodes = xmlNode.ChildNodes; XmlNodeList childNodes2 = xmlNode2.ChildNodes; for (int i = 0; i < childNodes.Count; i++) { canonicalXmlNodeList.Add(childNodes[i]); canonicalXmlNodeList2.Add(childNodes2[i]); if (Utils.NodeInList(childNodes[i], nodeList)) { MarkNodeAsIncluded(childNodes2[i]); } XmlAttributeCollection attributes = childNodes[i].Attributes; if (attributes == null) { continue; } for (int j = 0; j < attributes.Count; j++) { if (Utils.NodeInList(attributes[j], nodeList)) { MarkNodeAsIncluded(childNodes2[i].Attributes.Item(j)); } } } num++; } while (num < canonicalXmlNodeList.Count); } internal byte[] GetBytes() { StringBuilder stringBuilder = new StringBuilder(); _c14nDoc.Write(stringBuilder, DocPosition.BeforeRootElement, _ancMgr); return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(stringBuilder.ToString()); } internal byte[] GetDigestedBytes(HashAlgorithm hash) { _c14nDoc.WriteHash(hash, DocPosition.BeforeRootElement, _ancMgr); hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0); byte[] result = (byte[])hash.Hash.Clone(); hash.Initialize(); return result; } } internal class CanonicalXmlAttribute : XmlAttribute, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState) : base(prefix, localName, namespaceURI, doc) { IsInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { strBuilder.Append(" " + Name + "=\""); strBuilder.Append(Utils.EscapeAttributeValue(Value)); strBuilder.Append("\""); } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); byte[] bytes = uTF8Encoding.GetBytes(" " + Name + "=\""); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); bytes = uTF8Encoding.GetBytes(Utils.EscapeAttributeValue(Value)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); bytes = uTF8Encoding.GetBytes("\""); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } internal class CanonicalXmlCDataSection : XmlCDataSection, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlCDataSection(string data, XmlDocument doc, bool defaultNodeSetInclusionState) : base(data, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { strBuilder.Append(Utils.EscapeCData(Data)); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Utils.EscapeCData(Data)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal class CanonicalXmlComment : XmlComment, ICanonicalizableNode { private bool _isInNodeSet; private bool _includeComments; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public bool IncludeComments => _includeComments; public CanonicalXmlComment(string comment, XmlDocument doc, bool defaultNodeSetInclusionState, bool includeComments) : base(comment, doc) { _isInNodeSet = defaultNodeSetInclusionState; _includeComments = includeComments; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && IncludeComments) { if (docPos == DocPosition.AfterRootElement) { strBuilder.Append('\n'); } strBuilder.Append("<!--"); strBuilder.Append(Value); strBuilder.Append("-->"); if (docPos == DocPosition.BeforeRootElement) { strBuilder.Append('\n'); } } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && IncludeComments) { UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); byte[] bytes = uTF8Encoding.GetBytes("(char) 10"); if (docPos == DocPosition.AfterRootElement) { hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } bytes = uTF8Encoding.GetBytes("<!--"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); bytes = uTF8Encoding.GetBytes(Value); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); bytes = uTF8Encoding.GetBytes("-->"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); if (docPos == DocPosition.BeforeRootElement) { bytes = uTF8Encoding.GetBytes("(char) 10"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } } internal class CanonicalXmlDocument : XmlDocument, ICanonicalizableNode { private bool _defaultNodeSetInclusionState; private bool _includeComments; private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlDocument(bool defaultNodeSetInclusionState, bool includeComments) { base.PreserveWhitespace = true; _includeComments = includeComments; _isInNodeSet = (_defaultNodeSetInclusionState = defaultNodeSetInclusionState); } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { docPos = DocPosition.BeforeRootElement; foreach (XmlNode childNode in ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { CanonicalizationDispatcher.Write(childNode, strBuilder, DocPosition.InRootElement, anc); docPos = DocPosition.AfterRootElement; } else { CanonicalizationDispatcher.Write(childNode, strBuilder, docPos, anc); } } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { docPos = DocPosition.BeforeRootElement; foreach (XmlNode childNode in ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { CanonicalizationDispatcher.WriteHash(childNode, hash, DocPosition.InRootElement, anc); docPos = DocPosition.AfterRootElement; } else { CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc); } } } public override XmlElement CreateElement(string prefix, string localName, string namespaceURI) { return new CanonicalXmlElement(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState); } public override XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI) { return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState); } protected override XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) { return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState); } public override XmlText CreateTextNode(string text) { return new CanonicalXmlText(text, this, _defaultNodeSetInclusionState); } public override XmlWhitespace CreateWhitespace(string prefix) { return new CanonicalXmlWhitespace(prefix, this, _defaultNodeSetInclusionState); } public override XmlSignificantWhitespace CreateSignificantWhitespace(string text) { return new CanonicalXmlSignificantWhitespace(text, this, _defaultNodeSetInclusionState); } public override XmlProcessingInstruction CreateProcessingInstruction(string target, string data) { return new CanonicalXmlProcessingInstruction(target, data, this, _defaultNodeSetInclusionState); } public override XmlComment CreateComment(string data) { return new CanonicalXmlComment(data, this, _defaultNodeSetInclusionState, _includeComments); } public override XmlEntityReference CreateEntityReference(string name) { return new CanonicalXmlEntityReference(name, this, _defaultNodeSetInclusionState); } public override XmlCDataSection CreateCDataSection(string data) { return new CanonicalXmlCDataSection(data, this, _defaultNodeSetInclusionState); } } internal class CanonicalXmlElement : XmlElement, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState) : base(prefix, localName, namespaceURI, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { Hashtable nsLocallyDeclared = new Hashtable(); SortedList sortedList = new SortedList(new NamespaceSortOrder()); SortedList sortedList2 = new SortedList(new AttributeSortOrder()); XmlAttributeCollection attributes = Attributes; if (attributes != null) { foreach (XmlAttribute item in attributes) { if (((CanonicalXmlAttribute)item).IsInNodeSet || Utils.IsNamespaceNode(item) || Utils.IsXmlNamespaceNode(item)) { if (Utils.IsNamespaceNode(item)) { anc.TrackNamespaceNode(item, sortedList, nsLocallyDeclared); } else if (Utils.IsXmlNamespaceNode(item)) { anc.TrackXmlNamespaceNode(item, sortedList, sortedList2, nsLocallyDeclared); } else if (IsInNodeSet) { sortedList2.Add(item, null); } } } } if (!Utils.IsCommittedNamespace(this, Prefix, NamespaceURI)) { string name = ((Prefix.Length > 0) ? ("xmlns:" + Prefix) : "xmlns"); XmlAttribute xmlAttribute2 = OwnerDocument.CreateAttribute(name); xmlAttribute2.Value = NamespaceURI; anc.TrackNamespaceNode(xmlAttribute2, sortedList, nsLocallyDeclared); } if (IsInNodeSet) { anc.GetNamespacesToRender(this, sortedList2, sortedList, nsLocallyDeclared); strBuilder.Append("<" + Name); foreach (object key in sortedList.GetKeyList()) { (key as CanonicalXmlAttribute).Write(strBuilder, docPos, anc); } foreach (object key2 in sortedList2.GetKeyList()) { (key2 as CanonicalXmlAttribute).Write(strBuilder, docPos, anc); } strBuilder.Append(">"); } anc.EnterElementContext(); anc.LoadUnrenderedNamespaces(nsLocallyDeclared); anc.LoadRenderedNamespaces(sortedList); foreach (XmlNode childNode in ChildNodes) { CanonicalizationDispatcher.Write(childNode, strBuilder, docPos, anc); } anc.ExitElementContext(); if (IsInNodeSet) { strBuilder.Append("</" + Name + ">"); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { Hashtable nsLocallyDeclared = new Hashtable(); SortedList sortedList = new SortedList(new NamespaceSortOrder()); SortedList sortedList2 = new SortedList(new AttributeSortOrder()); UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); XmlAttributeCollection attributes = Attributes; if (attributes != null) { foreach (XmlAttribute item in attributes) { if (((CanonicalXmlAttribute)item).IsInNodeSet || Utils.IsNamespaceNode(item) || Utils.IsXmlNamespaceNode(item)) { if (Utils.IsNamespaceNode(item)) { anc.TrackNamespaceNode(item, sortedList, nsLocallyDeclared); } else if (Utils.IsXmlNamespaceNode(item)) { anc.TrackXmlNamespaceNode(item, sortedList, sortedList2, nsLocallyDeclared); } else if (IsInNodeSet) { sortedList2.Add(item, null); } } } } if (!Utils.IsCommittedNamespace(this, Prefix, NamespaceURI)) { string name = ((Prefix.Length > 0) ? ("xmlns:" + Prefix) : "xmlns"); XmlAttribute xmlAttribute2 = OwnerDocument.CreateAttribute(name); xmlAttribute2.Value = NamespaceURI; anc.TrackNamespaceNode(xmlAttribute2, sortedList, nsLocallyDeclared); } if (IsInNodeSet) { anc.GetNamespacesToRender(this, sortedList2, sortedList, nsLocallyDeclared); byte[] bytes = uTF8Encoding.GetBytes("<" + Name); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); foreach (object key in sortedList.GetKeyList()) { (key as CanonicalXmlAttribute).WriteHash(hash, docPos, anc); } foreach (object key2 in sortedList2.GetKeyList()) { (key2 as CanonicalXmlAttribute).WriteHash(hash, docPos, anc); } bytes = uTF8Encoding.GetBytes(">"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } anc.EnterElementContext(); anc.LoadUnrenderedNamespaces(nsLocallyDeclared); anc.LoadRenderedNamespaces(sortedList); foreach (XmlNode childNode in ChildNodes) { CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc); } anc.ExitElementContext(); if (IsInNodeSet) { byte[] bytes = uTF8Encoding.GetBytes("</" + Name + ">"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal class CanonicalXmlEntityReference : XmlEntityReference, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlEntityReference(string name, XmlDocument doc, bool defaultNodeSetInclusionState) : base(name, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { CanonicalizationDispatcher.WriteGenericNode(this, strBuilder, docPos, anc); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { CanonicalizationDispatcher.WriteHashGenericNode(this, hash, docPos, anc); } } } internal class CanonicalXmlNodeList : XmlNodeList, IList, ICollection, IEnumerable { private ArrayList _nodeArray; public override int Count => _nodeArray.Count; public bool IsFixedSize => _nodeArray.IsFixedSize; public bool IsReadOnly => _nodeArray.IsReadOnly; object IList.this[int index] { get { return _nodeArray[index]; } set { if (!(value is XmlNode)) { throw new ArgumentException("Type of input object is invalid.", "value"); } _nodeArray[index] = value; } } public object SyncRoot => _nodeArray.SyncRoot; public bool IsSynchronized => _nodeArray.IsSynchronized; internal CanonicalXmlNodeList() { _nodeArray = new ArrayList(); } public override XmlNode Item(int index) { return (XmlNode)_nodeArray[index]; } public override IEnumerator GetEnumerator() { return _nodeArray.GetEnumerator(); } public int Add(object value) { if (!(value is XmlNode)) { throw new ArgumentException("Type of input object is invalid.", "node"); } return _nodeArray.Add(value); } public void Clear() { _nodeArray.Clear(); } public bool Contains(object value) { return _nodeArray.Contains(value); } public int IndexOf(object value) { return _nodeArray.IndexOf(value); } public void Insert(int index, object value) { if (!(value is XmlNode)) { throw new ArgumentException("Type of input object is invalid.", "value"); } _nodeArray.Insert(index, value); } public void Remove(object value) { _nodeArray.Remove(value); } public void RemoveAt(int index) { _nodeArray.RemoveAt(index); } public void CopyTo(Array array, int index) { _nodeArray.CopyTo(array, index); } } internal class CanonicalXmlProcessingInstruction : XmlProcessingInstruction, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlProcessingInstruction(string target, string data, XmlDocument doc, bool defaultNodeSetInclusionState) : base(target, data, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { if (docPos == DocPosition.AfterRootElement) { strBuilder.Append('\n'); } strBuilder.Append("<?"); strBuilder.Append(Name); if (Value != null && Value.Length > 0) { strBuilder.Append(" " + Value); } strBuilder.Append("?>"); if (docPos == DocPosition.BeforeRootElement) { strBuilder.Append('\n'); } } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); byte[] bytes; if (docPos == DocPosition.AfterRootElement) { bytes = uTF8Encoding.GetBytes("(char) 10"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } bytes = uTF8Encoding.GetBytes("<?"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); bytes = uTF8Encoding.GetBytes(Name); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); if (Value != null && Value.Length > 0) { bytes = uTF8Encoding.GetBytes(" " + Value); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } bytes = uTF8Encoding.GetBytes("?>"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); if (docPos == DocPosition.BeforeRootElement) { bytes = uTF8Encoding.GetBytes("(char) 10"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } } internal class CanonicalXmlSignificantWhitespace : XmlSignificantWhitespace, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlSignificantWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { strBuilder.Append(Utils.EscapeWhitespaceData(Value)); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Utils.EscapeWhitespaceData(Value)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal class CanonicalXmlText : XmlText, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlText(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { strBuilder.Append(Utils.EscapeTextData(Value)); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Utils.EscapeTextData(Value)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal class CanonicalXmlWhitespace : XmlWhitespace, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { strBuilder.Append(Utils.EscapeWhitespaceData(Value)); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Utils.EscapeWhitespaceData(Value)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal class CanonicalizationDispatcher { private CanonicalizationDispatcher() { } public static void Write(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (node is ICanonicalizableNode) { ((ICanonicalizableNode)node).Write(strBuilder, docPos, anc); } else { WriteGenericNode(node, strBuilder, docPos, anc); } } public static void WriteGenericNode(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (node == null) { throw new ArgumentNullException("node"); } foreach (XmlNode childNode in node.ChildNodes) { Write(childNode, strBuilder, docPos, anc); } } public static void WriteHash(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (node is ICanonicalizableNode) { ((ICanonicalizableNode)node).WriteHash(hash, docPos, anc); } else { WriteHashGenericNode(node, hash, docPos, anc); } } public static void WriteHashGenericNode(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (node == null) { throw new ArgumentNullException("node"); } foreach (XmlNode childNode in node.ChildNodes) { WriteHash(childNode, hash, docPos, anc); } } } internal enum CertUsageType { Verification, Decryption } public sealed class CipherData { private XmlElement _cachedXml; private CipherReference _cipherReference; private byte[] _cipherValue; private bool CacheValid => _cachedXml != null; public CipherReference CipherReference { get { return _cipherReference; } set { if (value == null) { throw new ArgumentNullException("value"); } if (CipherValue != null) { throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element."); } _cipherReference = value; _cachedXml = null; } } public byte[] CipherValue { get { return _cipherValue; } set { if (value == null) { throw new ArgumentNullException("value"); } if (CipherReference != null) { throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element."); } _cipherValue = (byte[])value.Clone(); _cachedXml = null; } } public CipherData() { } public CipherData(byte[] cipherValue) { CipherValue = cipherValue; } public CipherData(CipherReference cipherReference) { CipherReference = cipherReference; } public XmlElement GetXml() { if (CacheValid) { return _cachedXml; } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal XmlElement GetXml(XmlDocument document) { XmlElement xmlElement = document.CreateElement("CipherData", "http://www.w3.org/2001/04/xmlenc#"); if (CipherValue != null) { XmlElement xmlElement2 = document.CreateElement("CipherValue", "http://www.w3.org/2001/04/xmlenc#"); xmlElement2.AppendChild(document.CreateTextNode(Convert.ToBase64String(CipherValue))); xmlElement.AppendChild(xmlElement2); } else { if (CipherReference == null) { throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element."); } xmlElement.AppendChild(CipherReference.GetXml(document)); } return xmlElement; } public void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#"); XmlNode xmlNode = value.SelectSingleNode("enc:CipherValue", xmlNamespaceManager); XmlNode xmlNode2 = value.SelectSingleNode("enc:CipherReference", xmlNamespaceManager); if (xmlNode != null) { if (xmlNode2 != null) { throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element."); } _cipherValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(xmlNode.InnerText)); } else { if (xmlNode2 == null) { throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element."); } _cipherReference = new CipherReference(); _cipherReference.LoadXml((XmlElement)xmlNode2); } _cachedXml = value; } } public sealed class CipherReference : EncryptedReference { private byte[] _cipherValue; internal byte[] CipherValue { get { if (!base.CacheValid) { return null; } return _cipherValue; } set { _cipherValue = value; } } public CipherReference() { base.ReferenceType = "CipherReference"; } public CipherReference(string uri) : base(uri) { base.ReferenceType = "CipherReference"; } public CipherReference(string uri, TransformChain transformChain) : base(uri, transformChain) { base.ReferenceType = "CipherReference"; } public override XmlElement GetXml() { if (base.CacheValid) { return _cachedXml; } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal new XmlElement GetXml(XmlDocument document) { if (base.ReferenceType == null) { throw new CryptographicException("The Reference type must be set in an EncryptedReference object."); } XmlElement xmlElement = document.CreateElement(base.ReferenceType, "http://www.w3.org/2001/04/xmlenc#"); if (!string.IsNullOrEmpty(base.Uri)) { xmlElement.SetAttribute("URI", base.Uri); } if (base.TransformChain.Count > 0) { xmlElement.AppendChild(base.TransformChain.GetXml(document, "http://www.w3.org/2001/04/xmlenc#")); } return xmlElement; } public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } base.ReferenceType = value.LocalName; string attribute = Utils.GetAttribute(value, "URI", "http://www.w3.org/2001/04/xmlenc#"); base.Uri = attribute ?? throw new CryptographicException("A Uri attribute is required for a CipherReference element."); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#"); XmlNode xmlNode = value.SelectSingleNode("enc:Transforms", xmlNamespaceManager); if (xmlNode != null) { base.TransformChain.LoadXml(xmlNode as XmlElement); } _cachedXml = value; } } internal static class CryptoHelpers { private static readonly char[] _invalidChars = new char[5] { ',', '`', '[', '*', '&' }; public static object CreateFromKnownName(string name) { return name switch { "http://www.w3.org/TR/2001/REC-xml-c14n-20010315" => new XmlDsigC14NTransform(), "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments" => new XmlDsigC14NWithCommentsTransform(), "http://www.w3.org/2001/10/xml-exc-c14n#" => new XmlDsigExcC14NTransform(), "http://www.w3.org/2001/10/xml-exc-c14n#WithComments" => new XmlDsigExcC14NWithCommentsTransform(), "http://www.w3.org/2000/09/xmldsig#base64" => new XmlDsigBase64Transform(), "http://www.w3.org/TR/1999/REC-xpath-19991116" => new XmlDsigXPathTransform(), "http://www.w3.org/TR/1999/REC-xslt-19991116" => new XmlDsigXsltTransform(), "http://www.w3.org/2000/09/xmldsig#enveloped-signature" => new XmlDsigEnvelopedSignatureTransform(), "http://www.w3.org/2002/07/decrypt#XML" => new XmlDecryptionTransform(), "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform" => new XmlLicenseTransform(), "http://www.w3.org/2000/09/xmldsig# X509Data" => new KeyInfoX509Data(), "http://www.w3.org/2000/09/xmldsig# KeyName" => new KeyInfoName(), "http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue" => new DSAKeyValue(), "http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue" => new RSAKeyValue(), "http://www.w3.org/2000/09/xmldsig# RetrievalMethod" => new KeyInfoRetrievalMethod(), "http://www.w3.org/2001/04/xmlenc# EncryptedKey" => new KeyInfoEncryptedKey(), "http://www.w3.org/2000/09/xmldsig#dsa-sha1" => new DSASignatureDescription(), "System.Security.Cryptography.DSASignatureDescription" => new DSASignatureDescription(), "http://www.w3.org/2000/09/xmldsig#rsa-sha1" => new RSAPKCS1SHA1SignatureDescription(), "System.Security.Cryptography.RSASignatureDescription" => new RSAPKCS1SHA1SignatureDescription(), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" => new RSAPKCS1SHA256SignatureDescription(), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384" => new RSAPKCS1SHA384SignatureDescription(), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512" => new RSAPKCS1SHA512SignatureDescription(), "http://www.w3.org/2000/09/xmldsig#sha1" => SHA1.Create(), "MD5" => MD5.Create(), "http://www.w3.org/2001/04/xmldsig-more#hmac-md5" => new HMACMD5(), "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" => TripleDES.Create(), _ => null, }; } public static T CreateFromName<T>(string name) where T : class { if (name == null || name.IndexOfAny(_invalidChars) >= 0) { return null; } try { return (CreateFromKnownName(name) ?? CryptoConfig.CreateFromName(name)) as T; } catch (Exception) { return null; } } } [Serializable] public class CryptoSignedXmlRecursionException : XmlException { public CryptoSignedXmlRecursionException() { } public CryptoSignedXmlRecursionException(string message) : base(message) { } public CryptoSignedXmlRecursionException(string message, Exception inner) : base(message, inner) { } protected CryptoSignedXmlRecursionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class DSAKeyValue : KeyInfoClause { private DSA _key; private const string KeyValueElementName = "KeyValue"; private const string DSAKeyValueElementName = "DSAKeyValue"; private const string PElementName = "P"; private const string QElementName = "Q"; private const string GElementName = "G"; private const string JElementName = "J"; private const string YElementName = "Y"; private const string SeedElementName = "Seed"; private const string PgenCounterElementName = "PgenCounter"; public DSA Key { get { return _key; } set { _key = value; } } public DSAKeyValue() { _key = DSA.Create(); } public DSAKeyValue(DSA key) { _key = key; } public override XmlElement GetXml() { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal override XmlElement GetXml(XmlDocument xmlDocument) { DSAParameters dSAParameters = _key.ExportParameters(includePrivateParameters: false); XmlElement xmlElement = xmlDocument.CreateElement("KeyValue", "http://www.w3.org/2000/09/xmldsig#"); XmlElement xmlElement2 = xmlDocument.CreateElement("DSAKeyValue", "http://www.w3.org/2000/09/xmldsig#"); XmlElement xmlElement3 = xmlDocument.CreateElement("P", "http://www.w3.org/2000/09/xmldsig#"); xmlElement3.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.P))); xmlElement2.AppendChild(xmlElement3); XmlElement xmlElement4 = xmlDocument.CreateElement("Q", "http://www.w3.org/2000/09/xmldsig#"); xmlElement4.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Q))); xmlElement2.AppendChild(xmlElement4); XmlElement xmlElement5 = xmlDocument.CreateElement("G", "http://www.w3.org/2000/09/xmldsig#"); xmlElement5.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.G))); xmlElement2.AppendChild(xmlElement5); XmlElement xmlElement6 = xmlDocument.CreateElement("Y", "http://www.w3.org/2000/09/xmldsig#"); xmlElement6.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Y))); xmlElement2.AppendChild(xmlElement6); if (dSAParameters.J != null) { XmlElement xmlElement7 = xmlDocument.CreateElement("J", "http://www.w3.org/2000/09/xmldsig#"); xmlElement7.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.J))); xmlElement2.AppendChild(xmlElement7); } if (dSAParameters.Seed != null) { XmlElement xmlElement8 = xmlDocument.CreateElement("Seed", "http://www.w3.org/2000/09/xmldsig#"); xmlElement8.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Seed))); xmlElement2.AppendChild(xmlElement8); XmlElement xmlElement
deps/System.Security.Principal.Windows.dll
Decompiled a day agousing System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Claims; using System.Security.Permissions; using FxResources.System.Security.Principal.Windows; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyDefaultAlias("System.Security.Principal.Windows")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("NotSupported", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("System.Security.Principal.Windows")] [assembly: AssemblyFileVersion("4.700.19.56404")] [assembly: AssemblyInformationalVersion("3.1.0+0f7f38c4fd323b26da10cce95f857f77f0f09b48")] [assembly: AssemblyProduct("Microsoft® .NET Core")] [assembly: AssemblyTitle("System.Security.Principal.Windows")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.1.3.0")] [module: UnverifiableCode] namespace FxResources.System.Security.Principal.Windows { internal static class SR { } } namespace Microsoft.Win32.SafeHandles { public sealed class SafeAccessTokenHandle : SafeHandle { public static SafeAccessTokenHandle InvalidHandle { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public override bool IsInvalid { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public SafeAccessTokenHandle(IntPtr handle) : base((IntPtr)0, ownsHandle: false) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } protected override bool ReleaseHandle() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string Arg_EmptyCollection => GetResourceString("Arg_EmptyCollection"); internal static string Arg_EnumIllegalVal => GetResourceString("Arg_EnumIllegalVal"); internal static string Argument_ImpersonateUser => GetResourceString("Argument_ImpersonateUser"); internal static string Argument_ImproperType => GetResourceString("Argument_ImproperType"); internal static string Argument_InvalidImpersonationToken => GetResourceString("Argument_InvalidImpersonationToken"); internal static string Argument_InvalidValue => GetResourceString("Argument_InvalidValue"); internal static string Argument_TokenZero => GetResourceString("Argument_TokenZero"); internal static string ArgumentOutOfRange_ArrayTooSmall => GetResourceString("ArgumentOutOfRange_ArrayTooSmall"); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); internal static string Argument_StringZeroLength => GetResourceString("Argument_StringZeroLength"); internal static string IdentityReference_AccountNameTooLong => GetResourceString("IdentityReference_AccountNameTooLong"); internal static string IdentityReference_CannotCreateLogonIdsSid => GetResourceString("IdentityReference_CannotCreateLogonIdsSid"); internal static string IdentityReference_DomainNameTooLong => GetResourceString("IdentityReference_DomainNameTooLong"); internal static string IdentityReference_DomainSidRequired => GetResourceString("IdentityReference_DomainSidRequired"); internal static string IdentityReference_IdentifierAuthorityTooLarge => GetResourceString("IdentityReference_IdentifierAuthorityTooLarge"); internal static string IdentityReference_IdentityNotMapped => GetResourceString("IdentityReference_IdentityNotMapped"); internal static string IdentityReference_InvalidNumberOfSubauthorities => GetResourceString("IdentityReference_InvalidNumberOfSubauthorities"); internal static string IdentityReference_InvalidSidRevision => GetResourceString("IdentityReference_InvalidSidRevision"); internal static string IdentityReference_MustBeIdentityReference => GetResourceString("IdentityReference_MustBeIdentityReference"); internal static string IdentityReference_NotAWindowsDomain => GetResourceString("IdentityReference_NotAWindowsDomain"); internal static string PlatformNotSupported_Principal => GetResourceString("PlatformNotSupported_Principal"); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString = null) { if (UsingResourceKeys()) { return defaultString ?? resourceKey; } string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text)) { return defaultString; } return text; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Security.Principal { public sealed class IdentityNotMappedException : SystemException { public IdentityReferenceCollection UnmappedIdentities { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public IdentityNotMappedException() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public IdentityNotMappedException(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public IdentityNotMappedException(string message, Exception inner) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public abstract class IdentityReference { public abstract string Value { get; } internal IdentityReference() { } public abstract override bool Equals(object o); public abstract override int GetHashCode(); public abstract bool IsValidTargetType(Type targetType); public static bool operator ==(IdentityReference left, IdentityReference right) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static bool operator !=(IdentityReference left, IdentityReference right) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public abstract override string ToString(); public abstract IdentityReference Translate(Type targetType); } public class IdentityReferenceCollection : ICollection<IdentityReference>, IEnumerable<IdentityReference>, IEnumerable { public int Count { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public IdentityReference this[int index] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } bool ICollection<IdentityReference>.IsReadOnly { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public IdentityReferenceCollection() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public IdentityReferenceCollection(int capacity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public void Add(IdentityReference identity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public void Clear() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public bool Contains(IdentityReference identity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public void CopyTo(IdentityReference[] array, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public IEnumerator<IdentityReference> GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public bool Remove(IdentityReference identity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } IEnumerator IEnumerable.GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public IdentityReferenceCollection Translate(Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public sealed class NTAccount : IdentityReference { public override string Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public NTAccount(string name) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public NTAccount(string domainName, string accountName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override bool Equals(object o) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override int GetHashCode() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override bool IsValidTargetType(Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static bool operator ==(NTAccount left, NTAccount right) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static bool operator !=(NTAccount left, NTAccount right) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override string ToString() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override IdentityReference Translate(Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier> { public static readonly int MaxBinaryLength; public static readonly int MinBinaryLength; public SecurityIdentifier AccountDomainSid { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public int BinaryLength { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public override string Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public SecurityIdentifier(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public SecurityIdentifier(IntPtr binaryForm) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public SecurityIdentifier(string sddlForm) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public int CompareTo(SecurityIdentifier sid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override bool Equals(object o) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public bool Equals(SecurityIdentifier sid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public void GetBinaryForm(byte[] binaryForm, int offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override int GetHashCode() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public bool IsAccountSid() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public bool IsEqualDomainSid(SecurityIdentifier sid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override bool IsValidTargetType(Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public bool IsWellKnown(WellKnownSidType type) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override string ToString() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override IdentityReference Translate(Type targetType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } [Flags] public enum TokenAccessLevels { AssignPrimary = 1, Duplicate = 2, Impersonate = 4, Query = 8, QuerySource = 0x10, AdjustPrivileges = 0x20, AdjustGroups = 0x40, AdjustDefault = 0x80, AdjustSessionId = 0x100, Read = 0x20008, Write = 0x200E0, AllAccess = 0xF01FF, MaximumAllowed = 0x2000000 } public enum WellKnownSidType { NullSid = 0, WorldSid = 1, LocalSid = 2, CreatorOwnerSid = 3, CreatorGroupSid = 4, CreatorOwnerServerSid = 5, CreatorGroupServerSid = 6, NTAuthoritySid = 7, DialupSid = 8, NetworkSid = 9, BatchSid = 10, InteractiveSid = 11, ServiceSid = 12, AnonymousSid = 13, ProxySid = 14, EnterpriseControllersSid = 15, SelfSid = 16, AuthenticatedUserSid = 17, RestrictedCodeSid = 18, TerminalServerSid = 19, RemoteLogonIdSid = 20, LogonIdsSid = 21, LocalSystemSid = 22, LocalServiceSid = 23, NetworkServiceSid = 24, BuiltinDomainSid = 25, BuiltinAdministratorsSid = 26, BuiltinUsersSid = 27, BuiltinGuestsSid = 28, BuiltinPowerUsersSid = 29, BuiltinAccountOperatorsSid = 30, BuiltinSystemOperatorsSid = 31, BuiltinPrintOperatorsSid = 32, BuiltinBackupOperatorsSid = 33, BuiltinReplicatorSid = 34, BuiltinPreWindows2000CompatibleAccessSid = 35, BuiltinRemoteDesktopUsersSid = 36, BuiltinNetworkConfigurationOperatorsSid = 37, AccountAdministratorSid = 38, AccountGuestSid = 39, AccountKrbtgtSid = 40, AccountDomainAdminsSid = 41, AccountDomainUsersSid = 42, AccountDomainGuestsSid = 43, AccountComputersSid = 44, AccountControllersSid = 45, AccountCertAdminsSid = 46, AccountSchemaAdminsSid = 47, AccountEnterpriseAdminsSid = 48, AccountPolicyAdminsSid = 49, AccountRasAndIasServersSid = 50, NtlmAuthenticationSid = 51, DigestAuthenticationSid = 52, SChannelAuthenticationSid = 53, ThisOrganizationSid = 54, OtherOrganizationSid = 55, BuiltinIncomingForestTrustBuildersSid = 56, BuiltinPerformanceMonitoringUsersSid = 57, BuiltinPerformanceLoggingUsersSid = 58, BuiltinAuthorizationAccessSid = 59, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This member has been depcreated and is only maintained for backwards compatability. WellKnownSidType values greater than MaxDefined may be defined in future releases.")] MaxDefined = 60, WinBuiltinTerminalServerLicenseServersSid = 60, WinBuiltinDCOMUsersSid = 61, WinBuiltinIUsersSid = 62, WinIUserSid = 63, WinBuiltinCryptoOperatorsSid = 64, WinUntrustedLabelSid = 65, WinLowLabelSid = 66, WinMediumLabelSid = 67, WinHighLabelSid = 68, WinSystemLabelSid = 69, WinWriteRestrictedCodeSid = 70, WinCreatorOwnerRightsSid = 71, WinCacheablePrincipalsGroupSid = 72, WinNonCacheablePrincipalsGroupSid = 73, WinEnterpriseReadonlyControllersSid = 74, WinAccountReadonlyControllersSid = 75, WinBuiltinEventLogReadersGroup = 76, WinNewEnterpriseReadonlyControllersSid = 77, WinBuiltinCertSvcDComAccessGroup = 78, WinMediumPlusLabelSid = 79, WinLocalLogonSid = 80, WinConsoleLogonSid = 81, WinThisOrganizationCertificateSid = 82, WinApplicationPackageAuthoritySid = 83, WinBuiltinAnyPackageSid = 84, WinCapabilityInternetClientSid = 85, WinCapabilityInternetClientServerSid = 86, WinCapabilityPrivateNetworkClientServerSid = 87, WinCapabilityPicturesLibrarySid = 88, WinCapabilityVideosLibrarySid = 89, WinCapabilityMusicLibrarySid = 90, WinCapabilityDocumentsLibrarySid = 91, WinCapabilitySharedUserCertificatesSid = 92, WinCapabilityEnterpriseAuthenticationSid = 93, WinCapabilityRemovableStorageSid = 94 } [ComVisible(true)] public enum WindowsAccountType { Normal, Guest, System, Anonymous } public enum WindowsBuiltInRole { Administrator = 544, User, Guest, PowerUser, AccountOperator, SystemOperator, PrintOperator, BackupOperator, Replicator } public class WindowsIdentity : ClaimsIdentity, IDisposable, IDeserializationCallback, ISerializable { public new const string DefaultIssuer = "AD AUTHORITY"; public SafeAccessTokenHandle AccessToken { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public sealed override string AuthenticationType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public override IEnumerable<Claim> Claims { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public virtual IEnumerable<Claim> DeviceClaims { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public IdentityReferenceCollection Groups { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public TokenImpersonationLevel ImpersonationLevel { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public virtual bool IsAnonymous { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public override bool IsAuthenticated { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public virtual bool IsGuest { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public virtual bool IsSystem { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public override string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public SecurityIdentifier Owner { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public virtual IntPtr Token { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public SecurityIdentifier User { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public virtual IEnumerable<Claim> UserClaims { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public WindowsIdentity(IntPtr userToken) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public WindowsIdentity(IntPtr userToken, string type) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType, bool isAuthenticated) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public WindowsIdentity(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } protected WindowsIdentity(WindowsIdentity identity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public WindowsIdentity(string sUserPrincipalName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override ClaimsIdentity Clone() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public static WindowsIdentity GetAnonymous() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static WindowsIdentity GetCurrent() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static WindowsIdentity GetCurrent(bool ifImpersonating) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } void IDeserializationCallback.OnDeserialization(object sender) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public class WindowsPrincipal : ClaimsPrincipal { public virtual IEnumerable<Claim> DeviceClaims { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public override IIdentity Identity { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public virtual IEnumerable<Claim> UserClaims { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } public WindowsPrincipal(WindowsIdentity ntIdentity) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public virtual bool IsInRole(int rid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public virtual bool IsInRole(SecurityIdentifier sid) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public virtual bool IsInRole(WindowsBuiltInRole role) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } public override bool IsInRole(string role) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal); } } }
deps/System.ServiceModel.Internals.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
#define DEBUG 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.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Diagnostics; using System.Runtime.Interop; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Security.Principal; using System.ServiceModel.Internals; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: Guid("a9b8c4b5-b4a9-4800-8268-e8ec3b93d9ac")] [assembly: InternalsVisibleTo("System.Activities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.Activities.Statements, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.Activities.Extended, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.Runtime.DurableInstancing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.Runtime.Serialization.Xaml, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.Runtime.Xaml, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.ServiceModel.Activation, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel.ServiceMoniker40, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.ServiceModel.Activities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel.Channels, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel.LocalChannel, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel.Discovery, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel.Routing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel.Web, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("Microsoft.ServiceModel.Web.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.WorkflowServices, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel.WasHosting, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.Xaml.Hosting, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("XamlBuildTask, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("SMSvcHost, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("SMDiagnostics, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("Microsoft.Transactions.Bridge, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("System.IO.Log, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("System.Runtime.Serialization, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.IdentityModel, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.IdentityModel.Selectors, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.IdentityModel.Services, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("WorkflowManagementService, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.Activities.DurableInstancing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("XsdBuildTask, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.ServiceModel.Friend, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("Microsoft.CDF.Test.Persistence, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("CDF.CIT.Scenarios.Common, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("WireTool, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("WsatTest, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("WCF.CIT.ChannelModel, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("System.Activities.Core.Presentation, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.Activities.Presentation, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("Microsoft.Activities.Build, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("Microsoft.VisualStudio.ServiceModel, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: AssemblyTitle("System.ServiceModel.Internals.dll")] [assembly: AssemblyDescription("Contains share code for some System.ServiceModel libraries")] [assembly: AssemblyDefaultAlias("System.ServiceModel.dll")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../ecma.pub")] [assembly: AllowPartiallyTrustedCallers] [assembly: ComCompatibleVersion(1, 0, 3300, 0)] [assembly: SecurityCritical(SecurityCriticalScope.Explicit)] [assembly: InternalsVisibleTo("System.Runtime.DurableInstancing, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.ServiceModel.Web, PublicKey=00000000000000000400000000000000")] [assembly: ComVisible(false)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] internal static class AssemblyRef { internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string EcmaPublicKey = "b77a5c561934e089"; public const string FrameworkPublicKeyFull = "00000000000000000400000000000000"; public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000"; public const string MicrosoftPublicKey = "b03f5f7f11d50a3a"; public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal static class SR { internal static string GetString(string name, params object[] args) { return GetString(CultureInfo.InvariantCulture, name, args); } internal static string GetString(CultureInfo culture, string name, params object[] args) { return string.Format(culture, name, args); } internal static string GetString(string name) { return name; } internal static string GetString(CultureInfo culture, string name) { return name; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2); } internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2) { return string.Format(ci, resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3); } internal static string GetResourceString(string str) { return str; } } namespace System.ServiceModel.Internals { internal static class LocalAppContextSwitches { public static readonly bool IncludeNullExceptionMessageInETWTrace; } } namespace System.Runtime { internal abstract class ActionItem { [SecurityCritical] private static class CallbackHelper { private static Action<object> invokeWithoutContextCallback; private static ContextCallback onContextAppliedCallback; public static Action<object> InvokeWithoutContextCallback { get { if (invokeWithoutContextCallback == null) { invokeWithoutContextCallback = InvokeWithoutContext; } return invokeWithoutContextCallback; } } public static ContextCallback OnContextAppliedCallback { get { if (onContextAppliedCallback == null) { onContextAppliedCallback = OnContextApplied; } return onContextAppliedCallback; } } private static void InvokeWithoutContext(object state) { ((ActionItem)state).Invoke(); ((ActionItem)state).isScheduled = false; } private static void OnContextApplied(object o) { ((ActionItem)o).Invoke(); ((ActionItem)o).isScheduled = false; } } private class DefaultActionItem : ActionItem { [SecurityCritical] private Action<object> callback; [SecurityCritical] private object state; private bool flowLegacyActivityId; private Guid activityId; private EventTraceActivity eventTraceActivity; [SecuritySafeCritical] public DefaultActionItem(Action<object> callback, object state, bool isLowPriority) { base.LowPriority = isLowPriority; this.callback = callback; this.state = state; if (WaitCallbackActionItem.ShouldUseActivity) { flowLegacyActivityId = true; activityId = DiagnosticTraceBase.ActivityId; } if (Fx.Trace.IsEnd2EndActivityTracingEnabled) { eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate(); if (TraceCore.ActionItemScheduledIsEnabled(Fx.Trace)) { TraceCore.ActionItemScheduled(Fx.Trace, eventTraceActivity); } } } [SecurityCritical] protected override void Invoke() { if (flowLegacyActivityId || Fx.Trace.IsEnd2EndActivityTracingEnabled) { TraceAndInvoke(); } else { callback(state); } } [SecurityCritical] private void TraceAndInvoke() { if (flowLegacyActivityId) { Guid guid = DiagnosticTraceBase.ActivityId; try { DiagnosticTraceBase.ActivityId = activityId; callback(state); return; } finally { DiagnosticTraceBase.ActivityId = guid; } } Guid empty = Guid.Empty; bool flag = false; try { if (eventTraceActivity != null) { empty = Trace.CorrelationManager.ActivityId; flag = true; Trace.CorrelationManager.ActivityId = eventTraceActivity.ActivityId; if (TraceCore.ActionItemCallbackInvokedIsEnabled(Fx.Trace)) { TraceCore.ActionItemCallbackInvoked(Fx.Trace, eventTraceActivity); } } callback(state); } finally { if (flag) { Trace.CorrelationManager.ActivityId = empty; } } } } private bool isScheduled; private bool lowPriority; public bool LowPriority { get { return lowPriority; } protected set { lowPriority = value; } } public static void Schedule(Action<object> callback, object state) { Schedule(callback, state, lowPriority: false); } [SecuritySafeCritical] public static void Schedule(Action<object> callback, object state, bool lowPriority) { if (PartialTrustHelpers.ShouldFlowSecurityContext || WaitCallbackActionItem.ShouldUseActivity || Fx.Trace.IsEnd2EndActivityTracingEnabled) { new DefaultActionItem(callback, state, lowPriority).Schedule(); } else { ScheduleCallback(callback, state, lowPriority); } } [SecurityCritical] protected abstract void Invoke(); [SecurityCritical] protected void Schedule() { if (isScheduled) { throw Fx.Exception.AsError(new InvalidOperationException("Action Item Is Already Scheduled")); } isScheduled = true; ScheduleCallback(CallbackHelper.InvokeWithoutContextCallback); } [SecurityCritical] protected void ScheduleWithoutContext() { if (isScheduled) { throw Fx.Exception.AsError(new InvalidOperationException("Action Item Is Already Scheduled")); } isScheduled = true; ScheduleCallback(CallbackHelper.InvokeWithoutContextCallback); } [SecurityCritical] private static void ScheduleCallback(Action<object> callback, object state, bool lowPriority) { if (lowPriority) { IOThreadScheduler.ScheduleCallbackLowPriNoFlow(callback, state); } else { IOThreadScheduler.ScheduleCallbackNoFlow(callback, state); } } [SecurityCritical] private void ScheduleCallback(Action<object> callback) { ScheduleCallback(callback, this, lowPriority); } } internal static class AssertHelper { internal static void FireAssert(string message) { try { } finally { Debug.Assert(condition: false, message); } } } internal enum AsyncCompletionResult { Queued, Completed } internal abstract class AsyncEventArgs : IAsyncEventArgs { private enum OperationState { Created, PendingCompletion, CompletedSynchronously, CompletedAsynchronously } private OperationState state; private object asyncState; private AsyncEventArgsCallback callback; private Exception exception; public Exception Exception => exception; public object AsyncState => asyncState; private OperationState State { set { switch (value) { case OperationState.PendingCompletion: if (state == OperationState.PendingCompletion) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncEventArgsCompletionPending(GetType()))); } break; case OperationState.CompletedSynchronously: case OperationState.CompletedAsynchronously: if (state != OperationState.PendingCompletion) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncEventArgsCompletedTwice(GetType()))); } break; } state = value; } } public void Complete(bool completedSynchronously) { Complete(completedSynchronously, null); } public virtual void Complete(bool completedSynchronously, Exception exception) { this.exception = exception; if (completedSynchronously) { State = OperationState.CompletedSynchronously; return; } State = OperationState.CompletedAsynchronously; callback(this); } protected void SetAsyncState(AsyncEventArgsCallback callback, object state) { if (callback == null) { throw Fx.Exception.ArgumentNull("callback"); } State = OperationState.PendingCompletion; asyncState = state; this.callback = callback; } } internal class AsyncEventArgs<TArgument> : AsyncEventArgs { public TArgument Arguments { get; private set; } public virtual void Set(AsyncEventArgsCallback callback, TArgument arguments, object state) { SetAsyncState(callback, state); Arguments = arguments; } } internal class AsyncEventArgs<TArgument, TResult> : AsyncEventArgs<TArgument> { public TResult Result { get; set; } } internal delegate void AsyncEventArgsCallback(IAsyncEventArgs eventArgs); internal abstract class AsyncResult : IAsyncResult { protected delegate bool AsyncCompletion(IAsyncResult result); private static AsyncCallback asyncCompletionWrapperCallback; private AsyncCallback callback; private bool completedSynchronously; private bool endCalled; private Exception exception; private bool isCompleted; private AsyncCompletion nextAsyncCompletion; private object state; private Action beforePrepareAsyncCompletionAction; private Func<IAsyncResult, bool> checkSyncValidationFunc; private ManualResetEvent manualResetEvent; private object thisLock; public object AsyncState => state; public WaitHandle AsyncWaitHandle { get { if (manualResetEvent != null) { return manualResetEvent; } lock (ThisLock) { if (manualResetEvent == null) { manualResetEvent = new ManualResetEvent(isCompleted); } } return manualResetEvent; } } public bool CompletedSynchronously => completedSynchronously; public bool HasCallback => callback != null; public bool IsCompleted => isCompleted; protected Action<AsyncResult, Exception> OnCompleting { get; set; } private object ThisLock => thisLock; protected Action<AsyncCallback, IAsyncResult> VirtualCallback { get; set; } protected AsyncResult(AsyncCallback callback, object state) { this.callback = callback; this.state = state; thisLock = new object(); } protected void Complete(bool completedSynchronously) { if (isCompleted) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultCompletedTwice(GetType()))); } this.completedSynchronously = completedSynchronously; if (OnCompleting != null) { try { OnCompleting(this, exception); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } exception = ex; } } if (completedSynchronously) { isCompleted = true; } else { lock (ThisLock) { isCompleted = true; if (manualResetEvent != null) { manualResetEvent.Set(); } } } if (callback == null) { return; } try { if (VirtualCallback != null) { VirtualCallback(callback, this); } else { callback(this); } } catch (Exception innerException) { if (Fx.IsFatal(innerException)) { throw; } throw Fx.Exception.AsError(new CallbackException("Async Callback Threw Exception", innerException)); } } protected void Complete(bool completedSynchronously, Exception exception) { this.exception = exception; Complete(completedSynchronously); } private static void AsyncCompletionWrapperCallback(IAsyncResult result) { if (result == null) { throw Fx.Exception.AsError(new InvalidOperationException("Invalid Null Async Result")); } if (result.CompletedSynchronously) { return; } AsyncResult asyncResult = (AsyncResult)result.AsyncState; if (!asyncResult.OnContinueAsyncCompletion(result)) { return; } AsyncCompletion nextCompletion = asyncResult.GetNextCompletion(); if (nextCompletion == null) { ThrowInvalidAsyncResult(result); } bool flag = false; Exception ex = null; try { flag = nextCompletion(result); } catch (Exception ex2) { if (Fx.IsFatal(ex2)) { throw; } flag = true; ex = ex2; } if (flag) { asyncResult.Complete(completedSynchronously: false, ex); } } protected virtual bool OnContinueAsyncCompletion(IAsyncResult result) { return true; } protected void SetBeforePrepareAsyncCompletionAction(Action beforePrepareAsyncCompletionAction) { this.beforePrepareAsyncCompletionAction = beforePrepareAsyncCompletionAction; } protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> checkSyncValidationFunc) { this.checkSyncValidationFunc = checkSyncValidationFunc; } protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback) { if (beforePrepareAsyncCompletionAction != null) { beforePrepareAsyncCompletionAction(); } nextAsyncCompletion = callback; if (asyncCompletionWrapperCallback == null) { asyncCompletionWrapperCallback = Fx.ThunkCallback(AsyncCompletionWrapperCallback); } return asyncCompletionWrapperCallback; } protected bool CheckSyncContinue(IAsyncResult result) { AsyncCompletion asyncCompletion; return TryContinueHelper(result, out asyncCompletion); } protected bool SyncContinue(IAsyncResult result) { if (TryContinueHelper(result, out var asyncCompletion)) { return asyncCompletion(result); } return false; } private bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback) { if (result == null) { throw Fx.Exception.AsError(new InvalidOperationException("Invalid Null Async Result")); } callback = null; if (checkSyncValidationFunc != null) { if (!checkSyncValidationFunc(result)) { return false; } } else if (!result.CompletedSynchronously) { return false; } callback = GetNextCompletion(); if (callback == null) { ThrowInvalidAsyncResult("Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion)."); } return true; } private AsyncCompletion GetNextCompletion() { AsyncCompletion result = nextAsyncCompletion; nextAsyncCompletion = null; return result; } protected static void ThrowInvalidAsyncResult(IAsyncResult result) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidAsyncResultImplementation(result.GetType()))); } protected static void ThrowInvalidAsyncResult(string debugText) { string message = "Invalid Async Result Implementation Generic"; throw Fx.Exception.AsError(new InvalidOperationException(message)); } protected static TAsyncResult End<TAsyncResult>(IAsyncResult result) where TAsyncResult : AsyncResult { if (result == null) { throw Fx.Exception.ArgumentNull("result"); } if (!(result is TAsyncResult val)) { throw Fx.Exception.Argument("result", "Invalid Async Result"); } if (val.endCalled) { throw Fx.Exception.AsError(new InvalidOperationException("Async Result Already Ended")); } val.endCalled = true; if (!val.isCompleted) { val.AsyncWaitHandle.WaitOne(); } if (val.manualResetEvent != null) { val.manualResetEvent.Close(); } if (val.exception != null) { throw Fx.Exception.AsError(val.exception); } return val; } } internal class AsyncWaitHandle { private class AsyncWaiter : ActionItem { [SecurityCritical] private Action<object, TimeoutException> callback; [SecurityCritical] private object state; private IOThreadTimer timer; private TimeSpan originalTimeout; public AsyncWaitHandle Parent { get; private set; } public bool TimedOut { get; set; } [SecuritySafeCritical] public AsyncWaiter(AsyncWaitHandle parent, Action<object, TimeoutException> callback, object state) { Parent = parent; this.callback = callback; this.state = state; } [SecuritySafeCritical] public void Call() { Schedule(); } [SecurityCritical] protected override void Invoke() { callback(state, TimedOut ? new TimeoutException(InternalSR.TimeoutOnOperation(originalTimeout)) : null); } public void SetTimer(Action<object> callback, object state, TimeSpan timeout) { if (timer != null) { throw Fx.Exception.AsError(new InvalidOperationException("Must Cancel Old Timer")); } originalTimeout = timeout; timer = new IOThreadTimer(callback, state, isTypicallyCanceledShortlyAfterBeingSet: false); timer.Set(timeout); } public void CancelTimer() { if (timer != null) { timer.Cancel(); timer = null; } } } private static Action<object> timerCompleteCallback; private List<AsyncWaiter> asyncWaiters; private bool isSignaled; private EventResetMode resetMode; private object syncObject; private int syncWaiterCount; public AsyncWaitHandle() : this(EventResetMode.AutoReset) { } public AsyncWaitHandle(EventResetMode resetMode) { this.resetMode = resetMode; syncObject = new object(); } public bool WaitAsync(Action<object, TimeoutException> callback, object state, TimeSpan timeout) { if (!isSignaled || (isSignaled && resetMode == EventResetMode.AutoReset)) { lock (syncObject) { if (isSignaled && resetMode == EventResetMode.AutoReset) { isSignaled = false; } else if (!isSignaled) { AsyncWaiter asyncWaiter = new AsyncWaiter(this, callback, state); if (asyncWaiters == null) { asyncWaiters = new List<AsyncWaiter>(); } asyncWaiters.Add(asyncWaiter); if (timeout != TimeSpan.MaxValue) { if (timerCompleteCallback == null) { timerCompleteCallback = OnTimerComplete; } asyncWaiter.SetTimer(timerCompleteCallback, asyncWaiter, timeout); } return false; } } } return true; } private static void OnTimerComplete(object state) { AsyncWaiter asyncWaiter = (AsyncWaiter)state; AsyncWaitHandle parent = asyncWaiter.Parent; bool flag = false; lock (parent.syncObject) { if (parent.asyncWaiters != null && parent.asyncWaiters.Remove(asyncWaiter)) { asyncWaiter.TimedOut = true; flag = true; } } asyncWaiter.CancelTimer(); if (flag) { asyncWaiter.Call(); } } public bool Wait(TimeSpan timeout) { if (!isSignaled || (isSignaled && resetMode == EventResetMode.AutoReset)) { lock (syncObject) { if (isSignaled && resetMode == EventResetMode.AutoReset) { isSignaled = false; } else if (!isSignaled) { bool flag = false; try { try { } finally { syncWaiterCount++; flag = true; } if (timeout == TimeSpan.MaxValue) { if (!Monitor.Wait(syncObject, -1)) { return false; } } else if (!Monitor.Wait(syncObject, timeout)) { return false; } } finally { if (flag) { syncWaiterCount--; } } } } } return true; } public void Set() { List<AsyncWaiter> list = null; AsyncWaiter asyncWaiter = null; if (!isSignaled) { lock (syncObject) { if (!isSignaled) { if (resetMode == EventResetMode.ManualReset) { isSignaled = true; Monitor.PulseAll(syncObject); list = asyncWaiters; asyncWaiters = null; } else if (syncWaiterCount > 0) { Monitor.Pulse(syncObject); } else if (asyncWaiters != null && asyncWaiters.Count > 0) { asyncWaiter = asyncWaiters[0]; asyncWaiters.RemoveAt(0); } else { isSignaled = true; } } } } if (list != null) { foreach (AsyncWaiter item in list) { item.CancelTimer(); item.Call(); } } if (asyncWaiter != null) { asyncWaiter.CancelTimer(); asyncWaiter.Call(); } } public void Reset() { isSignaled = false; } } internal sealed class BackoffTimeoutHelper { private static readonly int maxSkewMilliseconds = (int)(IOThreadTimer.SystemTimeResolutionTicks / 10000); private static readonly long maxDriftTicks = IOThreadTimer.SystemTimeResolutionTicks * 2; private static readonly TimeSpan defaultInitialWaitTime = TimeSpan.FromMilliseconds(1.0); private static readonly TimeSpan defaultMaxWaitTime = TimeSpan.FromMinutes(1.0); private DateTime deadline; private TimeSpan maxWaitTime; private TimeSpan waitTime; private IOThreadTimer backoffTimer; private Action<object> backoffCallback; private object backoffState; private Random random; private TimeSpan originalTimeout; public TimeSpan OriginalTimeout => originalTimeout; internal BackoffTimeoutHelper(TimeSpan timeout) : this(timeout, defaultMaxWaitTime) { } internal BackoffTimeoutHelper(TimeSpan timeout, TimeSpan maxWaitTime) : this(timeout, maxWaitTime, defaultInitialWaitTime) { } internal BackoffTimeoutHelper(TimeSpan timeout, TimeSpan maxWaitTime, TimeSpan initialWaitTime) { random = new Random(GetHashCode()); this.maxWaitTime = maxWaitTime; originalTimeout = timeout; Reset(timeout, initialWaitTime); } private void Reset(TimeSpan timeout, TimeSpan initialWaitTime) { if (timeout == TimeSpan.MaxValue) { deadline = DateTime.MaxValue; } else { deadline = DateTime.UtcNow + timeout; } waitTime = initialWaitTime; } public bool IsExpired() { if (deadline == DateTime.MaxValue) { return false; } return DateTime.UtcNow >= deadline; } public void WaitAndBackoff(Action<object> callback, object state) { if (backoffCallback != callback || backoffState != state) { if (backoffTimer != null) { backoffTimer.Cancel(); } backoffCallback = callback; backoffState = state; backoffTimer = new IOThreadTimer(callback, state, isTypicallyCanceledShortlyAfterBeingSet: false, maxSkewMilliseconds); } TimeSpan timeFromNow = WaitTimeWithDrift(); Backoff(); backoffTimer.Set(timeFromNow); } public void WaitAndBackoff() { Thread.Sleep(WaitTimeWithDrift()); Backoff(); } private TimeSpan WaitTimeWithDrift() { return Ticks.ToTimeSpan(Math.Max(Ticks.FromTimeSpan(defaultInitialWaitTime), Ticks.Add(Ticks.FromTimeSpan(waitTime), (uint)random.Next() % (2 * maxDriftTicks + 1) - maxDriftTicks))); } private void Backoff() { if (waitTime.Ticks >= maxWaitTime.Ticks / 2) { waitTime = maxWaitTime; } else { waitTime = TimeSpan.FromTicks(waitTime.Ticks * 2); } if (!(deadline != DateTime.MaxValue)) { return; } TimeSpan timeSpan = deadline - DateTime.UtcNow; if (waitTime > timeSpan) { waitTime = timeSpan; if (waitTime < TimeSpan.Zero) { waitTime = TimeSpan.Zero; } } } } internal class BufferedOutputStream : Stream { private InternalBufferManager bufferManager; private byte[][] chunks; private int chunkCount; private byte[] currentChunk; private int currentChunkSize; private int maxSize; private int maxSizeQuota; private int totalSize; private bool callerReturnsBuffer; private bool bufferReturned; private bool initialized; public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => totalSize; public override long Position { get { throw Fx.Exception.AsError(new NotSupportedException("Seek Not Supported")); } set { throw Fx.Exception.AsError(new NotSupportedException("Seek Not Supported")); } } public BufferedOutputStream() { chunks = new byte[4][]; } public BufferedOutputStream(int initialSize, int maxSize, InternalBufferManager bufferManager) : this() { Reinitialize(initialSize, maxSize, bufferManager); } public BufferedOutputStream(int maxSize) : this(0, maxSize, InternalBufferManager.Create(0L, int.MaxValue)) { } public void Reinitialize(int initialSize, int maxSizeQuota, InternalBufferManager bufferManager) { Reinitialize(initialSize, maxSizeQuota, maxSizeQuota, bufferManager); } public void Reinitialize(int initialSize, int maxSizeQuota, int effectiveMaxSize, InternalBufferManager bufferManager) { this.maxSizeQuota = maxSizeQuota; maxSize = effectiveMaxSize; this.bufferManager = bufferManager; currentChunk = bufferManager.TakeBuffer(initialSize); currentChunkSize = 0; totalSize = 0; chunkCount = 1; chunks[0] = currentChunk; initialized = true; } private void AllocNextChunk(int minimumChunkSize) { int num = ((currentChunk.Length <= 1073741823) ? (currentChunk.Length * 2) : int.MaxValue); if (minimumChunkSize > num) { num = minimumChunkSize; } byte[] array = bufferManager.TakeBuffer(num); if (chunkCount == chunks.Length) { byte[][] destinationArray = new byte[chunks.Length * 2][]; Array.Copy(chunks, destinationArray, chunks.Length); chunks = destinationArray; } chunks[chunkCount++] = array; currentChunk = array; currentChunkSize = 0; } public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { throw Fx.Exception.AsError(new NotSupportedException("Read Not Supported")); } public override int EndRead(IAsyncResult result) { throw Fx.Exception.AsError(new NotSupportedException("Read Not Supported")); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { Write(buffer, offset, size); return new CompletedAsyncResult(callback, state); } public override void EndWrite(IAsyncResult result) { CompletedAsyncResult.End(result); } public void Clear() { if (!callerReturnsBuffer) { for (int i = 0; i < chunkCount; i++) { bufferManager.ReturnBuffer(chunks[i]); chunks[i] = null; } } callerReturnsBuffer = false; initialized = false; bufferReturned = false; chunkCount = 0; currentChunk = null; } public override void Close() { } public override void Flush() { } public override int Read(byte[] buffer, int offset, int size) { throw Fx.Exception.AsError(new NotSupportedException("Read Not Supported")); } public override int ReadByte() { throw Fx.Exception.AsError(new NotSupportedException("Read Not Supported")); } public override long Seek(long offset, SeekOrigin origin) { throw Fx.Exception.AsError(new NotSupportedException("Seek Not Supported")); } public override void SetLength(long value) { throw Fx.Exception.AsError(new NotSupportedException("Seek Not Supported")); } public MemoryStream ToMemoryStream() { int bufferSize; return new MemoryStream(ToArray(out bufferSize), 0, bufferSize); } public byte[] ToArray(out int bufferSize) { byte[] array; if (chunkCount == 1) { array = currentChunk; bufferSize = currentChunkSize; callerReturnsBuffer = true; } else { array = bufferManager.TakeBuffer(totalSize); int num = 0; int num2 = chunkCount - 1; for (int i = 0; i < num2; i++) { byte[] array2 = chunks[i]; Buffer.BlockCopy(array2, 0, array, num, array2.Length); num += array2.Length; } Buffer.BlockCopy(currentChunk, 0, array, num, currentChunkSize); bufferSize = totalSize; } bufferReturned = true; return array; } public void Skip(int size) { WriteCore(null, 0, size); } public override void Write(byte[] buffer, int offset, int size) { WriteCore(buffer, offset, size); } protected virtual Exception CreateQuotaExceededException(int maxSizeQuota) { return new InvalidOperationException(InternalSR.BufferedOutputStreamQuotaExceeded(maxSizeQuota)); } private void WriteCore(byte[] buffer, int offset, int size) { if (size < 0) { throw Fx.Exception.ArgumentOutOfRange("size", size, "Value Must Be Non Negative"); } if (int.MaxValue - size < totalSize) { throw Fx.Exception.AsError(CreateQuotaExceededException(maxSizeQuota)); } int num = totalSize + size; if (num > maxSize) { throw Fx.Exception.AsError(CreateQuotaExceededException(maxSizeQuota)); } int num2 = currentChunk.Length - currentChunkSize; if (size > num2) { if (num2 > 0) { if (buffer != null) { Buffer.BlockCopy(buffer, offset, currentChunk, currentChunkSize, num2); } currentChunkSize = currentChunk.Length; offset += num2; size -= num2; } AllocNextChunk(size); } if (buffer != null) { Buffer.BlockCopy(buffer, offset, currentChunk, currentChunkSize, size); } totalSize = num; currentChunkSize += size; } public override void WriteByte(byte value) { if (totalSize == maxSize) { throw Fx.Exception.AsError(CreateQuotaExceededException(maxSize)); } if (currentChunkSize == currentChunk.Length) { AllocNextChunk(1); } currentChunk[currentChunkSize++] = value; } } [Serializable] internal class CallbackException : FatalException { public CallbackException() { } public CallbackException(string message, Exception innerException) : base(message, innerException) { } protected CallbackException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal class CompletedAsyncResult : AsyncResult { public CompletedAsyncResult(AsyncCallback callback, object state) : base(callback, state) { Complete(completedSynchronously: true); } public static void End(IAsyncResult result) { Fx.AssertAndThrowFatal(result.IsCompleted, "CompletedAsyncResult was not completed!"); AsyncResult.End<CompletedAsyncResult>(result); } } internal class CompletedAsyncResult<T> : AsyncResult { private T data; public CompletedAsyncResult(T data, AsyncCallback callback, object state) : base(callback, state) { this.data = data; Complete(completedSynchronously: true); } public static T End(IAsyncResult result) { Fx.AssertAndThrowFatal(result.IsCompleted, "CompletedAsyncResult<T> was not completed!"); return AsyncResult.End<CompletedAsyncResult<T>>(result).data; } } internal class CompletedAsyncResult<TResult, TParameter> : AsyncResult { private TResult resultData; private TParameter parameter; public CompletedAsyncResult(TResult resultData, TParameter parameter, AsyncCallback callback, object state) : base(callback, state) { this.resultData = resultData; this.parameter = parameter; Complete(completedSynchronously: true); } public static TResult End(IAsyncResult result, out TParameter parameter) { Fx.AssertAndThrowFatal(result.IsCompleted, "CompletedAsyncResult<T> was not completed!"); CompletedAsyncResult<TResult, TParameter> completedAsyncResult = AsyncResult.End<CompletedAsyncResult<TResult, TParameter>>(result); parameter = completedAsyncResult.parameter; return completedAsyncResult.resultData; } } internal enum ComputerNameFormat { NetBIOS, DnsHostName, Dns, DnsFullyQualified, PhysicalNetBIOS, PhysicalDnsHostName, PhysicalDnsDomain, PhysicalDnsFullyQualified } internal static class DiagnosticStrings { internal const string AppDomain = "AppDomain"; internal const string ChannelTag = "Channel"; internal const string Description = "Description"; internal const string DataTag = "Data"; internal const string DataItemsTag = "DataItems"; internal const string DescriptionTag = "Description"; internal const string ExceptionTag = "Exception"; internal const string ExceptionTypeTag = "ExceptionType"; internal const string ExceptionStringTag = "ExceptionString"; internal const string ExtendedDataTag = "ExtendedData"; internal const string InnerExceptionTag = "InnerException"; internal const string KeyTag = "Key"; internal const string MessageTag = "Message"; internal const string NamespaceTag = "xmlns"; internal const string NativeErrorCodeTag = "NativeErrorCode"; internal const string Separator = ":"; internal const string SeverityTag = "Severity"; internal const string SourceTag = "Source"; internal const string StackTraceTag = "StackTrace"; internal const string Task = "Task"; internal const string TraceCodeTag = "TraceIdentifier"; internal const string TraceRecordTag = "TraceRecord"; internal const string ValueTag = "Value"; } internal class DuplicateDetector<T> where T : class { private LinkedList<T> fifoList; private Dictionary<T, LinkedListNode<T>> items; private int capacity; private object thisLock; public DuplicateDetector(int capacity) { this.capacity = capacity; items = new Dictionary<T, LinkedListNode<T>>(); fifoList = new LinkedList<T>(); thisLock = new object(); } public bool AddIfNotDuplicate(T value) { bool result = false; lock (thisLock) { if (!items.ContainsKey(value)) { Add(value); result = true; } } return result; } private void Add(T value) { if (items.Count == capacity) { LinkedListNode<T> last = fifoList.Last; items.Remove(last.Value); fifoList.Remove(last); } items.Add(value, fifoList.AddFirst(value)); } public bool Remove(T value) { bool result = false; lock (thisLock) { if (items.TryGetValue(value, out var value2)) { items.Remove(value); fifoList.Remove(value2); result = true; } } return result; } public void Clear() { lock (thisLock) { fifoList.Clear(); items.Clear(); } } } internal class ExceptionTrace { private const ushort FailFastEventLogCategory = 6; private string eventSourceName; private readonly EtwDiagnosticTrace diagnosticTrace; public ExceptionTrace(string eventSourceName, EtwDiagnosticTrace diagnosticTrace) { this.eventSourceName = eventSourceName; this.diagnosticTrace = diagnosticTrace; } public void AsInformation(Exception exception) { TraceCore.HandledException(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception); } public void AsWarning(Exception exception) { TraceCore.HandledExceptionWarning(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception); } public Exception AsError(Exception exception) { if (exception is AggregateException aggregateException) { return AsError<Exception>(aggregateException); } if (exception is TargetInvocationException ex && ex.InnerException != null) { return AsError(ex.InnerException); } return TraceException(exception); } public Exception AsError(Exception exception, string eventSource) { if (exception is AggregateException aggregateException) { return AsError<Exception>(aggregateException, eventSource); } if (exception is TargetInvocationException ex && ex.InnerException != null) { return AsError(ex.InnerException, eventSource); } return TraceException(exception, eventSource); } public Exception AsError(TargetInvocationException targetInvocationException, string eventSource) { if (Fx.IsFatal(targetInvocationException)) { return targetInvocationException; } Exception innerException = targetInvocationException.InnerException; if (innerException != null) { return AsError(innerException, eventSource); } return TraceException((Exception)targetInvocationException, eventSource); } public Exception AsError<TPreferredException>(AggregateException aggregateException) { return AsError<TPreferredException>(aggregateException, eventSourceName); } public Exception AsError<TPreferredException>(AggregateException aggregateException, string eventSource) { if (Fx.IsFatal(aggregateException)) { return aggregateException; } ReadOnlyCollection<Exception> innerExceptions = aggregateException.Flatten().InnerExceptions; if (innerExceptions.Count == 0) { return TraceException(aggregateException, eventSource); } Exception ex = null; foreach (Exception item in innerExceptions) { Exception ex3 = ((item is TargetInvocationException ex2 && ex2.InnerException != null) ? ex2.InnerException : item); if (ex3 is TPreferredException && ex == null) { ex = ex3; } TraceException(ex3, eventSource); } if (ex == null) { ex = innerExceptions[0]; } return ex; } public ArgumentException Argument(string paramName, string message) { return TraceException(new ArgumentException(message, paramName)); } public ArgumentNullException ArgumentNull(string paramName) { return TraceException(new ArgumentNullException(paramName)); } public ArgumentNullException ArgumentNull(string paramName, string message) { return TraceException(new ArgumentNullException(paramName, message)); } public ArgumentException ArgumentNullOrEmpty(string paramName) { return Argument(paramName, InternalSR.ArgumentNullOrEmpty(paramName)); } public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message) { return TraceException(new ArgumentOutOfRangeException(paramName, actualValue, message)); } public ObjectDisposedException ObjectDisposed(string message) { return TraceException(new ObjectDisposedException(null, message)); } public void TraceUnhandledException(Exception exception) { TraceCore.UnhandledException(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception); } public void TraceHandledException(Exception exception, TraceEventType traceEventType) { switch (traceEventType) { case TraceEventType.Error: if (TraceCore.HandledExceptionErrorIsEnabled(diagnosticTrace)) { TraceCore.HandledExceptionError(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception); } break; case TraceEventType.Warning: if (TraceCore.HandledExceptionWarningIsEnabled(diagnosticTrace)) { TraceCore.HandledExceptionWarning(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception); } break; case TraceEventType.Verbose: if (TraceCore.HandledExceptionVerboseIsEnabled(diagnosticTrace)) { TraceCore.HandledExceptionVerbose(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception); } break; default: if (TraceCore.HandledExceptionIsEnabled(diagnosticTrace)) { TraceCore.HandledException(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception); } break; } } public void TraceEtwException(Exception exception, TraceEventType eventType) { switch (eventType) { case TraceEventType.Error: case TraceEventType.Warning: if (TraceCore.ThrowingEtwExceptionIsEnabled(diagnosticTrace)) { TraceCore.ThrowingEtwException(diagnosticTrace, eventSourceName, (exception != null) ? exception.ToString() : string.Empty, exception); } break; case TraceEventType.Critical: if (TraceCore.EtwUnhandledExceptionIsEnabled(diagnosticTrace)) { TraceCore.EtwUnhandledException(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception); } break; default: if (TraceCore.ThrowingEtwExceptionVerboseIsEnabled(diagnosticTrace)) { TraceCore.ThrowingEtwExceptionVerbose(diagnosticTrace, eventSourceName, (exception != null) ? exception.ToString() : string.Empty, exception); } break; } } private TException TraceException<TException>(TException exception) where TException : Exception { return TraceException(exception, eventSourceName); } [SecuritySafeCritical] private TException TraceException<TException>(TException exception, string eventSource) where TException : Exception { if (TraceCore.ThrowingExceptionIsEnabled(diagnosticTrace)) { TraceCore.ThrowingException(diagnosticTrace, eventSource, (exception != null) ? exception.ToString() : string.Empty, exception); } BreakOnException(exception); return exception; } [SecuritySafeCritical] private void BreakOnException(Exception exception) { } [MethodImpl(MethodImplOptions.NoInlining)] internal void TraceFailFast(string message) { EventLogger eventLogger = null; eventLogger = new EventLogger(eventSourceName, diagnosticTrace); TraceFailFast(message, eventLogger); } [MethodImpl(MethodImplOptions.NoInlining)] internal void TraceFailFast(string message, EventLogger logger) { if (logger == null) { return; } try { string text = null; try { text = new StackTrace().ToString(); } catch (Exception ex) { text = ex.Message; if (Fx.IsFatal(ex)) { throw; } } finally { logger.LogEvent(TraceEventType.Critical, 6, 3221291110u, message, text); } } catch (Exception ex2) { logger.LogEvent(TraceEventType.Critical, 6, 3221291111u, ex2.ToString()); if (Fx.IsFatal(ex2)) { throw; } } } } internal delegate void FastAsyncCallback(object state, Exception asyncException); [Serializable] internal class FatalException : SystemException { public FatalException() { } public FatalException(string message) : base(message) { } public FatalException(string message, Exception innerException) : base(message, innerException) { } protected FatalException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal static class Fx { public abstract class ExceptionHandler { public abstract bool HandleException(Exception exception); } public static class Tag { public enum CacheAttrition { None, ElementOnTimer, ElementOnGC, ElementOnCallback, FullPurgeOnTimer, FullPurgeOnEachAccess, PartialPurgeOnTimer, PartialPurgeOnEachAccess } public enum ThrottleAction { Reject, Pause } public enum ThrottleMetric { Count, Rate, Other } public enum Location { InProcess, OutOfProcess, LocalSystem, LocalOrRemoteSystem, RemoteSystem } public enum SynchronizationKind { LockStatement, MonitorWait, MonitorExplicit, InterlockedNoSpin, InterlockedWithSpin, FromFieldType } [Flags] public enum BlocksUsing { MonitorEnter = 0, MonitorWait = 1, ManualResetEvent = 2, AutoResetEvent = 3, AsyncResult = 4, IAsyncResult = 5, PInvoke = 6, InputQueue = 7, ThreadNeutralSemaphore = 8, PrivatePrimitive = 9, OtherInternalPrimitive = 0xA, OtherFrameworkPrimitive = 0xB, OtherInterop = 0xC, Other = 0xD, NonBlocking = 0xE } public static class Strings { internal const string ExternallyManaged = "externally managed"; internal const string AppDomain = "AppDomain"; internal const string DeclaringInstance = "instance of declaring class"; internal const string Unbounded = "unbounded"; internal const string Infinite = "infinite"; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true, Inherited = false)] [Conditional("DEBUG")] public sealed class FriendAccessAllowedAttribute : Attribute { public string AssemblyName { get; set; } public FriendAccessAllowedAttribute(string assemblyName) { AssemblyName = assemblyName; } } public static class Throws { [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class TimeoutAttribute : ThrowsAttribute { public TimeoutAttribute() : this("The operation timed out.") { } public TimeoutAttribute(string diagnosis) : base(typeof(TimeoutException), diagnosis) { } } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class CacheAttribute : Attribute { private readonly Type elementType; private readonly CacheAttrition cacheAttrition; public Type ElementType => elementType; public CacheAttrition CacheAttrition => cacheAttrition; public string Scope { get; set; } public string SizeLimit { get; set; } public string Timeout { get; set; } public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) { Scope = "instance of declaring class"; SizeLimit = "unbounded"; Timeout = "infinite"; if (elementType == null) { throw Exception.ArgumentNull("elementType"); } this.elementType = elementType; this.cacheAttrition = cacheAttrition; } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class QueueAttribute : Attribute { private readonly Type elementType; public Type ElementType => elementType; public string Scope { get; set; } public string SizeLimit { get; set; } public bool StaleElementsRemovedImmediately { get; set; } public bool EnqueueThrowsIfFull { get; set; } public QueueAttribute(Type elementType) { Scope = "instance of declaring class"; SizeLimit = "unbounded"; if (elementType == null) { throw Exception.ArgumentNull("elementType"); } this.elementType = elementType; } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class ThrottleAttribute : Attribute { private readonly ThrottleAction throttleAction; private readonly ThrottleMetric throttleMetric; private readonly string limit; public ThrottleAction ThrottleAction => throttleAction; public ThrottleMetric ThrottleMetric => throttleMetric; public string Limit => limit; public string Scope { get; set; } public ThrottleAttribute(ThrottleAction throttleAction, ThrottleMetric throttleMetric, string limit) { Scope = "AppDomain"; if (string.IsNullOrEmpty(limit)) { throw Exception.ArgumentNullOrEmpty("limit"); } this.throttleAction = throttleAction; this.throttleMetric = throttleMetric; this.limit = limit; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class ExternalResourceAttribute : Attribute { private readonly Location location; private readonly string description; public Location Location => location; public string Description => description; public ExternalResourceAttribute(Location location, string description) { this.location = location; this.description = description; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SynchronizationObjectAttribute : Attribute { public bool Blocking { get; set; } public string Scope { get; set; } public SynchronizationKind Kind { get; set; } public SynchronizationObjectAttribute() { Blocking = true; Scope = "instance of declaring class"; Kind = SynchronizationKind.FromFieldType; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SynchronizationPrimitiveAttribute : Attribute { private readonly BlocksUsing blocksUsing; public BlocksUsing BlocksUsing => blocksUsing; public bool SupportsAsync { get; set; } public bool Spins { get; set; } public string ReleaseMethod { get; set; } public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { this.blocksUsing = blocksUsing; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class BlockingAttribute : Attribute { public string CancelMethod { get; set; } public Type CancelDeclaringType { get; set; } public string Conditional { get; set; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class GuaranteeNonBlockingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class NonThrowingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public class ThrowsAttribute : Attribute { private readonly Type exceptionType; private readonly string diagnosis; public Type ExceptionType => exceptionType; public string Diagnosis => diagnosis; public ThrowsAttribute(Type exceptionType, string diagnosis) { if (exceptionType == null) { throw Exception.ArgumentNull("exceptionType"); } if (string.IsNullOrEmpty(diagnosis)) { throw Exception.ArgumentNullOrEmpty("diagnosis"); } this.exceptionType = exceptionType; this.diagnosis = diagnosis; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class InheritThrowsAttribute : Attribute { public Type FromDeclaringType { get; set; } public string From { get; set; } } [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class KnownXamlExternalAttribute : Attribute { } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class XamlVisibleAttribute : Attribute { public bool Visible { get; private set; } public XamlVisibleAttribute() : this(visible: true) { } public XamlVisibleAttribute(bool visible) { Visible = visible; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SecurityNoteAttribute : Attribute { public string Critical { get; set; } public string Safe { get; set; } public string Miscellaneous { get; set; } } } private abstract class Thunk<T> where T : class { [SecurityCritical] private T callback; internal T Callback { [SecuritySafeCritical] get { return callback; } } [SecuritySafeCritical] protected Thunk(T callback) { this.callback = callback; } } private sealed class ActionThunk<T1> : Thunk<Action<T1>> { public Action<T1> ThunkFrame => UnhandledExceptionFrame; public ActionThunk(Action<T1> callback) : base(callback) { } [SecuritySafeCritical] private void UnhandledExceptionFrame(T1 result) { RuntimeHelpers.PrepareConstrainedRegions(); try { base.Callback(result); } catch (Exception exception) { if (!HandleAtThreadBase(exception)) { throw; } } } } private sealed class AsyncThunk : Thunk<AsyncCallback> { public AsyncCallback ThunkFrame => UnhandledExceptionFrame; public AsyncThunk(AsyncCallback callback) : base(callback) { } [SecuritySafeCritical] private void UnhandledExceptionFrame(IAsyncResult result) { RuntimeHelpers.PrepareConstrainedRegions(); try { base.Callback(result); } catch (Exception exception) { if (!HandleAtThreadBase(exception)) { throw; } } } } private sealed class WaitThunk : Thunk<WaitCallback> { public WaitCallback ThunkFrame => UnhandledExceptionFrame; public WaitThunk(WaitCallback callback) : base(callback) { } [SecuritySafeCritical] private void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { base.Callback(state); } catch (Exception exception) { if (!HandleAtThreadBase(exception)) { throw; } } } } private sealed class TimerThunk : Thunk<TimerCallback> { public TimerCallback ThunkFrame => UnhandledExceptionFrame; public TimerThunk(TimerCallback callback) : base(callback) { } [SecuritySafeCritical] private void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { base.Callback(state); } catch (Exception exception) { if (!HandleAtThreadBase(exception)) { throw; } } } } private sealed class WaitOrTimerThunk : Thunk<WaitOrTimerCallback> { public WaitOrTimerCallback ThunkFrame => UnhandledExceptionFrame; public WaitOrTimerThunk(WaitOrTimerCallback callback) : base(callback) { } [SecuritySafeCritical] private void UnhandledExceptionFrame(object state, bool timedOut) { RuntimeHelpers.PrepareConstrainedRegions(); try { base.Callback(state, timedOut); } catch (Exception exception) { if (!HandleAtThreadBase(exception)) { throw; } } } } private sealed class SendOrPostThunk : Thunk<SendOrPostCallback> { public SendOrPostCallback ThunkFrame => UnhandledExceptionFrame; public SendOrPostThunk(SendOrPostCallback callback) : base(callback) { } [SecuritySafeCritical] private void UnhandledExceptionFrame(object state) { RuntimeHelpers.PrepareConstrainedRegions(); try { base.Callback(state); } catch (Exception exception) { if (!HandleAtThreadBase(exception)) { throw; } } } } [SecurityCritical] private sealed class IOCompletionThunk { private IOCompletionCallback callback; public unsafe IOCompletionCallback ThunkFrame => UnhandledExceptionFrame; public IOCompletionThunk(IOCompletionCallback callback) { this.callback = callback; } private unsafe void UnhandledExceptionFrame(uint error, uint bytesRead, NativeOverlapped* nativeOverlapped) { RuntimeHelpers.PrepareConstrainedRegions(); try { callback(error, bytesRead, nativeOverlapped); } catch (Exception exception) { if (!HandleAtThreadBase(exception)) { throw; } } } } [Serializable] private class InternalException : SystemException { public InternalException(string description) : base(InternalSR.ShipAssertExceptionMessage(description)) { } protected InternalException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] private class FatalInternalException : InternalException { public FatalInternalException(string description) : base(description) { } protected FatalInternalException(SerializationInfo info, StreamingContext context) : base(info, context) { } } private const string defaultEventSource = "System.Runtime"; private static ExceptionTrace exceptionTrace; private static EtwDiagnosticTrace diagnosticTrace; [SecurityCritical] private static ExceptionHandler asynchronousThreadExceptionHandler; public static ExceptionTrace Exception { get { if (exceptionTrace == null) { exceptionTrace = new ExceptionTrace("System.Runtime", Trace); } return exceptionTrace; } } public static EtwDiagnosticTrace Trace { get { if (diagnosticTrace == null) { diagnosticTrace = InitializeTracing(); } return diagnosticTrace; } } public static ExceptionHandler AsynchronousThreadExceptionHandler { [SecuritySafeCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return asynchronousThreadExceptionHandler; } [SecurityCritical] set { asynchronousThreadExceptionHandler = value; } } internal static bool AssertsFailFast => false; internal static Type[] BreakOnExceptionTypes => null; internal static bool FastDebug => false; internal static bool StealthDebugger => false; [SecuritySafeCritical] private static EtwDiagnosticTrace InitializeTracing() { EtwDiagnosticTrace etwDiagnosticTrace = new EtwDiagnosticTrace("System.Runtime", EtwDiagnosticTrace.DefaultEtwProviderId); if (etwDiagnosticTrace.EtwProvider != null) { etwDiagnosticTrace.RefreshState = (Action)Delegate.Combine(etwDiagnosticTrace.RefreshState, (Action)delegate { UpdateLevel(); }); } UpdateLevel(etwDiagnosticTrace); return etwDiagnosticTrace; } [Conditional("DEBUG")] public static void Assert(bool condition, string description) { } [Conditional("DEBUG")] public static void Assert(string description) { AssertHelper.FireAssert(description); } public static void AssertAndThrow(bool condition, string description) { if (!condition) { AssertAndThrow(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrow(string description) { TraceCore.ShipAssertExceptionMessage(Trace, description); throw new InternalException(description); } public static void AssertAndThrowFatal(bool condition, string description) { if (!condition) { AssertAndThrowFatal(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrowFatal(string description) { TraceCore.ShipAssertExceptionMessage(Trace, description); throw new FatalInternalException(description); } public static void AssertAndFailFast(bool condition, string description) { if (!condition) { AssertAndFailFast(description); } } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] public static Exception AssertAndFailFast(string description) { string message = InternalSR.FailFastMessage(description); try { try { Exception.TraceFailFast(message); } finally { Environment.FailFast(message); } } catch { throw; } return null; } public static bool IsFatal(Exception exception) { while (exception != null) { if (exception is FatalException || (exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) || exception is ThreadAbortException || exception is FatalInternalException) { return true; } if (exception is TypeInitializationException || exception is TargetInvocationException) { exception = exception.InnerException; continue; } if (!(exception is AggregateException)) { break; } foreach (Exception innerException in ((AggregateException)exception).InnerExceptions) { if (IsFatal(innerException)) { return true; } } break; } return false; } public static Action<T1> ThunkCallback<T1>(Action<T1> callback) { return new ActionThunk<T1>(callback).ThunkFrame; } public static AsyncCallback ThunkCallback(AsyncCallback callback) { return new AsyncThunk(callback).ThunkFrame; } public static WaitCallback ThunkCallback(WaitCallback callback) { return new WaitThunk(callback).ThunkFrame; } public static TimerCallback ThunkCallback(TimerCallback callback) { return new TimerThunk(callback).ThunkFrame; } public static WaitOrTimerCallback ThunkCallback(WaitOrTimerCallback callback) { return new WaitOrTimerThunk(callback).ThunkFrame; } public static SendOrPostCallback ThunkCallback(SendOrPostCallback callback) { return new SendOrPostThunk(callback).ThunkFrame; } [SecurityCritical] public static IOCompletionCallback ThunkCallback(IOCompletionCallback callback) { return new IOCompletionThunk(callback).ThunkFrame; } public static Guid CreateGuid(string guidString) { bool flag = false; Guid empty = Guid.Empty; try { empty = new Guid(guidString); flag = true; return empty; } finally { if (!flag) { AssertAndThrow("Creation of the Guid failed."); } } } public static bool TryCreateGuid(string guidString, out Guid result) { bool result2 = false; result = Guid.Empty; try { result = new Guid(guidString); result2 = true; } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } return result2; } public static byte[] AllocateByteArray(int size) { try { return new byte[size]; } catch (OutOfMemoryException innerException) { throw Exception.AsError(new InsufficientMemoryException(InternalSR.BufferAllocationFailed(size), innerException)); } } public static char[] AllocateCharArray(int size) { try { return new char[size]; } catch (OutOfMemoryException innerException) { throw Exception.AsError(new InsufficientMemoryException(InternalSR.BufferAllocationFailed(size * 2), innerException)); } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static void TraceExceptionNoThrow(Exception exception) { try { Exception.TraceUnhandledException(exception); } catch { } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static bool HandleAtThreadBase(Exception exception) { if (exception == null) { return false; } TraceExceptionNoThrow(exception); try { return AsynchronousThreadExceptionHandler?.HandleException(exception) ?? false; } catch (Exception exception2) { TraceExceptionNoThrow(exception2); } return false; } private static void UpdateLevel(EtwDiagnosticTrace trace) { if (trace != null && (TraceCore.ActionItemCallbackInvokedIsEnabled(trace) || TraceCore.ActionItemScheduledIsEnabled(trace))) { trace.SetEnd2EndActivityTracingEnabled(isEnd2EndTracingEnabled: true); } } private static void UpdateLevel() { UpdateLevel(Trace); } } internal static class FxCop { public static class Category { public const string Design = "Microsoft.Design"; public const string Globalization = "Microsoft.Globalization"; public const string Maintainability = "Microsoft.Maintainability"; public const string MSInternal = "Microsoft.MSInternal"; public const string Naming = "Microsoft.Naming"; public const string Performance = "Microsoft.Performance"; public const string Reliability = "Microsoft.Reliability"; public const string Security = "Microsoft.Security"; public const string Usage = "Microsoft.Usage"; public const string Configuration = "Configuration"; public const string ReliabilityBasic = "Reliability"; public const string Xaml = "XAML"; } public static class Rule { public const string AptcaMethodsShouldOnlyCallAptcaMethods = "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods"; public const string AssembliesShouldHaveValidStrongNames = "CA2210:AssembliesShouldHaveValidStrongNames"; public const string AvoidCallingProblematicMethods = "CA2001:AvoidCallingProblematicMethods"; public const string AvoidExcessiveComplexity = "CA1502:AvoidExcessiveComplexity"; public const string AvoidNamespacesWithFewTypes = "CA1020:AvoidNamespacesWithFewTypes"; public const string AvoidOutParameters = "CA1021:AvoidOutParameters"; public const string AvoidUncalledPrivateCode = "CA1811:AvoidUncalledPrivateCode"; public const string AvoidUninstantiatedInternalClasses = "CA1812:AvoidUninstantiatedInternalClasses"; public const string AvoidUnsealedAttributes = "CA1813:AvoidUnsealedAttributes"; public const string CollectionPropertiesShouldBeReadOnly = "CA2227:CollectionPropertiesShouldBeReadOnly"; public const string CollectionsShouldImplementGenericInterface = "CA1010:CollectionsShouldImplementGenericInterface"; public const string ConfigurationPropertyAttributeRule = "Configuration102:ConfigurationPropertyAttributeRule"; public const string ConfigurationValidatorAttributeRule = "Configuration104:ConfigurationValidatorAttributeRule"; public const string ConsiderPassingBaseTypesAsParameters = "CA1011:ConsiderPassingBaseTypesAsParameters"; public const string CommunicationObjectThrowIf = "Reliability106"; public const string ConfigurationPropertyNameRule = "Configuration103:ConfigurationPropertyNameRule"; public const string DefaultParametersShouldNotBeUsed = "CA1026:DefaultParametersShouldNotBeUsed"; public const string DefineAccessorsForAttributeArguments = "CA1019:DefineAccessorsForAttributeArguments"; public const string DiagnosticsUtilityIsFatal = "Reliability108"; public const string DisposableFieldsShouldBeDisposed = "CA2213:DisposableFieldsShouldBeDisposed"; public const string DoNotCallOverridableMethodsInConstructors = "CA2214:DoNotCallOverridableMethodsInConstructors"; public const string DoNotCatchGeneralExceptionTypes = "CA1031:DoNotCatchGeneralExceptionTypes"; public const string DoNotDeclareReadOnlyMutableReferenceTypes = "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes"; public const string DoNotDeclareVisibleInstanceFields = "CA1051:DoNotDeclareVisibleInstanceFields"; public const string DoNotLockOnObjectsWithWeakIdentity = "CA2002:DoNotLockOnObjectsWithWeakIdentity"; public const string DoNotIgnoreMethodResults = "CA1806:DoNotIgnoreMethodResults"; public const string DoNotIndirectlyExposeMethodsWithLinkDemands = "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands"; public const string DoNotPassLiteralsAsLocalizedParameters = "CA1303:DoNotPassLiteralsAsLocalizedParameters"; public const string DoNotRaiseReservedExceptionTypes = "CA2201:DoNotRaiseReservedExceptionTypes"; public const string EnumsShouldHaveZeroValue = "CA1008:EnumsShouldHaveZeroValue"; public const string FlagsEnumsShouldHavePluralNames = "CA1714:FlagsEnumsShouldHavePluralNames"; public const string GenericMethodsShouldProvideTypeParameter = "CA1004:GenericMethodsShouldProvideTypeParameter"; public const string IdentifiersShouldBeSpelledCorrectly = "CA1704:IdentifiersShouldBeSpelledCorrectly"; public const string IdentifiersShouldHaveCorrectSuffix = "CA1710:IdentifiersShouldHaveCorrectSuffix"; public const string IdentifiersShouldNotContainTypeNames = "CA1720:IdentifiersShouldNotContainTypeNames"; public const string IdentifiersShouldNotHaveIncorrectSuffix = "CA1711:IdentifiersShouldNotHaveIncorrectSuffix"; public const string IdentifiersShouldNotMatchKeywords = "CA1716:IdentifiersShouldNotMatchKeywords"; public const string ImplementStandardExceptionConstructors = "CA1032:ImplementStandardExceptionConstructors"; public const string InstantiateArgumentExceptionsCorrectly = "CA2208:InstantiateArgumentExceptionsCorrectly"; public const string InitializeReferenceTypeStaticFieldsInline = "CA1810:InitializeReferenceTypeStaticFieldsInline"; public const string InterfaceMethodsShouldBeCallableByChildTypes = "CA1033:InterfaceMethodsShouldBeCallableByChildTypes"; public const string MarkISerializableTypesWithSerializable = "CA2237:MarkISerializableTypesWithSerializable"; public const string InvariantAssertRule = "Reliability101:InvariantAssertRule"; public const string IsFatalRule = "Reliability108:IsFatalRule"; public const string MarkMembersAsStatic = "CA1822:MarkMembersAsStatic"; public const string NestedTypesShouldNotBeVisible = "CA1034:NestedTypesShouldNotBeVisible"; public const string NormalizeStringsToUppercase = "CA1308:NormalizeStringsToUppercase"; public const string OperatorOverloadsHaveNamedAlternates = "CA2225:OperatorOverloadsHaveNamedAlternates"; public const string PropertyNamesShouldNotMatchGetMethods = "CA1721:PropertyNamesShouldNotMatchGetMethods"; public const string PropertyTypesMustBeXamlVisible = "XAML1002:PropertyTypesMustBeXamlVisible"; public const string PropertyExternalTypesMustBeKnown = "XAML1010:PropertyExternalTypesMustBeKnown"; public const string ReplaceRepetitiveArgumentsWithParamsArray = "CA1025:ReplaceRepetitiveArgumentsWithParamsArray"; public const string ResourceStringsShouldBeSpelledCorrectly = "CA1703:ResourceStringsShouldBeSpelledCorrectly"; public const string ReviewSuppressUnmanagedCodeSecurityUsage = "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"; public const string ReviewUnusedParameters = "CA1801:ReviewUnusedParameters"; public const string SecureAsserts = "CA2106:SecureAsserts"; public const string SecureGetObjectDataOverrides = "CA2110:SecureGetObjectDataOverrides"; public const string ShortAcronymsShouldBeUppercase = "CA1706:ShortAcronymsShouldBeUppercase"; public const string SpecifyIFormatProvider = "CA1305:SpecifyIFormatProvider"; public const string SpecifyMarshalingForPInvokeStringArguments = "CA2101:SpecifyMarshalingForPInvokeStringArguments"; public const string StaticHolderTypesShouldNotHaveConstructors = "CA1053:StaticHolderTypesShouldNotHaveConstructors"; public const string SystemAndMicrosoftNamespacesRequireApproval = "CA:SystemAndMicrosoftNamespacesRequireApproval"; public const string UsePropertiesWhereAppropriate = "CA1024:UsePropertiesWhereAppropriate"; public const string UriPropertiesShouldNotBeStrings = "CA1056:UriPropertiesShouldNotBeStrings"; public const string VariableNamesShouldNotMatchFieldNames = "CA1500:VariableNamesShouldNotMatchFieldNames"; public const string ThunkCallbackRule = "Reliability109:ThunkCallbackRule"; public const string TransparentMethodsMustNotReferenceCriticalCode = "CA2140:TransparentMethodsMustNotReferenceCriticalCodeFxCopRule"; public const string TypeConvertersMustBePublic = "XAML1004:TypeConvertersMustBePublic"; public const string TypesMustHaveXamlCallableConstructors = "XAML1007:TypesMustHaveXamlCallableConstructors"; public const string TypeNamesShouldNotMatchNamespaces = "CA1724:TypeNamesShouldNotMatchNamespaces"; public const string TypesShouldHavePublicParameterlessConstructors = "XAML1009:TypesShouldHavePublicParameterlessConstructors"; public const string UseEventsWhereAppropriate = "CA1030:UseEventsWhereAppropriate"; public const string UseNewGuidHelperRule = "Reliability113:UseNewGuidHelperRule"; public const string WrapExceptionsRule = "Reliability102:WrapExceptionsRule"; } } internal static class HashHelper { public static byte[] ComputeHash(byte[] buffer) { int[] array = new int[16] { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 }; uint[] array2 = new uint[64] { 3614090360u, 3905402710u, 606105819u, 3250441966u, 4118548399u, 1200080426u, 2821735955u, 4249261313u, 1770035416u, 2336552879u, 4294925233u, 2304563134u, 1804603682u, 4254626195u, 2792965006u, 1236535329u, 4129170786u, 3225465664u, 643717713u, 3921069994u, 3593408605u, 38016083u, 3634488961u, 3889429448u, 568446438u, 3275163606u, 4107603335u, 1163531501u, 2850285829u, 4243563512u, 1735328473u, 2368359562u, 4294588738u, 2272392833u, 1839030562u, 4259657740u, 2763975236u, 1272893353u, 4139469664u, 3200236656u, 681279174u, 3936430074u, 3572445317u, 76029189u, 3654602809u, 3873151461u, 530742520u, 3299628645u, 4096336452u, 1126891415u, 2878612391u, 4237533241u, 1700485571u, 2399980690u, 4293915773u, 2240044497u, 1873313359u, 4264355552u, 2734768916u, 1309151649u, 4149444226u, 3174756917u, 718787259u, 3951481745u }; int num = (buffer.Length + 8) / 64 + 1; uint num2 = 1732584193u; uint num3 = 4023233417u; uint num4 = 2562383102u; uint num5 = 271733878u; for (int i = 0; i < num; i++) { byte[] array3 = buffer; int num6 = i * 64; if (num6 + 64 > buffer.Length) { array3 = new byte[64]; for (int j = num6; j < buffer.Length; j++) { array3[j - num6] = buffer[j]; } if (num6 <= buffer.Length) { array3[buffer.Length - num6] = 128; } if (i == num - 1) { array3[56] = (byte)(buffer.Length << 3); array3[57] = (byte)(buffer.Length >> 5); array3[58] = (byte)(buffer.Length >> 13); array3[59] = (byte)(buffer.Length >> 21); } num6 = 0; } uint num7 = num2; uint num8 = num3; uint num9 = num4; uint num10 = num5; for (int k = 0; k < 64; k++) { uint num11; int num12; if (k < 16) { num11 = (num8 & num9) | (~num8 & num10); num12 = k; } else if (k < 32) { num11 = (num8 & num10) | (num9 & ~num10); num12 = 5 * k + 1; } else if (k < 48) { num11 = num8 ^ num9 ^ num10; num12 = 3 * k + 5; } else { num11 = num9 ^ (num8 | ~num10); num12 = 7 * k; } num12 = (num12 & 0xF) * 4 + num6; uint num13 = num10; num10 = num9; num9 = num8; num8 = num7 + num11 + array2[k] + (uint)(array3[num12] + (array3[num12 + 1] << 8) + (array3[num12 + 2] << 16) + (array3[num12 + 3] << 24)); num8 = (num8 << array[(k & 3) | ((k >> 2) & -4)]) | (num8 >> 32 - array[(k & 3) | ((k >> 2) & -4)]); num8 += num9; num7 = num13; } num2 += num7; num3 += num8; num4 += num9; num5 += num10; } return new byte[16] { (byte)num2, (byte)(num2 >> 8), (byte)(num2 >> 16), (byte)(num2 >> 24), (byte)num3, (byte)(num3 >> 8), (byte)(num3 >> 16), (byte)(num3 >> 24), (byte)num4, (byte)(num4 >> 8), (byte)(num4 >> 16), (byte)(num4 >> 24), (byte)num5, (byte)(num5 >> 8), (byte)(num5 >> 16), (byte)(num5 >> 24) }; } } internal interface IAsyncEventArgs { object AsyncState { get; } Exception Exception { get; } } internal class IOThreadCancellationTokenSource : IDisposable { private static readonly Action<object> onCancel = Fx.ThunkCallback<object>(OnCancel); private readonly TimeSpan timeout; private CancellationTokenSource source; private CancellationToken? token; private IOThreadTimer timer; public CancellationToken Token { get { if (!token.HasValue) { if (timeout >= TimeoutHelper.MaxWait) { token = CancellationToken.None; } else { timer = new IOThreadTimer(onCancel, this, isTypicallyCanceledShortlyAfterBeingSet: true); source = new CancellationTokenSource(); timer.Set(timeout); token = source.Token; } } return token.Value; } } public IOThreadCancellationTokenSource(TimeSpan timeout) { TimeoutHelper.ThrowIfNegativeArgument(timeout); this.timeout = timeout; } public IOThreadCancellationTokenSource(int timeout) : this(TimeSpan.FromMilliseconds(timeout)) { } public void Dispose() { if (source != null && timer.Cancel()) { source.Dispose(); source = null; } } private static void OnCancel(object obj) { ((IOThreadCancellationTokenSource)obj).Cancel(); } private void Cancel() { source.Cancel(); source.Dispose(); source = null; } } internal class IOThreadScheduler { private static class Bits { public const int HiShift = 16; public const int HiOne = 65536; public const int LoHiBit = 32768; public const int HiHiBit = int.MinValue; public const int LoCountMask = 32767; public const int HiCountMask = 2147418112; public const int LoMask = 65535; public const int HiMask = -65536; public const int HiBits = -2147450880; public static int Count(int slot) { return (((slot >> 16) - slot + 2) & 0xFFFF) - 1; } public static int CountNoIdle(int slot) { return ((slot >> 16) - slot + 1) & 0xFFFF; } public static int IncrementLo(int slot) { return ((slot + 1) & 0xFFFF) | (slot & -65536); } public static bool IsComplete(int gate) { return (gate & -65536) == gate << 16; } } private struct Slot { private int gate; private Action<object> callback; private object state; public bool TryEnqueueWorkItem(Action<object> callback, object state, out bool wrapped) { int num = Interlocked.Increment(ref gate); wrapped = (num & 0x7FFF) != 1; if (wrapped) { if (((uint)num & 0x8000u) != 0 && Bits.IsComplete(num)) { Interlocked.CompareExchange(ref gate, 0, num); } return false; } this.state = state; this.callback = callback; num = Interlocked.Add(ref gate, 32768); if ((num & 0x7FFF0000) == 0) { return true; } this.state = null; this.callback = null; if (num >> 16 != (num & 0x7FFF) || Interlocked.CompareExchange(ref gate, 0, num) != num) { num = Interlocked.Add(ref gate, int.MinValue); if (Bits.IsComplete(num)) { Interlocked.CompareExchange(ref gate, 0, num); } } return false; } public void DequeueWorkItem(out Action<object> callback, out object state) { int num = Interlocked.Add(ref gate, 65536); if ((num & 0x8000) == 0) { callback = null; state = null; } else if ((num & 0x7FFF0000) == 65536) { callback = this.callback; state = this.state; this.state = null; this.callback = null; if ((num & 0x7FFF) != 1 || Interlocked.CompareExchange(ref gate, 0, num) != num) { num = Interlocked.Add(ref gate, int.MinValue); if (Bits.IsComplete(num)) { Interlocked.CompareExchange(ref gate, 0, num); } } } else { callback = null; state = null; if (Bits.IsComplete(num)) { Interlocked.CompareExchange(ref gate, 0, num); } } } } [SecurityCritical] private class ScheduledOverlapped { private unsafe readonly NativeOverlapped* nativeOverlapped; private IOThreadScheduler scheduler; public unsafe ScheduledOverlapped() { nativeOverlapped = new Overlapped().UnsafePack(Fx.ThunkCallback(IOCallback), null); } private unsafe void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { IOThreadScheduler iOThreadScheduler = scheduler; scheduler = null; Action<object> callback; object state; try { } finally { iOThreadScheduler.CompletionCallback(out callback, out state); } bool flag = true; while (flag) { callback?.Invoke(state); try { } finally { flag = iOThreadScheduler.TryCoalesce(out callback, out state); } } } public unsafe void Post(IOThreadScheduler iots) { scheduler = iots; ThreadPool.UnsafeQueueNativeOverlapped(nativeOverlapped); } public unsafe void Cleanup() { if (scheduler != null) { throw Fx.AssertAndThrowFatal("Cleanup called on an overlapped that is in-flight."); } Overlapped.Free(nativeOverlapped); } } private
deps/System.Text.Encoding.CodePages.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Text.Encoding.CodePages; using Microsoft.CodeAnalysis; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Encoding.CodePages")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides support for code-page based encodings, including Windows-1252, Shift-JIS, and GB2312.\r\n\r\nCommonly Used Types:\r\nSystem.Text.CodePagesEncodingProvider")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Encoding.CodePages")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 FxResources.System.Text.Encoding.CodePages { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); internal static string ArgumentOutOfRange_IndexCount => GetResourceString("ArgumentOutOfRange_IndexCount"); internal static string ArgumentOutOfRange_IndexCountBuffer => GetResourceString("ArgumentOutOfRange_IndexCountBuffer"); internal static string NotSupported_NoCodepageData => GetResourceString("NotSupported_NoCodepageData"); internal static string Argument_EncodingConversionOverflowBytes => GetResourceString("Argument_EncodingConversionOverflowBytes"); internal static string Argument_InvalidCharSequenceNoIndex => GetResourceString("Argument_InvalidCharSequenceNoIndex"); internal static string ArgumentOutOfRange_GetByteCountOverflow => GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"); internal static string Argument_EncodingConversionOverflowChars => GetResourceString("Argument_EncodingConversionOverflowChars"); internal static string ArgumentOutOfRange_GetCharCountOverflow => GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"); internal static string Argument_EncoderFallbackNotEmpty => GetResourceString("Argument_EncoderFallbackNotEmpty"); internal static string Argument_RecursiveFallback => GetResourceString("Argument_RecursiveFallback"); internal static string Argument_RecursiveFallbackBytes => GetResourceString("Argument_RecursiveFallbackBytes"); internal static string ArgumentOutOfRange_Range => GetResourceString("ArgumentOutOfRange_Range"); internal static string Argument_CodepageNotSupported => GetResourceString("Argument_CodepageNotSupported"); internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess"); internal static string ArgumentOutOfRange_IndexMustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_IndexMustBeLessOrEqual"); internal static string MissingEncodingNameResource => GetResourceString("MissingEncodingNameResource"); internal static string Globalization_cp_37 => GetResourceString("Globalization_cp_37"); internal static string Globalization_cp_437 => GetResourceString("Globalization_cp_437"); internal static string Globalization_cp_500 => GetResourceString("Globalization_cp_500"); internal static string Globalization_cp_708 => GetResourceString("Globalization_cp_708"); internal static string Globalization_cp_720 => GetResourceString("Globalization_cp_720"); internal static string Globalization_cp_737 => GetResourceString("Globalization_cp_737"); internal static string Globalization_cp_775 => GetResourceString("Globalization_cp_775"); internal static string Globalization_cp_850 => GetResourceString("Globalization_cp_850"); internal static string Globalization_cp_852 => GetResourceString("Globalization_cp_852"); internal static string Globalization_cp_855 => GetResourceString("Globalization_cp_855"); internal static string Globalization_cp_857 => GetResourceString("Globalization_cp_857"); internal static string Globalization_cp_858 => GetResourceString("Globalization_cp_858"); internal static string Globalization_cp_860 => GetResourceString("Globalization_cp_860"); internal static string Globalization_cp_861 => GetResourceString("Globalization_cp_861"); internal static string Globalization_cp_862 => GetResourceString("Globalization_cp_862"); internal static string Globalization_cp_863 => GetResourceString("Globalization_cp_863"); internal static string Globalization_cp_864 => GetResourceString("Globalization_cp_864"); internal static string Globalization_cp_865 => GetResourceString("Globalization_cp_865"); internal static string Globalization_cp_866 => GetResourceString("Globalization_cp_866"); internal static string Globalization_cp_869 => GetResourceString("Globalization_cp_869"); internal static string Globalization_cp_870 => GetResourceString("Globalization_cp_870"); internal static string Globalization_cp_874 => GetResourceString("Globalization_cp_874"); internal static string Globalization_cp_875 => GetResourceString("Globalization_cp_875"); internal static string Globalization_cp_932 => GetResourceString("Globalization_cp_932"); internal static string Globalization_cp_936 => GetResourceString("Globalization_cp_936"); internal static string Globalization_cp_949 => GetResourceString("Globalization_cp_949"); internal static string Globalization_cp_950 => GetResourceString("Globalization_cp_950"); internal static string Globalization_cp_1026 => GetResourceString("Globalization_cp_1026"); internal static string Globalization_cp_1047 => GetResourceString("Globalization_cp_1047"); internal static string Globalization_cp_1140 => GetResourceString("Globalization_cp_1140"); internal static string Globalization_cp_1141 => GetResourceString("Globalization_cp_1141"); internal static string Globalization_cp_1142 => GetResourceString("Globalization_cp_1142"); internal static string Globalization_cp_1143 => GetResourceString("Globalization_cp_1143"); internal static string Globalization_cp_1144 => GetResourceString("Globalization_cp_1144"); internal static string Globalization_cp_1145 => GetResourceString("Globalization_cp_1145"); internal static string Globalization_cp_1146 => GetResourceString("Globalization_cp_1146"); internal static string Globalization_cp_1147 => GetResourceString("Globalization_cp_1147"); internal static string Globalization_cp_1148 => GetResourceString("Globalization_cp_1148"); internal static string Globalization_cp_1149 => GetResourceString("Globalization_cp_1149"); internal static string Globalization_cp_1250 => GetResourceString("Globalization_cp_1250"); internal static string Globalization_cp_1251 => GetResourceString("Globalization_cp_1251"); internal static string Globalization_cp_1252 => GetResourceString("Globalization_cp_1252"); internal static string Globalization_cp_1253 => GetResourceString("Globalization_cp_1253"); internal static string Globalization_cp_1254 => GetResourceString("Globalization_cp_1254"); internal static string Globalization_cp_1255 => GetResourceString("Globalization_cp_1255"); internal static string Globalization_cp_1256 => GetResourceString("Globalization_cp_1256"); internal static string Globalization_cp_1257 => GetResourceString("Globalization_cp_1257"); internal static string Globalization_cp_1258 => GetResourceString("Globalization_cp_1258"); internal static string Globalization_cp_1361 => GetResourceString("Globalization_cp_1361"); internal static string Globalization_cp_10000 => GetResourceString("Globalization_cp_10000"); internal static string Globalization_cp_10001 => GetResourceString("Globalization_cp_10001"); internal static string Globalization_cp_10002 => GetResourceString("Globalization_cp_10002"); internal static string Globalization_cp_10003 => GetResourceString("Globalization_cp_10003"); internal static string Globalization_cp_10004 => GetResourceString("Globalization_cp_10004"); internal static string Globalization_cp_10005 => GetResourceString("Globalization_cp_10005"); internal static string Globalization_cp_10006 => GetResourceString("Globalization_cp_10006"); internal static string Globalization_cp_10007 => GetResourceString("Globalization_cp_10007"); internal static string Globalization_cp_10008 => GetResourceString("Globalization_cp_10008"); internal static string Globalization_cp_10010 => GetResourceString("Globalization_cp_10010"); internal static string Globalization_cp_10017 => GetResourceString("Globalization_cp_10017"); internal static string Globalization_cp_10021 => GetResourceString("Globalization_cp_10021"); internal static string Globalization_cp_10029 => GetResourceString("Globalization_cp_10029"); internal static string Globalization_cp_10079 => GetResourceString("Globalization_cp_10079"); internal static string Globalization_cp_10081 => GetResourceString("Globalization_cp_10081"); internal static string Globalization_cp_10082 => GetResourceString("Globalization_cp_10082"); internal static string Globalization_cp_20000 => GetResourceString("Globalization_cp_20000"); internal static string Globalization_cp_20001 => GetResourceString("Globalization_cp_20001"); internal static string Globalization_cp_20002 => GetResourceString("Globalization_cp_20002"); internal static string Globalization_cp_20003 => GetResourceString("Globalization_cp_20003"); internal static string Globalization_cp_20004 => GetResourceString("Globalization_cp_20004"); internal static string Globalization_cp_20005 => GetResourceString("Globalization_cp_20005"); internal static string Globalization_cp_20105 => GetResourceString("Globalization_cp_20105"); internal static string Globalization_cp_20106 => GetResourceString("Globalization_cp_20106"); internal static string Globalization_cp_20107 => GetResourceString("Globalization_cp_20107"); internal static string Globalization_cp_20108 => GetResourceString("Globalization_cp_20108"); internal static string Globalization_cp_20261 => GetResourceString("Globalization_cp_20261"); internal static string Globalization_cp_20269 => GetResourceString("Globalization_cp_20269"); internal static string Globalization_cp_20273 => GetResourceString("Globalization_cp_20273"); internal static string Globalization_cp_20277 => GetResourceString("Globalization_cp_20277"); internal static string Globalization_cp_20278 => GetResourceString("Globalization_cp_20278"); internal static string Globalization_cp_20280 => GetResourceString("Globalization_cp_20280"); internal static string Globalization_cp_20284 => GetResourceString("Globalization_cp_20284"); internal static string Globalization_cp_20285 => GetResourceString("Globalization_cp_20285"); internal static string Globalization_cp_20290 => GetResourceString("Globalization_cp_20290"); internal static string Globalization_cp_20297 => GetResourceString("Globalization_cp_20297"); internal static string Globalization_cp_20420 => GetResourceString("Globalization_cp_20420"); internal static string Globalization_cp_20423 => GetResourceString("Globalization_cp_20423"); internal static string Globalization_cp_20424 => GetResourceString("Globalization_cp_20424"); internal static string Globalization_cp_20833 => GetResourceString("Globalization_cp_20833"); internal static string Globalization_cp_20838 => GetResourceString("Globalization_cp_20838"); internal static string Globalization_cp_20866 => GetResourceString("Globalization_cp_20866"); internal static string Globalization_cp_20871 => GetResourceString("Globalization_cp_20871"); internal static string Globalization_cp_20880 => GetResourceString("Globalization_cp_20880"); internal static string Globalization_cp_20905 => GetResourceString("Globalization_cp_20905"); internal static string Globalization_cp_20924 => GetResourceString("Globalization_cp_20924"); internal static string Globalization_cp_20932 => GetResourceString("Globalization_cp_20932"); internal static string Globalization_cp_20936 => GetResourceString("Globalization_cp_20936"); internal static string Globalization_cp_20949 => GetResourceString("Globalization_cp_20949"); internal static string Globalization_cp_21025 => GetResourceString("Globalization_cp_21025"); internal static string Globalization_cp_21027 => GetResourceString("Globalization_cp_21027"); internal static string Globalization_cp_21866 => GetResourceString("Globalization_cp_21866"); internal static string Globalization_cp_28592 => GetResourceString("Globalization_cp_28592"); internal static string Globalization_cp_28593 => GetResourceString("Globalization_cp_28593"); internal static string Globalization_cp_28594 => GetResourceString("Globalization_cp_28594"); internal static string Globalization_cp_28595 => GetResourceString("Globalization_cp_28595"); internal static string Globalization_cp_28596 => GetResourceString("Globalization_cp_28596"); internal static string Globalization_cp_28597 => GetResourceString("Globalization_cp_28597"); internal static string Globalization_cp_28598 => GetResourceString("Globalization_cp_28598"); internal static string Globalization_cp_28599 => GetResourceString("Globalization_cp_28599"); internal static string Globalization_cp_28603 => GetResourceString("Globalization_cp_28603"); internal static string Globalization_cp_28605 => GetResourceString("Globalization_cp_28605"); internal static string Globalization_cp_29001 => GetResourceString("Globalization_cp_29001"); internal static string Globalization_cp_38598 => GetResourceString("Globalization_cp_38598"); internal static string Globalization_cp_50000 => GetResourceString("Globalization_cp_50000"); internal static string Globalization_cp_50220 => GetResourceString("Globalization_cp_50220"); internal static string Globalization_cp_50221 => GetResourceString("Globalization_cp_50221"); internal static string Globalization_cp_50222 => GetResourceString("Globalization_cp_50222"); internal static string Globalization_cp_50225 => GetResourceString("Globalization_cp_50225"); internal static string Globalization_cp_50227 => GetResourceString("Globalization_cp_50227"); internal static string Globalization_cp_50229 => GetResourceString("Globalization_cp_50229"); internal static string Globalization_cp_50930 => GetResourceString("Globalization_cp_50930"); internal static string Globalization_cp_50931 => GetResourceString("Globalization_cp_50931"); internal static string Globalization_cp_50933 => GetResourceString("Globalization_cp_50933"); internal static string Globalization_cp_50935 => GetResourceString("Globalization_cp_50935"); internal static string Globalization_cp_50937 => GetResourceString("Globalization_cp_50937"); internal static string Globalization_cp_50939 => GetResourceString("Globalization_cp_50939"); internal static string Globalization_cp_51932 => GetResourceString("Globalization_cp_51932"); internal static string Globalization_cp_51936 => GetResourceString("Globalization_cp_51936"); internal static string Globalization_cp_51949 => GetResourceString("Globalization_cp_51949"); internal static string Globalization_cp_52936 => GetResourceString("Globalization_cp_52936"); internal static string Globalization_cp_54936 => GetResourceString("Globalization_cp_54936"); internal static string Globalization_cp_57002 => GetResourceString("Globalization_cp_57002"); internal static string Globalization_cp_57003 => GetResourceString("Globalization_cp_57003"); internal static string Globalization_cp_57004 => GetResourceString("Globalization_cp_57004"); internal static string Globalization_cp_57005 => GetResourceString("Globalization_cp_57005"); internal static string Globalization_cp_57006 => GetResourceString("Globalization_cp_57006"); internal static string Globalization_cp_57007 => GetResourceString("Globalization_cp_57007"); internal static string Globalization_cp_57008 => GetResourceString("Globalization_cp_57008"); internal static string Globalization_cp_57009 => GetResourceString("Globalization_cp_57009"); internal static string Globalization_cp_57010 => GetResourceString("Globalization_cp_57010"); internal static string Globalization_cp_57011 => GetResourceString("Globalization_cp_57011"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.Versioning { internal abstract class OSPlatformAttribute : Attribute { public string PlatformName { get; } private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } public UnsupportedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public string Url { get; set; } public ObsoletedOSPlatformAttribute(string platformName) : base(platformName) { } public ObsoletedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute { public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute { public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Text { internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable { [StructLayout(LayoutKind.Explicit)] internal struct CodePageDataFileHeader { [FieldOffset(0)] internal char TableName; [FieldOffset(32)] internal ushort Version; [FieldOffset(40)] internal short CodePageCount; [FieldOffset(42)] internal short unused1; } [StructLayout(LayoutKind.Explicit, Pack = 2)] internal struct CodePageIndex { [FieldOffset(0)] internal char CodePageName; [FieldOffset(32)] internal short CodePage; [FieldOffset(34)] internal short ByteCount; [FieldOffset(36)] internal int Offset; } [StructLayout(LayoutKind.Explicit)] internal struct CodePageHeader { [FieldOffset(0)] internal char CodePageName; [FieldOffset(32)] internal ushort VersionMajor; [FieldOffset(34)] internal ushort VersionMinor; [FieldOffset(36)] internal ushort VersionRevision; [FieldOffset(38)] internal ushort VersionBuild; [FieldOffset(40)] internal short CodePage; [FieldOffset(42)] internal short ByteCount; [FieldOffset(44)] internal char UnicodeReplace; [FieldOffset(46)] internal ushort ByteReplace; } internal const string CODE_PAGE_DATA_FILE_NAME = "codepages.nlp"; protected int dataTableCodePage; protected int iExtraBytes; protected char[] arrayUnicodeBestFit; protected char[] arrayBytesBestFit; private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44; private const int CODEPAGE_HEADER_SIZE = 48; private static readonly byte[] s_codePagesDataHeader = new byte[44]; protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream("codepages.nlp"); protected static readonly object s_streamLock = new object(); protected byte[] m_codePageHeader = new byte[48]; protected int m_firstDataWordOffset; protected int m_dataSize; protected SafeAllocHHandle safeNativeMemoryHandle; internal BaseCodePageEncoding(int codepage) : this(codepage, codepage) { } internal BaseCodePageEncoding(int codepage, int dataCodePage) : base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null)) { ((InternalEncoderBestFitFallback)base.EncoderFallback).encoding = this; ((InternalDecoderBestFitFallback)base.DecoderFallback).encoding = this; dataTableCodePage = dataCodePage; LoadCodePageTables(); } internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codepage, enc, dec) { dataTableCodePage = dataCodePage; LoadCodePageTables(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } private unsafe static void ReadCodePageDataFileHeader(Stream stream, byte[] codePageDataFileHeader) { int num = stream.Read(codePageDataFileHeader, 0, codePageDataFileHeader.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageDataFileHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; char* ptr3 = &ptr2->TableName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ushort* ptr4 = &ptr2->Version; for (int j = 0; j < 4; j++) { ptr4[j] = BinaryPrimitives.ReverseEndianness(ptr4[j]); } ptr2->CodePageCount = BinaryPrimitives.ReverseEndianness(ptr2->CodePageCount); } } private unsafe static void ReadCodePageIndex(Stream stream, byte[] codePageIndex) { int num = stream.Read(codePageIndex, 0, codePageIndex.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageIndex[0]) { CodePageIndex* ptr2 = (CodePageIndex*)ptr; char* ptr3 = &ptr2->CodePageName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage); ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount); ptr2->Offset = BinaryPrimitives.ReverseEndianness(ptr2->Offset); } } private unsafe static void ReadCodePageHeader(Stream stream, byte[] codePageHeader) { int num = stream.Read(codePageHeader, 0, codePageHeader.Length); if (BitConverter.IsLittleEndian) { return; } fixed (byte* ptr = &codePageHeader[0]) { CodePageHeader* ptr2 = (CodePageHeader*)ptr; char* ptr3 = &ptr2->CodePageName; for (int i = 0; i < 16; i++) { ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]); } ptr2->VersionMajor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMajor); ptr2->VersionMinor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMinor); ptr2->VersionRevision = BinaryPrimitives.ReverseEndianness(ptr2->VersionRevision); ptr2->VersionBuild = BinaryPrimitives.ReverseEndianness(ptr2->VersionBuild); ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage); ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount); ptr2->UnicodeReplace = (char)BinaryPrimitives.ReverseEndianness(ptr2->UnicodeReplace); ptr2->ByteReplace = BinaryPrimitives.ReverseEndianness(ptr2->ByteReplace); } } internal static Stream GetEncodingDataStream(string tableName) { Stream manifestResourceStream = typeof(CodePagesEncodingProvider).Assembly.GetManifestResourceStream(tableName); if (manifestResourceStream == null) { throw new InvalidOperationException(); } ReadCodePageDataFileHeader(manifestResourceStream, s_codePagesDataHeader); return manifestResourceStream; } private void LoadCodePageTables() { if (!FindCodePage(dataTableCodePage)) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } LoadManagedCodePage(); } private unsafe bool FindCodePage(int codePage) { byte[] array = new byte[sizeof(CodePageIndex)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin); int codePageCount; fixed (byte* ptr = &s_codePagesDataHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; codePageCount = ptr2->CodePageCount; } fixed (byte* ptr3 = &array[0]) { CodePageIndex* ptr4 = (CodePageIndex*)ptr3; for (int i = 0; i < codePageCount; i++) { ReadCodePageIndex(s_codePagesEncodingDataStream, array); if (ptr4->CodePage == codePage) { long position = s_codePagesEncodingDataStream.Position; s_codePagesEncodingDataStream.Seek(ptr4->Offset, SeekOrigin.Begin); ReadCodePageHeader(s_codePagesEncodingDataStream, m_codePageHeader); m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; if (i == codePageCount - 1) { m_dataSize = (int)(s_codePagesEncodingDataStream.Length - ptr4->Offset - m_codePageHeader.Length); } else { s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin); int offset = ptr4->Offset; ReadCodePageIndex(s_codePagesEncodingDataStream, array); m_dataSize = ptr4->Offset - offset - m_codePageHeader.Length; } return true; } } } } return false; } internal unsafe static int GetCodePageByteSize(int codePage) { byte[] array = new byte[sizeof(CodePageIndex)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin); int codePageCount; fixed (byte* ptr = &s_codePagesDataHeader[0]) { CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr; codePageCount = ptr2->CodePageCount; } fixed (byte* ptr3 = &array[0]) { CodePageIndex* ptr4 = (CodePageIndex*)ptr3; for (int i = 0; i < codePageCount; i++) { ReadCodePageIndex(s_codePagesEncodingDataStream, array); if (ptr4->CodePage == codePage) { return ptr4->ByteCount; } } } } return 0; } protected abstract void LoadManagedCodePage(); protected unsafe byte* GetNativeMemory(int iSize) { if (safeNativeMemoryHandle == null) { byte* ptr = (byte*)(void*)Marshal.AllocHGlobal(iSize); safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)ptr); } return (byte*)(void*)safeNativeMemoryHandle.DangerousGetHandle(); } protected abstract void ReadBestFitTable(); internal char[] GetBestFitUnicodeToBytesData() { if (arrayUnicodeBestFit == null) { ReadBestFitTable(); } return arrayUnicodeBestFit; } internal char[] GetBestFitBytesToUnicodeData() { if (arrayBytesBestFit == null) { ReadBestFitTable(); } return arrayBytesBestFit; } internal void CheckMemorySection() { if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero) { LoadManagedCodePage(); } } } public sealed class CodePagesEncodingProvider : EncodingProvider { private static readonly EncodingProvider s_singleton = new CodePagesEncodingProvider(); private readonly Dictionary<int, Encoding> _encodings = new Dictionary<int, Encoding>(); private readonly ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim(); private const int ISCIIAssemese = 57006; private const int ISCIIBengali = 57003; private const int ISCIIDevanagari = 57002; private const int ISCIIGujarathi = 57010; private const int ISCIIKannada = 57008; private const int ISCIIMalayalam = 57009; private const int ISCIIOriya = 57007; private const int ISCIIPanjabi = 57011; private const int ISCIITamil = 57004; private const int ISCIITelugu = 57005; private const int ISOKorean = 50225; private const int ChineseHZ = 52936; private const int ISO2022JP = 50220; private const int ISO2022JPESC = 50221; private const int ISO2022JPSISO = 50222; private const int ISOSimplifiedCN = 50227; private const int EUCJP = 51932; private const int CodePageMacGB2312 = 10008; private const int CodePageMacKorean = 10003; private const int CodePageGB2312 = 20936; private const int CodePageDLLKorean = 20949; private const int GB18030 = 54936; private const int DuplicateEUCCN = 51936; private const int EUCKR = 51949; private const int EUCCN = 936; private const int ISO_8859_8I = 38598; private const int ISO_8859_8_Visual = 28598; public static EncodingProvider Instance => s_singleton; private static int SystemDefaultCodePage => 0; internal CodePagesEncodingProvider() { } public override Encoding? GetEncoding(int codepage) { if (codepage < 0 || codepage > 65535) { return null; } if (codepage == 0) { int systemDefaultCodePage = SystemDefaultCodePage; if (systemDefaultCodePage == 0) { return null; } return GetEncoding(systemDefaultCodePage); } Encoding value = null; _cacheLock.EnterUpgradeableReadLock(); try { if (_encodings.TryGetValue(codepage, out value)) { return value; } switch (BaseCodePageEncoding.GetCodePageByteSize(codepage)) { case 1: value = new SBCSCodePageEncoding(codepage); break; case 2: value = new DBCSCodePageEncoding(codepage); break; default: value = GetEncodingRare(codepage); if (value == null) { return null; } break; } _cacheLock.EnterWriteLock(); try { if (_encodings.TryGetValue(codepage, out var value2)) { return value2; } _encodings.Add(codepage, value); return value; } finally { _cacheLock.ExitWriteLock(); } } finally { _cacheLock.ExitUpgradeableReadLock(); } } public override Encoding? GetEncoding(string name) { int codePageFromName = System.Text.EncodingTable.GetCodePageFromName(name); if (codePageFromName == 0) { return null; } return GetEncoding(codePageFromName); } private static Encoding GetEncodingRare(int codepage) { Encoding result = null; switch (codepage) { case 57002: case 57003: case 57004: case 57005: case 57006: case 57007: case 57008: case 57009: case 57010: case 57011: result = new ISCIIEncoding(codepage); break; case 10008: result = new DBCSCodePageEncoding(10008, 20936); break; case 10003: result = new DBCSCodePageEncoding(10003, 20949); break; case 54936: result = new GB18030Encoding(); break; case 50220: case 50221: case 50222: case 50225: case 52936: result = new ISO2022Encoding(codepage); break; case 50227: case 51936: result = new DBCSCodePageEncoding(codepage, 936); break; case 51932: result = new EUCJPEncoding(); break; case 51949: result = new DBCSCodePageEncoding(codepage, 20949); break; case 38598: result = new SBCSCodePageEncoding(codepage, 28598); break; } return result; } } internal class DBCSCodePageEncoding : BaseCodePageEncoding { internal sealed class DBCSDecoder : System.Text.DecoderNLS { internal byte bLeftOver; internal override bool HasState => bLeftOver != 0; public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding) { } public override void Reset() { bLeftOver = 0; m_fallbackBuffer?.Reset(); } } protected unsafe char* mapBytesToUnicode = null; protected unsafe ushort* mapUnicodeToBytes = null; protected const char UNKNOWN_CHAR_FLAG = '\0'; protected const char UNICODE_REPLACEMENT_CHAR = '\ufffd'; protected const char LEAD_BYTE_CHAR = '\ufffe'; private ushort _bytesUnknown; private int _byteCountUnknown; protected char charUnknown; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public DBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, dataCodePage, enc, dec) { } internal unsafe static char ReadChar(char* pChar) { if (BitConverter.IsLittleEndian) { return *pChar; } return (char)BinaryPrimitives.ReverseEndianness(*pChar); } protected unsafe override void LoadManagedCodePage() { fixed (byte* ptr = &m_codePageHeader[0]) { CodePageHeader* ptr2 = (CodePageHeader*)ptr; if (ptr2->ByteCount != 2) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } _bytesUnknown = ptr2->ByteReplace; charUnknown = ptr2->UnicodeReplace; if (base.DecoderFallback is InternalDecoderBestFitFallback) { ((InternalDecoderBestFitFallback)base.DecoderFallback).cReplacement = charUnknown; } _byteCountUnknown = 1; if (_bytesUnknown > 255) { _byteCountUnknown++; } int num = 262148 + iExtraBytes; byte* nativeMemory = GetNativeMemory(num); Unsafe.InitBlockUnaligned(nativeMemory, 0, (uint)num); mapBytesToUnicode = (char*)nativeMemory; mapUnicodeToBytes = (ushort*)(nativeMemory + 131072); byte[] array = new byte[m_dataSize]; lock (BaseCodePageEncoding.s_streamLock) { BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); int num2 = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize); } fixed (byte* ptr3 = array) { char* ptr4 = (char*)ptr3; int num3 = 0; int num4 = 0; while (num3 < 65536) { char c = ReadChar(ptr4); ptr4++; switch (c) { case '\u0001': num3 = ReadChar(ptr4); ptr4++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num3 += c; continue; } switch (c) { case '\uffff': num4 = num3; c = (char)num3; break; case '\ufffe': num4 = num3; break; case '\ufffd': num3++; continue; default: num4 = num3; break; } if (CleanUpBytes(ref num4)) { if (c != '\ufffe') { mapUnicodeToBytes[(int)c] = (ushort)num4; } mapBytesToUnicode[num4] = c; } num3++; } } CleanUpEndBytes(mapBytesToUnicode); } } protected virtual bool CleanUpBytes(ref int bytes) { return true; } protected unsafe virtual void CleanUpEndBytes(char* chars) { } protected unsafe override void ReadBestFitTable() { lock (InternalSyncObject) { if (arrayUnicodeBestFit != null) { return; } byte[] array = new byte[m_dataSize]; lock (BaseCodePageEncoding.s_streamLock) { BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); int num = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize); } fixed (byte* ptr = array) { char* ptr2 = (char*)ptr; int num2 = 0; while (num2 < 65536) { char c = ReadChar(ptr2); ptr2++; switch (c) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; break; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c; break; default: num2++; break; } } char* ptr3 = ptr2; int num3 = 0; num2 = ReadChar(ptr2); ptr2++; while (num2 < 65536) { char c2 = ReadChar(ptr2); ptr2++; switch (c2) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c2; continue; } if (c2 != '\ufffd') { int bytes = num2; if (CleanUpBytes(ref bytes) && mapBytesToUnicode[bytes] != c2) { num3++; } } num2++; } char[] array2 = new char[num3 * 2]; num3 = 0; ptr2 = ptr3; num2 = ReadChar(ptr2); ptr2++; bool flag = false; while (num2 < 65536) { char c3 = ReadChar(ptr2); ptr2++; switch (c3) { case '\u0001': num2 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num2 += c3; continue; } if (c3 != '\ufffd') { int bytes2 = num2; if (CleanUpBytes(ref bytes2) && mapBytesToUnicode[bytes2] != c3) { if (bytes2 != num2) { flag = true; } array2[num3++] = (char)bytes2; array2[num3++] = c3; } } num2++; } if (flag) { for (int i = 0; i < array2.Length - 2; i += 2) { int num4 = i; char c4 = array2[i]; for (int j = i + 2; j < array2.Length; j += 2) { if (c4 > array2[j]) { c4 = array2[j]; num4 = j; } } if (num4 != i) { char c5 = array2[num4]; array2[num4] = array2[i]; array2[i] = c5; c5 = array2[num4 + 1]; array2[num4 + 1] = array2[i + 1]; array2[i + 1] = c5; } } } arrayBytesBestFit = array2; char* ptr4 = ptr2; int num5 = ReadChar(ptr2++); num3 = 0; while (num5 < 65536) { char c6 = ReadChar(ptr2); ptr2++; switch (c6) { case '\u0001': num5 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num5 += c6; continue; } if (c6 > '\0') { num3++; } num5++; } array2 = new char[num3 * 2]; ptr2 = ptr4; num5 = ReadChar(ptr2++); num3 = 0; while (num5 < 65536) { char c7 = ReadChar(ptr2); ptr2++; switch (c7) { case '\u0001': num5 = ReadChar(ptr2); ptr2++; continue; case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\a': case '\b': case '\t': case '\n': case '\v': case '\f': case '\r': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': num5 += c7; continue; } if (c7 > '\0') { int bytes3 = c7; if (CleanUpBytes(ref bytes3)) { array2[num3++] = (char)num5; array2[num3++] = mapBytesToUnicode[bytes3]; } } num5++; } arrayUnicodeBestFit = array2; } } } public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder) { CheckMemorySection(); char c = '\0'; if (encoder != null) { c = encoder.charLeftOver; if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); } } int num = 0; char* ptr = chars + count; EncoderFallbackBuffer encoderFallbackBuffer = null; EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); if (c > '\0') { encoderFallbackBuffer = encoder.FallbackBuffer; encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: false); encoderFallbackBufferHelper.InternalFallback(c, ref chars); } char c2; while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) { if (c2 == '\0') { c2 = *chars; chars++; } ushort num2 = mapUnicodeToBytes[(int)c2]; if (num2 == 0 && c2 != 0) { if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : base.EncoderFallback.CreateFallbackBuffer()); encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(ptr - count, ptr, encoder, _setEncoder: false); } encoderFallbackBufferHelper.InternalFallback(c2, ref chars); } else { num++; if (num2 >= 256) { num++; } } } return num; } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder) { CheckMemorySection(); EncoderFallbackBuffer encoderFallbackBuffer = null; char* ptr = chars + charCount; char* ptr2 = chars; byte* ptr3 = bytes; byte* ptr4 = bytes + byteCount; EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); char c = '\0'; if (encoder != null) { c = encoder.charLeftOver; encoderFallbackBuffer = encoder.FallbackBuffer; encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: true); if (encoder.m_throwOnOverflow && encoderFallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); } if (c > '\0') { encoderFallbackBufferHelper.InternalFallback(c, ref chars); } } char c2; while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr) { if (c2 == '\0') { c2 = *chars; chars++; } ushort num = mapUnicodeToBytes[(int)c2]; if (num == 0 && c2 != 0) { if (encoderFallbackBuffer == null) { encoderFallbackBuffer = base.EncoderFallback.CreateFallbackBuffer(); encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer); encoderFallbackBufferHelper.InternalInitialize(ptr - charCount, ptr, encoder, _setEncoder: true); } encoderFallbackBufferHelper.InternalFallback(c2, ref chars); continue; } if (num >= 256) { if (bytes + 1 >= ptr4) { if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) { chars--; } else { encoderFallbackBuffer.MovePrevious(); } ThrowBytesOverflow(encoder, chars == ptr2); break; } *bytes = (byte)(num >> 8); bytes++; } else if (bytes >= ptr4) { if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack) { chars--; } else { encoderFallbackBuffer.MovePrevious(); } ThrowBytesOverflow(encoder, chars == ptr2); break; } *bytes = (byte)(num & 0xFFu); bytes++; } if (encoder != null) { if (encoderFallbackBuffer != null && !encoderFallbackBufferHelper.bUsedEncoder) { encoder.charLeftOver = '\0'; } encoder.m_charsUsed = (int)(chars - ptr2); } return (int)(bytes - ptr3); } public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS baseDecoder) { CheckMemorySection(); DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder; DecoderFallbackBuffer decoderFallbackBuffer = null; byte* ptr = bytes + count; int num = count; DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0) { if (count == 0) { if (!dBCSDecoder.MustFlush) { return 0; } decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(bytes, null); byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver }; return decoderFallbackBufferHelper.InternalFallback(bytes2, bytes); } int num2 = dBCSDecoder.bLeftOver << 8; num2 |= *bytes; bytes++; if (mapBytesToUnicode[num2] == '\0' && num2 != 0) { num--; decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); byte[] bytes3 = new byte[2] { (byte)(num2 >> 8), (byte)num2 }; num += decoderFallbackBufferHelper.InternalFallback(bytes3, bytes); } } while (bytes < ptr) { int num3 = *bytes; bytes++; char c = mapBytesToUnicode[num3]; if (c == '\ufffe') { num--; if (bytes < ptr) { num3 <<= 8; num3 |= *bytes; bytes++; c = mapBytesToUnicode[num3]; } else { if (dBCSDecoder != null && !dBCSDecoder.MustFlush) { break; } num++; c = '\0'; } } if (c == '\0' && num3 != 0) { if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr - count, null); } num--; byte[] bytes4 = ((num3 >= 256) ? new byte[2] { (byte)(num3 >> 8), (byte)num3 } : new byte[1] { (byte)num3 }); num += decoderFallbackBufferHelper.InternalFallback(bytes4, bytes); } } return num; } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS baseDecoder) { CheckMemorySection(); DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder; byte* ptr = bytes; byte* ptr2 = bytes + byteCount; char* ptr3 = chars; char* ptr4 = chars + charCount; bool flag = false; DecoderFallbackBuffer decoderFallbackBuffer = null; DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0) { if (byteCount == 0) { if (!dBCSDecoder.MustFlush) { return 0; } decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(bytes, ptr4); byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver }; if (!decoderFallbackBufferHelper.InternalFallback(bytes2, bytes, ref chars)) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } dBCSDecoder.bLeftOver = 0; return (int)(chars - ptr3); } int num = dBCSDecoder.bLeftOver << 8; num |= *bytes; bytes++; char c = mapBytesToUnicode[num]; if (c == '\0' && num != 0) { decoderFallbackBuffer = dBCSDecoder.FallbackBuffer; decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4); byte[] bytes3 = new byte[2] { (byte)(num >> 8), (byte)num }; if (!decoderFallbackBufferHelper.InternalFallback(bytes3, bytes, ref chars)) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } } else { if (chars >= ptr4) { ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true); } *(chars++) = c; } } while (bytes < ptr2) { int num2 = *bytes; bytes++; char c2 = mapBytesToUnicode[num2]; if (c2 == '\ufffe') { if (bytes < ptr2) { num2 <<= 8; num2 |= *bytes; bytes++; c2 = mapBytesToUnicode[num2]; } else { if (dBCSDecoder != null && !dBCSDecoder.MustFlush) { flag = true; dBCSDecoder.bLeftOver = (byte)num2; break; } c2 = '\0'; } } if (c2 == '\0' && num2 != 0) { if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer()); decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer); decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4); } byte[] array = ((num2 >= 256) ? new byte[2] { (byte)(num2 >> 8), (byte)num2 } : new byte[1] { (byte)num2 }); if (!decoderFallbackBufferHelper.InternalFallback(array, bytes, ref chars)) { bytes -= array.Length; decoderFallbackBufferHelper.InternalReset(); ThrowCharsOverflow(dBCSDecoder, bytes == ptr); break; } continue; } if (chars >= ptr4) { bytes--; if (num2 >= 256) { bytes--; } ThrowCharsOverflow(dBCSDecoder, bytes == ptr); break; } *(chars++) = c2; } if (dBCSDecoder != null) { if (!flag) { dBCSDecoder.bLeftOver = 0; } dBCSDecoder.m_bytesUsed = (int)(bytes - ptr); } return (int)(chars - ptr3); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount + 1L; if (base.EncoderFallback.MaxCharCount > 1) { num *= base.EncoderFallback.MaxCharCount; } num *= 2; if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)byteCount + 1L; if (base.DecoderFallback.MaxCharCount > 1) { num *= base.DecoderFallback.MaxCharCount; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow); } return (int)num; } public override Decoder GetDecoder() { return new DBCSDecoder(this); } } internal sealed class InternalDecoderBestFitFallback : DecoderFallback { internal BaseCodePageEncoding encoding; internal char[] arrayBestFit; internal char cReplacement = '?'; public override int MaxCharCount => 1; internal InternalDecoderBestFitFallback(BaseCodePageEncoding _encoding) { encoding = _encoding; } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new InternalDecoderBestFitFallbackBuffer(this); } public override bool Equals([NotNullWhen(true)] object value) { if (value is InternalDecoderBestFitFallback internalDecoderBestFitFallback) { return encoding.CodePage == internalDecoderBestFitFallback.encoding.CodePage; } return false; } public override int GetHashCode() { return encoding.CodePage; } } internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer { internal char cBestFit; internal int iCount = -1; internal int iSize; private readonly InternalDecoderBestFitFallback _oFallback; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public override int Remaining { get { if (iCount <= 0) { return 0; } return iCount; } } public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback.arrayBestFit != null) { return; } lock (InternalSyncObject) { InternalDecoderBestFitFallback oFallback = _oFallback; if (oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData(); } } } public override bool Fallback(byte[] bytesUnknown, int index) { cBestFit = TryBestFit(bytesUnknown); if (cBestFit == '\0') { cBestFit = _oFallback.cReplacement; } iCount = (iSize = 1); return true; } public override char GetNextChar() { iCount--; if (iCount < 0) { return '\0'; } if (iCount == int.MaxValue) { iCount = -1; return '\0'; } return cBestFit; } public override bool MovePrevious() { if (iCount >= 0) { iCount++; } if (iCount >= 0) { return iCount <= iSize; } return false; } public override void Reset() { iCount = -1; } internal unsafe static int InternalFallback(byte[] bytes, byte* pBytes) { return 1; } private char TryBestFit(byte[] bytesCheck) { int num = 0; int num2 = _oFallback.arrayBestFit.Length; if (num2 == 0) { return '\0'; } if (bytesCheck.Length == 0 || bytesCheck.Length > 2) { return '\0'; } char c = ((bytesCheck.Length != 1) ? ((char)((bytesCheck[0] << 8) + bytesCheck[1])) : ((char)bytesCheck[0])); if (c < _oFallback.arrayBestFit[0] || c > _oFallback.arrayBestFit[num2 - 2]) { return '\0'; } int num3; while ((num3 = num2 - num) > 6) { int num4 = (num3 / 2 + num) & 0xFFFE; char c2 = _oFallback.arrayBestFit[num4]; if (c2 == c) { return _oFallback.arrayBestFit[num4 + 1]; } if (c2 < c) { num = num4; } else { num2 = num4; } } for (int num4 = num; num4 < num2; num4 += 2) { if (_oFallback.arrayBestFit[num4] == c) { return _oFallback.arrayBestFit[num4 + 1]; } } return '\0'; } } internal struct DecoderFallbackBufferHelper { internal unsafe byte* byteStart; internal unsafe char* charEnd; private readonly DecoderFallbackBuffer _fallbackBuffer; public unsafe DecoderFallbackBufferHelper(DecoderFallbackBuffer fallbackBuffer) { _fallbackBuffer = fallbackBuffer; byteStart = null; charEnd = null; } internal unsafe void InternalReset() { byteStart = null; _fallbackBuffer.Reset(); } internal unsafe void InternalInitialize(byte* _byteStart, char* _charEnd) { byteStart = _byteStart; charEnd = _charEnd; } internal unsafe bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { char* ptr = chars; bool flag = false; char nextChar; while ((nextChar = _fallbackBuffer.GetNextChar()) != 0) { if (char.IsSurrogate(nextChar)) { if (char.IsHighSurrogate(nextChar)) { if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = true; } else { if (!flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = false; } } if (ptr >= charEnd) { return false; } *(ptr++) = nextChar; } if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } chars = ptr; } return true; } internal unsafe int InternalFallback(byte[] bytes, byte* pBytes) { if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { int num = 0; bool flag = false; char nextChar; while ((nextChar = _fallbackBuffer.GetNextChar()) != 0) { if (char.IsSurrogate(nextChar)) { if (char.IsHighSurrogate(nextChar)) { if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = true; } else { if (!flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } flag = false; } } num++; } if (flag) { throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex); } return num; } return 0; } } internal class DecoderNLS : Decoder, ISerializable { protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_bytesUsed; internal DecoderFallback m_fallback; internal DecoderFallbackBuffer m_fallbackBuffer; internal new DecoderFallback Fallback => m_fallback; internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null; public new DecoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : DecoderFallback.ReplacementFallback.CreateFallbackBuffer()); } return m_fallbackBuffer; } } public bool MustFlush => m_mustFlush; internal virtual bool HasState => false; internal DecoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.DecoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override void Reset() { m_fallbackBuffer?.Reset(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, flush: false); } public unsafe override int GetCharCount(byte[] bytes, int index, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length == 0) { bytes = new byte[1]; } fixed (byte* ptr = &bytes[0]) { return GetCharCount(ptr + index, count, flush); } } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetCharCount(bytes, count, this); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush: false); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } if (bytes.Length == 0) { bytes = new byte[1]; } int charCount = chars.Length - charIndex; if (chars.Length == 0) { chars = new char[1]; } fixed (byte* ptr = &bytes[0]) { fixed (char* ptr2 = &chars[0]) { return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush); } } } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } public unsafe override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length == 0) { bytes = new byte[1]; } if (chars.Length == 0) { chars = new char[1]; } fixed (byte* ptr = &bytes[0]) { fixed (char* ptr2 = &chars[0]) { Convert(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = false; m_bytesUsed = 0; charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = m_bytesUsed; completed = bytesUsed == byteCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); } internal void ClearMustFlush() { m_mustFlush = false; } } internal sealed class InternalEncoderBestFitFallback : EncoderFallback { internal BaseCodePageEncoding encoding; internal char[] arrayBestFit; public override int MaxCharCount => 1; internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding) { encoding = _encoding; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } public override bool Equals([NotNullWhen(true)] object value) { if (value is InternalEncoderBestFitFallback internalEncoderBestFitFallback) { return encoding.CodePage == internalEncoderBestFitFallback.encoding.CodePage; } return false; } public override int GetHashCode() { return encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { private char _cBestFit; private readonly InternalEncoderBestFitFallback _oFallback; private int _iCount = -1; private int _iSize; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public override int Remaining { get { if (_iCount <= 0) { return 0; } return _iCount; } } public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback.arrayBestFit != null) { return; } lock (InternalSyncObject) { InternalEncoderBestFitFallback oFallback = _oFallback; if (oFallback.arrayBestFit == null) { oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } public override bool Fallback(char charUnknown, int index) { _iCount = (_iSize = 1); _cBestFit = TryBestFit(charUnknown); if (_cBestFit == '\0') { _cBestFit = '?'; } return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException("charUnknownHigh", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 55296, 56319)); } if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException("charUnknownLow", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 56320, 57343)); } _cBestFit = '?'; _iCount = (_iSize = 2); return true; } public override char GetNextChar() { _iCount--; if (_iCount < 0) { return '\0'; } if (_iCount == int.MaxValue) { _iCount = -1; return '\0'; } return _cBestFit; } public override bool MovePrevious() { if (_iCount >= 0) { _iCount++; } if (_iCount >= 0) { return _iCount <= _iSize; } return false; } public override void Reset() { _iCount = -1; } private char TryBestFit(char cUnknown) { int num = 0; int num2 = _oFallback.arrayBestFit.Length; int num3; while ((num3 = num2 - num) > 6) { int num4 = (num3 / 2 + num) & 0xFFFE; char c = _oFallback.arrayBestFit[num4]; if (c == cUnknown) { return _oFallback.arrayBestFit[num4 + 1]; } if (c < cUnknown) { num = num4; } else { num2 = num4; } } for (int num4 = num; num4 < num2; num4 += 2) { if (_oFallback.arrayBestFit[num4] == cUnknown) { return _oFallback.arrayBestFit[num4 + 1]; } } return '\0'; } } internal struct EncoderFallbackBufferHelper { internal unsafe char* charStart; internal unsafe char* charEnd; internal System.Text.EncoderNLS encoder; internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack; internal int iRecursionCount; private const int iMaxRecursion = 250; private readonly EncoderFallbackBuffer _fallbackBuffer; public unsafe EncoderFallbackBufferHelper(EncoderFallbackBuffer fallbackBuffer) { _fallbackBuffer = fallbackBuffer; bFallingBack = (bUsedEncoder = (setEncoder = false)); iRecursionCount = 0; charEnd = (charStart = null); encoder = null; } internal unsafe void InternalReset() { charStart = null; bFallingBack = false; iRecursionCount = 0; _fallbackBuffer.Reset(); } internal unsafe void InternalInitialize(char* _charStart, char* _charEnd, System.Text.EncoderNLS _encoder, bool _setEncoder) { charStart = _charStart; charEnd = _charEnd; encoder = _encoder; setEncoder = _setEncoder; bUsedEncoder = false; bFallingBack = false; iRecursionCount = 0; } internal char InternalGetNextChar() { char nextChar = _fallbackBuffer.GetNextChar(); bFallingBack = nextChar != '\0'; if (nextChar == '\0') { iRecursionCount = 0; } return nextChar; } internal unsafe bool InternalFallback(char ch, ref char* chars) { int index = (int)(chars - charStart) - 1; if (char.IsHighSurrogate(ch)) { if (chars >= charEnd) { if (encoder != null && !encoder.MustFlush) { if (setEncoder) { bUsedEncoder = true; encoder.charLeftOver = ch; } bFallingBack = false; return false; } } else { char c = *chars; if (char.IsLowSurrogate(c)) { if (bFallingBack && iRecursionCount++ > 250) { ThrowLastCharRecursive(char.ConvertToUtf32(ch, c)); } chars++; bFallingBack = _fallbackBuffer.Fallback(ch, c, index); return bFallingBack; } } } if (bFallingBack && iRecursionCount++ > 250) { ThrowLastCharRecursive(ch); } bFallingBack = _fallbackBuffer.Fallback(ch, index); return bFallingBack; } internal static void ThrowLastCharRecursive(int charRecursive) { throw new ArgumentException(System.SR.Format(System.SR.Argument_RecursiveFallback, charRecursive), "chars"); } } internal class EncoderNLS : Encoder, ISerializable { internal char charLeftOver; protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_charsUsed; internal EncoderFallback m_fallback; internal EncoderFallbackBuffer m_fallbackBuffer; internal new EncoderFallback Fallback => m_fallback; internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null; public new EncoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : EncoderFallback.ReplacementFallback.CreateFallbackBuffer()); } return m_fallbackBuffer; } } public Encoding Encoding => m_encoding; public bool MustFlush => m_mustFlush; internal virtual bool HasState => charLeftOver != '\0'; internal EncoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.EncoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override void Reset() { charLeftOver = '\0'; m_fallbackBuffer?.Reset(); } public unsafe override int GetByteCount(char[] chars, int index, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length == 0) { chars = new char[1]; } int num = -1; fixed (char* ptr = &chars[0]) { num = GetByteCount(ptr + index, count, flush); } return num; } public unsafe override int GetByteCount(char* chars, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetByteCount(chars, count, this); } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } if (chars.Length == 0) { chars = new char[1]; } int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) { bytes = new byte[1]; } fixed (char* ptr = &chars[0]) { fixed (byte* ptr2 = &bytes[0]) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush); } } } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); } public unsafe override void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length == 0) { chars = new char[1]; } if (bytes.Length == 0) { bytes = new byte[1]; } fixed (char* ptr = &chars[0]) { fixed (byte* ptr2 = &bytes[0]) { Convert(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } public unsafe override void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } m_mustFlush = flush; m_throwOnOverflow = false; m_charsUsed = 0; bytesUsed = m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = m_charsUsed; completed = charsUsed == charCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); } internal void ClearMustFlush() { m_mustFlush = false; } } internal sealed class EncodingByteBuffer { private unsafe byte* _bytes; private unsafe readonly byte* _byteStart; private unsafe readonly byte* _byteEnd; private unsafe char* _chars; private unsafe readonly char* _charStart; private unsafe readonly char* _charEnd; private int _byteCountResult; private readonly EncodingNLS _enc; private readonly System.Text.EncoderNLS _encoder; internal EncoderFallbackBuffer fallbackBuffer; internal EncoderFallbackBufferHelper fallbackBufferHelper; internal unsafe bool MoreData { get { if (fallbackBuffer.Remaining <= 0) { return _chars < _charEnd; } return true; } } internal unsafe int CharsUsed => (int)(_chars - _charStart); internal int Count => _byteCountResult; internal unsafe EncodingByteBuffer(EncodingNLS inEncoding, System.Text.EncoderNLS inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount) { _enc = inEncoding; _encoder = inEncoder; _charStart = inCharStart; _chars = inCharStart; _charEnd = inCharStart + inCharCount; _bytes = inByteStart; _byteStart = inByteStart; _byteEnd = inByteStart + inByteCount; if (_encoder == null) { fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = _encoder.FallbackBuffer; if (_encoder.m_throwOnOverflow && _encoder.InternalHasFallbackBuffer && fallbackBuffer.Remaining > 0) { throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback.GetType())); } } fallbackBufferHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackBufferHelper.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); } internal unsafe bool AddByte(byte b, int moreBytesExpected) { if (_bytes != null) { if (_bytes >= _byteEnd - moreBytesExpected) { MovePrevious(bThrow: true); return false; } *(_bytes++) = b; } _byteCountResult++; return true; } internal bool AddByte(byte b1) { return AddByte(b1, 0); } internal bool AddByte(byte b1, byte b2) { return AddByte(b1, b2, 0); } internal bool AddByte(byte b1, byte b2, int moreBytesExpected) { if (AddByte(b1, 1 + moreBytesExpected)) { return AddByte(b2, moreBytesExpected); } return false; } internal bool AddByte(byte b1, byte b2, byte b3) { return AddByte(b1, b2, b3, 0); } internal bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected) { if (AddByte(b1, 2 + moreBytesExpected) && AddByte(b2, 1 + moreBytesExpected)) { return AddByte(b3, moreBytesExpected); } return false; } internal bool AddByte(byte b1, byte b2, byte b3, byte b4) { if (AddByte(b1, 3) && AddByte(b2, 2) && AddByte(b3, 1)) { return AddByte(b4, 0); } return false; } internal unsafe void MovePrevious(bool bThrow) { if (fallbackBufferHelper.bFallingBack) { fallbackBuffer.MovePrevious(); } else if (_chars > _charStart) { _chars--; } if (bThrow) { _enc.ThrowBytesOverflow(_encoder, _bytes == _byteStart); } } internal unsafe bool Fallback(char charFallback) { return fallbackBufferHelper.InternalFallback(charFallback, ref _chars); } internal unsafe char GetNextChar() { char c = fallbackBufferHelper.InternalGetNextChar(); if (c == '\0' && _chars < _charEnd) { c = *(_chars++); } return c; } } internal sealed class EncodingCharBuffer { private unsafe char* _chars; private unsafe readonly char* _charStart; private unsafe readonly char* _charEnd; private int _charCountResult; private readonly EncodingNLS _enc; private readonly System.Text.DecoderNLS _decoder; private unsafe readonly byte* _byteStart; private unsafe readonly byte* _byteEnd; private unsafe byte* _bytes; private readonly DecoderFallbackBuffer _fallbackBuffer; private DecoderFallbackBufferHelper _fallbackBufferHelper; internal unsafe bool MoreData => _bytes < _byteEnd; internal unsafe int BytesUsed => (int)(_bytes - _byteStart); internal int Count => _charCountResult; internal unsafe EncodingCharBuffer(EncodingNLS enc, System.Text.DecoderNLS decoder, char* charStart, int charCount, byte* byteStart, int byteCount) { _enc = enc; _decoder = decoder; _chars = charStart; _charStart = charStart; _charEnd = charStart + charCount; _byteStart = byteStart; _bytes = byteStart; _byteEnd = byteStart + byteCount; if (_decoder == null) { _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); } else { _fallbackBuffer = _decoder.FallbackBuffer; } _fallbackBufferHelper = new DecoderFallbackBufferHelper(_fallbackBuffer); _fallbackBufferHelper.InternalInitialize(_bytes, _charEnd); } internal unsafe bool AddChar(char ch, int numBytes) { if (_chars != null) { if (_chars >= _charEnd) { _bytes -= numBytes; _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); return false; } *(_chars++) = ch; } _charCountResult++; return true; } internal bool AddChar(char ch) { return AddChar(ch, 1); } internal unsafe bool AddChar(char ch1, char ch2, int numBytes) { if (_chars >= _charEnd - 1) { _bytes -= numBytes; _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); return false; } if (AddChar(ch1, numBytes)) { return AddChar(ch2, numBytes); } return false; } internal unsafe void AdjustBytes(int count) { _bytes += count; } internal unsafe bool EvenMoreData(int count) { return _bytes <= _byteEnd - count; } internal unsafe byte GetNextByte() { if (_bytes >= _byteEnd) { return 0; } return *(_bytes++); } internal bool Fallback(byte fallbackByte) { byte[] byteBuffer = new byte[1] { fallbackByte }; return Fallback(byteBuffer); } internal bool Fallback(byte byte1, byte byte2) { byte[] byteBuffer = new byte[2] { byte1, byte2 }; return Fallback(byteBuffer); } internal bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4) { byte[] byteBuffer = new byte[4] { byte1, byte2, byte3, byte4 }; return Fallback(byteBuffer); } internal unsafe bool Fallback(byte[] byteBuffer) { if (_chars != null) { char* chars = _chars; if (!_fallbackBufferHelper.InternalFallback(byteBuffer, _bytes, ref _chars)) { _bytes -= byteBuffer.Length; _fallbackBufferHelper.InternalReset(); _enc.ThrowCharsOverflow(_decoder, _chars == _charStart); return false; } _charCountResult += (int)(_chars - chars); } else { _charCountResult += _fallbackBufferHelper.InternalFallback(byteBuffer, _bytes); } return true; } } internal abstract class EncodingNLS : Encoding { private string _encodingName; private string _webName; public override string EncodingName { get { if (_encodingName == null) { _encodingName = GetLocalizedEncodingNameResource(CodePage); if (_encodingName == null) { throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage)); } if (_encodingName.StartsWith("Globalization_cp_", StringComparison.OrdinalIgnoreCase)) { _encodingName = System.Text.EncodingTable.GetEnglishNameFromCodePage(CodePage); if (_encodingName == null) { throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage)); } } } return _encodingName; } } public override string WebName { get { if (_webName == null) { _webName = System.Text.EncodingTable.GetWebNameFromCodePage(CodePage); if (_webName == null) { throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage)); } } return _webName; } } public override string HeaderName => CodePage switch { 932 => "iso-2022-jp", 50221 => "iso-2022-jp", 50225 => "euc-kr", _ => WebName, }; public override string BodyName => CodePage switch { 932 => "iso-2022-jp", 1250 => "iso-8859-2", 1251 => "koi8-r", 1252 => "iso-8859-1", 1253 => "iso-8859-7", 1254 => "iso-8859-9", 50221 => "iso-2022-jp", 50225 => "iso-2022-kr", _ => WebName, }; protected EncodingNLS(int codePage) : base(codePage) { } protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, enc, dec) { } public unsafe abstract int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder); public unsafe abstract int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder); public unsafe abstract int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS decoder); public unsafe abstract int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS decoder); public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { throw new ArgumentNullException("chars"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length == 0) { return 0; } fixed (char* ptr = &chars[0]) { return GetByteCount(ptr + index, count, null); } } public unsafe override int GetByteCount(string s) { if (s == null) { throw new ArgumentNullException("s"); } fixed (char* chars = s) { return GetByteCount(chars, s.Length, null); } } public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { throw new ArgumentNullException("chars"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCount(chars, count, null); } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null) { throw new ArgumentNullException("s"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (s.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("s", System.SR.ArgumentOutOfRange_IndexCount); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) { bytes = new byte[1]; } fixed (char* ptr = s) { fixed (byte* ptr2 = &bytes[0]) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) { throw new ArgumentNullException("chars"); } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); } if (chars.Length == 0) { return 0; } int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) { bytes = new byte[1]; } fixed (char* ptr = &chars[0]) { fixed (byte* ptr2
deps/System.Text.Encodings.Web.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Encodings.Web; using System.Text.Unicode; using System.Threading; using FxResources.System.Text.Encodings.Web; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Encodings.Web")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides types for encoding and escaping strings for use in JavaScript, HyperText Markup Language (HTML), and uniform resource locators (URL).\r\n\r\nCommonly Used Types:\r\nSystem.Text.Encodings.Web.HtmlEncoder\r\nSystem.Text.Encodings.Web.UrlEncoder\r\nSystem.Text.Encodings.Web.JavaScriptEncoder")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Encodings.Web")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] 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] internal sealed class IsByRefLikeAttribute : 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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [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 NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = 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 FxResources.System.Text.Encodings.Web { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { byte value = readOnlySpan[i]; ToCharsBuffer(value, buffer, num, casing); num += 2; } return buffer.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { if (IntPtr.Size == 8) { ulong num = (uint)(c - 48); ulong num2 = (ulong)(-17875860044349952L << (int)num); ulong num3 = num - 64; return (long)(num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string TextEncoderDoesNotImplementMaxOutputCharsPerInputChar => GetResourceString("TextEncoderDoesNotImplementMaxOutputCharsPerInputChar"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Numerics { internal static class BitOperations { private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32] { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Log2(uint value) { return Log2SoftwareFallback(value | 1u); } private static int Log2SoftwareFallback(uint value) { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (nint)(value * 130329821 >> 27)); } } } namespace System.Text { internal static class UnicodeDebug { [Conditional("DEBUG")] internal static void AssertIsBmpCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsBmpCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsHighSurrogateCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsHighSurrogateCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsLowSurrogateCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsLowSurrogateCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsValidCodePoint(uint codePoint) { System.Text.UnicodeUtility.IsValidCodePoint(codePoint); } [Conditional("DEBUG")] internal static void AssertIsValidScalar(uint scalarValue) { System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue); } [Conditional("DEBUG")] internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue) { if (System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue)) { System.Text.UnicodeUtility.IsBmpCodePoint(scalarValue); } } private static string ToHexString(uint codePoint) { return FormattableString.Invariant($"U+{codePoint:X4}"); } } internal static class UnicodeUtility { public const uint ReplacementChar = 65533u; public static int GetPlane(uint codePoint) { return (int)(codePoint >> 16); } public static uint GetScalarFromUtf16SurrogatePair(uint highSurrogateCodePoint, uint lowSurrogateCodePoint) { return (highSurrogateCodePoint << 10) + lowSurrogateCodePoint - 56613888; } public static int GetUtf16SequenceLength(uint value) { value -= 65536; value += 33554432; value >>= 24; return (int)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void GetUtf16SurrogatesFromSupplementaryPlaneScalar(uint value, out char highSurrogateCodePoint, out char lowSurrogateCodePoint) { highSurrogateCodePoint = (char)(value + 56557568 >> 10); lowSurrogateCodePoint = (char)((value & 0x3FF) + 56320); } public static int GetUtf8SequenceLength(uint value) { int num = (int)(value - 2048) >> 31; value ^= 0xF800u; value -= 63616; value += 67108864; value >>= 24; return (int)value + num * 2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAsciiCodePoint(uint value) { return value <= 127; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsBmpCodePoint(uint value) { return value <= 65535; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHighSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 55296u, 56319u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound) { return value - lowerBound <= upperBound - lowerBound; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLowSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 56320u, 57343u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsSurrogateCodePoint(uint value) { return IsInRangeInclusive(value, 55296u, 57343u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidCodePoint(uint codePoint) { return codePoint <= 1114111; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValidUnicodeScalar(uint value) { return ((value - 1114112) ^ 0xD800) >= 4293855232u; } } internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span<char> RawChars => _chars; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if ((uint)capacity > (uint)_chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; Span<char> chars = _chars; if ((uint)pos < (uint)chars.Length) { chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.AsSpan().CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } Span<char> span = _chars.Slice(_pos, length); for (int i = 0; i < span.Length; i++) { span[i] = *(value++); } _pos += length; } public void Append(ReadOnlySpan<char> value) { int pos = _pos; if (pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<char> AppendSpan(int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } _pos = pos + length; return _chars.Slice(pos, length); } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowAndAppend(char c) { Grow(1); Append(c); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalCapacityBeyondPos) { int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u)); char[] array = ArrayPool<char>.Shared.Rent(minimumLength); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(System.Text.ValueStringBuilder); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } } internal readonly struct Rune : IEquatable<Rune> { private const int MaxUtf16CharsPerRune = 2; private const char HighSurrogateStart = '\ud800'; private const char LowSurrogateStart = '\udc00'; private const int HighSurrogateRange = 1023; private readonly uint _value; public bool IsAscii => System.Text.UnicodeUtility.IsAsciiCodePoint(_value); public bool IsBmp => System.Text.UnicodeUtility.IsBmpCodePoint(_value); public static Rune ReplacementChar => UnsafeCreate(65533u); public int Utf16SequenceLength => System.Text.UnicodeUtility.GetUtf16SequenceLength(_value); public int Value => (int)_value; public Rune(uint value) { if (!System.Text.UnicodeUtility.IsValidUnicodeScalar(value)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } _value = value; } public Rune(int value) : this((uint)value) { } private Rune(uint scalarValue, bool _) { _value = scalarValue; } public static bool operator ==(Rune left, Rune right) { return left._value == right._value; } public static bool operator !=(Rune left, Rune right) { return left._value != right._value; } public static bool IsControl(Rune value) { return ((value._value + 1) & 0xFFFFFF7Fu) <= 32; } public static OperationStatus DecodeFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed) { if (!source.IsEmpty) { char c = source[0]; if (TryCreate(c, out result)) { charsConsumed = 1; return OperationStatus.Done; } if (1u < (uint)source.Length) { char lowSurrogate = source[1]; if (TryCreate(c, lowSurrogate, out result)) { charsConsumed = 2; return OperationStatus.Done; } } else if (char.IsHighSurrogate(c)) { goto IL_004c; } charsConsumed = 1; result = ReplacementChar; return OperationStatus.InvalidData; } goto IL_004c; IL_004c: charsConsumed = source.Length; result = ReplacementChar; return OperationStatus.NeedMoreData; } public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> source, out Rune result, out int bytesConsumed) { int num = 0; uint num2; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2)) { goto IL_0021; } if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 194u, 244u)) { num2 = num2 - 194 << 6; num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } int num3 = (sbyte)source[num]; if (num3 < -64) { num2 += (uint)num3; num2 += 128; num2 += 128; if (num2 < 2048) { goto IL_0021; } if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 3072u, 3087u)) { num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } num3 = (sbyte)source[num]; if (num3 < -64) { num2 <<= 6; num2 += (uint)num3; num2 += 128; num2 -= 131072; if (num2 > 65535) { num++; if ((uint)num >= (uint)source.Length) { goto IL_0163; } num3 = (sbyte)source[num]; if (num3 >= -64) { goto IL_0153; } num2 <<= 6; num2 += (uint)num3; num2 += 128; num2 -= 4194304; } goto IL_0021; } } } } else { num = 1; } goto IL_0153; } goto IL_0163; IL_0021: bytesConsumed = num + 1; result = UnsafeCreate(num2); return OperationStatus.Done; IL_0153: bytesConsumed = num; result = ReplacementChar; return OperationStatus.InvalidData; IL_0163: bytesConsumed = num; result = ReplacementChar; return OperationStatus.NeedMoreData; } public override bool Equals([NotNullWhen(true)] object obj) { if (obj is Rune other) { return Equals(other); } return false; } public bool Equals(Rune other) { return this == other; } public override int GetHashCode() { return Value; } public static bool TryCreate(char ch, out Rune result) { if (!System.Text.UnicodeUtility.IsSurrogateCodePoint(ch)) { result = UnsafeCreate(ch); return true; } result = default(Rune); return false; } public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result) { uint num = (uint)(highSurrogate - 55296); uint num2 = (uint)(lowSurrogate - 56320); if ((num | num2) <= 1023) { result = UnsafeCreate((uint)((int)(num << 10) + (lowSurrogate - 56320) + 65536)); return true; } result = default(Rune); return false; } public bool TryEncodeToUtf16(Span<char> destination, out int charsWritten) { if (destination.Length >= 1) { if (IsBmp) { destination[0] = (char)_value; charsWritten = 1; return true; } if (destination.Length >= 2) { System.Text.UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out destination[0], out destination[1]); charsWritten = 2; return true; } } charsWritten = 0; return false; } public bool TryEncodeToUtf8(Span<byte> destination, out int bytesWritten) { if (destination.Length >= 1) { if (IsAscii) { destination[0] = (byte)_value; bytesWritten = 1; return true; } if (destination.Length >= 2) { if (_value <= 2047) { destination[0] = (byte)(_value + 12288 >> 6); destination[1] = (byte)((_value & 0x3F) + 128); bytesWritten = 2; return true; } if (destination.Length >= 3) { if (_value <= 65535) { destination[0] = (byte)(_value + 917504 >> 12); destination[1] = (byte)(((_value & 0xFC0) >> 6) + 128); destination[2] = (byte)((_value & 0x3F) + 128); bytesWritten = 3; return true; } if (destination.Length >= 4) { destination[0] = (byte)(_value + 62914560 >> 18); destination[1] = (byte)(((_value & 0x3F000) >> 12) + 128); destination[2] = (byte)(((_value & 0xFC0) >> 6) + 128); destination[3] = (byte)((_value & 0x3F) + 128); bytesWritten = 4; return true; } } } } bytesWritten = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Rune UnsafeCreate(uint scalarValue) { return new Rune(scalarValue, _: false); } } } namespace System.Text.Unicode { internal static class UnicodeHelpers { internal const int UNICODE_LAST_CODEPOINT = 1114111; private static ReadOnlySpan<byte> DefinedCharsBitmapSpan => new byte[8192] { 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 0, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 240, 215, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 127, 254, 255, 255, 255, 255, 255, 231, 254, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 135, 31, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 255, 255, 63, 255, 127, 255, 255, 255, 79, 255, 7, 255, 255, 255, 127, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 239, 159, 249, 255, 255, 253, 197, 243, 159, 121, 128, 176, 207, 255, 255, 127, 238, 135, 249, 255, 255, 253, 109, 211, 135, 57, 2, 94, 192, 255, 127, 0, 238, 191, 251, 255, 255, 253, 237, 243, 191, 59, 1, 0, 207, 255, 3, 254, 238, 159, 249, 255, 255, 253, 237, 243, 159, 57, 224, 176, 207, 255, 255, 0, 236, 199, 61, 214, 24, 199, 255, 195, 199, 61, 129, 0, 192, 255, 255, 7, 255, 223, 253, 255, 255, 253, 255, 243, 223, 61, 96, 39, 207, 255, 128, 255, 255, 223, 253, 255, 255, 253, 239, 243, 223, 61, 96, 96, 207, 255, 14, 0, 255, 223, 253, 255, 255, 255, 255, 255, 223, 253, 240, 255, 207, 255, 255, 255, 238, 255, 127, 252, 255, 255, 251, 47, 127, 132, 95, 255, 192, 255, 28, 0, 254, 255, 255, 255, 255, 255, 255, 135, 255, 255, 255, 15, 0, 0, 0, 0, 214, 247, 255, 255, 175, 255, 255, 63, 95, 127, 255, 243, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 31, 254, 255, 255, 255, 255, 254, 255, 255, 255, 223, 255, 223, 255, 7, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 61, 127, 61, 255, 255, 255, 255, 255, 61, 255, 255, 255, 255, 61, 127, 61, 255, 127, 255, 255, 255, 255, 255, 255, 255, 61, 255, 255, 255, 255, 255, 255, 255, 255, 231, 255, 255, 255, 31, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 63, 128, 255, 255, 127, 0, 255, 255, 15, 0, 255, 223, 13, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 3, 255, 3, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 7, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 255, 255, 255, 127, 255, 15, 255, 15, 241, 255, 255, 255, 255, 63, 31, 0, 255, 255, 255, 255, 255, 15, 255, 255, 255, 3, 255, 199, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 159, 255, 3, 255, 3, 255, 63, 255, 255, 255, 127, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 240, 255, 255, 255, 255, 255, 255, 255, 248, 255, 227, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 231, 255, 0, 255, 255, 255, 255, 255, 7, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 63, 255, 255, 255, 255, 63, 63, 255, 170, 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, 223, 255, 223, 255, 207, 239, 255, 255, 220, 127, 0, 248, 255, 255, 255, 124, 255, 255, 255, 255, 255, 127, 223, 255, 243, 255, 255, 127, 255, 31, 255, 255, 255, 255, 1, 0, 255, 255, 255, 255, 1, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 255, 7, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 254, 255, 255, 255, 255, 191, 32, 255, 255, 255, 255, 255, 255, 255, 128, 1, 128, 255, 255, 127, 0, 127, 127, 127, 127, 127, 127, 127, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 0, 0, 0, 255, 255, 255, 251, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 0, 0, 255, 15, 254, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 224, 255, 255, 255, 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 127, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 235, 3, 0, 0, 252, 255, 255, 255, 255, 255, 255, 31, 255, 3, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 63, 192, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 128, 255, 255, 255, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 195, 255, 255, 255, 127, 255, 255, 255, 255, 255, 255, 127, 0, 255, 63, 255, 243, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 0, 0, 248, 255, 255, 127, 0, 126, 126, 126, 0, 127, 127, 255, 255, 255, 255, 255, 255, 255, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 3, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 15, 0, 255, 255, 127, 248, 255, 255, 255, 255, 255, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 3, 0, 0, 0, 0, 127, 0, 248, 224, 255, 255, 127, 95, 219, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 7, 0, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, 255, 255, 255, 128, 0, 0, 0, 0, 255, 255, 255, 255, 255, 3, 255, 255, 255, 255, 255, 255, 247, 255, 127, 15, 223, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 252, 252, 252, 28, 127, 127, 0, 62 }; internal static ReadOnlySpan<byte> GetDefinedBmpCodePointsBitmapLittleEndian() { return DefinedCharsBitmapSpan; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void GetUtf16SurrogatePairFromAstralScalarValue(uint scalar, out char highSurrogate, out char lowSurrogate) { highSurrogate = (char)(scalar + 56557568 >> 10); lowSurrogate = (char)((scalar & 0x3FF) + 56320); } internal static int GetUtf8RepresentationForScalarValue(uint scalar) { if (scalar <= 127) { return (byte)scalar; } if (scalar <= 2047) { byte b = (byte)(0xC0u | (scalar >> 6)); byte b2 = (byte)(0x80u | (scalar & 0x3Fu)); return (b2 << 8) | b; } if (scalar <= 65535) { byte b3 = (byte)(0xE0u | (scalar >> 12)); byte b4 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu)); byte b5 = (byte)(0x80u | (scalar & 0x3Fu)); return (((b5 << 8) | b4) << 8) | b3; } byte b6 = (byte)(0xF0u | (scalar >> 18)); byte b7 = (byte)(0x80u | ((scalar >> 12) & 0x3Fu)); byte b8 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu)); byte b9 = (byte)(0x80u | (scalar & 0x3Fu)); return (((((b9 << 8) | b8) << 8) | b7) << 8) | b6; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsSupplementaryCodePoint(int scalar) { return (scalar & -65536) != 0; } } public sealed class UnicodeRange { public int FirstCodePoint { get; private set; } public int Length { get; private set; } public UnicodeRange(int firstCodePoint, int length) { if (firstCodePoint < 0 || firstCodePoint > 65535) { throw new ArgumentOutOfRangeException("firstCodePoint"); } if (length < 0 || (long)firstCodePoint + (long)length > 65536) { throw new ArgumentOutOfRangeException("length"); } FirstCodePoint = firstCodePoint; Length = length; } public static UnicodeRange Create(char firstCharacter, char lastCharacter) { if (lastCharacter < firstCharacter) { throw new ArgumentOutOfRangeException("lastCharacter"); } return new UnicodeRange(firstCharacter, 1 + (lastCharacter - firstCharacter)); } } public static class UnicodeRanges { private static UnicodeRange _none; private static UnicodeRange _all; private static UnicodeRange _u0000; private static UnicodeRange _u0080; private static UnicodeRange _u0100; private static UnicodeRange _u0180; private static UnicodeRange _u0250; private static UnicodeRange _u02B0; private static UnicodeRange _u0300; private static UnicodeRange _u0370; private static UnicodeRange _u0400; private static UnicodeRange _u0500; private static UnicodeRange _u0530; private static UnicodeRange _u0590; private static UnicodeRange _u0600; private static UnicodeRange _u0700; private static UnicodeRange _u0750; private static UnicodeRange _u0780; private static UnicodeRange _u07C0; private static UnicodeRange _u0800; private static UnicodeRange _u0840; private static UnicodeRange _u0860; private static UnicodeRange _u0870; private static UnicodeRange _u08A0; private static UnicodeRange _u0900; private static UnicodeRange _u0980; private static UnicodeRange _u0A00; private static UnicodeRange _u0A80; private static UnicodeRange _u0B00; private static UnicodeRange _u0B80; private static UnicodeRange _u0C00; private static UnicodeRange _u0C80; private static UnicodeRange _u0D00; private static UnicodeRange _u0D80; private static UnicodeRange _u0E00; private static UnicodeRange _u0E80; private static UnicodeRange _u0F00; private static UnicodeRange _u1000; private static UnicodeRange _u10A0; private static UnicodeRange _u1100; private static UnicodeRange _u1200; private static UnicodeRange _u1380; private static UnicodeRange _u13A0; private static UnicodeRange _u1400; private static UnicodeRange _u1680; private static UnicodeRange _u16A0; private static UnicodeRange _u1700; private static UnicodeRange _u1720; private static UnicodeRange _u1740; private static UnicodeRange _u1760; private static UnicodeRange _u1780; private static UnicodeRange _u1800; private static UnicodeRange _u18B0; private static UnicodeRange _u1900; private static UnicodeRange _u1950; private static UnicodeRange _u1980; private static UnicodeRange _u19E0; private static UnicodeRange _u1A00; private static UnicodeRange _u1A20; private static UnicodeRange _u1AB0; private static UnicodeRange _u1B00; private static UnicodeRange _u1B80; private static UnicodeRange _u1BC0; private static UnicodeRange _u1C00; private static UnicodeRange _u1C50; private static UnicodeRange _u1C80; private static UnicodeRange _u1C90; private static UnicodeRange _u1CC0; private static UnicodeRange _u1CD0; private static UnicodeRange _u1D00; private static UnicodeRange _u1D80; private static UnicodeRange _u1DC0; private static UnicodeRange _u1E00; private static UnicodeRange _u1F00; private static UnicodeRange _u2000; private static UnicodeRange _u2070; private static UnicodeRange _u20A0; private static UnicodeRange _u20D0; private static UnicodeRange _u2100; private static UnicodeRange _u2150; private static UnicodeRange _u2190; private static UnicodeRange _u2200; private static UnicodeRange _u2300; private static UnicodeRange _u2400; private static UnicodeRange _u2440; private static UnicodeRange _u2460; private static UnicodeRange _u2500; private static UnicodeRange _u2580; private static UnicodeRange _u25A0; private static UnicodeRange _u2600; private static UnicodeRange _u2700; private static UnicodeRange _u27C0; private static UnicodeRange _u27F0; private static UnicodeRange _u2800; private static UnicodeRange _u2900; private static UnicodeRange _u2980; private static UnicodeRange _u2A00; private static UnicodeRange _u2B00; private static UnicodeRange _u2C00; private static UnicodeRange _u2C60; private static UnicodeRange _u2C80; private static UnicodeRange _u2D00; private static UnicodeRange _u2D30; private static UnicodeRange _u2D80; private static UnicodeRange _u2DE0; private static UnicodeRange _u2E00; private static UnicodeRange _u2E80; private static UnicodeRange _u2F00; private static UnicodeRange _u2FF0; private static UnicodeRange _u3000; private static UnicodeRange _u3040; private static UnicodeRange _u30A0; private static UnicodeRange _u3100; private static UnicodeRange _u3130; private static UnicodeRange _u3190; private static UnicodeRange _u31A0; private static UnicodeRange _u31C0; private static UnicodeRange _u31F0; private static UnicodeRange _u3200; private static UnicodeRange _u3300; private static UnicodeRange _u3400; private static UnicodeRange _u4DC0; private static UnicodeRange _u4E00; private static UnicodeRange _uA000; private static UnicodeRange _uA490; private static UnicodeRange _uA4D0; private static UnicodeRange _uA500; private static UnicodeRange _uA640; private static UnicodeRange _uA6A0; private static UnicodeRange _uA700; private static UnicodeRange _uA720; private static UnicodeRange _uA800; private static UnicodeRange _uA830; private static UnicodeRange _uA840; private static UnicodeRange _uA880; private static UnicodeRange _uA8E0; private static UnicodeRange _uA900; private static UnicodeRange _uA930; private static UnicodeRange _uA960; private static UnicodeRange _uA980; private static UnicodeRange _uA9E0; private static UnicodeRange _uAA00; private static UnicodeRange _uAA60; private static UnicodeRange _uAA80; private static UnicodeRange _uAAE0; private static UnicodeRange _uAB00; private static UnicodeRange _uAB30; private static UnicodeRange _uAB70; private static UnicodeRange _uABC0; private static UnicodeRange _uAC00; private static UnicodeRange _uD7B0; private static UnicodeRange _uF900; private static UnicodeRange _uFB00; private static UnicodeRange _uFB50; private static UnicodeRange _uFE00; private static UnicodeRange _uFE10; private static UnicodeRange _uFE20; private static UnicodeRange _uFE30; private static UnicodeRange _uFE50; private static UnicodeRange _uFE70; private static UnicodeRange _uFF00; private static UnicodeRange _uFFF0; public static UnicodeRange None => _none ?? CreateEmptyRange(ref _none); public static UnicodeRange All => _all ?? CreateRange(ref _all, '\0', '\uffff'); public static UnicodeRange BasicLatin => _u0000 ?? CreateRange(ref _u0000, '\0', '\u007f'); public static UnicodeRange Latin1Supplement => _u0080 ?? CreateRange(ref _u0080, '\u0080', 'ÿ'); public static UnicodeRange LatinExtendedA => _u0100 ?? CreateRange(ref _u0100, 'Ā', 'ſ'); public static UnicodeRange LatinExtendedB => _u0180 ?? CreateRange(ref _u0180, 'ƀ', 'ɏ'); public static UnicodeRange IpaExtensions => _u0250 ?? CreateRange(ref _u0250, 'ɐ', 'ʯ'); public static UnicodeRange SpacingModifierLetters => _u02B0 ?? CreateRange(ref _u02B0, 'ʰ', '\u02ff'); public static UnicodeRange CombiningDiacriticalMarks => _u0300 ?? CreateRange(ref _u0300, '\u0300', '\u036f'); public static UnicodeRange GreekandCoptic => _u0370 ?? CreateRange(ref _u0370, 'Ͱ', 'Ͽ'); public static UnicodeRange Cyrillic => _u0400 ?? CreateRange(ref _u0400, 'Ѐ', 'ӿ'); public static UnicodeRange CyrillicSupplement => _u0500 ?? CreateRange(ref _u0500, 'Ԁ', 'ԯ'); public static UnicodeRange Armenian => _u0530 ?? CreateRange(ref _u0530, '\u0530', '֏'); public static UnicodeRange Hebrew => _u0590 ?? CreateRange(ref _u0590, '\u0590', '\u05ff'); public static UnicodeRange Arabic => _u0600 ?? CreateRange(ref _u0600, '\u0600', 'ۿ'); public static UnicodeRange Syriac => _u0700 ?? CreateRange(ref _u0700, '܀', 'ݏ'); public static UnicodeRange ArabicSupplement => _u0750 ?? CreateRange(ref _u0750, 'ݐ', 'ݿ'); public static UnicodeRange Thaana => _u0780 ?? CreateRange(ref _u0780, 'ހ', '\u07bf'); public static UnicodeRange NKo => _u07C0 ?? CreateRange(ref _u07C0, '߀', '߿'); public static UnicodeRange Samaritan => _u0800 ?? CreateRange(ref _u0800, 'ࠀ', '\u083f'); public static UnicodeRange Mandaic => _u0840 ?? CreateRange(ref _u0840, 'ࡀ', '\u085f'); public static UnicodeRange SyriacSupplement => _u0860 ?? CreateRange(ref _u0860, 'ࡠ', '\u086f'); public static UnicodeRange ArabicExtendedB => _u0870 ?? CreateRange(ref _u0870, '\u0870', '\u089f'); public static UnicodeRange ArabicExtendedA => _u08A0 ?? CreateRange(ref _u08A0, 'ࢠ', '\u08ff'); public static UnicodeRange Devanagari => _u0900 ?? CreateRange(ref _u0900, '\u0900', 'ॿ'); public static UnicodeRange Bengali => _u0980 ?? CreateRange(ref _u0980, 'ঀ', '\u09ff'); public static UnicodeRange Gurmukhi => _u0A00 ?? CreateRange(ref _u0A00, '\u0a00', '\u0a7f'); public static UnicodeRange Gujarati => _u0A80 ?? CreateRange(ref _u0A80, '\u0a80', '\u0aff'); public static UnicodeRange Oriya => _u0B00 ?? CreateRange(ref _u0B00, '\u0b00', '\u0b7f'); public static UnicodeRange Tamil => _u0B80 ?? CreateRange(ref _u0B80, '\u0b80', '\u0bff'); public static UnicodeRange Telugu => _u0C00 ?? CreateRange(ref _u0C00, '\u0c00', '౿'); public static UnicodeRange Kannada => _u0C80 ?? CreateRange(ref _u0C80, 'ಀ', '\u0cff'); public static UnicodeRange Malayalam => _u0D00 ?? CreateRange(ref _u0D00, '\u0d00', 'ൿ'); public static UnicodeRange Sinhala => _u0D80 ?? CreateRange(ref _u0D80, '\u0d80', '\u0dff'); public static UnicodeRange Thai => _u0E00 ?? CreateRange(ref _u0E00, '\u0e00', '\u0e7f'); public static UnicodeRange Lao => _u0E80 ?? CreateRange(ref _u0E80, '\u0e80', '\u0eff'); public static UnicodeRange Tibetan => _u0F00 ?? CreateRange(ref _u0F00, 'ༀ', '\u0fff'); public static UnicodeRange Myanmar => _u1000 ?? CreateRange(ref _u1000, 'က', '႟'); public static UnicodeRange Georgian => _u10A0 ?? CreateRange(ref _u10A0, 'Ⴀ', 'ჿ'); public static UnicodeRange HangulJamo => _u1100 ?? CreateRange(ref _u1100, 'ᄀ', 'ᇿ'); public static UnicodeRange Ethiopic => _u1200 ?? CreateRange(ref _u1200, 'ሀ', '\u137f'); public static UnicodeRange EthiopicSupplement => _u1380 ?? CreateRange(ref _u1380, 'ᎀ', '\u139f'); public static UnicodeRange Cherokee => _u13A0 ?? CreateRange(ref _u13A0, 'Ꭰ', '\u13ff'); public static UnicodeRange UnifiedCanadianAboriginalSyllabics => _u1400 ?? CreateRange(ref _u1400, '᐀', 'ᙿ'); public static UnicodeRange Ogham => _u1680 ?? CreateRange(ref _u1680, '\u1680', '\u169f'); public static UnicodeRange Runic => _u16A0 ?? CreateRange(ref _u16A0, 'ᚠ', '\u16ff'); public static UnicodeRange Tagalog => _u1700 ?? CreateRange(ref _u1700, 'ᜀ', '\u171f'); public static UnicodeRange Hanunoo => _u1720 ?? CreateRange(ref _u1720, 'ᜠ', '\u173f'); public static UnicodeRange Buhid => _u1740 ?? CreateRange(ref _u1740, 'ᝀ', '\u175f'); public static UnicodeRange Tagbanwa => _u1760 ?? CreateRange(ref _u1760, 'ᝠ', '\u177f'); public static UnicodeRange Khmer => _u1780 ?? CreateRange(ref _u1780, 'ក', '\u17ff'); public static UnicodeRange Mongolian => _u1800 ?? CreateRange(ref _u1800, '᠀', '\u18af'); public static UnicodeRange UnifiedCanadianAboriginalSyllabicsExtended => _u18B0 ?? CreateRange(ref _u18B0, 'ᢰ', '\u18ff'); public static UnicodeRange Limbu => _u1900 ?? CreateRange(ref _u1900, 'ᤀ', '᥏'); public static UnicodeRange TaiLe => _u1950 ?? CreateRange(ref _u1950, 'ᥐ', '\u197f'); public static UnicodeRange NewTaiLue => _u1980 ?? CreateRange(ref _u1980, 'ᦀ', '᧟'); public static UnicodeRange KhmerSymbols => _u19E0 ?? CreateRange(ref _u19E0, '᧠', '᧿'); public static UnicodeRange Buginese => _u1A00 ?? CreateRange(ref _u1A00, 'ᨀ', '᨟'); public static UnicodeRange TaiTham => _u1A20 ?? CreateRange(ref _u1A20, 'ᨠ', '\u1aaf'); public static UnicodeRange CombiningDiacriticalMarksExtended => _u1AB0 ?? CreateRange(ref _u1AB0, '\u1ab0', '\u1aff'); public static UnicodeRange Balinese => _u1B00 ?? CreateRange(ref _u1B00, '\u1b00', '\u1b7f'); public static UnicodeRange Sundanese => _u1B80 ?? CreateRange(ref _u1B80, '\u1b80', 'ᮿ'); public static UnicodeRange Batak => _u1BC0 ?? CreateRange(ref _u1BC0, 'ᯀ', '᯿'); public static UnicodeRange Lepcha => _u1C00 ?? CreateRange(ref _u1C00, 'ᰀ', 'ᱏ'); public static UnicodeRange OlChiki => _u1C50 ?? CreateRange(ref _u1C50, '᱐', '᱿'); public static UnicodeRange CyrillicExtendedC => _u1C80 ?? CreateRange(ref _u1C80, 'ᲀ', '\u1c8f'); public static UnicodeRange GeorgianExtended => _u1C90 ?? CreateRange(ref _u1C90, 'Ა', 'Ჿ'); public static UnicodeRange SundaneseSupplement => _u1CC0 ?? CreateRange(ref _u1CC0, '᳀', '\u1ccf'); public static UnicodeRange VedicExtensions => _u1CD0 ?? CreateRange(ref _u1CD0, '\u1cd0', '\u1cff'); public static UnicodeRange PhoneticExtensions => _u1D00 ?? CreateRange(ref _u1D00, 'ᴀ', 'ᵿ'); public static UnicodeRange PhoneticExtensionsSupplement => _u1D80 ?? CreateRange(ref _u1D80, 'ᶀ', 'ᶿ'); public static UnicodeRange CombiningDiacriticalMarksSupplement => _u1DC0 ?? CreateRange(ref _u1DC0, '\u1dc0', '\u1dff'); public static UnicodeRange LatinExtendedAdditional => _u1E00 ?? CreateRange(ref _u1E00, 'Ḁ', 'ỿ'); public static UnicodeRange GreekExtended => _u1F00 ?? CreateRange(ref _u1F00, 'ἀ', '\u1fff'); public static UnicodeRange GeneralPunctuation => _u2000 ?? CreateRange(ref _u2000, '\u2000', '\u206f'); public static UnicodeRange SuperscriptsandSubscripts => _u2070 ?? CreateRange(ref _u2070, '⁰', '\u209f'); public static UnicodeRange CurrencySymbols => _u20A0 ?? CreateRange(ref _u20A0, '₠', '\u20cf'); public static UnicodeRange CombiningDiacriticalMarksforSymbols => _u20D0 ?? CreateRange(ref _u20D0, '\u20d0', '\u20ff'); public static UnicodeRange LetterlikeSymbols => _u2100 ?? CreateRange(ref _u2100, '℀', '⅏'); public static UnicodeRange NumberForms => _u2150 ?? CreateRange(ref _u2150, '⅐', '\u218f'); public static UnicodeRange Arrows => _u2190 ?? CreateRange(ref _u2190, '←', '⇿'); public static UnicodeRange MathematicalOperators => _u2200 ?? CreateRange(ref _u2200, '∀', '⋿'); public static UnicodeRange MiscellaneousTechnical => _u2300 ?? CreateRange(ref _u2300, '⌀', '⏿'); public static UnicodeRange ControlPictures => _u2400 ?? CreateRange(ref _u2400, '␀', '\u243f'); public static UnicodeRange OpticalCharacterRecognition => _u2440 ?? CreateRange(ref _u2440, '⑀', '\u245f'); public static UnicodeRange EnclosedAlphanumerics => _u2460 ?? CreateRange(ref _u2460, '①', '⓿'); public static UnicodeRange BoxDrawing => _u2500 ?? CreateRange(ref _u2500, '─', '╿'); public static UnicodeRange BlockElements => _u2580 ?? CreateRange(ref _u2580, '▀', '▟'); public static UnicodeRange GeometricShapes => _u25A0 ?? CreateRange(ref _u25A0, '■', '◿'); public static UnicodeRange MiscellaneousSymbols => _u2600 ?? CreateRange(ref _u2600, '☀', '⛿'); public static UnicodeRange Dingbats => _u2700 ?? CreateRange(ref _u2700, '✀', '➿'); public static UnicodeRange MiscellaneousMathematicalSymbolsA => _u27C0 ?? CreateRange(ref _u27C0, '⟀', '⟯'); public static UnicodeRange SupplementalArrowsA => _u27F0 ?? CreateRange(ref _u27F0, '⟰', '⟿'); public static UnicodeRange BraillePatterns => _u2800 ?? CreateRange(ref _u2800, '⠀', '⣿'); public static UnicodeRange SupplementalArrowsB => _u2900 ?? CreateRange(ref _u2900, '⤀', '⥿'); public static UnicodeRange MiscellaneousMathematicalSymbolsB => _u2980 ?? CreateRange(ref _u2980, '⦀', '⧿'); public static UnicodeRange SupplementalMathematicalOperators => _u2A00 ?? CreateRange(ref _u2A00, '⨀', '⫿'); public static UnicodeRange MiscellaneousSymbolsandArrows => _u2B00 ?? CreateRange(ref _u2B00, '⬀', '⯿'); public static UnicodeRange Glagolitic => _u2C00 ?? CreateRange(ref _u2C00, 'Ⰰ', '\u2c5f'); public static UnicodeRange LatinExtendedC => _u2C60 ?? CreateRange(ref _u2C60, 'Ⱡ', 'Ɀ'); public static UnicodeRange Coptic => _u2C80 ?? CreateRange(ref _u2C80, 'Ⲁ', '⳿'); public static UnicodeRange GeorgianSupplement => _u2D00 ?? CreateRange(ref _u2D00, 'ⴀ', '\u2d2f'); public static UnicodeRange Tifinagh => _u2D30 ?? CreateRange(ref _u2D30, 'ⴰ', '\u2d7f'); public static UnicodeRange EthiopicExtended => _u2D80 ?? CreateRange(ref _u2D80, 'ⶀ', '\u2ddf'); public static UnicodeRange CyrillicExtendedA => _u2DE0 ?? CreateRange(ref _u2DE0, '\u2de0', '\u2dff'); public static UnicodeRange SupplementalPunctuation => _u2E00 ?? CreateRange(ref _u2E00, '⸀', '\u2e7f'); public static UnicodeRange CjkRadicalsSupplement => _u2E80 ?? CreateRange(ref _u2E80, '⺀', '\u2eff'); public static UnicodeRange KangxiRadicals => _u2F00 ?? CreateRange(ref _u2F00, '⼀', '\u2fdf'); public static UnicodeRange IdeographicDescriptionCharacters => _u2FF0 ?? CreateRange(ref _u2FF0, '⿰', '\u2fff'); public static UnicodeRange CjkSymbolsandPunctuation => _u3000 ?? CreateRange(ref _u3000, '\u3000', '〿'); public static UnicodeRange Hiragana => _u3040 ?? CreateRange(ref _u3040, '\u3040', 'ゟ'); public static UnicodeRange Katakana => _u30A0 ?? CreateRange(ref _u30A0, '゠', 'ヿ'); public static UnicodeRange Bopomofo => _u3100 ?? CreateRange(ref _u3100, '\u3100', 'ㄯ'); public static UnicodeRange HangulCompatibilityJamo => _u3130 ?? CreateRange(ref _u3130, '\u3130', '\u318f'); public static UnicodeRange Kanbun => _u3190 ?? CreateRange(ref _u3190, '㆐', '㆟'); public static UnicodeRange BopomofoExtended => _u31A0 ?? CreateRange(ref _u31A0, 'ㆠ', 'ㆿ'); public static UnicodeRange CjkStrokes => _u31C0 ?? CreateRange(ref _u31C0, '㇀', '\u31ef'); public static UnicodeRange KatakanaPhoneticExtensions => _u31F0 ?? CreateRange(ref _u31F0, 'ㇰ', 'ㇿ'); public static UnicodeRange EnclosedCjkLettersandMonths => _u3200 ?? CreateRange(ref _u3200, '㈀', '㋿'); public static UnicodeRange CjkCompatibility => _u3300 ?? CreateRange(ref _u3300, '㌀', '㏿'); public static UnicodeRange CjkUnifiedIdeographsExtensionA => _u3400 ?? CreateRange(ref _u3400, '㐀', '䶿'); public static UnicodeRange YijingHexagramSymbols => _u4DC0 ?? CreateRange(ref _u4DC0, '䷀', '䷿'); public static UnicodeRange CjkUnifiedIdeographs => _u4E00 ?? CreateRange(ref _u4E00, '一', '\u9fff'); public static UnicodeRange YiSyllables => _uA000 ?? CreateRange(ref _uA000, 'ꀀ', '\ua48f'); public static UnicodeRange YiRadicals => _uA490 ?? CreateRange(ref _uA490, '꒐', '\ua4cf'); public static UnicodeRange Lisu => _uA4D0 ?? CreateRange(ref _uA4D0, 'ꓐ', '꓿'); public static UnicodeRange Vai => _uA500 ?? CreateRange(ref _uA500, 'ꔀ', '\ua63f'); public static UnicodeRange CyrillicExtendedB => _uA640 ?? CreateRange(ref _uA640, 'Ꙁ', '\ua69f'); public static UnicodeRange Bamum => _uA6A0 ?? CreateRange(ref _uA6A0, 'ꚠ', '\ua6ff'); public static UnicodeRange ModifierToneLetters => _uA700 ?? CreateRange(ref _uA700, '\ua700', 'ꜟ'); public static UnicodeRange LatinExtendedD => _uA720 ?? CreateRange(ref _uA720, '\ua720', 'ꟿ'); public static UnicodeRange SylotiNagri => _uA800 ?? CreateRange(ref _uA800, 'ꠀ', '\ua82f'); public static UnicodeRange CommonIndicNumberForms => _uA830 ?? CreateRange(ref _uA830, '꠰', '\ua83f'); public static UnicodeRange Phagspa => _uA840 ?? CreateRange(ref _uA840, 'ꡀ', '\ua87f'); public static UnicodeRange Saurashtra => _uA880 ?? CreateRange(ref _uA880, '\ua880', '\ua8df'); public static UnicodeRange DevanagariExtended => _uA8E0 ?? CreateRange(ref _uA8E0, '\ua8e0', '\ua8ff'); public static UnicodeRange KayahLi => _uA900 ?? CreateRange(ref _uA900, '꤀', '꤯'); public static UnicodeRange Rejang => _uA930 ?? CreateRange(ref _uA930, 'ꤰ', '꥟'); public static UnicodeRange HangulJamoExtendedA => _uA960 ?? CreateRange(ref _uA960, 'ꥠ', '\ua97f'); public static UnicodeRange Javanese => _uA980 ?? CreateRange(ref _uA980, '\ua980', '꧟'); public static UnicodeRange MyanmarExtendedB => _uA9E0 ?? CreateRange(ref _uA9E0, 'ꧠ', '\ua9ff'); public static UnicodeRange Cham => _uAA00 ?? CreateRange(ref _uAA00, 'ꨀ', '꩟'); public static UnicodeRange MyanmarExtendedA => _uAA60 ?? CreateRange(ref _uAA60, 'ꩠ', 'ꩿ'); public static UnicodeRange TaiViet => _uAA80 ?? CreateRange(ref _uAA80, 'ꪀ', '꫟'); public static UnicodeRange MeeteiMayekExtensions => _uAAE0 ?? CreateRange(ref _uAAE0, 'ꫠ', '\uaaff'); public static UnicodeRange EthiopicExtendedA => _uAB00 ?? CreateRange(ref _uAB00, '\uab00', '\uab2f'); public static UnicodeRange LatinExtendedE => _uAB30 ?? CreateRange(ref _uAB30, 'ꬰ', '\uab6f'); public static UnicodeRange CherokeeSupplement => _uAB70 ?? CreateRange(ref _uAB70, 'ꭰ', 'ꮿ'); public static UnicodeRange MeeteiMayek => _uABC0 ?? CreateRange(ref _uABC0, 'ꯀ', '\uabff'); public static UnicodeRange HangulSyllables => _uAC00 ?? CreateRange(ref _uAC00, '가', '\ud7af'); public static UnicodeRange HangulJamoExtendedB => _uD7B0 ?? CreateRange(ref _uD7B0, 'ힰ', '\ud7ff'); public static UnicodeRange CjkCompatibilityIdeographs => _uF900 ?? CreateRange(ref _uF900, '豈', '\ufaff'); public static UnicodeRange AlphabeticPresentationForms => _uFB00 ?? CreateRange(ref _uFB00, 'ff', 'ﭏ'); public static UnicodeRange ArabicPresentationFormsA => _uFB50 ?? CreateRange(ref _uFB50, 'ﭐ', '\ufdff'); public static UnicodeRange VariationSelectors => _uFE00 ?? CreateRange(ref _uFE00, '\ufe00', '\ufe0f'); public static UnicodeRange VerticalForms => _uFE10 ?? CreateRange(ref _uFE10, '︐', '\ufe1f'); public static UnicodeRange CombiningHalfMarks => _uFE20 ?? CreateRange(ref _uFE20, '\ufe20', '\ufe2f'); public static UnicodeRange CjkCompatibilityForms => _uFE30 ?? CreateRange(ref _uFE30, '︰', '\ufe4f'); public static UnicodeRange SmallFormVariants => _uFE50 ?? CreateRange(ref _uFE50, '﹐', '\ufe6f'); public static UnicodeRange ArabicPresentationFormsB => _uFE70 ?? CreateRange(ref _uFE70, 'ﹰ', '\ufeff'); public static UnicodeRange HalfwidthandFullwidthForms => _uFF00 ?? CreateRange(ref _uFF00, '\uff00', '\uffef'); public static UnicodeRange Specials => _uFFF0 ?? CreateRange(ref _uFFF0, '\ufff0', '\uffff'); [MethodImpl(MethodImplOptions.NoInlining)] private static UnicodeRange CreateEmptyRange([NotNull] ref UnicodeRange range) { Volatile.Write(ref range, new UnicodeRange(0, 0)); return range; } [MethodImpl(MethodImplOptions.NoInlining)] private static UnicodeRange CreateRange([NotNull] ref UnicodeRange range, char first, char last) { Volatile.Write(ref range, UnicodeRange.Create(first, last)); return range; } } } namespace System.Text.Encodings.Web { internal struct AsciiByteMap { private const int BufferSize = 128; private unsafe fixed byte Buffer[128]; internal unsafe void InsertAsciiChar(char key, byte value) { if (key < '\u0080') { Buffer[(uint)key] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe readonly bool TryLookup(Rune key, out byte value) { if (key.IsAscii) { byte b = Buffer[(uint)key.Value]; if (b != 0) { value = b; return true; } } value = 0; return false; } } internal struct AllowedBmpCodePointsBitmap { private const int BitmapLengthInDWords = 2048; private unsafe fixed uint Bitmap[2048]; [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void AllowChar(char value) { _GetIndexAndOffset(value, out UIntPtr index, out int offset); ref uint reference = ref Bitmap[(ulong)index]; reference |= (uint)(1 << offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void ForbidChar(char value) { _GetIndexAndOffset(value, out UIntPtr index, out int offset); ref uint reference = ref Bitmap[(ulong)index]; reference &= (uint)(~(1 << offset)); } public void ForbidHtmlCharacters() { ForbidChar('<'); ForbidChar('>'); ForbidChar('&'); ForbidChar('\''); ForbidChar('"'); ForbidChar('+'); } public unsafe void ForbidUndefinedCharacters() { fixed (uint* pointer = Bitmap) { ReadOnlySpan<byte> definedBmpCodePointsBitmapLittleEndian = UnicodeHelpers.GetDefinedBmpCodePointsBitmapLittleEndian(); Span<uint> span = new Span<uint>(pointer, 2048); for (int i = 0; i < span.Length; i++) { span[i] &= BinaryPrimitives.ReadUInt32LittleEndian(definedBmpCodePointsBitmapLittleEndian.Slice(i * 4)); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe readonly bool IsCharAllowed(char value) { _GetIndexAndOffset(value, out UIntPtr index, out int offset); if ((Bitmap[(ulong)index] & (uint)(1 << offset)) != 0) { return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe read
deps/System.Text.Json.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Encodings.Web; using System.Text.Json.Nodes; using System.Text.Json.Reflection; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Converters; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; using FxResources.System.Text.Json; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Text.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nThe System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")] [assembly: AssemblyFileVersion("8.0.1825.31117")] [assembly: AssemblyInformationalVersion("8.0.18+ef853a71052646a42abf17e888ec6d9a69614ad9")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Text.Json")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] 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] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : 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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [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 FxResources.System.Text.Json { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { byte value = readOnlySpan[i]; ToCharsBuffer(value, buffer, num, casing); num += 2; } return buffer.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { if (IntPtr.Size == 8) { ulong num = (uint)(c - 48); ulong num2 = (ulong)(-17875860044349952L << (int)num); ulong num3 = num - 64; return (long)(num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; internal const string EncryptionPolicyDiagId = "SYSLIB0040"; internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations."; internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041"; internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys."; internal const string EccXmlExportImportDiagId = "SYSLIB0042"; internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead."; internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043"; internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."; internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044"; internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead."; internal const string CryptoStringFactoryDiagId = "SYSLIB0045"; internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code."; internal const string ControlledExecutionRunDiagId = "SYSLIB0046"; internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution."; internal const string XmlSecureResolverDiagId = "SYSLIB0047"; internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead."; internal const string RsaEncryptDecryptDiagId = "SYSLIB0048"; internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties."; internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049"; internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used."; internal const string LegacyFormatterDiagId = "SYSLIB0050"; internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code."; internal const string LegacyFormatterImplDiagId = "SYSLIB0051"; internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported."; internal const string RegexExtensibilityDiagId = "SYSLIB0052"; internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size."; internal const string AesGcmTagConstructorDiagId = "SYSLIB0053"; } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge"); internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss"); internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16"); internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16"); internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose"); internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty"); internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8"); internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64"); internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16"); internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16"); internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8"); internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray"); internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty"); internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose"); internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject"); internal static string DepthTooLarge => GetResourceString("DepthTooLarge"); internal static string DestinationTooShort => GetResourceString("DestinationTooShort"); internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid"); internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound"); internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound"); internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson"); internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound"); internal static string ExpectedFalse => GetResourceString("ExpectedFalse"); internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens"); internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken"); internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound"); internal static string ExpectedNull => GetResourceString("ExpectedNull"); internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound"); internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound"); internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound"); internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound"); internal static string ExpectedTrue => GetResourceString("ExpectedTrue"); internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound"); internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan"); internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter"); internal static string InvalidCast => GetResourceString("InvalidCast"); internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString"); internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString"); internal static string InvalidEnumTypeWithSpecialChar => GetResourceString("InvalidEnumTypeWithSpecialChar"); internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive"); internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString"); internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments"); internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType"); internal static string DefaultTypeInfoResolverImmutable => GetResourceString("DefaultTypeInfoResolverImmutable"); internal static string TypeInfoResolverChainImmutable => GetResourceString("TypeInfoResolverChainImmutable"); internal static string TypeInfoImmutable => GetResourceString("TypeInfoImmutable"); internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive"); internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid"); internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray"); internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty"); internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge"); internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge"); internal static string FormatDecimal => GetResourceString("FormatDecimal"); internal static string FormatDouble => GetResourceString("FormatDouble"); internal static string FormatInt32 => GetResourceString("FormatInt32"); internal static string FormatInt64 => GetResourceString("FormatInt64"); internal static string FormatSingle => GetResourceString("FormatSingle"); internal static string FormatUInt32 => GetResourceString("FormatUInt32"); internal static string FormatUInt64 => GetResourceString("FormatUInt64"); internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal"); internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign"); internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData"); internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported"); internal static string ValueTooLarge => GetResourceString("ValueTooLarge"); internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd"); internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue"); internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType"); internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize"); internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar"); internal static string InvalidComparison => GetResourceString("InvalidComparison"); internal static string UnsupportedFormat => GetResourceString("UnsupportedFormat"); internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment"); internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd"); internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd"); internal static string SerializerOptionsReadOnly => GetResourceString("SerializerOptionsReadOnly"); internal static string SerializerOptions_InvalidChainedResolver => GetResourceString("SerializerOptions_InvalidChainedResolver"); internal static string StreamNotWritable => GetResourceString("StreamNotWritable"); internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter"); internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict"); internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull"); internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid"); internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute"); internal static string ExtensionDataConflictsWithUnmappedMemberHandling => GetResourceString("ExtensionDataConflictsWithUnmappedMemberHandling"); internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType"); internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization"); internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment"); internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment"); internal static string CannotSkip => GetResourceString("CannotSkip"); internal static string NotEnoughData => GetResourceString("NotEnoughData"); internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator"); internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments"); internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor"); internal static string DeserializePolymorphicInterface => GetResourceString("DeserializePolymorphicInterface"); internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible"); internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid"); internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead"); internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible"); internal static string ResolverTypeNotCompatible => GetResourceString("ResolverTypeNotCompatible"); internal static string ResolverTypeInfoOptionsNotCompatible => GetResourceString("ResolverTypeInfoOptionsNotCompatible"); internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite"); internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull"); internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute"); internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize"); internal static string FormatByte => GetResourceString("FormatByte"); internal static string FormatInt16 => GetResourceString("FormatInt16"); internal static string FormatSByte => GetResourceString("FormatSByte"); internal static string FormatUInt16 => GetResourceString("FormatUInt16"); internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected"); internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber"); internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable"); internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound"); internal static string MetadataIdIsNotFirstProperty => GetResourceString("MetadataIdIsNotFirstProperty"); internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType"); internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues"); internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed"); internal static string MetadataInvalidPropertyInArrayMetadata => GetResourceString("MetadataInvalidPropertyInArrayMetadata"); internal static string MetadataStandaloneValuesProperty => GetResourceString("MetadataStandaloneValuesProperty"); internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties"); internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound"); internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString"); internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign"); internal static string MetadataUnexpectedProperty => GetResourceString("MetadataUnexpectedProperty"); internal static string UnmappedJsonProperty => GetResourceString("UnmappedJsonProperty"); internal static string MetadataDuplicateTypeProperty => GetResourceString("MetadataDuplicateTypeProperty"); internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter"); internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding"); internal static string ObjectWithParameterizedCtorRefMetadataNotSupported => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotSupported"); internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull"); internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType"); internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam"); internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded"); internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType"); internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported"); internal static string JsonIncludeOnInaccessibleProperty => GetResourceString("JsonIncludeOnInaccessibleProperty"); internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember"); internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection"); internal static string ConstructorContainsNullParameterNames => GetResourceString("ConstructorContainsNullParameterNames"); internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified"); internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid"); internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported"); internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid"); internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid"); internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes"); internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType"); internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue"); internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull"); internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory"); internal static string SerializerConverterFactoryInvalidArgument => GetResourceString("SerializerConverterFactoryInvalidArgument"); internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType"); internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray"); internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent"); internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected"); internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert"); internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement"); internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed"); internal static string NodeWrongType => GetResourceString("NodeWrongType"); internal static string NodeParentWrongType => GetResourceString("NodeParentWrongType"); internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey"); internal static string SerializerContextOptionsReadOnly => GetResourceString("SerializerContextOptionsReadOnly"); internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid"); internal static string NoMetadataForType => GetResourceString("NoMetadataForType"); internal static string AmbiguousMetadataForType => GetResourceString("AmbiguousMetadataForType"); internal static string CollectionIsReadOnly => GetResourceString("CollectionIsReadOnly"); internal static string ArrayIndexNegative => GetResourceString("ArrayIndexNegative"); internal static string ArrayTooSmall => GetResourceString("ArrayTooSmall"); internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty"); internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties"); internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual"); internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember"); internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported"); internal static string Polymorphism_BaseConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_BaseConverterDoesNotSupportMetadata"); internal static string Polymorphism_DerivedConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_DerivedConverterDoesNotSupportMetadata"); internal static string Polymorphism_TypeDoesNotSupportPolymorphism => GetResourceString("Polymorphism_TypeDoesNotSupportPolymorphism"); internal static string Polymorphism_DerivedTypeIsNotSupported => GetResourceString("Polymorphism_DerivedTypeIsNotSupported"); internal static string Polymorphism_DerivedTypeIsAlreadySpecified => GetResourceString("Polymorphism_DerivedTypeIsAlreadySpecified"); internal static string Polymorphism_TypeDicriminatorIdIsAlreadySpecified => GetResourceString("Polymorphism_TypeDicriminatorIdIsAlreadySpecified"); internal static string Polymorphism_InvalidCustomTypeDiscriminatorPropertyName => GetResourceString("Polymorphism_InvalidCustomTypeDiscriminatorPropertyName"); internal static string Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes => GetResourceString("Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes"); internal static string Polymorphism_UnrecognizedTypeDiscriminator => GetResourceString("Polymorphism_UnrecognizedTypeDiscriminator"); internal static string Polymorphism_RuntimeTypeNotSupported => GetResourceString("Polymorphism_RuntimeTypeNotSupported"); internal static string Polymorphism_RuntimeTypeDiamondAmbiguity => GetResourceString("Polymorphism_RuntimeTypeDiamondAmbiguity"); internal static string InvalidJsonTypeInfoOperationForKind => GetResourceString("InvalidJsonTypeInfoOperationForKind"); internal static string CreateObjectConverterNotCompatible => GetResourceString("CreateObjectConverterNotCompatible"); internal static string JsonPropertyInfoBoundToDifferentParent => GetResourceString("JsonPropertyInfoBoundToDifferentParent"); internal static string JsonSerializerOptionsNoTypeInfoResolverSpecified => GetResourceString("JsonSerializerOptionsNoTypeInfoResolverSpecified"); internal static string JsonSerializerIsReflectionDisabled => GetResourceString("JsonSerializerIsReflectionDisabled"); internal static string JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo => GetResourceString("JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo"); internal static string JsonPropertyRequiredAndNotDeserializable => GetResourceString("JsonPropertyRequiredAndNotDeserializable"); internal static string JsonPropertyRequiredAndExtensionData => GetResourceString("JsonPropertyRequiredAndExtensionData"); internal static string JsonRequiredPropertiesMissing => GetResourceString("JsonRequiredPropertiesMissing"); internal static string ObjectCreationHandlingPopulateNotSupportedByConverter => GetResourceString("ObjectCreationHandlingPopulateNotSupportedByConverter"); internal static string ObjectCreationHandlingPropertyMustHaveAGetter => GetResourceString("ObjectCreationHandlingPropertyMustHaveAGetter"); internal static string ObjectCreationHandlingPropertyValueTypeMustHaveASetter => GetResourceString("ObjectCreationHandlingPropertyValueTypeMustHaveASetter"); internal static string ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization => GetResourceString("ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization"); internal static string ObjectCreationHandlingPropertyCannotAllowReadOnlyMember => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReadOnlyMember"); internal static string ObjectCreationHandlingPropertyCannotAllowReferenceHandling => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReferenceHandling"); internal static string ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors => GetResourceString("ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors"); internal static string FormatInt128 => GetResourceString("FormatInt128"); internal static string FormatUInt128 => GetResourceString("FormatUInt128"); internal static string FormatHalf => GetResourceString("FormatHalf"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class ObsoleteAttribute : Attribute { public string Message { get; } public bool IsError { get; } public string DiagnosticId { get; set; } public string UrlFormat { get; set; } public ObsoleteAttribute() { } public ObsoleteAttribute(string message) { Message = message; } public ObsoleteAttribute(string message, bool error) { Message = message; IsError = error; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class DynamicDependencyAttribute : Attribute { public string MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public Type Type { get; } public string TypeName { get; } public string AssemblyName { get; } public string Condition { get; set; } public DynamicDependencyAttribute(string memberSignature) { MemberSignature = memberSignature; } public DynamicDependencyAttribute(string memberSignature, Type type) { MemberSignature = memberSignature; Type = type; } public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) { MemberTypes = memberTypes; Type = type; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } } [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.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; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = Array.Empty<object>(); } public StringSyntaxAttribute(string syntax, params object[] arguments) { Syntax = syntax; Arguments = arguments; } } [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.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class RequiresPreviewFeaturesAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string message) { Message = message; } } } namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } } namespace System.Collections.Generic { internal sealed class ReferenceEqualityComparer : IEqualityComparer<object>, IEqualityComparer { public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer(); private ReferenceEqualityComparer() { } public new bool Equals(object x, object y) { return x == y; } public int GetHashCode(object obj) { return RuntimeHelpers.GetHashCode(obj); } } internal static class StackExtensions { public static bool TryPeek<T>(this Stack<T> stack, [MaybeNullWhen(false)] out T result) { if (stack.Count > 0) { result = stack.Peek(); return true; } result = default(T); return false; } public static bool TryPop<T>(this Stack<T> stack, [MaybeNullWhen(false)] out T result) { if (stack.Count > 0) { result = stack.Pop(); return true; } result = default(T); return false; } } } namespace System.Buffers { internal sealed class ArrayBufferWriter<T> : IBufferWriter<T> { private const int ArrayMaxLength = 2147483591; private const int DefaultInitialBufferSize = 256; private T[] _buffer; private int _index; public ReadOnlyMemory<T> WrittenMemory => _buffer.AsMemory(0, _index); public ReadOnlySpan<T> WrittenSpan => _buffer.AsSpan(0, _index); public int WrittenCount => _index; public int Capacity => _buffer.Length; public int FreeCapacity => _buffer.Length - _index; public ArrayBufferWriter() { _buffer = Array.Empty<T>(); _index = 0; } public ArrayBufferWriter(int initialCapacity) { if (initialCapacity <= 0) { throw new ArgumentException(null, "initialCapacity"); } _buffer = new T[initialCapacity]; _index = 0; } public void Clear() { _buffer.AsSpan(0, _index).Clear(); _index = 0; } public void ResetWrittenCount() { _index = 0; } public void Advance(int count) { if (count < 0) { throw new ArgumentException(null, "count"); } if (_index > _buffer.Length - count) { ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length); } _index += count; } public Memory<T> GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _buffer.AsMemory(_index); } public Span<T> GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _buffer.AsSpan(_index); } private void CheckAndResizeBuffer(int sizeHint) { if (sizeHint < 0) { throw new ArgumentException("sizeHint"); } if (sizeHint == 0) { sizeHint = 1; } if (sizeHint <= FreeCapacity) { return; } int num = _buffer.Length; int num2 = Math.Max(sizeHint, num); if (num == 0) { num2 = Math.Max(num2, 256); } int num3 = num + num2; if ((uint)num3 > 2147483647u) { uint num4 = (uint)(num - FreeCapacity + sizeHint); if (num4 > 2147483591) { ThrowOutOfMemoryException(num4); } num3 = 2147483591; } Array.Resize(ref _buffer, num3); } private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity) { throw new InvalidOperationException(System.SR.Format(System.SR.BufferWriterAdvancedTooFar, capacity)); } private static void ThrowOutOfMemoryException(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } } } namespace System.Buffers.Text { internal enum SequenceValidity { Empty, WellFormed, Incomplete, Invalid } } namespace System.Text.Json { internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, IDisposable { private byte[] _rentedBuffer; private int _index; private const int MinimumBufferSize = 256; public const int MaximumBufferSize = 2147483591; public ReadOnlyMemory<byte> WrittenMemory => _rentedBuffer.AsMemory(0, _index); public int WrittenCount => _index; public int Capacity => _rentedBuffer.Length; public int FreeCapacity => _rentedBuffer.Length - _index; private PooledByteBufferWriter() { } public PooledByteBufferWriter(int initialCapacity) : this() { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public void Clear() { ClearHelper(); } public void ClearAndReturnBuffers() { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer); } private void ClearHelper() { _rentedBuffer.AsSpan(0, _index).Clear(); _index = 0; } public void Dispose() { if (_rentedBuffer != null) { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer); } } public void InitializeEmptyInstance(int initialCapacity) { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public static PooledByteBufferWriter CreateEmptyInstanceForCaching() { return new PooledByteBufferWriter(); } public void Advance(int count) { _index += count; } public Memory<byte> GetMemory(int sizeHint = 256) { CheckAndResizeBuffer(sizeHint); return _rentedBuffer.AsMemory(_index); } public Span<byte> GetSpan(int sizeHint = 256) { CheckAndResizeBuffer(sizeHint); return _rentedBuffer.AsSpan(_index); } internal Task WriteToStreamAsync(Stream destination, CancellationToken cancellationToken) { return destination.WriteAsync(_rentedBuffer, 0, _index, cancellationToken); } internal void WriteToStream(Stream destination) { destination.Write(_rentedBuffer, 0, _index); } private void CheckAndResizeBuffer(int sizeHint) { int num = _rentedBuffer.Length; int num2 = num - _index; if (_index >= 1073741795) { sizeHint = Math.Max(sizeHint, 2147483591 - num); } if (sizeHint <= num2) { return; } int num3 = Math.Max(sizeHint, num); int num4 = num + num3; if ((uint)num4 > 2147483591u) { num4 = num + sizeHint; if ((uint)num4 > 2147483591u) { ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4); } } byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = ArrayPool<byte>.Shared.Rent(num4); Span<byte> span = rentedBuffer.AsSpan(0, _index); span.CopyTo(_rentedBuffer); span.Clear(); ArrayPool<byte>.Shared.Return(rentedBuffer); } } internal static class ThrowHelper { public const string ExceptionSourceValueToRethrowAsJsonException = "System.Text.Json.Rethrowable"; [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } [DoesNotReturn] public static void ThrowArgumentNullException(string parameterName) { throw new ArgumentNullException(parameterName); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_MaxDepthMustBePositive(string parameterName) { throw GetArgumentOutOfRangeException(parameterName, System.SR.MaxDepthMustBePositive); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(string parameterName, string message) { return new ArgumentOutOfRangeException(parameterName, message); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_CommentEnumMustBeInRange(string parameterName) { throw GetArgumentOutOfRangeException(parameterName, System.SR.CommentHandlingMustBeValid); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_ArrayIndexNegative(string paramName) { throw new ArgumentOutOfRangeException(paramName, System.SR.ArrayIndexNegative); } [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(Type typeToConvert) { throw new ArgumentOutOfRangeException("typeToConvert", System.SR.Format(System.SR.SerializerConverterFactoryInvalidArgument, typeToConvert.FullName)); } [DoesNotReturn] public static void ThrowArgumentException_ArrayTooSmall(string paramName) { throw new ArgumentException(System.SR.ArrayTooSmall, paramName); } private static ArgumentException GetArgumentException(string message) { return new ArgumentException(message); } [DoesNotReturn] public static void ThrowArgumentException(string message) { throw GetArgumentException(message); } public static InvalidOperationException GetInvalidOperationException_CallFlushFirst(int _buffered) { return GetInvalidOperationException(System.SR.Format(System.SR.CallFlushToAvoidDataLoss, _buffered)); } [DoesNotReturn] public static void ThrowArgumentException_DestinationTooShort() { throw GetArgumentException(System.SR.DestinationTooShort); } [DoesNotReturn] public static void ThrowArgumentException_PropertyNameTooLarge(int tokenLength) { throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, tokenLength)); } [DoesNotReturn] public static void ThrowArgumentException_ValueTooLarge(long tokenLength) { throw GetArgumentException(System.SR.Format(System.SR.ValueTooLarge, tokenLength)); } [DoesNotReturn] public static void ThrowArgumentException_ValueNotSupported() { throw GetArgumentException(System.SR.SpecialNumberValuesNotSupported); } [DoesNotReturn] public static void ThrowInvalidOperationException_NeedLargerSpan() { throw GetInvalidOperationException(System.SR.FailedToGetLargerSpan); } [DoesNotReturn] public static void ThrowPropertyNameTooLargeArgumentException(int length) { throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, length)); } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<byte> propertyName, ReadOnlySpan<byte> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<byte> propertyName, ReadOnlySpan<char> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<char> propertyName, ReadOnlySpan<byte> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowArgumentException(ReadOnlySpan<char> propertyName, ReadOnlySpan<char> value) { if (propertyName.Length > 166666666) { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } else { ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length)); } } [DoesNotReturn] public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan<byte> propertyName, int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth >= maxDepth) { ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } else { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } } [DoesNotReturn] public static void ThrowInvalidOperationException(int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } [DoesNotReturn] public static void ThrowInvalidOperationException(string message) { throw GetInvalidOperationException(message); } private static InvalidOperationException GetInvalidOperationException(string message) { return new InvalidOperationException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowInvalidOperationException_DepthNonZeroOrEmptyJson(int currentDepth) { throw GetInvalidOperationException(currentDepth); } private static InvalidOperationException GetInvalidOperationException(int currentDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth != 0) { return GetInvalidOperationException(System.SR.Format(System.SR.ZeroDepthAtEnd, currentDepth)); } return GetInvalidOperationException(System.SR.EmptyJsonIsInvalid); } [DoesNotReturn] public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan<char> propertyName, int currentDepth, int maxDepth) { currentDepth &= 0x7FFFFFFF; if (currentDepth >= maxDepth) { ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, maxDepth)); } else { ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length)); } } public static InvalidOperationException GetInvalidOperationException_ExpectedArray(JsonTokenType tokenType) { return GetInvalidOperationException("array", tokenType); } public static InvalidOperationException GetInvalidOperationException_ExpectedObject(JsonTokenType tokenType) { return GetInvalidOperationException("object", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedNumber(JsonTokenType tokenType) { throw GetInvalidOperationException("number", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedBoolean(JsonTokenType tokenType) { throw GetInvalidOperationException("boolean", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType) { throw GetInvalidOperationException("string", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedPropertyName(JsonTokenType tokenType) { throw GetInvalidOperationException("propertyName", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedStringComparison(JsonTokenType tokenType) { throw GetInvalidOperationException(tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedComment(JsonTokenType tokenType) { throw GetInvalidOperationException("comment", tokenType); } [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSkipOnPartial() { throw GetInvalidOperationException(System.SR.CannotSkip); } private static InvalidOperationException GetInvalidOperationException(string message, JsonTokenType tokenType) { return GetInvalidOperationException(System.SR.Format(System.SR.InvalidCast, tokenType, message)); } private static InvalidOperationException GetInvalidOperationException(JsonTokenType tokenType) { return GetInvalidOperationException(System.SR.Format(System.SR.InvalidComparison, tokenType)); } [DoesNotReturn] internal static void ThrowJsonElementWrongTypeException(JsonTokenType expectedType, JsonTokenType actualType) { throw GetJsonElementWrongTypeException(expectedType.ToValueKind(), actualType.ToValueKind()); } internal static InvalidOperationException GetJsonElementWrongTypeException(JsonValueKind expectedType, JsonValueKind actualType) { return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedType, actualType)); } internal static InvalidOperationException GetJsonElementWrongTypeException(string expectedTypeName, JsonValueKind actualType) { return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedTypeName, actualType)); } [DoesNotReturn] public static void ThrowJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte = 0, ReadOnlySpan<byte> bytes = default(ReadOnlySpan<byte>)) { throw GetJsonReaderException(ref json, resource, nextByte, bytes); } [MethodImpl(MethodImplOptions.NoInlining)] public static JsonException GetJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, ReadOnlySpan<byte> bytes) { string resourceString = GetResourceString(ref json, resource, nextByte, JsonHelpers.Utf8GetString(bytes)); long lineNumber = json.CurrentState._lineNumber; long bytePositionInLine = json.CurrentState._bytePositionInLine; resourceString += $" LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}."; return new JsonReaderException(resourceString, lineNumber, bytePositionInLine); } private static bool IsPrintable(byte value) { if (value >= 32) { return value < 127; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string GetPrintableString(byte value) { if (!IsPrintable(value)) { return $"0x{value:X2}"; } char c = (char)value; return c.ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, string characters) { string printableString = GetPrintableString(nextByte); string result = ""; switch (resource) { case ExceptionResource.ArrayDepthTooLarge: result = System.SR.Format(System.SR.ArrayDepthTooLarge, json.CurrentState.Options.MaxDepth); break; case ExceptionResource.MismatchedObjectArray: result = System.SR.Format(System.SR.MismatchedObjectArray, printableString); break; case ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd: result = System.SR.TrailingCommaNotAllowedBeforeArrayEnd; break; case ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd: result = System.SR.TrailingCommaNotAllowedBeforeObjectEnd; break; case ExceptionResource.EndOfStringNotFound: result = System.SR.EndOfStringNotFound; break; case ExceptionResource.RequiredDigitNotFoundAfterSign: result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterSign, printableString); break; case ExceptionResource.RequiredDigitNotFoundAfterDecimal: result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterDecimal, printableString); break; case ExceptionResource.RequiredDigitNotFoundEndOfData: result = System.SR.RequiredDigitNotFoundEndOfData; break; case ExceptionResource.ExpectedEndAfterSingleJson: result = System.SR.Format(System.SR.ExpectedEndAfterSingleJson, printableString); break; case ExceptionResource.ExpectedEndOfDigitNotFound: result = System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, printableString); break; case ExceptionResource.ExpectedNextDigitEValueNotFound: result = System.SR.Format(System.SR.ExpectedNextDigitEValueNotFound, printableString); break; case ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound: result = System.SR.Format(System.SR.ExpectedSeparatorAfterPropertyNameNotFound, printableString); break; case ExceptionResource.ExpectedStartOfPropertyNotFound: result = System.SR.Format(System.SR.ExpectedStartOfPropertyNotFound, printableString); break; case ExceptionResource.ExpectedStartOfPropertyOrValueNotFound: result = System.SR.ExpectedStartOfPropertyOrValueNotFound; break; case ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment: result = System.SR.Format(System.SR.ExpectedStartOfPropertyOrValueAfterComment, printableString); break; case ExceptionResource.ExpectedStartOfValueNotFound: result = System.SR.Format(System.SR.ExpectedStartOfValueNotFound, printableString); break; case ExceptionResource.ExpectedValueAfterPropertyNameNotFound: result = System.SR.ExpectedValueAfterPropertyNameNotFound; break; case ExceptionResource.FoundInvalidCharacter: result = System.SR.Format(System.SR.FoundInvalidCharacter, printableString); break; case ExceptionResource.InvalidEndOfJsonNonPrimitive: result = System.SR.Format(System.SR.InvalidEndOfJsonNonPrimitive, json.TokenType); break; case ExceptionResource.ObjectDepthTooLarge: result = System.SR.Format(System.SR.ObjectDepthTooLarge, json.CurrentState.Options.MaxDepth); break; case ExceptionResource.ExpectedFalse: result = System.SR.Format(System.SR.ExpectedFalse, characters); break; case ExceptionResource.ExpectedNull: result = System.SR.Format(System.SR.ExpectedNull, characters); break; case ExceptionResource.ExpectedTrue: result = System.SR.Format(System.SR.ExpectedTrue, characters); break; case ExceptionResource.InvalidCharacterWithinString: result = System.SR.Format(System.SR.InvalidCharacterWithinString, printableString); break; case ExceptionResource.InvalidCharacterAfterEscapeWithinString: result = System.SR.Format(System.SR.InvalidCharacterAfterEscapeWithinString, printableString); break; case ExceptionResource.InvalidHexCharacterWithinString: result = System.SR.Format(System.SR.InvalidHexCharacterWithinString, printableString); break; case ExceptionResource.EndOfCommentNotFound: result = System.SR.EndOfCommentNotFound; break; case ExceptionResource.ZeroDepthAtEnd: result = System.SR.Format(System.SR.ZeroDepthAtEnd); break; case ExceptionResource.ExpectedJsonTokens: result = System.SR.ExpectedJsonTokens; break; case ExceptionResource.NotEnoughData: result = System.SR.NotEnoughData; break; case ExceptionResource.ExpectedOneCompleteToken: result = System.SR.ExpectedOneCompleteToken; break; case ExceptionResource.InvalidCharacterAtStartOfComment: result = System.SR.Format(System.SR.InvalidCharacterAtStartOfComment, printableString); break; case ExceptionResource.UnexpectedEndOfDataWhileReadingComment: result = System.SR.Format(System.SR.UnexpectedEndOfDataWhileReadingComment); break; case ExceptionResource.UnexpectedEndOfLineSeparator: result = System.SR.Format(System.SR.UnexpectedEndOfLineSeparator); break; case ExceptionResource.InvalidLeadingZeroInNumber: result = System.SR.Format(System.SR.InvalidLeadingZeroInNumber, printableString); break; } return result; } [DoesNotReturn] public static void ThrowInvalidOperationException(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { throw GetInvalidOperationException(resource, currentDepth, maxDepth, token, tokenType); } [DoesNotReturn] public static void ThrowArgumentException_InvalidCommentValue() { throw new ArgumentException(System.SR.CannotWriteCommentWithEmbeddedDelimiter); } [DoesNotReturn] public static void ThrowArgumentException_InvalidUTF8(ReadOnlySpan<byte> value) { StringBuilder stringBuilder = new StringBuilder(); int num = Math.Min(value.Length, 10); for (int i = 0; i < num; i++) { byte b = value[i]; if (IsPrintable(b)) { stringBuilder.Append((char)b); } else { stringBuilder.Append($"0x{b:X2}"); } } if (num < value.Length) { stringBuilder.Append("..."); } throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF8, stringBuilder)); } [DoesNotReturn] public static void ThrowArgumentException_InvalidUTF16(int charAsInt) { throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF16, $"0x{charAsInt:X2}")); } [DoesNotReturn] public static void ThrowInvalidOperationException_ReadInvalidUTF16(int charAsInt) { throw GetInvalidOperationException(System.SR.Format(System.SR.CannotReadInvalidUTF16, $"0x{charAsInt:X2}")); } [DoesNotReturn] public static void ThrowInvalidOperationException_ReadIncompleteUTF16() { throw GetInvalidOperationException(System.SR.CannotReadIncompleteUTF16); } public static InvalidOperationException GetInvalidOperationException_ReadInvalidUTF8(DecoderFallbackException innerException = null) { return GetInvalidOperationException(System.SR.CannotTranscodeInvalidUtf8, innerException); } public static ArgumentException GetArgumentException_ReadInvalidUTF16(EncoderFallbackException innerException) { return new ArgumentException(System.SR.CannotTranscodeInvalidUtf16, innerException); } public static InvalidOperationException GetInvalidOperationException(string message, Exception innerException) { InvalidOperationException ex = new InvalidOperationException(message, innerException); ex.Source = "System.Text.Json.Rethrowable"; return ex; } [MethodImpl(MethodImplOptions.NoInlining)] public static InvalidOperationException GetInvalidOperationException(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { string resourceString = GetResourceString(resource, currentDepth, maxDepth, token, tokenType); InvalidOperationException invalidOperationException = GetInvalidOperationException(resourceString); invalidOperationException.Source = "System.Text.Json.Rethrowable"; return invalidOperationException; } [DoesNotReturn] public static void ThrowOutOfMemoryException(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ExceptionResource resource, int currentDepth, int maxDepth, byte token, JsonTokenType tokenType) { string result = ""; switch (resource) { case ExceptionResource.MismatchedObjectArray: result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWriteEndAfterProperty, (char)token) : System.SR.Format(System.SR.MismatchedObjectArray, (char)token)); break; case ExceptionResource.DepthTooLarge: result = System.SR.Format(System.SR.DepthTooLarge, currentDepth & 0x7FFFFFFF, maxDepth); break; case ExceptionResource.CannotStartObjectArrayWithoutProperty: result = System.SR.Format(System.SR.CannotStartObjectArrayWithoutProperty, tokenType); break; case ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose: result = System.SR.Format(System.SR.CannotStartObjectArrayAfterPrimitiveOrClose, tokenType); break; case ExceptionResource.CannotWriteValueWithinObject: result = System.SR.Format(System.SR.CannotWriteValueWithinObject, tokenType); break; case ExceptionResource.CannotWritePropertyWithinArray: result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWritePropertyAfterProperty) : System.SR.Format(System.SR.CannotWritePropertyWithinArray, tokenType)); break; case ExceptionResource.CannotWriteValueAfterPrimitiveOrClose: result = System.SR.Format(System.SR.CannotWriteValueAfterPrimitiveOrClose, tokenType); break; } return result; } [DoesNotReturn] public static void ThrowFormatException() { throw new FormatException { Source = "System.Text.Json.Rethrowable" }; } public static void ThrowFormatException(NumericType numericType) { string message = ""; switch (numericType) { case NumericType.Byte: message = System.SR.FormatByte; break; case NumericType.SByte: message = System.SR.FormatSByte; break; case NumericType.Int16: message = System.SR.FormatInt16; break; case NumericType.Int32: message = System.SR.FormatInt32; break; case NumericType.Int64: message = System.SR.FormatInt64; break; case NumericType.Int128: message = System.SR.FormatInt128; break; case NumericType.UInt16: message = System.SR.FormatUInt16; break; case NumericType.UInt32: message = System.SR.FormatUInt32; break; case NumericType.UInt64: message = System.SR.FormatUInt64; break; case NumericType.UInt128: message = System.SR.FormatUInt128; break; case NumericType.Half: message = System.SR.FormatHalf; break; case NumericType.Single: message = System.SR.FormatSingle; break; case NumericType.Double: message = System.SR.FormatDouble; break; case NumericType.Decimal: message = System.SR.FormatDecimal; break; } throw new FormatException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowFormatException(DataType dataType) { string message = ""; switch (dataType) { case DataType.Boolean: case DataType.DateOnly: case DataType.DateTime: case DataType.DateTimeOffset: case DataType.TimeOnly: case DataType.TimeSpan: case DataType.Guid: case DataType.Version: message = System.SR.Format(System.SR.UnsupportedFormat, dataType); break; case DataType.Base64String: message = System.SR.CannotDecodeInvalidBase64; break; } throw new FormatException(message) { Source = "System.Text.Json.Rethrowable" }; } [DoesNotReturn] public static void ThrowInvalidOperationException_ExpectedChar(JsonTokenType tokenType) { throw GetInvalidOperationException("char", tokenType); } [DoesNotReturn] public static void ThrowObjectDisposedException_Utf8JsonWriter() { throw new ObjectDisposedException("Utf8JsonWriter"); } [DoesNotReturn] public static void ThrowObjectDisposedException_JsonDocument() { throw new ObjectDisposedException("JsonDocument"); } [DoesNotReturn] public static void ThrowArgumentException_NodeValueNotAllowed(string paramName) { throw new ArgumentException(System.SR.NodeValueNotAllowed, paramName); } [DoesNotReturn] public static void ThrowArgumentException_DuplicateKey(string paramName, string propertyName) { throw new ArgumentException(System.SR.Format(System.SR.NodeDuplicateKey, propertyName), paramName); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeAlreadyHasParent() { throw new InvalidOperationException(System.SR.NodeAlreadyHasParent); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeCycleDetected() { throw new InvalidOperationException(System.SR.NodeCycleDetected); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeElementCannotBeObjectOrArray() { throw new InvalidOperationException(System.SR.NodeElementCannotBeObjectOrArray); } [DoesNotReturn] public static void ThrowNotSupportedException_CollectionIsReadOnly() { throw GetNotSupportedException_CollectionIsReadOnly(); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeWrongType(string typeName) { throw new InvalidOperationException(System.SR.Format(System.SR.NodeWrongType, typeName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_NodeParentWrongType(string typeName) { throw new InvalidOperationException(System.SR.Format(System.SR.NodeParentWrongType, typeName)); } public static NotSupportedException GetNotSupportedException_CollectionIsReadOnly() { return new NotSupportedException(System.SR.CollectionIsReadOnly); } [DoesNotReturn] public static void ThrowArgumentException_DeserializeWrongType(Type type, object value) { throw new ArgumentException(System.SR.Format(System.SR.DeserializeWrongType, type, value.GetType())); } [DoesNotReturn] public static void ThrowArgumentException_SerializerDoesNotSupportComments(string paramName) { throw new ArgumentException(System.SR.JsonSerializerDoesNotSupportComments, paramName); } [DoesNotReturn] public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType) { throw new NotSupportedException(System.SR.Format(System.SR.SerializationNotSupportedType, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType) { throw new NotSupportedException(System.SR.Format(System.SR.TypeRequiresAsyncSerialization, propertyType)); } [DoesNotReturn] public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter) { throw new NotSupportedException(System.SR.Format(System.SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType())); } [DoesNotReturn] public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) { throw new JsonException(System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType) { throw new InvalidCastException(System.SR.Format(System.SR.DeserializeUnableToAssignValue, typeOfValue, declaredType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType) { throw new InvalidOperationException(System.SR.Format(System.SR.DeserializeUnableToAssignNull, declaredType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPopulateNotSupportedByConverter(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPopulateNotSupportedByConverter, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyMustHaveAGetter(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyMustHaveAGetter, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyValueTypeMustHaveASetter(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyValueTypeMustHaveASetter, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReadOnlyMember(JsonPropertyInfo propertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.ObjectCreationHandlingPropertyCannotAllowReadOnlyMember, propertyInfo.Name, propertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ObjectCreationHandlingPropertyCannotAllowReferenceHandling() { throw new InvalidOperationException(System.SR.ObjectCreationHandlingPropertyCannotAllowReferenceHandling); } [DoesNotReturn] public static void ThrowNotSupportedException_ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors() { throw new NotSupportedException(System.SR.ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors); } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterRead(JsonConverter converter) { throw new JsonException(System.SR.Format(System.SR.SerializationConverterRead, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializationConverterWrite(JsonConverter converter) { throw new JsonException(System.SR.Format(System.SR.SerializationConverterWrite, converter)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException_SerializerCycleDetected(int maxDepth) { throw new JsonException(System.SR.Format(System.SR.SerializerCycleDetected, maxDepth)) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowJsonException(string message = null) { throw new JsonException(message) { AppendPathInformation = true }; } [DoesNotReturn] public static void ThrowArgumentException_CannotSerializeInvalidType(string paramName, Type typeToConvert, Type declaringType, string propertyName) { if (declaringType == null) { throw new ArgumentException(System.SR.Format(System.SR.CannotSerializeInvalidType, typeToConvert), paramName); } throw new ArgumentException(System.SR.Format(System.SR.CannotSerializeInvalidMember, typeToConvert, propertyName, declaringType), paramName); } [DoesNotReturn] public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type typeToConvert, Type declaringType, MemberInfo memberInfo) { if (declaringType == null) { throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidType, typeToConvert)); } throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidMember, typeToConvert, memberInfo.Name, declaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterNotCompatible, converterType, type)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ResolverTypeNotCompatible(Type requestedType, Type actualType) { throw new InvalidOperationException(System.SR.Format(System.SR.ResolverTypeNotCompatible, actualType, requestedType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_ResolverTypeInfoOptionsNotCompatible() { throw new InvalidOperationException(System.SR.ResolverTypeInfoOptionsNotCompatible); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonSerializerOptionsNoTypeInfoResolverSpecified() { throw new InvalidOperationException(System.SR.JsonSerializerOptionsNoTypeInfoResolverSpecified); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonSerializerIsReflectionDisabled() { throw new InvalidOperationException(System.SR.JsonSerializerIsReflectionDisabled); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo memberInfo) { string text = classType.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeInvalid, text)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo memberInfo, Type typeToConvert) { string text = classTypeAttributeIsOn.ToString(); if (memberInfo != null) { text = text + "." + memberInfo.Name; } throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeNotCompatible, text, typeToConvert)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerOptionsReadOnly(JsonSerializerContext context) { string message = ((context == null) ? System.SR.SerializerOptionsReadOnly : System.SR.SerializerContextOptionsReadOnly); throw new InvalidOperationException(message); } [DoesNotReturn] public static void ThrowInvalidOperationException_DefaultTypeInfoResolverImmutable() { throw new InvalidOperationException(System.SR.DefaultTypeInfoResolverImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_TypeInfoResolverChainImmutable() { throw new InvalidOperationException(System.SR.TypeInfoResolverChainImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_TypeInfoImmutable() { throw new InvalidOperationException(System.SR.TypeInfoImmutable); } [DoesNotReturn] public static void ThrowInvalidOperationException_InvalidChainedResolver() { throw new InvalidOperationException(System.SR.SerializerOptions_InvalidChainedResolver); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, string propertyName) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameConflict, type, propertyName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerPropertyNameNull(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameNull, jsonPropertyInfo.DeclaringType, jsonPropertyInfo.MemberName)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonPropertyRequiredAndNotDeserializable(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyRequiredAndNotDeserializable, jsonPropertyInfo.Name, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowInvalidOperationException_JsonPropertyRequiredAndExtensionData(JsonPropertyInfo jsonPropertyInfo) { throw new InvalidOperationException(System.SR.Format(System.SR.JsonPropertyRequiredAndExtensionData, jsonPropertyInfo.Name, jsonPropertyInfo.DeclaringType)); } [DoesNotReturn] public static void ThrowJsonException_JsonRequiredPropertyMissing(JsonTypeInfo parent, BitArray requiredPropertiesSet) { StringBuilder stringBuilder = new StringBuilder(); bool flag = true; foreach (KeyValuePair<string, JsonPropertyInfo> item in parent.PropertyCache.List) { JsonPropertyInfo value = item.Value; if (value.IsRequired && !requiredPropertiesSet[value.RequiredPropertyIndex]) { if (!flag) { stringBuilder.Append(CultureInfo.CurrentUICulture.TextInfo.ListSeparator); stringBuilder.Append(' '); } stringBuilder.Append(value.Name); flag = false; if (stringBuilder.Length >= 50) { break; } } } throw new JsonException(System.SR.Format(System.SR.JsonRequiredPropertiesMissing, parent.Type, stringBuilder.ToString())); } [DoesNotReturn] public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy) { throw new InvalidOperationException(System.SR.Format(System.SR.NamingPolicyReturnNull, namingPolicy)); } [DoesNotReturn] public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType) { throw new InvalidOperationException(System.SR.Format(System
deps/System.Threading.Channels.dll
Decompiled a day agousing System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using FxResources.System.Threading.Channels; using Internal; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Threading.Channels")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides types for passing data between producers and consumers.\r\n\r\nCommonly Used Types:\r\nSystem.Threading.Channel\r\nSystem.Threading.Channel<T>")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Threading.Channels")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("8.0.0.0")] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 FxResources.System.Threading.Channels { internal static class SR { } } namespace Internal { internal static class PaddingHelpers { internal const int CACHE_LINE_SIZE = 128; } [StructLayout(LayoutKind.Explicit, Size = 124)] internal struct PaddingFor32 { } } namespace System { [StructLayout(LayoutKind.Sequential, Size = 1)] internal readonly struct VoidResult { } internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; internal const string EncryptionPolicyDiagId = "SYSLIB0040"; internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations."; internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041"; internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys."; internal const string EccXmlExportImportDiagId = "SYSLIB0042"; internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead."; internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043"; internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."; internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044"; internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead."; internal const string CryptoStringFactoryDiagId = "SYSLIB0045"; internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code."; internal const string ControlledExecutionRunDiagId = "SYSLIB0046"; internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution."; internal const string XmlSecureResolverDiagId = "SYSLIB0047"; internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead."; internal const string RsaEncryptDecryptDiagId = "SYSLIB0048"; internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties."; internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049"; internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used."; internal const string LegacyFormatterDiagId = "SYSLIB0050"; internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code."; internal const string LegacyFormatterImplDiagId = "SYSLIB0051"; internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported."; internal const string RegexExtensibilityDiagId = "SYSLIB0052"; internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size."; internal const string AesGcmTagConstructorDiagId = "SYSLIB0053"; } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ChannelClosedException_DefaultMessage => GetResourceString("ChannelClosedException_DefaultMessage"); internal static string InvalidOperation_IncompleteAsyncOperation => GetResourceString("InvalidOperation_IncompleteAsyncOperation"); internal static string InvalidOperation_MultipleContinuations => GetResourceString("InvalidOperation_MultipleContinuations"); internal static string InvalidOperation_IncorrectToken => GetResourceString("InvalidOperation_IncorrectToken"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Collections.Generic { [DebuggerDisplay("Count = {_size}")] internal sealed class Deque<T> { private T[] _array = Array.Empty<T>(); private int _head; private int _tail; private int _size; public int Count => _size; public bool IsEmpty => _size == 0; public void EnqueueTail(T item) { if (_size == _array.Length) { Grow(); } _array[_tail] = item; if (++_tail == _array.Length) { _tail = 0; } _size++; } public T DequeueHead() { T result = _array[_head]; _array[_head] = default(T); if (++_head == _array.Length) { _head = 0; } _size--; return result; } public T PeekHead() { return _array[_head]; } public T PeekTail() { int num = _tail - 1; if (num == -1) { num = _array.Length - 1; } return _array[num]; } public T DequeueTail() { if (--_tail == -1) { _tail = _array.Length - 1; } T result = _array[_tail]; _array[_tail] = default(T); _size--; return result; } public IEnumerator<T> GetEnumerator() { int pos = _head; int count = _size; while (count-- > 0) { yield return _array[pos]; pos = (pos + 1) % _array.Length; } } private void Grow() { int num = (int)((long)_array.Length * 2L); if (num < _array.Length + 4) { num = _array.Length + 4; } T[] array = new T[num]; if (_head == 0) { Array.Copy(_array, array, _size); } else { Array.Copy(_array, _head, array, 0, _array.Length - _head); Array.Copy(_array, 0, array, _array.Length - _head, _tail); } _array = array; _head = 0; _tail = _size; } } } namespace System.Collections.Concurrent { internal interface IProducerConsumerQueue<T> : IEnumerable<T>, IEnumerable { bool IsEmpty { get; } int Count { get; } void Enqueue(T item); bool TryDequeue([MaybeNullWhen(false)] out T result); int GetCountSafe(object syncObj); } [DebuggerDisplay("Count = {Count}")] internal sealed class MultiProducerMultiConsumerQueue<T> : ConcurrentQueue<T>, IProducerConsumerQueue<T>, IEnumerable<T>, IEnumerable { bool IProducerConsumerQueue<T>.IsEmpty => base.IsEmpty; int IProducerConsumerQueue<T>.Count => base.Count; void IProducerConsumerQueue<T>.Enqueue(T item) { Enqueue(item); } bool IProducerConsumerQueue<T>.TryDequeue([MaybeNullWhen(false)] out T result) { return TryDequeue(out result); } int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { return base.Count; } } [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))] internal sealed class SingleProducerSingleConsumerQueue<T> : IProducerConsumerQueue<T>, IEnumerable<T>, IEnumerable { [StructLayout(LayoutKind.Sequential)] private sealed class Segment { internal Segment _next; internal readonly T[] _array; internal SegmentState _state; internal Segment(int size) { _array = new T[size]; } } private struct SegmentState { internal Internal.PaddingFor32 _pad0; internal volatile int _first; internal int _lastCopy; internal Internal.PaddingFor32 _pad1; internal int _firstCopy; internal volatile int _last; internal Internal.PaddingFor32 _pad2; } private sealed class SingleProducerSingleConsumerQueue_DebugView { private readonly SingleProducerSingleConsumerQueue<T> _queue; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => new List<T>(_queue).ToArray(); public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue) { _queue = queue; } } private const int InitialSegmentSize = 32; private const int MaxSegmentSize = 16777216; private volatile Segment _head; private volatile Segment _tail; public bool IsEmpty { get { Segment head = _head; if (head._state._first != head._state._lastCopy) { return false; } if (head._state._first != head._state._last) { return false; } return head._next == null; } } public int Count { get { int num = 0; for (Segment segment = _head; segment != null; segment = segment._next) { int num2 = segment._array.Length; int first; int last; do { first = segment._state._first; last = segment._state._last; } while (first != segment._state._first); num += (last - first) & (num2 - 1); } return num; } } public SingleProducerSingleConsumerQueue() { _head = (_tail = new Segment(32)); } public void Enqueue(T item) { Segment segment = _tail; T[] array = segment._array; int last = segment._state._last; int num = (last + 1) & (array.Length - 1); if (num != segment._state._firstCopy) { array[last] = item; segment._state._last = num; } else { EnqueueSlow(item, ref segment); } } private void EnqueueSlow(T item, ref Segment segment) { if (segment._state._firstCopy != segment._state._first) { segment._state._firstCopy = segment._state._first; Enqueue(item); return; } int size = Math.Min(_tail._array.Length * 2, 16777216); Segment segment2 = new Segment(size); segment2._array[0] = item; segment2._state._last = 1; segment2._state._lastCopy = 1; try { } finally { Volatile.Write(ref _tail._next, segment2); _tail = segment2; } } public bool TryDequeue([MaybeNullWhen(false)] out T result) { Segment head = _head; T[] array = head._array; int first = head._state._first; if (first != head._state._lastCopy) { result = array[first]; array[first] = default(T); head._state._first = (first + 1) & (array.Length - 1); return true; } return TryDequeueSlow(head, array, peek: false, out result); } public bool TryPeek([MaybeNullWhen(false)] out T result) { Segment head = _head; T[] array = head._array; int first = head._state._first; if (first != head._state._lastCopy) { result = array[first]; return true; } return TryDequeueSlow(head, array, peek: true, out result); } private bool TryDequeueSlow(Segment segment, T[] array, bool peek, [MaybeNullWhen(false)] out T result) { if (segment._state._last != segment._state._lastCopy) { segment._state._lastCopy = segment._state._last; if (!peek) { return TryDequeue(out result); } return TryPeek(out result); } if (segment._next != null && segment._state._first == segment._state._last) { segment = segment._next; array = segment._array; _head = segment; } int first = segment._state._first; if (first == segment._state._last) { result = default(T); return false; } result = array[first]; if (!peek) { array[first] = default(T); segment._state._first = (first + 1) & (segment._array.Length - 1); segment._state._lastCopy = segment._state._last; } return true; } public bool TryDequeueIf(Predicate<T> predicate, [MaybeNullWhen(false)] out T result) { Segment head = _head; T[] array = head._array; int first = head._state._first; if (first != head._state._lastCopy) { result = array[first]; if (predicate == null || predicate(result)) { array[first] = default(T); head._state._first = (first + 1) & (array.Length - 1); return true; } result = default(T); return false; } return TryDequeueIfSlow(predicate, head, array, out result); } private bool TryDequeueIfSlow(Predicate<T> predicate, Segment segment, T[] array, [MaybeNullWhen(false)] out T result) { if (segment._state._last != segment._state._lastCopy) { segment._state._lastCopy = segment._state._last; return TryDequeueIf(predicate, out result); } if (segment._next != null && segment._state._first == segment._state._last) { segment = segment._next; array = segment._array; _head = segment; } int first = segment._state._first; if (first == segment._state._last) { result = default(T); return false; } result = array[first]; if (predicate == null || predicate(result)) { array[first] = default(T); segment._state._first = (first + 1) & (segment._array.Length - 1); segment._state._lastCopy = segment._state._last; return true; } result = default(T); return false; } public void Clear() { T result; while (TryDequeue(out result)) { } } public IEnumerator<T> GetEnumerator() { for (Segment segment = _head; segment != null; segment = segment._next) { for (int pt = segment._state._first; pt != segment._state._last; pt = (pt + 1) & (segment._array.Length - 1)) { yield return segment._array[pt]; } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { lock (syncObj) { return Count; } } } } namespace System.Threading.Channels { internal abstract class AsyncOperation { protected static readonly Action<object> s_availableSentinel = AvailableSentinel; protected static readonly Action<object> s_completedSentinel = CompletedSentinel; private static void AvailableSentinel(object s) { } private static void CompletedSentinel(object s) { } protected static void ThrowIncompleteOperationException() { throw new InvalidOperationException(System.SR.InvalidOperation_IncompleteAsyncOperation); } protected static void ThrowMultipleContinuations() { throw new InvalidOperationException(System.SR.InvalidOperation_MultipleContinuations); } protected static void ThrowIncorrectCurrentIdException() { throw new InvalidOperationException(System.SR.InvalidOperation_IncorrectToken); } } internal class AsyncOperation<TResult> : AsyncOperation, IValueTaskSource, IValueTaskSource<TResult> { private readonly CancellationTokenRegistration _registration; private readonly bool _pooled; private readonly bool _runContinuationsAsynchronously; private volatile int _completionReserved; private TResult _result; private ExceptionDispatchInfo _error; private Action<object> _continuation; private object _continuationState; private object _schedulingContext; private ExecutionContext _executionContext; private short _currentId; public AsyncOperation<TResult> Next { get; set; } public CancellationToken CancellationToken { get; } public ValueTask ValueTask => new ValueTask(this, _currentId); public ValueTask<TResult> ValueTaskOfT => new ValueTask<TResult>(this, _currentId); internal bool IsCompleted => (object)_continuation == AsyncOperation.s_completedSentinel; public AsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false) { _continuation = (pooled ? AsyncOperation.s_availableSentinel : null); _pooled = pooled; _runContinuationsAsynchronously = runContinuationsAsynchronously; if (cancellationToken.CanBeCanceled) { CancellationToken = cancellationToken; _registration = UnsafeRegister(cancellationToken, delegate(object s) { AsyncOperation<TResult> asyncOperation = (AsyncOperation<TResult>)s; asyncOperation.TrySetCanceled(asyncOperation.CancellationToken); }, this); } } public ValueTaskSourceStatus GetStatus(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (IsCompleted) { if (_error != null) { if (!(_error.SourceException is OperationCanceledException)) { return ValueTaskSourceStatus.Faulted; } return ValueTaskSourceStatus.Canceled; } return ValueTaskSourceStatus.Succeeded; } return ValueTaskSourceStatus.Pending; } public TResult GetResult(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (!IsCompleted) { AsyncOperation.ThrowIncompleteOperationException(); } ExceptionDispatchInfo error = _error; TResult result = _result; _currentId++; if (_pooled) { Volatile.Write(ref _continuation, AsyncOperation.s_availableSentinel); } error?.Throw(); return result; } void IValueTaskSource.GetResult(short token) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (!IsCompleted) { AsyncOperation.ThrowIncompleteOperationException(); } ExceptionDispatchInfo error = _error; _currentId++; if (_pooled) { Volatile.Write(ref _continuation, AsyncOperation.s_availableSentinel); } error?.Throw(); } public bool TryOwnAndReset() { if ((object)Interlocked.CompareExchange(ref _continuation, null, AsyncOperation.s_availableSentinel) == AsyncOperation.s_availableSentinel) { _continuationState = null; _result = default(TResult); _error = null; _schedulingContext = null; _executionContext = null; return true; } return false; } public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { if (_currentId != token) { AsyncOperation.ThrowIncorrectCurrentIdException(); } if (_continuationState != null) { AsyncOperation.ThrowMultipleContinuations(); } _continuationState = state; if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { _executionContext = ExecutionContext.Capture(); } SynchronizationContext synchronizationContext = null; TaskScheduler taskScheduler = null; if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { synchronizationContext = SynchronizationContext.Current; if (synchronizationContext != null && synchronizationContext.GetType() != typeof(SynchronizationContext)) { _schedulingContext = synchronizationContext; } else { synchronizationContext = null; taskScheduler = TaskScheduler.Current; if (taskScheduler != TaskScheduler.Default) { _schedulingContext = taskScheduler; } } } Action<object> action = Interlocked.CompareExchange(ref _continuation, continuation, null); if (action == null) { return; } if ((object)action != AsyncOperation.s_completedSentinel) { AsyncOperation.ThrowMultipleContinuations(); } if (_schedulingContext == null) { if (_executionContext == null) { UnsafeQueueUserWorkItem(continuation, state); } else { QueueUserWorkItem(continuation, state); } } else if (synchronizationContext != null) { synchronizationContext.Post(delegate(object s) { KeyValuePair<Action<object>, object> keyValuePair = (KeyValuePair<Action<object>, object>)s; keyValuePair.Key(keyValuePair.Value); }, new KeyValuePair<Action<object>, object>(continuation, state)); } else { Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, taskScheduler); } } public bool UnregisterCancellation() { if (CancellationToken.CanBeCanceled) { _registration.Dispose(); return _completionReserved == 0; } return true; } public bool TrySetResult(TResult item) { UnregisterCancellation(); if (TryReserveCompletionIfCancelable()) { _result = item; SignalCompletion(); return true; } return false; } public bool TrySetException(Exception exception) { UnregisterCancellation(); if (TryReserveCompletionIfCancelable()) { _error = ExceptionDispatchInfo.Capture(exception); SignalCompletion(); return true; } return false; } public bool TrySetCanceled(CancellationToken cancellationToken = default(CancellationToken)) { if (TryReserveCompletionIfCancelable()) { _error = ExceptionDispatchInfo.Capture(new OperationCanceledException(cancellationToken)); SignalCompletion(); return true; } return false; } private bool TryReserveCompletionIfCancelable() { if (CancellationToken.CanBeCanceled) { return Interlocked.CompareExchange(ref _completionReserved, 1, 0) == 0; } return true; } private void SignalCompletion() { if (_continuation == null && Interlocked.CompareExchange(ref _continuation, AsyncOperation.s_completedSentinel, null) == null) { return; } if (_schedulingContext == null) { if (_runContinuationsAsynchronously) { UnsafeQueueSetCompletionAndInvokeContinuation(); return; } } else if (_schedulingContext is SynchronizationContext synchronizationContext) { if (_runContinuationsAsynchronously || synchronizationContext != SynchronizationContext.Current) { synchronizationContext.Post(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this); return; } } else { TaskScheduler taskScheduler = (TaskScheduler)_schedulingContext; if (_runContinuationsAsynchronously || taskScheduler != TaskScheduler.Current) { Task.Factory.StartNew(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, taskScheduler); return; } } SetCompletionAndInvokeContinuation(); } private void SetCompletionAndInvokeContinuation() { if (_executionContext == null) { Action<object> continuation = _continuation; _continuation = AsyncOperation.s_completedSentinel; continuation(_continuationState); return; } ExecutionContext.Run(_executionContext, delegate(object s) { AsyncOperation<TResult> asyncOperation = (AsyncOperation<TResult>)s; Action<object> continuation2 = asyncOperation._continuation; asyncOperation._continuation = AsyncOperation.s_completedSentinel; continuation2(asyncOperation._continuationState); }, this); } private void UnsafeQueueSetCompletionAndInvokeContinuation() { ThreadPool.UnsafeQueueUserWorkItem(delegate(object s) { ((AsyncOperation<TResult>)s).SetCompletionAndInvokeContinuation(); }, this); } private static void UnsafeQueueUserWorkItem(Action<object> action, object state) { QueueUserWorkItem(action, state); } private static void QueueUserWorkItem(Action<object> action, object state) { Task.Factory.StartNew(action, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } private static CancellationTokenRegistration UnsafeRegister(CancellationToken cancellationToken, Action<object> action, object state) { return cancellationToken.Register(action, state); } } internal sealed class VoidAsyncOperationWithData<TData> : AsyncOperation<VoidResult> { public TData Item { get; set; } public VoidAsyncOperationWithData(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false) : base(runContinuationsAsynchronously, cancellationToken, pooled) { } } [DebuggerDisplay("Items = {ItemsCountForDebugger}, Capacity = {_bufferedCapacity}, Mode = {_mode}, Closed = {ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class BoundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items = {ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class BoundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly BoundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanCount => true; public override bool CanPeek => true; public override int Count { get { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { return parent._items.Count; } } } private int ItemsCountForDebugger => _parent._items.Count; internal BoundedChannelReader(BoundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override bool TryRead([MaybeNullWhen(false)] out T item) { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { item = DequeueItemAndPostProcess(); return true; } } item = default(T); return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { item = parent._items.PeekHead(); return true; } } item = default(T); return false; } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<T>(DequeueItemAndPostProcess()); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<T> readerSingleton = _readerSingleton; if (readerSingleton.TryOwnAndReset()) { parent._blockedReaders.EnqueueTail(readerSingleton); return readerSingleton.ValueTaskOfT; } } AsyncOperation<T> asyncOperation = new AsyncOperation<T>(parent._runContinuationsAsynchronously | cancellationToken.CanBeCanceled, cancellationToken); parent._blockedReaders.EnqueueTail(asyncOperation); return asyncOperation.ValueTaskOfT; } } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(parent._runContinuationsAsynchronously | cancellationToken.CanBeCanceled, cancellationToken); ChannelUtilities.QueueWaiter(ref _parent._waitingReadersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } private T DequeueItemAndPostProcess() { BoundedChannel<T> parent = _parent; T result = parent._items.DequeueHead(); if (parent._doneWriting != null) { if (parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } } else { while (!parent._blockedWriters.IsEmpty) { VoidAsyncOperationWithData<T> voidAsyncOperationWithData = parent._blockedWriters.DequeueHead(); if (voidAsyncOperationWithData.TrySetResult(default(VoidResult))) { parent._items.EnqueueTail(voidAsyncOperationWithData.Item); return result; } } ChannelUtilities.WakeUpWaiters(ref parent._waitingWritersTail, result: true); } return result; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items = {ItemsCountForDebugger}, Capacity = {CapacityForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class BoundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly BoundedChannel<T> _parent; private readonly VoidAsyncOperationWithData<T> _writerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; private int ItemsCountForDebugger => _parent._items.Count; private int CapacityForDebugger => _parent._bufferedCapacity; internal BoundedChannelWriter(BoundedChannel<T> parent) { _parent = parent; _writerSingleton = new VoidAsyncOperationWithData<T>(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true); } public override bool TryComplete(Exception error) { BoundedChannel<T> parent = _parent; bool isEmpty; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; isEmpty = parent._items.IsEmpty; } if (isEmpty) { ChannelUtilities.Complete(parent._completion, error); } ChannelUtilities.FailOperations<AsyncOperation<T>, T>(parent._blockedReaders, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.FailOperations<VoidAsyncOperationWithData<T>, VoidResult>(parent._blockedWriters, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.WakeUpWaiters(ref parent._waitingReadersTail, result: false, error); ChannelUtilities.WakeUpWaiters(ref parent._waitingWritersTail, result: false, error); return true; } public override bool TryWrite(T item) { AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> listTail = null; BoundedChannel<T> parent = _parent; bool lockTaken = false; try { Monitor.Enter(parent.SyncObj, ref lockTaken); if (parent._doneWriting != null) { return false; } int count = parent._items.Count; if (count != 0) { if (count < parent._bufferedCapacity) { parent._items.EnqueueTail(item); return true; } if (parent._mode == BoundedChannelFullMode.Wait) { return false; } if (parent._mode == BoundedChannelFullMode.DropWrite) { Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(item); return true; } T obj = ((parent._mode == BoundedChannelFullMode.DropNewest) ? parent._items.DequeueTail() : parent._items.DequeueHead()); parent._items.EnqueueTail(item); Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(obj); return true; } while (!parent._blockedReaders.IsEmpty) { AsyncOperation<T> asyncOperation2 = parent._blockedReaders.DequeueHead(); if (asyncOperation2.UnregisterCancellation()) { asyncOperation = asyncOperation2; break; } } if (asyncOperation == null) { parent._items.EnqueueTail(item); listTail = parent._waitingReadersTail; if (listTail == null) { return true; } parent._waitingReadersTail = null; } } finally { if (lockTaken) { Monitor.Exit(parent.SyncObj); } } if (asyncOperation != null) { bool flag = asyncOperation.TrySetResult(item); } else { ChannelUtilities.WakeUpWaiters(ref listTail, result: true); } return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } BoundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (parent._items.Count < parent._bufferedCapacity || parent._mode != 0) { return new ValueTask<bool>(result: true); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingWritersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(runContinuationsAsynchronously: true, cancellationToken); ChannelUtilities.QueueWaiter(ref parent._waitingWritersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask(Task.FromCanceled(cancellationToken)); } AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> listTail = null; BoundedChannel<T> parent = _parent; bool lockTaken = false; try { Monitor.Enter(parent.SyncObj, ref lockTaken); if (parent._doneWriting != null) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(parent._doneWriting))); } int count = parent._items.Count; if (count != 0) { if (count < parent._bufferedCapacity) { parent._items.EnqueueTail(item); return default(ValueTask); } if (parent._mode == BoundedChannelFullMode.Wait) { if (!cancellationToken.CanBeCanceled) { VoidAsyncOperationWithData<T> writerSingleton = _writerSingleton; if (writerSingleton.TryOwnAndReset()) { writerSingleton.Item = item; parent._blockedWriters.EnqueueTail(writerSingleton); return writerSingleton.ValueTask; } } VoidAsyncOperationWithData<T> voidAsyncOperationWithData = new VoidAsyncOperationWithData<T>(runContinuationsAsynchronously: true, cancellationToken); voidAsyncOperationWithData.Item = item; parent._blockedWriters.EnqueueTail(voidAsyncOperationWithData); return voidAsyncOperationWithData.ValueTask; } if (parent._mode == BoundedChannelFullMode.DropWrite) { Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(item); return default(ValueTask); } T obj = ((parent._mode == BoundedChannelFullMode.DropNewest) ? parent._items.DequeueTail() : parent._items.DequeueHead()); parent._items.EnqueueTail(item); Monitor.Exit(parent.SyncObj); lockTaken = false; parent._itemDropped?.Invoke(obj); return default(ValueTask); } while (!parent._blockedReaders.IsEmpty) { AsyncOperation<T> asyncOperation2 = parent._blockedReaders.DequeueHead(); if (asyncOperation2.UnregisterCancellation()) { asyncOperation = asyncOperation2; break; } } if (asyncOperation == null) { parent._items.EnqueueTail(item); listTail = parent._waitingReadersTail; if (listTail == null) { return default(ValueTask); } parent._waitingReadersTail = null; } } finally { if (lockTaken) { Monitor.Exit(parent.SyncObj); } } if (asyncOperation != null) { bool flag = asyncOperation.TrySetResult(item); } else { ChannelUtilities.WakeUpWaiters(ref listTail, result: true); } return default(ValueTask); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly BoundedChannelFullMode _mode; private readonly Action<T> _itemDropped; private readonly TaskCompletionSource _completion; private readonly int _bufferedCapacity; private readonly Deque<T> _items = new Deque<T>(); private readonly Deque<AsyncOperation<T>> _blockedReaders = new Deque<AsyncOperation<T>>(); private readonly Deque<VoidAsyncOperationWithData<T>> _blockedWriters = new Deque<VoidAsyncOperationWithData<T>>(); private AsyncOperation<bool> _waitingReadersTail; private AsyncOperation<bool> _waitingWritersTail; private readonly bool _runContinuationsAsynchronously; private Exception _doneWriting; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal BoundedChannel(int bufferedCapacity, BoundedChannelFullMode mode, bool runContinuationsAsynchronously, Action<T> itemDropped) { _bufferedCapacity = bufferedCapacity; _mode = mode; _runContinuationsAsynchronously = runContinuationsAsynchronously; _itemDropped = itemDropped; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new BoundedChannelReader(this); base.Writer = new BoundedChannelWriter(this); } [Conditional("DEBUG")] private void AssertInvariants() { _ = _items.IsEmpty; _ = _items.Count; _ = _bufferedCapacity; _ = _blockedReaders.IsEmpty; _ = _blockedWriters.IsEmpty; _ = _completion.Task.IsCompleted; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } public enum BoundedChannelFullMode { Wait, DropNewest, DropOldest, DropWrite } public static class Channel { public static Channel<T> CreateUnbounded<T>() { return new UnboundedChannel<T>(runContinuationsAsynchronously: true); } public static Channel<T> CreateUnbounded<T>(UnboundedChannelOptions options) { if (options == null) { throw new ArgumentNullException("options"); } if (options.SingleReader) { return new SingleConsumerUnboundedChannel<T>(!options.AllowSynchronousContinuations); } return new UnboundedChannel<T>(!options.AllowSynchronousContinuations); } public static Channel<T> CreateBounded<T>(int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity"); } return new BoundedChannel<T>(capacity, BoundedChannelFullMode.Wait, runContinuationsAsynchronously: true, null); } public static Channel<T> CreateBounded<T>(BoundedChannelOptions options) { return CreateBounded<T>(options, null); } public static Channel<T> CreateBounded<T>(BoundedChannelOptions options, Action<T>? itemDropped) { if (options == null) { throw new ArgumentNullException("options"); } return new BoundedChannel<T>(options.Capacity, options.FullMode, !options.AllowSynchronousContinuations, itemDropped); } } [Serializable] public class ChannelClosedException : InvalidOperationException { public ChannelClosedException() : base(System.SR.ChannelClosedException_DefaultMessage) { } public ChannelClosedException(string? message) : base(message) { } public ChannelClosedException(Exception? innerException) : base(System.SR.ChannelClosedException_DefaultMessage, innerException) { } public ChannelClosedException(string? message, Exception? innerException) : base(message, innerException) { } protected ChannelClosedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public abstract class ChannelOptions { public bool SingleWriter { get; set; } public bool SingleReader { get; set; } public bool AllowSynchronousContinuations { get; set; } } public sealed class BoundedChannelOptions : ChannelOptions { private int _capacity; private BoundedChannelFullMode _mode; public int Capacity { get { return _capacity; } set { if (value < 1) { throw new ArgumentOutOfRangeException("value"); } _capacity = value; } } public BoundedChannelFullMode FullMode { get { return _mode; } set { if ((uint)value <= 3u) { _mode = value; return; } throw new ArgumentOutOfRangeException("value"); } } public BoundedChannelOptions(int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity"); } _capacity = capacity; } } public sealed class UnboundedChannelOptions : ChannelOptions { } public abstract class ChannelReader<T> { public virtual Task Completion => ChannelUtilities.s_neverCompletingTask; public virtual bool CanCount => false; public virtual bool CanPeek => false; public virtual int Count { get { throw new NotSupportedException(); } } public abstract bool TryRead([MaybeNullWhen(false)] out T item); public virtual bool TryPeek([MaybeNullWhen(false)] out T item) { item = default(T); return false; } public abstract ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default(CancellationToken)); public virtual ValueTask<T> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } try { if (TryRead(out var item)) { return new ValueTask<T>(item); } } catch (Exception ex) when (!(ex is ChannelClosedException) && !(ex is OperationCanceledException)) { return new ValueTask<T>(Task.FromException<T>(ex)); } return ReadAsyncCore(cancellationToken); async ValueTask<T> ReadAsyncCore(CancellationToken ct) { T item2; do { if (!(await WaitToReadAsync(ct).ConfigureAwait(continueOnCapturedContext: false))) { throw new ChannelClosedException(); } } while (!TryRead(out item2)); return item2; } } public virtual async IAsyncEnumerable<T> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { while (await WaitToReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { T item; while (TryRead(out item)) { yield return item; } } } } internal static class ChannelUtilities { internal static readonly Exception s_doneWritingSentinel = new Exception("s_doneWritingSentinel"); internal static readonly Task<bool> s_trueTask = Task.FromResult(result: true); internal static readonly Task<bool> s_falseTask = Task.FromResult(result: false); internal static readonly Task s_neverCompletingTask = new TaskCompletionSource<bool>().Task; internal static void Complete(TaskCompletionSource tcs, Exception error = null) { if (error is OperationCanceledException ex) { tcs.TrySetCanceled(ex.CancellationToken); } else if (error != null && error != s_doneWritingSentinel) { if (tcs.TrySetException(error)) { _ = tcs.Task.Exception; } } else { tcs.TrySetResult(); } } internal static ValueTask<T> GetInvalidCompletionValueTask<T>(Exception error) { Task<T> task = ((error == s_doneWritingSentinel) ? Task.FromException<T>(CreateInvalidCompletionException()) : ((error is OperationCanceledException ex) ? Task.FromCanceled<T>(ex.CancellationToken.IsCancellationRequested ? ex.CancellationToken : new CancellationToken(canceled: true)) : Task.FromException<T>(CreateInvalidCompletionException(error)))); return new ValueTask<T>(task); } internal static void QueueWaiter(ref AsyncOperation<bool> tail, AsyncOperation<bool> waiter) { AsyncOperation<bool> asyncOperation = tail; if (asyncOperation == null) { waiter.Next = waiter; } else { waiter.Next = asyncOperation.Next; asyncOperation.Next = waiter; } tail = waiter; } internal static void WakeUpWaiters(ref AsyncOperation<bool> listTail, bool result, Exception error = null) { AsyncOperation<bool> asyncOperation = listTail; if (asyncOperation != null) { listTail = null; AsyncOperation<bool> next = asyncOperation.Next; AsyncOperation<bool> asyncOperation2 = next; do { AsyncOperation<bool> next2 = asyncOperation2.Next; asyncOperation2.Next = null; bool flag = ((error != null) ? asyncOperation2.TrySetException(error) : asyncOperation2.TrySetResult(result)); asyncOperation2 = next2; } while (asyncOperation2 != next); } } internal static void FailOperations<T, TInner>(Deque<T> operations, Exception error) where T : AsyncOperation<TInner> { while (!operations.IsEmpty) { operations.DequeueHead().TrySetException(error); } } internal static Exception CreateInvalidCompletionException(Exception inner = null) { if (!(inner is OperationCanceledException)) { if (inner == null || inner == s_doneWritingSentinel) { return new ChannelClosedException(); } return new ChannelClosedException(inner); } return inner; } } public abstract class ChannelWriter<T> { public virtual bool TryComplete(Exception? error = null) { return false; } public abstract bool TryWrite(T item); public abstract ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken = default(CancellationToken)); public virtual ValueTask WriteAsync(T item, CancellationToken cancellationToken = default(CancellationToken)) { try { return cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled<T>(cancellationToken)) : (TryWrite(item) ? default(ValueTask) : WriteAsyncCore(item, cancellationToken)); } catch (Exception exception) { return new ValueTask(Task.FromException(exception)); } } private async ValueTask WriteAsyncCore(T innerItem, CancellationToken ct) { while (await WaitToWriteAsync(ct).ConfigureAwait(continueOnCapturedContext: false)) { if (TryWrite(innerItem)) { return; } } throw ChannelUtilities.CreateInvalidCompletionException(); } public void Complete(Exception? error = null) { if (!TryComplete(error)) { throw ChannelUtilities.CreateInvalidCompletionException(); } } } public abstract class Channel<T> : Channel<T, T> { } public abstract class Channel<TWrite, TRead> { public ChannelReader<TRead> Reader { get; protected set; } public ChannelWriter<TWrite> Writer { get; protected set; } public static implicit operator ChannelReader<TRead>(Channel<TWrite, TRead> channel) { return channel.Reader; } public static implicit operator ChannelWriter<TWrite>(Channel<TWrite, TRead> channel) { return channel.Writer; } } internal interface IDebugEnumerable<T> { IEnumerator<T> GetEnumerator(); } internal sealed class DebugEnumeratorDebugView<T> { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get; } public DebugEnumeratorDebugView(IDebugEnumerable<T> enumerable) { List<T> list = new List<T>(); foreach (T item in enumerable) { list.Add(item); } Items = list.ToArray(); } } [DebuggerDisplay("Items = {ItemsCountForDebugger}, Closed = {ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class SingleConsumerUnboundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items = {ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly SingleConsumerUnboundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanPeek => true; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelReader(SingleConsumerUnboundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } if (TryRead(out var item)) { return new ValueTask<T>(item); } SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<T> asyncOperation; AsyncOperation<T> asyncOperation2; lock (parent.SyncObj) { if (TryRead(out item)) { return new ValueTask<T>(item); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } asyncOperation = parent._blockedReader; if (!cancellationToken.CanBeCanceled && _readerSingleton.TryOwnAndReset()) { asyncOperation2 = _readerSingleton; if (asyncOperation2 == asyncOperation) { asyncOperation = null; } } else { asyncOperation2 = new AsyncOperation<T>(_parent._runContinuationsAsynchronously, cancellationToken); } parent._blockedReader = asyncOperation2; } asyncOperation?.TrySetCanceled(); return asyncOperation2.ValueTaskOfT; } public override bool TryRead([MaybeNullWhen(false)] out T item) { SingleConsumerUnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out item)) { if (parent._doneWriting != null && parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } return true; } return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { return _parent._items.TryPeek(out item); } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } if (!_parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<bool> asyncOperation = null; AsyncOperation<bool> asyncOperation2; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } asyncOperation = parent._waitingReader; if (!cancellationToken.CanBeCanceled && _waiterSingleton.TryOwnAndReset()) { asyncOperation2 = _waiterSingleton; if (asyncOperation2 == asyncOperation) { asyncOperation = null; } } else { asyncOperation2 = new AsyncOperation<bool>(_parent._runContinuationsAsynchronously, cancellationToken); } parent._waitingReader = asyncOperation2; } asyncOperation?.TrySetCanceled(); return asyncOperation2.ValueTaskOfT; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items = {ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly SingleConsumerUnboundedChannel<T> _parent; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelWriter(SingleConsumerUnboundedChannel<T> parent) { _parent = parent; } public override bool TryComplete(Exception error) { AsyncOperation<T> asyncOperation = null; AsyncOperation<bool> asyncOperation2 = null; bool flag = false; SingleConsumerUnboundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; if (parent._items.IsEmpty) { flag = true; if (parent._blockedReader != null) { asyncOperation = parent._blockedReader; parent._blockedReader = null; } if (parent._waitingReader != null) { asyncOperation2 = parent._waitingReader; parent._waitingReader = null; } } } if (flag) { ChannelUtilities.Complete(parent._completion, error); } if (asyncOperation != null) { error = ChannelUtilities.CreateInvalidCompletionException(error); asyncOperation.TrySetException(error); } if (asyncOperation2 != null) { if (error != null) { asyncOperation2.TrySetException(error); } else { asyncOperation2.TrySetResult(item: false); } } return true; } public override bool TryWrite(T item) { SingleConsumerUnboundedChannel<T> parent = _parent; AsyncOperation<T> asyncOperation; do { asyncOperation = null; AsyncOperation<bool> asyncOperation2 = null; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } asyncOperation = parent._blockedReader; if (asyncOperation != null) { parent._blockedReader = null; } else { parent._items.Enqueue(item); asyncOperation2 = parent._waitingReader; if (asyncOperation2 == null) { return true; } parent._waitingReader = null; } } if (asyncOperation2 != null) { asyncOperation2.TrySetResult(item: true); return true; } } while (!asyncOperation.TrySetResult(item)); return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { Exception doneWriting = _parent._doneWriting; if (!cancellationToken.IsCancellationRequested) { if (doneWriting != null) { if (doneWriting == ChannelUtilities.s_doneWritingSentinel) { return default(ValueTask<bool>); } return new ValueTask<bool>(Task.FromException<bool>(doneWriting)); } return new ValueTask<bool>(result: true); } return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { if (!TryWrite(item)) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(_parent._doneWriting))); } return default(ValueTask); } return new ValueTask(Task.FromCanceled(cancellationToken)); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly TaskCompletionSource _completion; private readonly SingleProducerSingleConsumerQueue<T> _items = new SingleProducerSingleConsumerQueue<T>(); private readonly bool _runContinuationsAsynchronously; private volatile Exception _doneWriting; private AsyncOperation<T> _blockedReader; private AsyncOperation<bool> _waitingReader; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal SingleConsumerUnboundedChannel(bool runContinuationsAsynchronously) { _runContinuationsAsynchronously = runContinuationsAsynchronously; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new UnboundedChannelReader(this); base.Writer = new UnboundedChannelWriter(this); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } internal sealed class TaskCompletionSource : TaskCompletionSource<VoidResult> { public TaskCompletionSource(TaskCreationOptions creationOptions) : base(creationOptions) { } public bool TrySetResult() { return TrySetResult(default(VoidResult)); } } [DebuggerDisplay("Items = {ItemsCountForDebugger}, Closed = {ChannelIsClosedForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] internal sealed class UnboundedChannel<T> : Channel<T>, IDebugEnumerable<T> { [DebuggerDisplay("Items = {Count}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelReader : ChannelReader<T>, IDebugEnumerable<T> { internal readonly UnboundedChannel<T> _parent; private readonly AsyncOperation<T> _readerSingleton; private readonly AsyncOperation<bool> _waiterSingleton; public override Task Completion => _parent._completion.Task; public override bool CanCount => true; public override bool CanPeek => true; public override int Count => _parent._items.Count; internal UnboundedChannelReader(UnboundedChannel<T> parent) { _parent = parent; _readerSingleton = new AsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); _waiterSingleton = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true); } public override ValueTask<T> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken)); } UnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out var result)) { CompleteIfDone(parent); return new ValueTask<T>(result); } lock (parent.SyncObj) { if (parent._items.TryDequeue(out result)) { CompleteIfDone(parent); return new ValueTask<T>(result); } if (parent._doneWriting != null) { return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<T> readerSingleton = _readerSingleton; if (readerSingleton.TryOwnAndReset()) { parent._blockedReaders.EnqueueTail(readerSingleton); return readerSingleton.ValueTaskOfT; } } AsyncOperation<T> asyncOperation = new AsyncOperation<T>(parent._runContinuationsAsynchronously, cancellationToken); parent._blockedReaders.EnqueueTail(asyncOperation); return asyncOperation.ValueTaskOfT; } } public override bool TryRead([MaybeNullWhen(false)] out T item) { UnboundedChannel<T> parent = _parent; if (parent._items.TryDequeue(out item)) { CompleteIfDone(parent); return true; } item = default(T); return false; } public override bool TryPeek([MaybeNullWhen(false)] out T item) { return _parent._items.TryPeek(out item); } private static void CompleteIfDone(UnboundedChannel<T> parent) { if (parent._doneWriting != null && parent._items.IsEmpty) { ChannelUtilities.Complete(parent._completion, parent._doneWriting); } } public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } if (!_parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } UnboundedChannel<T> parent = _parent; lock (parent.SyncObj) { if (!parent._items.IsEmpty) { return new ValueTask<bool>(result: true); } if (parent._doneWriting != null) { return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>); } if (!cancellationToken.CanBeCanceled) { AsyncOperation<bool> waiterSingleton = _waiterSingleton; if (waiterSingleton.TryOwnAndReset()) { ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, waiterSingleton); return waiterSingleton.ValueTaskOfT; } } AsyncOperation<bool> asyncOperation = new AsyncOperation<bool>(parent._runContinuationsAsynchronously, cancellationToken); ChannelUtilities.QueueWaiter(ref parent._waitingReadersTail, asyncOperation); return asyncOperation.ValueTaskOfT; } } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } [DebuggerDisplay("Items = {ItemsCountForDebugger}")] [DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))] private sealed class UnboundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T> { internal readonly UnboundedChannel<T> _parent; private int ItemsCountForDebugger => _parent._items.Count; internal UnboundedChannelWriter(UnboundedChannel<T> parent) { _parent = parent; } public override bool TryComplete(Exception error) { UnboundedChannel<T> parent = _parent; bool isEmpty; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel; isEmpty = parent._items.IsEmpty; } if (isEmpty) { ChannelUtilities.Complete(parent._completion, error); } ChannelUtilities.FailOperations<AsyncOperation<T>, T>(parent._blockedReaders, ChannelUtilities.CreateInvalidCompletionException(error)); ChannelUtilities.WakeUpWaiters(ref parent._waitingReadersTail, result: false, error); return true; } public override bool TryWrite(T item) { UnboundedChannel<T> parent = _parent; AsyncOperation<bool> listTail; while (true) { AsyncOperation<T> asyncOperation = null; listTail = null; lock (parent.SyncObj) { if (parent._doneWriting != null) { return false; } if (parent._blockedReaders.IsEmpty) { parent._items.Enqueue(item); listTail = parent._waitingReadersTail; if (listTail == null) { return true; } parent._waitingReadersTail = null; } else { asyncOperation = parent._blockedReaders.DequeueHead(); } } if (asyncOperation == null) { break; } if (asyncOperation.TrySetResult(item)) { return true; } } ChannelUtilities.WakeUpWaiters(ref listTail, result: true); return true; } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken) { Exception doneWriting = _parent._doneWriting; if (!cancellationToken.IsCancellationRequested) { if (doneWriting != null) { if (doneWriting == ChannelUtilities.s_doneWritingSentinel) { return default(ValueTask<bool>); } return new ValueTask<bool>(Task.FromException<bool>(doneWriting)); } return new ValueTask<bool>(result: true); } return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)); } public override ValueTask WriteAsync(T item, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { if (!TryWrite(item)) { return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(_parent._doneWriting))); } return default(ValueTask); } return new ValueTask(Task.FromCanceled(cancellationToken)); } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _parent._items.GetEnumerator(); } } private readonly TaskCompletionSource _completion; private readonly ConcurrentQueue<T> _items = new ConcurrentQueue<T>(); private readonly Deque<AsyncOperation<T>> _blockedReaders = new Deque<AsyncOperation<T>>(); private readonly bool _runContinuationsAsynchronously; private AsyncOperation<bool> _waitingReadersTail; private Exception _doneWriting; private object SyncObj => _items; private int ItemsCountForDebugger => _items.Count; private bool ChannelIsClosedForDebugger => _doneWriting != null; internal UnboundedChannel(bool runContinuationsAsynchronously) { _runContinuationsAsynchronously = runContinuationsAsynchronously; _completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None); base.Reader = new UnboundedChannelReader(this); base.Writer = new UnboundedChannelWriter(this); } [Conditional("DEBUG")] private void AssertInvariants() { if (!_items.IsEmpty) { _ = _runContinuationsAsynchronously; } if (!_blockedReaders.IsEmpty || _waitingReadersTail != null) { _ = _runContinuationsAsynchronously; } _ = _completion.Task.IsCompleted; } IEnumerator<T> IDebugEnumerable<T>.GetEnumerator() { return _items.GetEnumerator(); } } }
deps/System.Threading.Tasks.Extensions.dll
Decompiled a day agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Threading.Tasks.Sources; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Threading.Tasks.Extensions")] [assembly: AssemblyDescription("System.Threading.Tasks.Extensions")] [assembly: AssemblyDefaultAlias("System.Threading.Tasks.Extensions")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyInformationalVersion("4.0.0.0")] [assembly: AssemblyFileVersion("4.0.0.0")] [assembly: AssemblyVersion("4.2.0.0")] [assembly: TypeForwardedTo(typeof(AsyncMethodBuilderAttribute))] [assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder))] [assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder<>))] [assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable))] [assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable<>))] [assembly: TypeForwardedTo(typeof(ValueTaskAwaiter))] [assembly: TypeForwardedTo(typeof(ValueTaskAwaiter<>))] [assembly: TypeForwardedTo(typeof(IValueTaskSource))] [assembly: TypeForwardedTo(typeof(IValueTaskSource<>))] [assembly: TypeForwardedTo(typeof(ValueTaskSourceOnCompletedFlags))] [assembly: TypeForwardedTo(typeof(ValueTaskSourceStatus))] [assembly: TypeForwardedTo(typeof(ValueTask))] [assembly: TypeForwardedTo(typeof(ValueTask<>))]
deps/System.Transactions.dll
Decompiled a day agousing System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Threading; using System.Transactions.Configuration; using Unity; [assembly: BestFitMapping(false)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Transactions.dll")] [assembly: AssemblyDescription("System.Transactions.dll")] [assembly: AssemblyDefaultAlias("System.Transactions.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(false)] [assembly: AllowPartiallyTrustedCallers] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: AssemblyVersion("4.0.0.0")] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal sealed class Locale { private Locale() { } public static string GetText(string msg) { return msg; } public static string GetText(string fmt, params object[] args) { return string.Format(fmt, args); } } namespace System { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoTODOAttribute : Attribute { private string comment; public string Comment => comment; public MonoTODOAttribute() { } public MonoTODOAttribute(string comment) { this.comment = comment; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoDocumentationNoteAttribute : MonoTODOAttribute { public MonoDocumentationNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoExtensionAttribute : MonoTODOAttribute { public MonoExtensionAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoInternalNoteAttribute : MonoTODOAttribute { public MonoInternalNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoLimitationAttribute : MonoTODOAttribute { public MonoLimitationAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoNotSupportedAttribute : MonoTODOAttribute { public MonoNotSupportedAttribute(string comment) : base(comment) { } } } namespace System.Transactions { [Serializable] public sealed class CommittableTransaction : Transaction, ISerializable, IDisposable, IAsyncResult { private TransactionOptions options; private AsyncCallback callback; private object user_defined_state; private IAsyncResult asyncResult; object IAsyncResult.AsyncState => user_defined_state; WaitHandle IAsyncResult.AsyncWaitHandle => asyncResult.AsyncWaitHandle; bool IAsyncResult.CompletedSynchronously => asyncResult.CompletedSynchronously; bool IAsyncResult.IsCompleted => asyncResult.IsCompleted; public CommittableTransaction() : this(default(TransactionOptions)) { } public CommittableTransaction(TimeSpan timeout) : base(IsolationLevel.Serializable) { options = default(TransactionOptions); options.Timeout = timeout; } public CommittableTransaction(TransactionOptions options) : base(options.IsolationLevel) { this.options = options; } public IAsyncResult BeginCommit(AsyncCallback asyncCallback, object asyncState) { callback = asyncCallback; user_defined_state = asyncState; AsyncCallback asyncCallback2 = null; if (asyncCallback != null) { asyncCallback2 = CommitCallback; } asyncResult = BeginCommitInternal(asyncCallback2); return this; } public void EndCommit(IAsyncResult asyncResult) { if (asyncResult != this) { throw new ArgumentException("The IAsyncResult parameter must be the same parameter as returned by BeginCommit.", "asyncResult"); } EndCommitInternal(this.asyncResult); } private void CommitCallback(IAsyncResult ar) { if (asyncResult == null && ar.CompletedSynchronously) { asyncResult = ar; } callback(this); } public void Commit() { CommitInternal(); } [MonoTODO("Not implemented")] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } } public delegate Transaction HostCurrentTransactionCallback(); public delegate void TransactionCompletedEventHandler(object sender, TransactionEventArgs e); public delegate void TransactionStartedEventHandler(object sender, TransactionEventArgs e); public enum DependentCloneOption { BlockCommitUntilComplete, RollbackIfNotComplete } [Serializable] [MonoTODO("Not supported yet")] public sealed class DependentTransaction : Transaction, ISerializable { private bool completed; internal bool Completed => completed; internal DependentTransaction(Transaction parent, DependentCloneOption option) : base(parent.IsolationLevel) { } [MonoTODO] public void Complete() { throw new NotImplementedException(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { completed = info.GetBoolean("completed"); } internal DependentTransaction() { ThrowStub.ThrowNotSupportedException(); } } public class Enlistment { internal bool done; internal Enlistment() { done = false; } public void Done() { done = true; InternalOnDone(); } internal virtual void InternalOnDone() { } } [Flags] public enum EnlistmentOptions { None = 0, EnlistDuringPrepareRequired = 1 } public enum EnterpriseServicesInteropOption { None, Automatic, Full } [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDtcTransaction { void Abort(IntPtr reason, int retaining, int async); void Commit(int retaining, int commitType, int reserved); void GetTransactionInfo(IntPtr transactionInformation); } public interface IEnlistmentNotification { void Commit(Enlistment enlistment); void InDoubt(Enlistment enlistment); void Prepare(PreparingEnlistment preparingEnlistment); void Rollback(Enlistment enlistment); } public interface IPromotableSinglePhaseNotification : ITransactionPromoter { void Initialize(); void Rollback(SinglePhaseEnlistment singlePhaseEnlistment); void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment); } public interface ISimpleTransactionSuperior : ITransactionPromoter { void Rollback(); } public interface ISinglePhaseNotification : IEnlistmentNotification { void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment); } public interface ITransactionPromoter { byte[] Promote(); } public enum IsolationLevel { Serializable, RepeatableRead, ReadCommitted, ReadUncommitted, Snapshot, Chaos, Unspecified } public class PreparingEnlistment : Enlistment { private bool prepared; private Transaction tx; private IEnlistmentNotification enlisted; private WaitHandle waitHandle; private Exception ex; internal bool IsPrepared => prepared; internal WaitHandle WaitHandle => waitHandle; internal IEnlistmentNotification EnlistmentNotification => enlisted; internal Exception Exception { get { return ex; } set { ex = value; } } internal PreparingEnlistment(Transaction tx, IEnlistmentNotification enlisted) { this.tx = tx; this.enlisted = enlisted; waitHandle = new ManualResetEvent(initialState: false); } public void ForceRollback() { ForceRollback(null); } internal override void InternalOnDone() { Prepared(); } [MonoTODO] public void ForceRollback(Exception e) { tx.Rollback(e, enlisted); ((ManualResetEvent)waitHandle).Set(); } [MonoTODO] public void Prepared() { prepared = true; ((ManualResetEvent)waitHandle).Set(); } [MonoTODO] public byte[] RecoveryInformation() { throw new NotImplementedException(); } internal PreparingEnlistment() { ThrowStub.ThrowNotSupportedException(); } } public class SinglePhaseEnlistment : Enlistment { private Transaction tx; private object abortingEnlisted; internal SinglePhaseEnlistment() { } internal SinglePhaseEnlistment(Transaction tx, object abortingEnlisted) { this.tx = tx; this.abortingEnlisted = abortingEnlisted; } public void Aborted() { Aborted(null); } public void Aborted(Exception e) { if (tx != null) { tx.Rollback(e, abortingEnlisted); } } [MonoTODO] public void Committed() { } [MonoTODO("Not implemented")] public void InDoubt() { throw new NotImplementedException(); } [MonoTODO("Not implemented")] public void InDoubt(Exception e) { throw new NotImplementedException(); } } [Serializable] public sealed class SubordinateTransaction : Transaction { public SubordinateTransaction(IsolationLevel isoLevel, ISimpleTransactionSuperior superior) : base(isoLevel) { throw new NotImplementedException(); } } [Serializable] public class Transaction : IDisposable, ISerializable { private delegate void AsyncCommit(); [ThreadStatic] private static Transaction ambient; private Transaction internalTransaction; private IsolationLevel level; private TransactionInformation info; private ArrayList dependents; private List<IEnlistmentNotification> volatiles; private List<ISinglePhaseNotification> durables; private IPromotableSinglePhaseNotification pspe; private AsyncCommit asyncCommit; private bool committing; private bool committed; private bool aborted; private TransactionScope scope; private Exception innerException; private Guid tag; internal List<IEnlistmentNotification> Volatiles { get { if (volatiles == null) { volatiles = new List<IEnlistmentNotification>(); } return volatiles; } } internal List<ISinglePhaseNotification> Durables { get { if (durables == null) { durables = new List<ISinglePhaseNotification>(); } return durables; } } internal IPromotableSinglePhaseNotification Pspe => pspe; public static Transaction Current { get { EnsureIncompleteCurrentScope(); return CurrentInternal; } set { EnsureIncompleteCurrentScope(); CurrentInternal = value; } } internal static Transaction CurrentInternal { get { return ambient; } set { ambient = value; } } public IsolationLevel IsolationLevel { get { EnsureIncompleteCurrentScope(); return level; } } public TransactionInformation TransactionInformation { get { EnsureIncompleteCurrentScope(); return info; } } public Guid PromoterType { get { throw new NotImplementedException(); } } private bool Aborted { get { return aborted; } set { aborted = value; if (aborted) { info.Status = TransactionStatus.Aborted; } } } internal TransactionScope Scope { get { return scope; } set { scope = value; } } internal event TransactionCompletedEventHandler TransactionCompletedInternal; public event TransactionCompletedEventHandler TransactionCompleted { add { if (internalTransaction != null) { internalTransaction.TransactionCompleted += value; } TransactionCompletedInternal += value; } remove { if (internalTransaction != null) { internalTransaction.TransactionCompleted -= value; } TransactionCompletedInternal -= value; } } internal Transaction(IsolationLevel isolationLevel) { dependents = new ArrayList(); tag = Guid.NewGuid(); base..ctor(); info = new TransactionInformation(); level = isolationLevel; } internal Transaction(Transaction other) { dependents = new ArrayList(); tag = Guid.NewGuid(); base..ctor(); level = other.level; info = other.info; dependents = other.dependents; volatiles = other.Volatiles; durables = other.Durables; pspe = other.Pspe; this.TransactionCompletedInternal = other.TransactionCompletedInternal; internalTransaction = other; } [MonoTODO] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } public Transaction Clone() { return new Transaction(this); } public void Dispose() { if (TransactionInformation.Status == TransactionStatus.Active) { Rollback(); } } [MonoTODO] public DependentTransaction DependentClone(DependentCloneOption cloneOption) { DependentTransaction dependentTransaction = new DependentTransaction(this, cloneOption); dependents.Add(dependentTransaction); return dependentTransaction; } [MonoTODO("Only SinglePhase commit supported for durable resource managers.")] [PermissionSet(SecurityAction.LinkDemand)] public Enlistment EnlistDurable(Guid resourceManagerIdentifier, IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions) { throw new NotImplementedException("DTC unsupported, only SinglePhase commit supported for durable resource managers."); } [MonoTODO("Only Local Transaction Manager supported. Cannot have more than 1 durable resource per transaction. Only EnlistmentOptions.None supported yet.")] [PermissionSet(SecurityAction.LinkDemand)] public Enlistment EnlistDurable(Guid resourceManagerIdentifier, ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions) { EnsureIncompleteCurrentScope(); if (pspe != null || Durables.Count > 0) { throw new NotImplementedException("DTC unsupported, multiple durable resource managers aren't supported."); } if (enlistmentOptions != 0) { throw new NotImplementedException("EnlistmentOptions other than None aren't supported"); } Durables.Add(singlePhaseNotification); return new Enlistment(); } public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification) { EnsureIncompleteCurrentScope(); if (pspe != null || Durables.Count > 0) { return false; } pspe = promotableSinglePhaseNotification; pspe.Initialize(); return true; } public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification promotableNotification, Guid distributedTransactionIdentifier) { throw new NotImplementedException(); } public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType) { throw new NotImplementedException(); } public byte[] GetPromotedToken() { throw new NotImplementedException(); } [MonoTODO("EnlistmentOptions being ignored")] public Enlistment EnlistVolatile(IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions) { return EnlistVolatileInternal(enlistmentNotification, enlistmentOptions); } [MonoTODO("EnlistmentOptions being ignored")] public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions) { return EnlistVolatileInternal(singlePhaseNotification, enlistmentOptions); } private Enlistment EnlistVolatileInternal(IEnlistmentNotification notification, EnlistmentOptions options) { EnsureIncompleteCurrentScope(); Volatiles.Add(notification); return new Enlistment(); } [MonoTODO("Only Local Transaction Manager supported. Cannot have more than 1 durable resource per transaction.")] [PermissionSet(SecurityAction.LinkDemand)] public Enlistment PromoteAndEnlistDurable(Guid manager, IPromotableSinglePhaseNotification promotableNotification, ISinglePhaseNotification notification, EnlistmentOptions options) { throw new NotImplementedException("DTC unsupported, multiple durable resource managers aren't supported."); } public override bool Equals(object obj) { return Equals(obj as Transaction); } private bool Equals(Transaction t) { if ((object)t == this) { return true; } if ((object)t == null) { return false; } if (level == t.level) { return info == t.info; } return false; } public static bool operator ==(Transaction x, Transaction y) { return x?.Equals(y) ?? ((object)y == null); } public static bool operator !=(Transaction x, Transaction y) { return !(x == y); } public override int GetHashCode() { return (int)level ^ info.GetHashCode() ^ dependents.GetHashCode(); } public void Rollback() { Rollback(null); } public void Rollback(Exception e) { EnsureIncompleteCurrentScope(); Rollback(e, null); } internal void Rollback(Exception ex, object abortingEnlisted) { if (aborted) { FireCompleted(); return; } if (info.Status == TransactionStatus.Committed) { throw new TransactionException("Transaction has already been committed. Cannot accept any new work."); } innerException = ex; SinglePhaseEnlistment singlePhaseEnlistment = new SinglePhaseEnlistment(); foreach (IEnlistmentNotification @volatile in Volatiles) { if (@volatile != abortingEnlisted) { @volatile.Rollback(singlePhaseEnlistment); } } List<ISinglePhaseNotification> list = Durables; if (list.Count > 0 && list[0] != abortingEnlisted) { list[0].Rollback(singlePhaseEnlistment); } if (pspe != null && pspe != abortingEnlisted) { pspe.Rollback(singlePhaseEnlistment); } Aborted = true; FireCompleted(); } protected IAsyncResult BeginCommitInternal(AsyncCallback callback) { if (committed || committing) { throw new InvalidOperationException("Commit has already been called for this transaction."); } committing = true; asyncCommit = DoCommit; return asyncCommit.BeginInvoke(callback, null); } protected void EndCommitInternal(IAsyncResult ar) { asyncCommit.EndInvoke(ar); } internal void CommitInternal() { if (committed || committing) { throw new InvalidOperationException("Commit has already been called for this transaction."); } committing = true; try { DoCommit(); } catch (TransactionException) { throw; } catch (Exception ex2) { throw new TransactionAbortedException("Transaction failed", ex2); } } private void DoCommit() { if (Scope != null && (!Scope.IsComplete || !Scope.IsDisposed)) { Rollback(null, null); CheckAborted(); } List<IEnlistmentNotification> list = Volatiles; List<ISinglePhaseNotification> list2 = Durables; if (list.Count == 1 && list2.Count == 0 && list[0] is ISinglePhaseNotification single) { DoSingleCommit(single); Complete(); return; } if (list.Count > 0) { DoPreparePhase(); } if (list2.Count > 0) { DoSingleCommit(list2[0]); } if (pspe != null) { DoSingleCommit(pspe); } if (list.Count > 0) { DoCommitPhase(); } Complete(); } private void Complete() { committing = false; committed = true; if (!aborted) { info.Status = TransactionStatus.Committed; } FireCompleted(); } internal void InitScope(TransactionScope scope) { CheckAborted(); if (committed) { throw new InvalidOperationException("Commit has already been called on this transaction."); } Scope = scope; } private static void PrepareCallbackWrapper(object state) { PreparingEnlistment preparingEnlistment = state as PreparingEnlistment; try { preparingEnlistment.EnlistmentNotification.Prepare(preparingEnlistment); } catch (Exception exception) { preparingEnlistment.Exception = exception; if (!preparingEnlistment.IsPrepared) { ((ManualResetEvent)preparingEnlistment.WaitHandle).Set(); } } } private void DoPreparePhase() { foreach (IEnlistmentNotification @volatile in Volatiles) { PreparingEnlistment preparingEnlistment = new PreparingEnlistment(this, @volatile); ThreadPool.QueueUserWorkItem(PrepareCallbackWrapper, preparingEnlistment); TimeSpan timeout = ((Scope != null) ? Scope.Timeout : TransactionManager.DefaultTimeout); if (!preparingEnlistment.WaitHandle.WaitOne(timeout, exitContext: true)) { Aborted = true; throw new TimeoutException("Transaction timedout"); } if (preparingEnlistment.Exception != null) { innerException = preparingEnlistment.Exception; Aborted = true; break; } if (!preparingEnlistment.IsPrepared) { Aborted = true; break; } } CheckAborted(); } private void DoCommitPhase() { foreach (IEnlistmentNotification @volatile in Volatiles) { Enlistment enlistment = new Enlistment(); @volatile.Commit(enlistment); } } private void DoSingleCommit(ISinglePhaseNotification single) { if (single != null) { single.SinglePhaseCommit(new SinglePhaseEnlistment(this, single)); CheckAborted(); } } private void DoSingleCommit(IPromotableSinglePhaseNotification single) { if (single != null) { single.SinglePhaseCommit(new SinglePhaseEnlistment(this, single)); CheckAborted(); } } private void CheckAborted() { if (aborted || (Scope != null && Scope.IsAborted)) { throw new TransactionAbortedException("Transaction has aborted", innerException); } } private void FireCompleted() { if (this.TransactionCompletedInternal != null) { this.TransactionCompletedInternal(this, new TransactionEventArgs(this)); } } private static void EnsureIncompleteCurrentScope() { if (CurrentInternal == null || CurrentInternal.Scope == null || !CurrentInternal.Scope.IsComplete) { return; } throw new InvalidOperationException("The current TransactionScope is already complete"); } internal Transaction() { ThrowStub.ThrowNotSupportedException(); } } [Serializable] public class TransactionAbortedException : TransactionException { public TransactionAbortedException() { } public TransactionAbortedException(string message) : base(message) { } public TransactionAbortedException(string message, Exception innerException) : base(message, innerException) { } protected TransactionAbortedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class TransactionEventArgs : EventArgs { private Transaction transaction; public Transaction Transaction => transaction; public TransactionEventArgs() { } internal TransactionEventArgs(Transaction transaction) : this() { this.transaction = transaction; } } [Serializable] public class TransactionException : SystemException { public TransactionException() { } public TransactionException(string message) : base(message) { } public TransactionException(string message, Exception innerException) : base(message, innerException) { } protected TransactionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class TransactionInDoubtException : TransactionException { public TransactionInDoubtException() { } public TransactionInDoubtException(string message) : base(message) { } public TransactionInDoubtException(string message, Exception innerException) : base(message, innerException) { } protected TransactionInDoubtException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class TransactionInformation { private string local_id; private Guid dtcId = Guid.Empty; private DateTime creation_time; private TransactionStatus status; public DateTime CreationTime => creation_time; public Guid DistributedIdentifier { get { return dtcId; } internal set { dtcId = value; } } public string LocalIdentifier => local_id; public TransactionStatus Status { get { return status; } internal set { status = value; } } internal TransactionInformation() { status = TransactionStatus.Active; creation_time = DateTime.Now.ToUniversalTime(); local_id = Guid.NewGuid().ToString() + ":1"; } private TransactionInformation(TransactionInformation other) { local_id = other.local_id; dtcId = other.dtcId; creation_time = other.creation_time; status = other.status; } internal TransactionInformation Clone(TransactionInformation other) { return new TransactionInformation(other); } } [MonoTODO] public static class TransactionInterop { public static readonly Guid PromoterTypeDtc = new Guid("14229753-FFE1-428D-82B7-DF73045CB8DA"); [MonoTODO] public static IDtcTransaction GetDtcTransaction(Transaction transaction) { throw new NotImplementedException(); } [MonoTODO] public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts) { throw new NotImplementedException(); } [MonoTODO] public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative) { throw new NotImplementedException(); } [MonoTODO] public static Transaction GetTransactionFromExportCookie(byte[] cookie) { throw new NotImplementedException(); } [MonoTODO] public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken) { throw new NotImplementedException(); } [MonoTODO] public static byte[] GetTransmitterPropagationToken(Transaction transaction) { throw new NotImplementedException(); } [MonoTODO] public static byte[] GetWhereabouts() { throw new NotImplementedException(); } } public static class TransactionManager { private static DefaultSettingsSection defaultSettings; private static MachineSettingsSection machineSettings; private static TimeSpan defaultTimeout; private static TimeSpan maxTimeout; public static TimeSpan DefaultTimeout { get { if (defaultSettings != null) { return defaultSettings.Timeout; } return defaultTimeout; } } [MonoTODO("Not implemented")] public static HostCurrentTransactionCallback HostCurrentCallback { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public static TimeSpan MaximumTimeout { get { if (machineSettings != null) { return machineSettings.MaxTimeout; } return maxTimeout; } } public static event TransactionStartedEventHandler DistributedTransactionStarted; static TransactionManager() { defaultTimeout = new TimeSpan(0, 1, 0); maxTimeout = new TimeSpan(0, 10, 0); defaultSettings = ConfigurationManager.GetSection("system.transactions/defaultSettings") as DefaultSettingsSection; machineSettings = ConfigurationManager.GetSection("system.transactions/machineSettings") as MachineSettingsSection; } [MonoTODO("Not implemented")] public static void RecoveryComplete(Guid resourceManagerIdentifier) { throw new NotImplementedException(); } [MonoTODO("Not implemented")] public static Enlistment Reenlist(Guid resourceManagerIdentifier, byte[] recoveryInformation, IEnlistmentNotification enlistmentNotification) { throw new NotImplementedException(); } } [Serializable] public class TransactionManagerCommunicationException : TransactionException { public TransactionManagerCommunicationException() { } public TransactionManagerCommunicationException(string message) : base(message) { } public TransactionManagerCommunicationException(string message, Exception innerException) : base(message, innerException) { } protected TransactionManagerCommunicationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public struct TransactionOptions { private IsolationLevel level; private TimeSpan timeout; public IsolationLevel IsolationLevel { get { return level; } set { level = value; } } public TimeSpan Timeout { get { return timeout; } set { timeout = value; } } internal TransactionOptions(IsolationLevel level, TimeSpan timeout) { this.level = level; this.timeout = timeout; } public static bool operator ==(TransactionOptions x, TransactionOptions y) { if (x.level == y.level) { return x.timeout == y.timeout; } return false; } public static bool operator !=(TransactionOptions x, TransactionOptions y) { if (x.level == y.level) { return x.timeout != y.timeout; } return true; } public override bool Equals(object obj) { if (!(obj is TransactionOptions)) { return false; } return this == (TransactionOptions)obj; } public override int GetHashCode() { return (int)level ^ timeout.GetHashCode(); } } [Serializable] public class TransactionPromotionException : TransactionException { public TransactionPromotionException() { } public TransactionPromotionException(string message) : base(message) { } public TransactionPromotionException(string message, Exception innerException) : base(message, innerException) { } protected TransactionPromotionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public sealed class TransactionScope : IDisposable { private static TransactionOptions defaultOptions = new TransactionOptions(IsolationLevel.Serializable, TransactionManager.DefaultTimeout); private Timer scopeTimer; private Transaction transaction; private Transaction oldTransaction; private TransactionScope parentScope; private TimeSpan timeout; private int nested; private bool disposed; private bool completed; private bool aborted; private bool isRoot; private bool asyncFlowEnabled; internal bool IsAborted => aborted; internal bool IsDisposed => disposed; internal bool IsComplete => completed; internal TimeSpan Timeout => timeout; public TransactionScope() : this(TransactionScopeOption.Required, TransactionManager.DefaultTimeout) { } public TransactionScope(TransactionScopeAsyncFlowOption asyncFlowOption) : this(TransactionScopeOption.Required, TransactionManager.DefaultTimeout, asyncFlowOption) { } public TransactionScope(Transaction transactionToUse) : this(transactionToUse, TransactionManager.DefaultTimeout) { } public TransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout) : this(transactionToUse, scopeTimeout, EnterpriseServicesInteropOption.None) { } [MonoTODO("EnterpriseServicesInteropOption not supported.")] public TransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout, EnterpriseServicesInteropOption interopOption) { Initialize(TransactionScopeOption.Required, transactionToUse, defaultOptions, interopOption, scopeTimeout, TransactionScopeAsyncFlowOption.Suppress); } public TransactionScope(TransactionScopeOption scopeOption) : this(scopeOption, TransactionManager.DefaultTimeout) { } public TransactionScope(TransactionScopeOption scopeOption, TimeSpan scopeTimeout) : this(scopeOption, scopeTimeout, TransactionScopeAsyncFlowOption.Suppress) { } public TransactionScope(TransactionScopeOption option, TransactionScopeAsyncFlowOption asyncFlow) : this(option, TransactionManager.DefaultTimeout, asyncFlow) { } public TransactionScope(TransactionScopeOption scopeOption, TimeSpan scopeTimeout, TransactionScopeAsyncFlowOption asyncFlow) { Initialize(scopeOption, null, defaultOptions, EnterpriseServicesInteropOption.None, scopeTimeout, asyncFlow); } public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions) : this(scopeOption, transactionOptions, EnterpriseServicesInteropOption.None) { } [MonoTODO("EnterpriseServicesInteropOption not supported")] public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions, EnterpriseServicesInteropOption interopOption) { Initialize(scopeOption, null, transactionOptions, interopOption, transactionOptions.Timeout, TransactionScopeAsyncFlowOption.Suppress); } public TransactionScope(Transaction transactionToUse, TransactionScopeAsyncFlowOption asyncFlowOption) { throw new NotImplementedException(); } public TransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout, TransactionScopeAsyncFlowOption asyncFlowOption) { throw new NotImplementedException(); } public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions, TransactionScopeAsyncFlowOption asyncFlowOption) { throw new NotImplementedException(); } private void Initialize(TransactionScopeOption scopeOption, Transaction tx, TransactionOptions options, EnterpriseServicesInteropOption interop, TimeSpan scopeTimeout, TransactionScopeAsyncFlowOption asyncFlow) { completed = false; isRoot = false; nested = 0; asyncFlowEnabled = asyncFlow == TransactionScopeAsyncFlowOption.Enabled; if (scopeTimeout < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("scopeTimeout"); } timeout = scopeTimeout; oldTransaction = Transaction.CurrentInternal; Transaction.CurrentInternal = (transaction = InitTransaction(tx, scopeOption, options)); if (transaction != null) { transaction.InitScope(this); } if (parentScope != null) { parentScope.nested++; } if (timeout != TimeSpan.Zero) { scopeTimer = new Timer(TimerCallback, this, scopeTimeout, TimeSpan.Zero); } } private static void TimerCallback(object state) { if (!(state is TransactionScope transactionScope)) { throw new TransactionException("TransactionScopeTimerObjectInvalid", null); } transactionScope.TimeoutScope(); } private void TimeoutScope() { if (!completed && transaction != null) { try { transaction.Rollback(); aborted = true; } catch (ObjectDisposedException) { } catch (TransactionException) { } } } private Transaction InitTransaction(Transaction tx, TransactionScopeOption scopeOption, TransactionOptions options) { if (tx != null) { return tx; } switch (scopeOption) { case TransactionScopeOption.Suppress: if (Transaction.CurrentInternal != null) { parentScope = Transaction.CurrentInternal.Scope; } return null; case TransactionScopeOption.Required: if (Transaction.CurrentInternal == null) { isRoot = true; return new Transaction(options.IsolationLevel); } parentScope = Transaction.CurrentInternal.Scope; return Transaction.CurrentInternal; default: if (Transaction.CurrentInternal != null) { parentScope = Transaction.CurrentInternal.Scope; } isRoot = true; return new Transaction(options.IsolationLevel); } } public void Complete() { if (completed) { throw new InvalidOperationException("The current TransactionScope is already complete. You should dispose the TransactionScope."); } completed = true; } public void Dispose() { if (disposed) { return; } disposed = true; if (parentScope != null) { parentScope.nested--; } if (nested > 0) { transaction.Rollback(); throw new InvalidOperationException("TransactionScope nested incorrectly"); } if (Transaction.CurrentInternal != transaction && !asyncFlowEnabled) { if (transaction != null) { transaction.Rollback(); } if (Transaction.CurrentInternal != null) { Transaction.CurrentInternal.Rollback(); } throw new InvalidOperationException("Transaction.Current has changed inside of the TransactionScope"); } if (scopeTimer != null) { scopeTimer.Dispose(); } if (asyncFlowEnabled) { if (oldTransaction != null) { oldTransaction.Scope = parentScope; } Transaction currentInternal = Transaction.CurrentInternal; if (!(transaction == null) || !(currentInternal == null)) { currentInternal.Scope = parentScope; Transaction.CurrentInternal = oldTransaction; transaction.Scope = null; if (IsAborted) { throw new TransactionAbortedException("Transaction has aborted"); } if (!IsComplete) { transaction.Rollback(); currentInternal.Rollback(); } else if (isRoot) { currentInternal.CommitInternal(); transaction.CommitInternal(); } } return; } if (Transaction.CurrentInternal == oldTransaction && oldTransaction != null) { oldTransaction.Scope = parentScope; } Transaction.CurrentInternal = oldTransaction; if (!(transaction == null)) { if (IsAborted) { transaction.Scope = null; throw new TransactionAbortedException("Transaction has aborted"); } if (!IsComplete) { transaction.Rollback(); } else if (isRoot) { transaction.CommitInternal(); transaction.Scope = null; } } } } public enum TransactionScopeAsyncFlowOption { Suppress, Enabled } public enum TransactionScopeOption { Required, RequiresNew, Suppress } public enum TransactionStatus { Active, Committed, Aborted, InDoubt } } namespace System.Transactions.Configuration { public class DefaultSettingsSection : ConfigurationSection { [TimeSpanValidator(MinValueString = "00:00:00", MaxValueString = "10675199.02:48:05.4775807")] [ConfigurationProperty("timeout", DefaultValue = "00:01:00")] public TimeSpan Timeout { get { return (TimeSpan)((ConfigurationElement)this)["timeout"]; } set { ((ConfigurationElement)this)["timeout"] = value; } } [ConfigurationProperty("distributedTransactionManagerName", DefaultValue = "")] public string DistributedTransactionManagerName { get { return ((ConfigurationElement)this)["distributedTransactionManagerName"] as string; } set { ((ConfigurationElement)this)["distributedTransactionManagerName"] = value; } } } public class MachineSettingsSection : ConfigurationSection { [TimeSpanValidator(MinValueString = "00:00:00", MaxValueString = "10675199.02:48:05.4775807")] [ConfigurationProperty("maxTimeout", DefaultValue = "00:10:00")] public TimeSpan MaxTimeout { get { return (TimeSpan)((ConfigurationElement)this)["maxTimeout"]; } set { ((ConfigurationElement)this)["maxTimeout"] = value; } } } public class TransactionsSectionGroup : ConfigurationSectionGroup { [ConfigurationProperty("defaultSettings")] public DefaultSettingsSection DefaultSettings => (DefaultSettingsSection)(object)((ConfigurationSectionGroup)this).Sections["defaultSettings"]; [ConfigurationProperty("machineSettings")] public MachineSettingsSection MachineSettings => (MachineSettingsSection)(object)((ConfigurationSectionGroup)this).Sections["machineSettings"]; public static TransactionsSectionGroup GetSectionGroup(Configuration config) { if (config == null) { throw new ArgumentNullException("config"); } return config.GetSectionGroup("system.transactions") as TransactionsSectionGroup; } } } namespace System.Transactions { [Serializable] public sealed class DistributedTransactionPermission : CodeAccessPermission, IUnrestrictedPermission { public DistributedTransactionPermission(PermissionState state) { ThrowStub.ThrowNotSupportedException(); } public override IPermission Copy() { ThrowStub.ThrowNotSupportedException(); return null; } public override void FromXml(SecurityElement securityElement) { ThrowStub.ThrowNotSupportedException(); } public override IPermission Intersect(IPermission target) { ThrowStub.ThrowNotSupportedException(); return null; } public override bool IsSubsetOf(IPermission target) { ThrowStub.ThrowNotSupportedException(); return default(bool); } public bool IsUnrestricted() { ThrowStub.ThrowNotSupportedException(); return default(bool); } public override SecurityElement ToXml() { ThrowStub.ThrowNotSupportedException(); return null; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public sealed class DistributedTransactionPermissionAttribute : CodeAccessSecurityAttribute { public DistributedTransactionPermissionAttribute(SecurityAction action) { } public override IPermission CreatePermission() { ThrowStub.ThrowNotSupportedException(); return null; } } } namespace Unity { internal sealed class ThrowStub : ObjectDisposedException { public static void ThrowNotSupportedException() { throw new PlatformNotSupportedException(); } } }
deps/System.Windows.Forms.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Configuration; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Printing; using System.Drawing.Text; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Timers; using System.Windows.Forms; using System.Windows.Forms.Automation; using System.Windows.Forms.CarbonInternal; using System.Windows.Forms.ComponentModel.Com2Interop; using System.Windows.Forms.Design; using System.Windows.Forms.Layout; using System.Windows.Forms.PropertyGridInternal; using System.Windows.Forms.RTF; using System.Windows.Forms.Theming; using System.Windows.Forms.Theming.Default; using System.Windows.Forms.Theming.VisualStyles; using System.Windows.Forms.VisualStyles; using System.Windows.Forms.WebBrowserDialogs; using System.Xml; using Accessibility; using Microsoft.Win32; using Mono.Unix; using Mono.Unix.Native; using Mono.WebBrowser; using Mono.WebBrowser.DOM; using Unity; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Windows.Forms.dll")] [assembly: AssemblyDescription("System.Windows.Forms.dll")] [assembly: AssemblyDefaultAlias("System.Windows.Forms.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: CLSCompliant(true)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] [assembly: Dependency("System.Drawing,", LoadHint.Always)] [assembly: Dependency("System,", LoadHint.Always)] [assembly: StringFreezing] [assembly: ComCompatibleVersion(1, 0, 3300, 0)] [assembly: InternalsVisibleTo("UIAutomationWinforms, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")] [assembly: InternalsVisibleTo("Mono.WinformsSupport, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("CocoaDriver, PublicKey=0024000004800000940000000602000000240000525341310004000001000100dfb6f531e52a405fce7bb127fdff8b462a29426618ae319093a6479dbc037c76ce025581c272d47806d3c4c9a65304b7ddacff806e6c7e6483f985a5ac39498190c87b7ddb13d3e9c7107f0ceef392ce3fd01391fd9f61199449fd8702ab0d9c2d32dee637bc557ecc7f75c85b350d0d80d8efdb5bdaa6ecaddae0a23a1eb8db")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } namespace System { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoTODOAttribute : Attribute { private string comment; public string Comment => comment; public MonoTODOAttribute() { } public MonoTODOAttribute(string comment) { this.comment = comment; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoDocumentationNoteAttribute : MonoTODOAttribute { public MonoDocumentationNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoExtensionAttribute : MonoTODOAttribute { public MonoExtensionAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoInternalNoteAttribute : MonoTODOAttribute { public MonoInternalNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoLimitationAttribute : MonoTODOAttribute { public MonoLimitationAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoNotSupportedAttribute : MonoTODOAttribute { public MonoNotSupportedAttribute(string comment) : base(comment) { } } internal static class MonoToolsLocator { public static readonly string Mono; public static readonly string McsCSharpCompiler; public static readonly string VBCompiler; public static readonly string AssemblyLinker; static MonoToolsLocator() { string directoryName = Path.GetDirectoryName((string)typeof(Environment).GetProperty("GacPath", BindingFlags.Static | BindingFlags.NonPublic).GetGetMethod(nonPublic: true).Invoke(null, null)); if (Path.DirectorySeparatorChar == '\\') { StringBuilder stringBuilder = new StringBuilder(1024); GetModuleFileName(IntPtr.Zero, stringBuilder, stringBuilder.Capacity); string text = stringBuilder.ToString(); string fileName = Path.GetFileName(text); if (fileName.StartsWith("mono") && fileName.EndsWith(".exe")) { Mono = text; } if (!File.Exists(Mono)) { Mono = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(directoryName)), "bin\\mono.exe"); } if (!File.Exists(Mono)) { Mono = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(directoryName))), "mono\\mini\\mono.exe"); } McsCSharpCompiler = Path.Combine(directoryName, "4.5", "mcs.exe"); if (!File.Exists(McsCSharpCompiler)) { McsCSharpCompiler = Path.Combine(Path.GetDirectoryName(directoryName), "lib", "net_4_x", "mcs.exe"); } VBCompiler = Path.Combine(directoryName, "4.5\\vbnc.exe"); AssemblyLinker = Path.Combine(directoryName, "4.5\\al.exe"); if (!File.Exists(AssemblyLinker)) { AssemblyLinker = Path.Combine(Path.GetDirectoryName(directoryName), "lib\\net_4_x\\al.exe"); } return; } Mono = Path.Combine(directoryName, "bin", "mono"); if (!File.Exists(Mono)) { Mono = "mono"; } string localPath = new Uri(typeof(object).Assembly.CodeBase).LocalPath; McsCSharpCompiler = Path.GetFullPath(Path.Combine(localPath, "..", "..", "..", "..", "bin", "mcs")); if (!File.Exists(McsCSharpCompiler)) { McsCSharpCompiler = "mcs"; } VBCompiler = Path.GetFullPath(Path.Combine(localPath, "..", "..", "..", "..", "bin", "vbnc")); if (!File.Exists(VBCompiler)) { VBCompiler = "vbnc"; } AssemblyLinker = Path.GetFullPath(Path.Combine(localPath, "..", "..", "..", "..", "bin", "al")); if (!File.Exists(AssemblyLinker)) { AssemblyLinker = "al"; } } [DllImport("kernel32.dll")] private static extern uint GetModuleFileName([In] IntPtr hModule, [Out] StringBuilder lpFilename, [In] int nSize); } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] internal sealed class MWFCategoryAttribute : CategoryAttribute { public MWFCategoryAttribute() { } public MWFCategoryAttribute(string category) : base(category) { } protected override string GetLocalizedString(string value) { return Locale.GetText(value); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] internal sealed class MWFDescriptionAttribute : DescriptionAttribute { public override string Description => Locale.GetText(base.Description); public MWFDescriptionAttribute() { } public MWFDescriptionAttribute(string category) : base(category) { } } } namespace System.Resources { internal sealed class AssemblyNamesTypeResolutionService : ITypeResolutionService { public AssemblyNamesTypeResolutionService(AssemblyName[] names) { } public Assembly GetAssembly(AssemblyName name) { return GetAssembly(name, throwOnError: true); } public Assembly GetAssembly(AssemblyName name, bool throwOnError) { throw new NotImplementedException(); } public Type GetType(string name) { return GetType(name, throwOnError: true); } public Type GetType(string name, bool throwOnError) { return GetType(name, throwOnError, ignoreCase: false); } public Type GetType(string name, bool throwOnError, bool ignoreCase) { Type? type = Type.GetType(name, throwOnError: false, ignoreCase); if (type == null && throwOnError) { throw new ArgumentException($"Could not find a type for a name. The type name was `{name}'"); } return type; } public void ReferenceAssembly(AssemblyName name) { throw new NotImplementedException(); } public string GetPathOfAssembly(AssemblyName name) { throw new NotImplementedException(); } } internal class ByteArrayFromResXHandler : ResXDataNodeHandler, IWritableHandler { private string dataString; public string DataString => dataString; public ByteArrayFromResXHandler(string data) { dataString = data; } public override object GetValue(ITypeResolutionService typeResolver) { return Convert.FromBase64String(dataString); } public override object GetValue(AssemblyName[] assemblyNames) { return Convert.FromBase64String(dataString); } public override string GetValueTypeName(ITypeResolutionService typeResolver) { return ResolveType(typeof(byte[]).AssemblyQualifiedName, typeResolver).AssemblyQualifiedName; } public override string GetValueTypeName(AssemblyName[] assemblyNames) { return typeof(byte[]).AssemblyQualifiedName; } } internal class FileRefHandler : ResXDataNodeHandler { private ResXFileRef resXFileRef; public FileRefHandler(ResXFileRef fileRef) { resXFileRef = fileRef; } public override object GetValue(ITypeResolutionService typeResolver) { return GetValue(); } public override object GetValue(AssemblyName[] assemblyNames) { return GetValue(); } public override string GetValueTypeName(ITypeResolutionService typeResolver) { Type type = ResolveType(resXFileRef.TypeName, typeResolver); if (type == null) { return resXFileRef.TypeName; } return type.AssemblyQualifiedName; } public override string GetValueTypeName(AssemblyName[] assemblyNames) { Type type = ResolveType(resXFileRef.TypeName, assemblyNames); if (type == null) { return resXFileRef.TypeName; } return type.AssemblyQualifiedName; } private object GetValue() { TypeConverter converter = TypeDescriptor.GetConverter(typeof(ResXFileRef)); try { return converter.ConvertFromInvariantString(resXFileRef.ToString()); } catch (ArgumentNullException ex) { if (ex.ParamName == "type") { throw new TypeLoadException("Could not find type", ex); } throw ex; } } } internal class InMemoryHandler : ResXDataNodeHandler { private object value; public InMemoryHandler(object valueObject) { value = valueObject; } public override object GetValue(ITypeResolutionService typeResolver) { return value; } public override object GetValue(AssemblyName[] assemblyNames) { return value; } public override string GetValueTypeName(ITypeResolutionService typeResolver) { if (value == null) { return null; } return value.GetType().AssemblyQualifiedName; } public override string GetValueTypeName(AssemblyName[] assemblyNames) { if (value == null) { return null; } return value.GetType().AssemblyQualifiedName; } } internal class NullRefHandler : ResXDataNodeHandler, IWritableHandler { private string dataString; public string DataString => dataString; public NullRefHandler(string _dataString) { dataString = _dataString; } public override object GetValue(ITypeResolutionService typeResolver) { return null; } public override object GetValue(AssemblyName[] assemblyNames) { return null; } public override string GetValueTypeName(ITypeResolutionService typeResolver) { return typeof(object).AssemblyQualifiedName; } public override string GetValueTypeName(AssemblyName[] assemblyNames) { return typeof(object).AssemblyQualifiedName; } } [Serializable] public sealed class ResXDataNode : ISerializable { private string name; private ResXFileRef fileRef; private string comment; private Point pos; internal ResXDataNodeHandler handler; public string Comment { get { return comment ?? string.Empty; } set { comment = value; } } public ResXFileRef FileRef => fileRef; public string Name { get { return name ?? string.Empty; } set { if (value == null) { throw new ArgumentNullException("name"); } if (value == string.Empty) { throw new ArgumentException("name"); } name = value; } } internal bool IsWritable => handler is IWritableHandler; internal string MimeType { get; set; } internal string Type { get; set; } internal string DataString { get { if (IsWritable) { return ((IWritableHandler)handler).DataString; } throw new NotSupportedException("Node Not Writable"); } } public ResXDataNode(string name, object value) : this(name, value, Point.Empty) { } public ResXDataNode(string name, ResXFileRef fileRef) { if (name == null) { throw new ArgumentNullException("name"); } if (fileRef == null) { throw new ArgumentNullException("fileRef"); } if (name.Length == 0) { throw new ArgumentException("name"); } this.name = name; this.fileRef = fileRef; pos = Point.Empty; handler = new FileRefHandler(fileRef); } internal ResXDataNode(string name, object value, Point position) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException("name"); } Type type = ((value == null) ? typeof(object) : value.GetType()); if (value != null && !type.IsSerializable) { throw new InvalidOperationException($"'{name}' of type '{type}' cannot be added because it is not serializable"); } this.name = name; pos = position; handler = new InMemoryHandler(value); } internal ResXDataNode(string nameAtt, string mimeTypeAtt, string typeAtt, string dataString, string commentString, Point position, string basePath) { name = nameAtt; comment = commentString; pos = position; MimeType = mimeTypeAtt; Type = typeAtt; if (!string.IsNullOrEmpty(mimeTypeAtt)) { if (!string.IsNullOrEmpty(typeAtt)) { handler = new TypeConverterFromResXHandler(dataString, mimeTypeAtt, typeAtt); } else { handler = new SerializedFromResXHandler(dataString, mimeTypeAtt); } } else if (!string.IsNullOrEmpty(typeAtt)) { if (typeAtt.StartsWith("System.Resources.ResXNullRef, System.Windows.Forms")) { handler = new NullRefHandler(typeAtt); } else if (typeAtt.StartsWith("System.Byte[], mscorlib")) { handler = new ByteArrayFromResXHandler(dataString); } else if (typeAtt.StartsWith("System.Resources.ResXFileRef, System.Windows.Forms")) { ResXFileRef resXFileRef = BuildFileRef(dataString, basePath); handler = new FileRefHandler(resXFileRef); fileRef = resXFileRef; } else { handler = new TypeConverterFromResXHandler(dataString, mimeTypeAtt, typeAtt); } } else { handler = new InMemoryHandler(dataString); } if (handler == null) { throw new Exception("handler is null"); } } public Point GetNodePosition() { return pos; } public string GetValueTypeName(AssemblyName[] names) { return handler.GetValueTypeName(names); } public string GetValueTypeName(ITypeResolutionService typeResolver) { return handler.GetValueTypeName(typeResolver); } public object GetValue(AssemblyName[] names) { return handler.GetValue(names); } public object GetValue(ITypeResolutionService typeResolver) { return handler.GetValue(typeResolver); } private ResXFileRef BuildFileRef(string dataString, string basePath) { string[] array = ResXFileRef.Parse(dataString); if (array.Length < 2) { throw new ArgumentException("ResXFileRef cannot be generated"); } string fileName = array[0]; if (basePath != null) { fileName = Path.Combine(basePath, array[0]); } string typeName = array[1]; if (array.Length == 3) { Encoding encoding = Encoding.GetEncoding(array[2]); return new ResXFileRef(fileName, typeName, encoding); } return new ResXFileRef(fileName, typeName); } void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { si.AddValue("Name", Name); si.AddValue("Comment", Comment); } public ResXDataNode(string name, object value, Func<Type, string> typeNameConverter) { ThrowStub.ThrowNotSupportedException(); } public ResXDataNode(string name, ResXFileRef fileRef, Func<Type, string> typeNameConverter) { ThrowStub.ThrowNotSupportedException(); } } internal interface IWritableHandler { string DataString { get; } } internal abstract class ResXDataNodeHandler { public abstract object GetValue(ITypeResolutionService typeResolver); public abstract object GetValue(AssemblyName[] assemblyNames); public abstract string GetValueTypeName(ITypeResolutionService typeResolver); public abstract string GetValueTypeName(AssemblyName[] assemblyNames); public virtual object GetValueForResX() { return GetValue((AssemblyName[])null); } protected Type ResolveType(string typeString) { return Type.GetType(typeString); } protected Type ResolveType(string typeString, AssemblyName[] assemblyNames) { Type type = null; if (assemblyNames != null) { for (int i = 0; i < assemblyNames.Length; i++) { type = Assembly.Load(assemblyNames[i]).GetType(typeString, throwOnError: false); if (type != null) { return type; } } } if (type == null) { type = ResolveType(typeString); } return type; } protected Type ResolveType(string typeString, ITypeResolutionService typeResolver) { Type type = null; if (typeResolver != null) { type = typeResolver.GetType(typeString); } if (type == null) { type = ResolveType(typeString); } return type; } } [Serializable] [TypeConverter(typeof(Converter))] public class ResXFileRef { public class Converter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { //IL_0114: Unknown result type (might be due to invalid IL or missing references) if (!(value is string)) { return null; } string[] array = Parse((string)value); if (array.Length == 1) { throw new ArgumentException("value"); } string text = array[0]; if (Path.DirectorySeparatorChar == '/') { text = text.Replace("\\", "/"); } Type type = Type.GetType(array[1]); if (type == typeof(string)) { Encoding encoding = ((array.Length <= 2) ? Encoding.Default : Encoding.GetEncoding(array[2])); using TextReader textReader = new StreamReader(text, encoding); return textReader.ReadToEnd(); } byte[] array2; using (FileStream fileStream = new FileStream(text, FileMode.Open, FileAccess.Read, FileShare.Read)) { array2 = new byte[fileStream.Length]; fileStream.Read(array2, 0, (int)fileStream.Length); } if (type == typeof(byte[])) { return array2; } if (type == typeof(Bitmap) && Path.GetExtension(text) == ".ico") { return new Icon((Stream)new MemoryStream(array2)).ToBitmap(); } if (type == typeof(MemoryStream)) { return new MemoryStream(array2); } return Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, new object[1] { new MemoryStream(array2) }, culture); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType != typeof(string)) { return base.ConvertTo(context, culture, value, destinationType); } return ((ResXFileRef)value).ToString(); } } private string filename; private string typename; private Encoding textFileEncoding; public string FileName => filename; public Encoding TextFileEncoding => textFileEncoding; public string TypeName => typename; public ResXFileRef(string fileName, string typeName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (typeName == null) { throw new ArgumentNullException("typeName"); } filename = fileName; typename = typeName; } public ResXFileRef(string fileName, string typeName, Encoding textFileEncoding) : this(fileName, typeName) { this.textFileEncoding = textFileEncoding; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); if (filename != null) { stringBuilder.Append(filename); } stringBuilder.Append(';'); if (typename != null) { stringBuilder.Append(typename); } if (textFileEncoding != null) { stringBuilder.Append(';'); stringBuilder.Append(textFileEncoding.WebName); } return stringBuilder.ToString(); } internal static string[] Parse(string fileRef) { if (fileRef == null) { throw new ArgumentNullException("fileRef"); } return fileRef.Split(';'); } } [Serializable] internal class ResXNullRef { } public class ResXResourceReader : IResourceReader, IEnumerable, IDisposable { private class ResXHeader { private string resMimeType; private string reader; private string version; private string writer; public string ResMimeType { get { return resMimeType; } set { resMimeType = value; } } public string Reader { get { return reader; } set { reader = value; } } public string Version { get { return version; } set { version = value; } } public string Writer { get { return writer; } set { writer = value; } } public bool IsValid { get { if (string.Compare(ResMimeType, ResXResourceWriter.ResMimeType) != 0) { return false; } if (Reader == null || Writer == null) { return false; } if (Reader.Split(',')[0].Trim() != typeof(ResXResourceReader).FullName) { return false; } if (Writer.Split(',')[0].Trim() != typeof(ResXResourceWriter).FullName) { return false; } return true; } } public void Verify() { if (!IsValid) { throw new ArgumentException("Invalid ResX input. Could not find valid \"resheader\" tags for the ResX reader & writer type names."); } } } private string fileName; private Stream stream; private TextReader reader; private OrderedDictionary hasht; private ITypeResolutionService typeresolver; private XmlTextReader xmlReader; private string basepath; private bool useResXDataNodes; private AssemblyName[] assemblyNames; private OrderedDictionary hashtm; public string BasePath { get { return basepath; } set { basepath = value; } } public bool UseResXDataNodes { get { return useResXDataNodes; } set { if (xmlReader != null) { throw new InvalidOperationException(); } useResXDataNodes = value; } } public ResXResourceReader(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new ArgumentException("Stream was not readable."); } this.stream = stream; } public ResXResourceReader(Stream stream, ITypeResolutionService typeResolver) : this(stream) { typeresolver = typeResolver; } public ResXResourceReader(string fileName) { this.fileName = fileName; } public ResXResourceReader(string fileName, ITypeResolutionService typeResolver) : this(fileName) { typeresolver = typeResolver; } public ResXResourceReader(TextReader reader) { this.reader = reader; } public ResXResourceReader(TextReader reader, ITypeResolutionService typeResolver) : this(reader) { typeresolver = typeResolver; } public ResXResourceReader(Stream stream, AssemblyName[] assemblyNames) : this(stream) { this.assemblyNames = assemblyNames; } public ResXResourceReader(string fileName, AssemblyName[] assemblyNames) : this(fileName) { this.assemblyNames = assemblyNames; } public ResXResourceReader(TextReader reader, AssemblyName[] assemblyNames) : this(reader) { this.assemblyNames = assemblyNames; } ~ResXResourceReader() { Dispose(disposing: false); } private void LoadData() { hasht = new OrderedDictionary(); hashtm = new OrderedDictionary(); if (fileName != null) { stream = File.OpenRead(fileName); } try { xmlReader = null; if (stream != null) { xmlReader = new XmlTextReader(stream); } else if (reader != null) { xmlReader = new XmlTextReader(reader); } if (xmlReader == null) { throw new InvalidOperationException("ResourceReader is closed."); } xmlReader.WhitespaceHandling = WhitespaceHandling.None; ResXHeader resXHeader = new ResXHeader(); try { while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { switch (xmlReader.LocalName) { case "resheader": ParseHeaderNode(resXHeader); break; case "data": ParseDataNode(meta: false); break; case "metadata": ParseDataNode(meta: true); break; } } } } catch (XmlException innerException) { throw new ArgumentException("Invalid ResX input.", innerException); } catch (SerializationException ex) { throw ex; } catch (TargetInvocationException ex2) { throw ex2; } catch (Exception ex3) { XmlException innerException2 = new XmlException(ex3.Message, ex3, xmlReader.LineNumber, xmlReader.LinePosition); throw new ArgumentException("Invalid ResX input.", innerException2); } resXHeader.Verify(); } finally { if (fileName != null) { stream.Close(); stream = null; } xmlReader = null; } } private void ParseHeaderNode(ResXHeader header) { string attribute = GetAttribute("name"); if (attribute != null) { if (string.Compare(attribute, "resmimetype", ignoreCase: true) == 0) { header.ResMimeType = GetHeaderValue(); } else if (string.Compare(attribute, "reader", ignoreCase: true) == 0) { header.Reader = GetHeaderValue(); } else if (string.Compare(attribute, "version", ignoreCase: true) == 0) { header.Version = GetHeaderValue(); } else if (string.Compare(attribute, "writer", ignoreCase: true) == 0) { header.Writer = GetHeaderValue(); } } } private string GetHeaderValue() { string text = null; xmlReader.ReadStartElement(); if (xmlReader.NodeType == XmlNodeType.Element) { return xmlReader.ReadElementString(); } return xmlReader.Value.Trim(); } private string GetAttribute(string name) { if (!xmlReader.HasAttributes) { return null; } for (int i = 0; i < xmlReader.AttributeCount; i++) { xmlReader.MoveToAttribute(i); if (string.Compare(xmlReader.Name, name, ignoreCase: true) == 0) { string value = xmlReader.Value; xmlReader.MoveToElement(); return value; } } xmlReader.MoveToElement(); return null; } private string GetDataValue(bool meta, out string comment) { string result = null; comment = null; while (xmlReader.Read() && (xmlReader.NodeType != XmlNodeType.EndElement || !(xmlReader.LocalName == (meta ? "metadata" : "data")))) { if (xmlReader.NodeType == XmlNodeType.Element) { if (xmlReader.Name.Equals("value")) { xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; result = xmlReader.ReadString(); xmlReader.WhitespaceHandling = WhitespaceHandling.None; } else if (xmlReader.Name.Equals("comment")) { xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; comment = xmlReader.ReadString(); xmlReader.WhitespaceHandling = WhitespaceHandling.None; if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.LocalName == (meta ? "metadata" : "data")) { break; } } } else { result = xmlReader.Value.Trim(); } } return result; } private void ParseDataNode(bool meta) { OrderedDictionary orderedDictionary = ((meta && !useResXDataNodes) ? hashtm : hasht); Point position = new Point(xmlReader.LineNumber, xmlReader.LinePosition); string attribute = GetAttribute("name"); string attribute2 = GetAttribute("type"); string attribute3 = GetAttribute("mimetype"); string comment = null; string dataValue = GetDataValue(meta, out comment); ResXDataNode resXDataNode = new ResXDataNode(attribute, attribute3, attribute2, dataValue, comment, position, BasePath); if (useResXDataNodes) { orderedDictionary[attribute] = resXDataNode; return; } if (attribute == null) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Could not find a name for a resource. The resource value was '{0}'.", resXDataNode.GetValue((AssemblyName[])null).ToString())); } if (assemblyNames != null) { try { orderedDictionary[attribute] = resXDataNode.GetValue(assemblyNames); return; } catch (TypeLoadException ex) { if (resXDataNode.handler is TypeConverterFromResXHandler) { orderedDictionary[attribute] = null; return; } throw ex; } } try { orderedDictionary[attribute] = resXDataNode.GetValue(typeresolver); } catch (TypeLoadException ex2) { if (resXDataNode.handler is TypeConverterFromResXHandler) { orderedDictionary[attribute] = null; return; } throw ex2; } } public void Close() { if (reader != null) { reader.Close(); reader = null; } } public IDictionaryEnumerator GetEnumerator() { if (hasht == null) { LoadData(); } return hasht.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IResourceReader)this).GetEnumerator(); } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } public static ResXResourceReader FromFileContents(string fileContents) { return new ResXResourceReader(new StringReader(fileContents)); } public static ResXResourceReader FromFileContents(string fileContents, ITypeResolutionService typeResolver) { return new ResXResourceReader(new StringReader(fileContents), typeResolver); } public static ResXResourceReader FromFileContents(string fileContents, AssemblyName[] assemblyNames) { return new ResXResourceReader(new StringReader(fileContents), assemblyNames); } public IDictionaryEnumerator GetMetadataEnumerator() { if (hashtm == null) { LoadData(); } return hashtm.GetEnumerator(); } } public class ResXResourceSet : ResourceSet { public ResXResourceSet(Stream stream) { Reader = new ResXResourceReader(stream); base.Table = new Hashtable(); ReadResources(); } public ResXResourceSet(string fileName) { Reader = new ResXResourceReader(fileName); base.Table = new Hashtable(); ReadResources(); } public override Type GetDefaultReader() { return typeof(ResXResourceReader); } public override Type GetDefaultWriter() { return typeof(ResXResourceWriter); } } public class ResXResourceWriter : IResourceWriter, IDisposable { private string filename; private Stream stream; private TextWriter textwriter; private XmlTextWriter writer; private bool written; private string base_path; public static readonly string BinSerializedObjectMimeType = "application/x-microsoft.net.object.binary.base64"; public static readonly string ByteArraySerializedObjectMimeType = "application/x-microsoft.net.object.bytearray.base64"; public static readonly string DefaultSerializedObjectMimeType = BinSerializedObjectMimeType; public static readonly string ResMimeType = "text/microsoft-resx"; public static readonly string ResourceSchema = schema; public static readonly string SoapSerializedObjectMimeType = "application/x-microsoft.net.object.soap.base64"; public static readonly string Version = "2.0"; private static string schema = "\n <xsd:schema id='root' xmlns='' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>\n <xsd:element name='root' msdata:IsDataSet='true'>\n <xsd:complexType>\n <xsd:choice maxOccurs='unbounded'>\n <xsd:element name='data'>\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />\n <xsd:element name='comment' type='xsd:string' minOccurs='0' msdata:Ordinal='2' />\n </xsd:sequence>\n <xsd:attribute name='name' type='xsd:string' msdata:Ordinal='1' />\n <xsd:attribute name='type' type='xsd:string' msdata:Ordinal='3' />\n <xsd:attribute name='mimetype' type='xsd:string' msdata:Ordinal='4' />\n </xsd:complexType>\n </xsd:element>\n <xsd:element name='resheader'>\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />\n </xsd:sequence>\n <xsd:attribute name='name' type='xsd:string' use='required' />\n </xsd:complexType>\n </xsd:element>\n </xsd:choice>\n </xsd:complexType>\n </xsd:element>\n </xsd:schema>\n".Replace("'", "\""); public string BasePath { get { return base_path; } set { base_path = value; } } public ResXResourceWriter(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanWrite) { throw new ArgumentException("stream is not writable.", "stream"); } this.stream = stream; } public ResXResourceWriter(TextWriter textWriter) { if (textWriter == null) { throw new ArgumentNullException("textWriter"); } textwriter = textWriter; } public ResXResourceWriter(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } filename = fileName; } ~ResXResourceWriter() { Dispose(disposing: false); } private void InitWriter() { if (filename != null) { stream = File.Open(filename, FileMode.Create); } if (textwriter == null) { textwriter = new StreamWriter(stream, Encoding.UTF8); } writer = new XmlTextWriter(textwriter); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteRaw(schema); WriteHeader("resmimetype", "text/microsoft-resx"); WriteHeader("version", "1.3"); WriteHeader("reader", typeof(ResXResourceReader).AssemblyQualifiedName); WriteHeader("writer", typeof(ResXResourceWriter).AssemblyQualifiedName); } private void WriteHeader(string name, string value) { writer.WriteStartElement("resheader"); writer.WriteAttributeString("name", name); writer.WriteStartElement("value"); writer.WriteString(value); writer.WriteEndElement(); writer.WriteEndElement(); } private void WriteNiceBase64(byte[] value, int offset, int length) { string text = Convert.ToBase64String(value, offset, length); StringBuilder stringBuilder = new StringBuilder(text, text.Length + (text.Length + 160) / 80 * 3); int i = 0; int num = 80 + Environment.NewLine.Length + 1; string value2 = Environment.NewLine + "\t"; for (; i < stringBuilder.Length; i += num) { stringBuilder.Insert(i, value2); } stringBuilder.Insert(stringBuilder.Length, Environment.NewLine); writer.WriteString(stringBuilder.ToString()); } private void WriteBytes(string name, Type type, byte[] value, int offset, int length) { WriteBytes(name, type, value, offset, length, string.Empty); } private void WriteBytes(string name, Type type, byte[] value, int offset, int length, string comment) { writer.WriteStartElement("data"); writer.WriteAttributeString("name", name); if (type != null) { writer.WriteAttributeString("type", type.AssemblyQualifiedName); if (type != typeof(byte[])) { writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType); } writer.WriteStartElement("value"); WriteNiceBase64(value, offset, length); } else { writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType); writer.WriteStartElement("value"); writer.WriteBase64(value, offset, length); } writer.WriteEndElement(); if (comment != null && !comment.Equals(string.Empty)) { writer.WriteStartElement("comment"); writer.WriteString(comment); writer.WriteEndElement(); } writer.WriteEndElement(); } private void WriteBytes(string name, Type type, byte[] value, string comment) { WriteBytes(name, type, value, 0, value.Length, comment); } private void WriteString(string name, string value) { WriteString(name, value, null); } private void WriteString(string name, string value, Type type) { WriteString(name, value, type, string.Empty); } private void WriteString(string name, string value, Type type, string comment) { writer.WriteStartElement("data"); writer.WriteAttributeString("name", name); if (type != null) { writer.WriteAttributeString("type", type.AssemblyQualifiedName); } writer.WriteStartElement("value"); writer.WriteString(value); writer.WriteEndElement(); if (comment != null && !comment.Equals(string.Empty)) { writer.WriteStartElement("comment"); writer.WriteString(comment); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteWhitespace("\n "); } public void AddResource(string name, byte[] value) { if (name == null) { throw new ArgumentNullException("name"); } if (value == null) { throw new ArgumentNullException("value"); } if (written) { throw new InvalidOperationException("The resource is already generated."); } if (writer == null) { InitWriter(); } WriteBytes(name, value.GetType(), value, null); } public void AddResource(string name, object value) { AddResource(name, value, string.Empty); } private void AddResource(string name, object value, string comment) { if (value is string) { AddResource(name, (string)value, comment); return; } if (name == null) { throw new ArgumentNullException("name"); } if (value != null && !value.GetType().IsSerializable) { throw new InvalidOperationException($"The element '{name}' of type '{value.GetType().Name}' is not serializable."); } if (written) { throw new InvalidOperationException("The resource is already generated."); } if (writer == null) { InitWriter(); } if (value is byte[]) { WriteBytes(name, value.GetType(), (byte[])value, comment); return; } if (value == null) { WriteString(name, "", typeof(ResXNullRef), comment); return; } TypeConverter converter = TypeDescriptor.GetConverter(value); if (value is ResXFileRef) { ResXFileRef value2 = ProcessFileRefBasePath((ResXFileRef)value); string value3 = converter.ConvertToInvariantString(value2); WriteString(name, value3, value.GetType(), comment); return; } if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) { string value4 = converter.ConvertToInvariantString(value); WriteString(name, value4, value.GetType(), comment); return; } if (converter != null && converter.CanConvertTo(typeof(byte[])) && converter.CanConvertFrom(typeof(byte[]))) { byte[] value5 = (byte[])converter.ConvertTo(value, typeof(byte[])); WriteBytes(name, value.GetType(), value5, comment); return; } MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); try { binaryFormatter.Serialize(memoryStream, value); } catch (Exception ex) { throw new InvalidOperationException("Cannot add a " + value.GetType()?.ToString() + "because it cannot be serialized: " + ex.Message); } WriteBytes(name, null, memoryStream.GetBuffer(), 0, (int)memoryStream.Length, comment); memoryStream.Close(); } public void AddResource(string name, string value) { AddResource(name, value, string.Empty); } private void AddResource(string name, string value, string comment) { if (name == null) { throw new ArgumentNullException("name"); } if (value == null) { throw new ArgumentNullException("value"); } if (written) { throw new InvalidOperationException("The resource is already generated."); } if (writer == null) { InitWriter(); } WriteString(name, value, null, comment); } [MonoTODO("Stub, not implemented")] public virtual void AddAlias(string aliasName, AssemblyName assemblyName) { } public void AddResource(ResXDataNode node) { if (node == null) { throw new ArgumentNullException("node"); } if (writer == null) { InitWriter(); } if (node.IsWritable) { WriteWritableNode(node); } else if (node.FileRef != null) { AddResource(node.Name, node.FileRef, node.Comment); } else { AddResource(node.Name, node.GetValue((AssemblyName[])null), node.Comment); } } private ResXFileRef ProcessFileRefBasePath(ResXFileRef fileRef) { if (string.IsNullOrEmpty(BasePath)) { return fileRef; } return new ResXFileRef(AbsoluteToRelativePath(BasePath, fileRef.FileName), fileRef.TypeName, fileRef.TextFileEncoding); } private static bool IsSeparator(char ch) { if (ch != Path.DirectorySeparatorChar && ch != Path.AltDirectorySeparatorChar) { return ch == Path.VolumeSeparatorChar; } return true; } private unsafe static string AbsoluteToRelativePath(string baseDirectoryPath, string absPath) { if (string.IsNullOrEmpty(baseDirectoryPath)) { return absPath; } baseDirectoryPath = baseDirectoryPath.TrimEnd(Path.DirectorySeparatorChar); fixed (char* ptr = baseDirectoryPath) { fixed (char* ptr3 = absPath) { char* ptr2 = ptr + baseDirectoryPath.Length; char* ptr4 = ptr3 + absPath.Length; char* ptr5 = ptr4; char* ptr6 = ptr2; int num = 0; char* ptr7 = ptr3; char* ptr8 = ptr; while (ptr7 < ptr4 && *ptr7 == *ptr8) { if (IsSeparator(*ptr7)) { num++; ptr5 = ptr7 + 1; ptr6 = ptr8; } ptr7++; ptr8++; if (ptr8 >= ptr2) { if (ptr7 >= ptr4 || IsSeparator(*ptr7)) { num++; ptr5 = ptr7 + 1; ptr6 = ptr8; } break; } } if (num == 0) { return absPath; } if (ptr5 >= ptr4) { return "."; } if (ptr7 >= ptr4 && IsSeparator(*ptr8)) { ptr5 = ptr7 + 1; ptr6 = ptr8; } int num2 = 0; for (; ptr6 < ptr2; ptr6++) { if (IsSeparator(*ptr6)) { num2++; } } char[] array = new char[num2 * 2 + num2 + ptr4 - ptr5]; fixed (char* ptr9 = array) { char* ptr10 = ptr9; for (int i = 0; i < num2; i++) { *(ptr10++) = '.'; *(ptr10++) = '.'; *(ptr10++) = Path.DirectorySeparatorChar; } while (ptr5 < ptr4) { *(ptr10++) = *(ptr5++); } } return new string(array); } } } private void WriteWritableNode(ResXDataNode node) { writer.WriteStartElement("data"); writer.WriteAttributeString("name", node.Name); if (node.Type != null && !node.Type.Equals(string.Empty)) { writer.WriteAttributeString("type", node.Type); } if (node.MimeType != null && !node.MimeType.Equals(string.Empty)) { writer.WriteAttributeString("mimetype", node.MimeType); } writer.WriteStartElement("value"); writer.WriteString(node.DataString); writer.WriteEndElement(); if (node.Comment != null && !node.Comment.Equals(string.Empty)) { writer.WriteStartElement("comment"); writer.WriteString(node.Comment); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteWhitespace("\n "); } public void AddMetadata(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } if (value == null) { throw new ArgumentNullException("value"); } if (written) { throw new InvalidOperationException("The resource is already generated."); } if (writer == null) { InitWriter(); } writer.WriteStartElement("metadata"); writer.WriteAttributeString("name", name); writer.WriteAttributeString("xml:space", "preserve"); writer.WriteElementString("value", value); writer.WriteEndElement(); } public void AddMetadata(string name, byte[] value) { if (name == null) { throw new ArgumentNullException("name"); } if (value == null) { throw new ArgumentNullException("value"); } if (written) { throw new InvalidOperationException("The resource is already generated."); } if (writer == null) { InitWriter(); } writer.WriteStartElement("metadata"); writer.WriteAttributeString("name", name); writer.WriteAttributeString("type", value.GetType().AssemblyQualifiedName); writer.WriteStartElement("value"); WriteNiceBase64(value, 0, value.Length); writer.WriteEndElement(); writer.WriteEndElement(); } public void AddMetadata(string name, object value) { if (value is string) { AddMetadata(name, (string)value); return; } if (value is byte[]) { AddMetadata(name, (byte[])value); return; } if (name == null) { throw new ArgumentNullException("name"); } if (value == null) { throw new ArgumentNullException("value"); } if (!value.GetType().IsSerializable) { throw new InvalidOperationException($"The element '{name}' of type '{value.GetType().Name}' is not serializable."); } if (written) { throw new InvalidOperationException("The resource is already generated."); } if (writer == null) { InitWriter(); } Type type = value.GetType(); TypeConverter converter = TypeDescriptor.GetConverter(value); if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) { string text = converter.ConvertToInvariantString(value); writer.WriteStartElement("metadata"); writer.WriteAttributeString("name", name); if (type != null) { writer.WriteAttributeString("type", type.AssemblyQualifiedName); } writer.WriteStartElement("value"); writer.WriteString(text); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteWhitespace("\n "); return; } if (converter != null && converter.CanConvertTo(typeof(byte[])) && converter.CanConvertFrom(typeof(byte[]))) { byte[] array = (byte[])converter.ConvertTo(value, typeof(byte[])); writer.WriteStartElement("metadata"); writer.WriteAttributeString("name", name); if (type != null) { writer.WriteAttributeString("type", type.AssemblyQualifiedName); writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType); writer.WriteStartElement("value"); WriteNiceBase64(array, 0, array.Length); } else { writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType); writer.WriteStartElement("value"); writer.WriteBase64(array, 0, array.Length); } writer.WriteEndElement(); writer.WriteEndElement(); return; } MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); try { binaryFormatter.Serialize(memoryStream, value); } catch (Exception ex) { throw new InvalidOperationException("Cannot add a " + value.GetType()?.ToString() + "because it cannot be serialized: " + ex.Message); } writer.WriteStartElement("metadata"); writer.WriteAttributeString("name", name); if (type != null) { writer.WriteAttributeString("type", type.AssemblyQualifiedName); writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType); writer.WriteStartElement("value"); WriteNiceBase64(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length); } else { writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType); writer.WriteStartElement("value"); writer.WriteBase64(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length); } writer.WriteEndElement(); writer.WriteEndElement(); memoryStream.Close(); } public void Close() { if (!written) { Generate(); } if (writer != null) { writer.Close(); stream = null; filename = null; textwriter = null; } } public virtual void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public void Generate() { if (written) { throw new InvalidOperationException("The resource is already generated."); } written = true; writer.WriteEndElement(); writer.Flush(); } protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } public ResXResourceWriter(Stream stream, Func<Type, string> typeNameConverter) { ThrowStub.ThrowNotSupportedException(); } public ResXResourceWriter(TextWriter textWriter, Func<Type, string> typeNameConverter) { ThrowStub.ThrowNotSupportedException(); } public ResXResourceWriter(string fileName, Func<Type, string> typeNameConverter) { ThrowStub.ThrowNotSupportedException(); } } internal class SerializedFromResXHandler : ResXDataNodeHandler, IWritableHandler { private sealed class CustomBinder : SerializationBinder { private ITypeResolutionService typeResolver; public CustomBinder(ITypeResolutionService _typeResolver) { typeResolver = _typeResolver; } public override Type BindToType(string assemblyName, string typeName) { Type type = null; string text = $"{typeName}, {assemblyName}"; if (typeResolver != null) { type = typeResolver.GetType(text); } if (type == null) { type = Type.GetType(text); } return type; } } private string dataString; private string mime_type; private CustomBinder binder; public string DataString => dataString; public SerializedFromResXHandler(string data, string _mime_type) { dataString = data; mime_type = _mime_type; } public override object GetValue(ITypeResolutionService typeResolver) { return DeserializeObject(typeResolver); } public override object GetValue(AssemblyName[] assemblyNames) { return DeserializeObject(new AssemblyNamesTypeResolutionService(assemblyNames)); } public override string GetValueTypeName(ITypeResolutionService typeResolver) { return InternalGetValueType(typeResolver); } public override string GetValueTypeName(AssemblyName[] assemblyNames) { return InternalGetValueType(null); } private string InternalGetValueType(ITypeResolutionService typeResolver) { object obj; try { obj = DeserializeObject(typeResolver); } catch { return typeof(object).AssemblyQualifiedName; } return obj?.GetType().AssemblyQualifiedName; } private object DeserializeObject(ITypeResolutionService typeResolver) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown try { if (mime_type == ResXResourceWriter.SoapSerializedObjectMimeType) { SoapFormatter val = new SoapFormatter(); if (binder == null) { binder = new CustomBinder(typeResolver); } val.Binder = binder; using MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(dataString)); return val.Deserialize((Stream)memoryStream); } if (mime_type == ResXResourceWriter.BinSerializedObjectMimeType) { BinaryFormatter binaryFormatter = new BinaryFormatter(); if (binder == null) { binder = new CustomBinder(typeResolver); } binaryFormatter.Binder = binder; using MemoryStream serializationStream = new MemoryStream(Convert.FromBase64String(dataString)); return binaryFormatter.Deserialize(serializationStream); } return null; } catch (SerializationException ex) { if (ex.Message.StartsWith("Couldn't find assembly")) { throw new ArgumentException(ex.Message); } throw ex; } } } internal class TypeConverterFromResXHandler : ResXDataNodeHandler, IWritableHandler { private string dataString; private string mime_type; private string typeString; public string DataString => dataString; public TypeConverterFromResXHandler(string data, string _mime_type, string _typeString) { dataString = data; mime_type = _mime_type; typeString = _typeString; } public override object GetValue(ITypeResolutionService typeResolver) { if (!string.IsNullOrEmpty(mime_type) && mime_type != ResXResourceWriter.ByteArraySerializedObjectMimeType) { return null; } Type type = ResolveType(typeString, typeResolver); if (type == null) { throw new TypeLoadException(); } TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter == null) { throw new TypeLoadException(); } return ConvertData(converter); } public override object GetValue(AssemblyName[] assemblyNames) { if (!string.IsNullOrEmpty(mime_type) && mime_type != ResXResourceWriter.ByteArraySerializedObjectMimeType) { return null; } Type type = ResolveType(typeString, assemblyNames); if (type == null) { throw new TypeLoadException(); } TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter == null) { throw new TypeLoadException(); } return ConvertData(converter); } public override string GetValueTypeName(ITypeResolutionService typeResolver) { Type type = ResolveType(typeString, typeResolver); if (type == null) { return typeString; } return type.AssemblyQualifiedName; } public override string GetValueTypeName(AssemblyName[] assemblyNames) { Type type = ResolveType(typeString, assemblyNames); if (type == null) { return typeString; } return type.AssemblyQualifiedName; } private object ConvertData(TypeConverter c) { if (mime_type == ResXResourceWriter.ByteArraySerializedObjectMimeType) { if (c.CanConvertFrom(typeof(byte[]))) { return c.ConvertFrom(Convert.FromBase64String(dataString)); } } else { if (!string.IsNullOrEmpty(mime_type)) { throw new Exception("shouldnt get here, invalid mime type"); } if (c.CanConvertFrom(typeof(string))) { return c.ConvertFromInvariantString(dataString); } } throw new TypeLoadException("No converter for this type found"); } } } namespace System.Windows.Forms { internal static class Locale { private static ResourceManager rm; public static ResourceManager ResourceManager => rm; static Locale() { rm = new ResourceManager("System.Windows.Forms", Assembly.GetExecutingAssembly()); } public static string GetText(string msg) { string @string = ResourceManager.GetString(msg); if (@string != null) { return @string; } return msg; } public static string GetText(string msg, params object[] args) { return string.Format(GetText(msg), args); } } internal class DebugHelper { private struct Data { public MethodBase method; public object[] args; public Data(MethodBase m, object[] a) { method = m; args = a; } } private static Stack<Data> methods; static DebugHelper() { methods = new Stack<Data>(); Debug.AutoFlush = true; } [Conditional("DEBUG")] internal static void DumpCallers() { StackTrace stackTrace = new StackTrace(fNeedFileInfo: true); int frameCount = stackTrace.FrameCount; for (int i = 1; i < frameCount; i++) { StackFrame? frame = stackTrace.GetFrame(i); frame.GetMethod(); string fileName = frame.GetFileName(); if (fileName != null && fileName.Length > 1) { fileName = fileName.Substring(fileName.LastIndexOf(Path.DirectorySeparatorChar) + 1); } } } [Conditional("DEBUG")] internal static void DumpCallers(int count) { StackTrace stackTrace = new StackTrace(fNeedFileInfo: true); int num = ((count > stackTrace.FrameCount) ? stackTrace.FrameCount : count); for (int i = 1; i < num; i++) { StackFrame? frame = stackTrace.GetFrame(i); frame.GetMethod(); string fileName = frame.GetFileName(); if (fileName != null && fileName.Length > 1) { fileName = fileName.Substring(fileName.LastIndexOf(Path.DirectorySeparatorChar) + 1); } } } [Conditional("DEBUG")] internal static void Enter() { StackTrace stackTrace = new StackTrace(); methods.Push(new Data(stackTrace.GetFrame(1).GetMethod(), null)); } [Conditional("DEBUG")] internal static void Enter(object[] args) { StackTrace stackTrace = new StackTrace(); methods.Push(new Data(stackTrace.GetFrame(1).GetMethod(), args)); } [Conditional("DEBUG")] internal static void Leave() { if (methods.Count > 0) { methods.Pop(); } } [Conditional("DEBUG")] internal static void Print() { if (methods.Count != 0) { methods.Peek(); } } [Conditional("DEBUG")] internal static void Print(int index) { if (methods.Count != 0 && methods.Count > index && index >= 0) { Stack<Data> stack = new Stack<Data>(index - 1); for (int i = 0; i < index; i++) { stack.Push(methods.Pop()); } methods.Peek(); for (int j = 0; j < stack.Count; j++) { methods.Push(stack.Pop()); } stack = null; } } [Conditional("DEBUG")] internal static void Print(string methodName, string parameterName) { if (methods.Count == 0) { return; } Stack<Data> stack = new Stack<Data>(); Data data = methods.Peek(); bool flag = false; for (int i = 0; i < methods.Count; i++) { data = methods.Peek(); if (data.method.Name.Equals(methodName)) { flag = true; break; } stack.Push(methods.Pop()); } for (int j = 0; j < stack.Count; j++) { methods.Push(stack.Pop()); } stack = null; if (!flag) { return; } ParameterInfo[] parameters = data.method.GetParameters(); for (int k = 0; k < parameters.Length; k++) { if (parameters[k].Name == parameterName) { _ = parameters[k].ParameterType == typeof(IntPtr); } } } [Conditional("DEBUG")] internal static void Print(string parameterName) { if (methods.Count == 0) { return; } ParameterInfo[] parameters = methods.Peek().method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].Name == parameterName) { _ = parameters[i].ParameterType == typeof(IntPtr); } } } [Conditional("DEBUG")] internal static void WriteLine(object arg) { } [Conditional("DEBUG")] internal static void WriteLine(string format, params object[] arg) { } [Conditional("DEBUG")] internal static void WriteLine(string message) { } [Conditional("DEBUG")] internal static void Indent() { } [Conditional("DEBUG")] internal static void Unindent() { } [Conditional("TRACE")] internal static void TraceWriteLine(string format, params object[] arg) { } [Conditional("TRACE")] internal static void TraceWriteLine(string message) { } } public enum AccessibleEvents { SystemSound = 1, SystemAlert = 2, SystemForeground = 3, SystemMenuStart = 4, SystemMenuEnd = 5, SystemMenuPopupStart = 6, SystemMenuPopupEnd = 7, SystemCaptureStart = 8, SystemCaptureEnd = 9, SystemMoveSizeStart = 10, SystemMoveSizeEnd = 11, SystemContextHelpStart = 12, SystemContextHelpEnd = 13, SystemDragDropStart = 14, SystemDragDropEnd = 15, SystemDialogStart = 16, SystemDialogEnd = 17, SystemScrollingStart = 18, SystemScrollingEnd = 19, SystemSwitchStart = 20, SystemSwitchEnd = 21, SystemMinimizeStart = 22, SystemMinimizeEnd = 23, Create = 32768, Destroy = 32769, Show = 32770, Hide = 32771, Reorder = 32772, Focus = 32773, Selection = 32774, SelectionAdd = 32775, SelectionRemove = 32776, SelectionWithin = 32777, StateChange = 32778, LocationChange = 32779, NameChange = 32780, DescriptionChange = 32781, ValueChange = 32782, ParentChange = 32783, HelpChange = 32784, DefaultActionChange = 32785, AcceleratorChange = 32786 } public enum AccessibleNavigation { Up = 1, Down, Left, Right, Next, Previous, FirstChild, LastChild } [ComVisible(true)] public class AccessibleObject : StandardOleMarshalObject, IReflect, IAccessible { internal string name; internal string value; internal Control owner; internal AccessibleRole role; internal AccessibleStates state; internal string default_action; internal string description; internal string help; internal string keyboard_shortcut; public virtual Rectangle Bounds => owner.Bounds; public virtual string DefaultAction => default_action; public virtual string Description => description; public virtual string Help => help; public virtual string KeyboardShortcut => keyboard_shortcut; public virtual string Name { get { return name; } set { name = value; } } public virtual AccessibleObject Parent { get { if (owner != null && owner.Parent != null) { return owner.Parent.AccessibilityObject; } return null; } } public virtual AccessibleRole Role => role; public virtual AccessibleStates State { get { if (owner != null) { if (owner.Focused) { state |= AccessibleStates.Focused; } if (owner.CanFocus) { state |= AccessibleStates.Focusable; } if (!owner.Visible) { state |= AccessibleStates.Invisible; } } return state; } } public virtual string Value { get { return value; } set { this.value = value; } } Type IReflect.UnderlyingSystemType { get { throw new NotImplementedException(); } } int IAccessible.accChildCount { get { throw new NotImplementedException(); } } object IAccessible.accFocus { get { throw new NotImplementedException(); } } object IAccessible.accParent { get { throw new NotImplementedException(); } } object IAccessible.accSelection { get { throw new NotImplementedException(); } } public AccessibleObject() { owner = null; value = null; name = null; role = AccessibleRole.Default; default_action = null; description = null; help = null; keyboard_shortcut = null; state = AccessibleStates.None; } internal AccessibleObject(Control owner) : this() { this.owner = owner; } public virtual void DoDefaultAction() { if (owner != null) { owner.DoDefaultAction(); } } public virtual AccessibleObject GetChild(int index) { if (owner != null && index < owner.Controls.Count) { return owner.Controls[index].AccessibilityObject; } return null; } public virtual int GetChildCount() { if (owner != null) { return owner.Controls.Count; } return -1; } public virtual AccessibleObject GetFocused() { if (owner.has_focus) { return owner.AccessibilityObject; } return FindFocusControl(owner); } public virtual int GetHelpTopic(out string fileName) { fileName = null; return -1; } public virtual AccessibleObject GetSelected() { if ((state & AccessibleStates.Selected) != 0) { return this; } return FindSelectedControl(owner); } public virtual AccessibleObject HitTest(int x, int y) { return FindHittestControl(owner, x, y)?.AccessibilityObject; } public virtual AccessibleObject Navigate(AccessibleNavigation navdir) { int num = ((owner.Parent == null) ? (-1) : owner.Parent.Controls.IndexOf(owner)); switch (navdir) { case AccessibleNavigation.Up: if (owner.Parent != null) { for (int k = 0; k < owner.Parent.Controls.Count; k++) { if (owner != owner.Parent.Controls[k] && owner.Parent.Controls[k].Top < owner.Top) { return owner.Parent.Controls[k].AccessibilityObject; } } } return owner.AccessibilityObject; case AccessibleNavigation.Down: if (owner.Parent != null) { for (int j = 0; j < owner.Parent.Controls.Count; j++) { if (owner != owner.Parent.Controls[j] && owner.Parent.Controls[j].Top > owner.Bottom) { return owner.Parent.Controls[j].AccessibilityObject; } } } return owner.AccessibilityObject; case AccessibleNavigation.Left: if (owner.Parent != null) { for (int i = 0; i < owner.Parent.Controls.Count; i++) { if (owner != owner.Parent.Controls[i] && owner.Parent.Controls[i].Left < owner.Left) { return owner.Parent.Controls[i].AccessibilityObject; } } } return owner.AccessibilityObject; case AccessibleNavigation.Right: if (owner.Parent != null) { for (int l = 0; l < owner.Parent.Controls.Count; l++) { if (owner != owner.Parent.Controls[l] && owner.Parent.Controls[l].Left > owner.Right) { return owner.Parent.Controls[l].AccessibilityObject; } } } return owner.AccessibilityObject; case AccessibleNavigation.Next: if (owner.Parent != null) { if (num + 1 < owner.Parent.Controls.Count) { return owner.Parent.Controls[num + 1].AccessibilityObject; } return owner.Parent.Controls[0].AccessibilityObject; } return owner.AccessibilityObject; case AccessibleNavigation.Previous: if (owner.Parent != null) { if (num > 0) { return owner.Parent.Controls[num - 1].AccessibilityObject; } return owner.Parent.Controls[owner.Parent.Controls.Count - 1].AccessibilityObject; } return owner.AccessibilityObject; case AccessibleNavigation.FirstChild: if (owner.Controls.Count > 0) { return owner.Controls[0].AccessibilityObject; } return owner.AccessibilityObject; case AccessibleNavigation.LastChild: if (owner.Controls.Count > 0) { return owner.Controls[owner.Controls.Count - 1].AccessibilityObject; } return owner.AccessibilityObject; default: return owner.AccessibilityObject; } } public virtual void Select(AccessibleSelection flags) { if ((flags & AccessibleSelection.TakeFocus) != 0) { owner.Focus(); } } protected void UseStdAccessibleObjects(IntPtr handle) { } protected void UseStdAccessibleObjects(IntPtr handle, int objid) { UseStdAccessibleObjects(handle, 0); } internal static AccessibleObject FindFocusControl(Control parent) { if (parent != null) { for (int i = 0; i < parent.Controls.Count; i++) { Control control = parent.Controls[i]; if ((control.AccessibilityObject.state & AccessibleStates.Focused) != 0) { return control.AccessibilityObject; } if (control.Controls.Count > 0) { AccessibleObject accessibleObject = FindFocusControl(control); if (accessibleObject != null) { return accessibleObject; } } } } return null; } internal static AccessibleObject FindSelectedControl(Control parent) { if (parent != null) { for (int i = 0; i < parent.Controls.Count; i++) { Control control = parent.Controls[i]; if ((control.AccessibilityObject.state & AccessibleStates.Selected) != 0) { return control.AccessibilityObject; } if (control.Controls.Count > 0) { AccessibleObject accessibleObject = FindSelectedControl(control); if (accessibleObject != null) { return accessibleObject; } } } } return null; } internal static Control FindHittestControl(Control parent, int x, int y) { Point p = new Point(x, y); Point pt = parent.PointToClient(p); if (parent.ClientRectangle.Contains(pt)) { return parent; } for (int i = 0; i < parent.Controls.Count; i++) { Control control = parent.Controls[i]; pt = control.PointToClient(p); if (control.ClientRectangle.Contains(pt)) { return control; } if (control.Controls.Count > 0) { Control control2 = FindHittestControl(control, x, y); if (control2 != null) { return control2; } } } return null; } FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) { throw new NotImplementedException(); } MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) { throw new NotImplementedException(); } MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) { throw new NotImplementedException(); } PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) { throw new NotImplementedException(); } object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotImplementedException(); } void IAccessible.accDoDefaultAction(object childID) { throw new NotImplementedException(); } object IAccessible.accHitTest(int xLeft, int yTop) { throw new NotImplementedException(); } void IAccessible.accLocation(out int pxLeft, out int pyTop, out int pcxWidth, out int pcyHeight, object childID) { throw new NotImplementedException(); } object IAccessible.accNavigate(int navDir, object childID) { throw new NotImplementedException(); } void IAccessible.accSelect(int flagsSelect, object childID) { throw new NotImplementedException(); } object IAccessible.get_accChild(object childID) { throw new NotImplementedException(); } string IAccessible.get_accDefaultAction(object childID) { throw new NotImplementedException(); } string IAccessible.get_accDescription(object childID) { throw new NotImplementedException(); } string IAccessible.get_accHelp(object childID) { throw new NotImplementedException(); } int IAccessible.get_accHelpTopic(out string pszHelpFile, object childID) { throw new NotImplementedException(); } string IAccessible.get_accKeyboardShortcut(object childID) { throw new NotImplementedException(); } string IAccessible.get_accName(object childID) { throw new NotImplementedException(); } object IAccessible.get_accRole(object childID) { throw new NotImplementedException(); } object IAccessible.get_accState(object childID) { throw new NotImplementedException(); } string IAccessible.get_accValue(object childID) { throw new NotImplementedException(); } void IAccessible.set_accName(object childID, string newName) { throw new NotImplementedException(); } void IAccessible.set_accValue(object childID, string newValue) { throw new NotImplementedException(); } public bool RaiseAutomationNotification(AutomationNotificationKind notificationKind, AutomationNotificationProcessing notificationProcessing, string notificationText) { ThrowStub.ThrowNotSupportedException(); return default(bool); } public virtual bool RaiseLiveRegionChanged() { ThrowStub.ThrowNotSupportedException(); return default(bool); } } public enum AccessibleRole { None = 0, TitleBar = 1, MenuBar = 2, ScrollBar = 3, Grip = 4, Sound = 5, Cursor = 6, Caret = 7, Alert = 8, Window = 9, Client = 10, MenuPopup = 11, MenuItem = 12, ToolTip = 13, Application = 14, Document = 15, Pane = 16, Chart = 17, Dialog = 18, Border = 19, Grouping = 20, Separator = 21, ToolBar = 22, StatusBar = 23, Table = 24, ColumnHeader = 25, RowHeader = 26, Column = 27, Row = 28, Cell = 29, Link = 30, HelpBalloon = 31, Character = 32, List = 33, ListItem = 34, Outline = 35, OutlineItem = 36, PageTab = 37, PropertyPage = 38, Indicator = 39, Graphic = 40, StaticText = 41, Text = 42, PushButton = 43, CheckButton = 44, RadioButton = 45, ComboBox = 46, DropList = 47, ProgressBar = 48, Dial = 49, HotkeyField = 50, Slider = 51, SpinButton = 52, Diagram = 53, Animation = 54, Equation = 55, ButtonDropDown = 56, ButtonMenu = 57, ButtonDropDownGrid = 58, WhiteSpace = 59, PageTabList = 60, Clock = 61, Default = -1, SplitButton = 62, IpAddress = 63, OutlineButton = 64 } [Flags] public enum AccessibleSelection { None = 0, TakeFocus = 1, TakeSelection = 2, ExtendSelection = 4, AddSelection = 8, RemoveSelection = 0x10 } [Flags] public enum AccessibleStates { None = 0, Unavailable = 1, Selected = 2, Focused = 4, Pressed = 8, Checked = 0x10, Mixed = 0x20, Indeterminate = 0x20, ReadOnly = 0x40, HotTracked = 0x80, Default = 0x100, Expanded = 0x200, Collapsed = 0x400, Busy = 0x800, Floating = 0x1000, Marqueed = 0x2000, Animated = 0x4000, Invisible = 0x8000, Offscreen = 0x10000, Sizeable = 0x20000, Moveable = 0x40000, SelfVoicing = 0x80000, Focusable = 0x100000, Selectable = 0x200000, Linked = 0x400000, Traversed = 0x800000, MultiSelectable = 0x1000000, ExtSelectable = 0x2000000, AlertLow = 0x4000000, AlertMedium = 0x8000000, AlertHigh = 0x10000000, Protected = 0x20000000, [Obsolete] Valid = 0x3FFFFFFF, HasPopup = 0x40000000 } public sealed class AmbientProperties { private System.Drawing.Color fore_color; private System.Drawing.Color back_color; private Font font; private Cursor cursor; public System.Drawing.Color BackColor { get { return back_color; } set { back_color = value; } } public Cursor Cursor { get { return cursor; } set { cursor = value; } } public Font Font { get { return font; } set { font = value; } } public System.Drawing.Color ForeColor { get { return fore_color; } set { fore_color = value; } } } [Editor("System.Windows.Forms.Design.AnchorEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] [Flags] public enum AnchorStyles { None = 0, Top = 1, Bottom = 2, Left = 4, Right = 8 } [ComVisible(true)] public enum Appearance { Normal, Button } public sealed class Application { internal class MWFThread { private ApplicationContext context; private bool messageloop_started; private bool handling_exception; private int thread_id; private static readonly Hashtable threads = new Hashtable(); public ApplicationContext Context { get { return context; } set { context = value; } } public bool MessageLoop { get { return messageloop_started; } set { messageloop_started = value; } } public bool HandlingException { get { return handling_exception; } set { handling_exception = value; } } public static int LoopCount { get { lock (threads) { int num = 0; foreach (MWFThread value in threads.Values) { if (value.messageloop_started) { num++; } } return num; } } } public static MWFThread Current { get { MWFThread mWFThread = null; lock (threads) { mWFThread = (MWFThread)threads[Thread.CurrentThread.GetHashCode()]; if (mWFThread == null) { mWFThread = new MWFThread(); mWFThread.thread_id = Thread.CurrentThread.GetHashCode(); threads[mWFThread.thread_id] = mWFThread; } } return mWFThread; } } private MWFThread() { } public void Exit() { if (context != null) { context.ExitThread(); } context = null; if (Application.ThreadExit != null) { Application.ThreadExit(null, EventArgs.Empty); } if (LoopCount == 0 && Application.ApplicationExit != null) { Application.ApplicationExit(null, EventArgs.Empty); } ((MWFThread)threads[thread_id]).MessageLoop = false; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public delegate bool MessageLoopCallback(); private static bool browser_embedded; private static InputLanguage input_language; private static string safe_caption_format; private static readonly ArrayList message_filters; private static readonly FormCollection forms; private static bool use_wait_cursor; private static ToolStrip keyboard_capture; private static VisualStyleState visual_style_state; private static bool visual_styles_enabled; internal static bool use_compatible_text_rendering; public static bool AllowQuit => !browser_embedded; public static string CommonAppDataPath => CreateDataPath(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)); public static RegistryKey CommonAppDataRegistry { get { string subkey = $"Software\\{CompanyName}\\{ProductName}\\{ProductVersion}"; return Registry.LocalMachine.CreateSubKey(subkey); } } public static string CompanyName { get { string text = string.Empty; Assembly assembly = Assembly.GetEntryAssembly(); if (assembly == null) { assembly = Assembly.GetCallingAssembly(); } AssemblyCompanyAttribute[] array = (AssemblyCompanyAttribute[])assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), inherit: true); if (array != null && array.Length != 0) { text = array[0].Company; } if ((text == null || text.Length == 0) && assembly.EntryPoint != null) { text = assembly.EntryPoint.DeclaringType.Namespace; if (text != null) { int num = text.IndexOf('.'); if (num >= 0) { text = text.Substring(0, num); } } } if ((text == null || text.Length == 0) && assembly.EntryPoint != null) { text = assembly.EntryPoint.DeclaringType.FullName; } return text; } } public static CultureInfo CurrentCulture { get { return Thread.CurrentThread.CurrentUICulture; } set { Thread.CurrentThread.CurrentUICulture = value; } } public static InputLanguage CurrentInputLanguage { get { return input_language; } set { input_language = value; } } public static string ExecutablePath => Path.GetFullPath(Environment.GetCommandLineArgs()[0]); public static string LocalUserAppDataPath => CreateDataPath(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); public static bool MessageLoop => MWFThread.Current.MessageLoop; public static string ProductName { get { string text = string.Empty; Assembly assembly = Assembly.GetEntryAssembly(); if (assembly == null) { assembly = Assembly.GetCallingAssembly(); } AssemblyProductAttribute[] array = (AssemblyProductAttribute[])assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), inherit: true); if (array != null && array.Length != 0) { text = array[0].Product; } if ((text == null || text.Length == 0) && assembly.EntryPoint != null) { text = assembly.EntryPoint.DeclaringType.Namespace; if (text != null) { int num = text.LastIndexOf('.'); if (num >= 0 && num < text.Length - 1) { text = text.Substring(num + 1); } } if (text == null || text.Length == 0) { text = assembly.EntryPoint.DeclaringType.FullName; } } return text; } } public static string ProductVersion { get { string text = string.Empty; Assembly assembly = Assembly.GetEntryAssembly(); if (assembly == null) { assembly = Assembly.GetCallingAssembly(); } if (Attribute.GetCustomAttribute(assembly, typeof(AssemblyInformationalVersionAttribute)) is AssemblyInformationalVersionAttribute assemblyInformationalVersionAttribute) { text = assemblyInformationalVersionAttribute.InformationalVersion; } if ((text == null || text.Length == 0) && Attribute.GetCustomAttribute(assembly, typeof(AssemblyFileVersionAttribute)) is AssemblyFileVersionAttribute assemblyFileVersionAttribute) { text = assemblyFileVersionAttribute.Version; } if (text == null || text.Length == 0) { text = assembly.GetName().Version.ToString(); } return text; } } public static string SafeTopLevelCaptionFormat { get { return safe_caption_format; } set { safe_caption_format = value; } } public static string StartupPath => Path.GetDirectoryName(ExecutablePath); public static string UserAppDataPath => CreateDataPath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); public static RegistryKey UserAppDataRegistry { get { string subkey = $"Software\\{CompanyName}\\{ProductName}\\{ProductVersion}"; return Registry.CurrentUser.CreateSubKey(subkey); } } public static bool UseWaitCursor { get { return use_wait_cursor; } set { use_wait_cursor = value; if (!use_wait_cursor) { return; } foreach (Form openForm in OpenForms) { openForm.Cursor = Cursors.WaitCursor; } } } public static bool RenderWithVisualStyles { get { if (VisualStyleInformation.IsSupportedByOS) { if (!VisualStyleInformation.IsEnabledByUser) { return false; } if (!XplatUI.ThemesEnabled) { return false; } if (VisualStyleState == VisualStyleState.ClientAndNonClientAreasEnabled) { return true; } if (VisualStyleState == VisualStyleState.ClientAreaEnabled) { return true; } } return false; } } public static VisualStyleState VisualStyleState { get { return visual_style_state; } set { visual_style_state = value; } } public static FormCollection OpenForms => forms; internal static ToolStrip KeyboardCapture { get { return keyboard_capture; } set { keyboard_capture = value; } } internal static bool VisualStylesEnabled => visual_styles_enabled; public static event EventHandler ApplicationExit; public static event EventHandler Idle { add { XplatUI.Idle += value; } remove { XplatUI.Idle -= value; } } public static event EventHandler ThreadExit; public static event ThreadExceptionEventHandler ThreadException; internal static event EventHandler FormAdded; internal static event EventHandler PreRun; [MonoTODO] [EditorBrowsable(EditorBrowsableState.Advanced)] public static event EventHandler EnterThreadModal; [EditorBrowsable(EditorBrowsableState.Advanced)] [MonoTODO] public static event EventHandler LeaveThreadModal; private Application() { browser_embedded = false; } static Application() { input_language = InputLanguage.CurrentInputLanguage; safe_caption_format = "{1} - {0} - {2}"; message_filters = new ArrayList(); forms = new FormCollection(); visual_style_state = VisualStyleState.ClientAndNonClientAreasEnabled; use_compatible_text_rendering = true; InitializeUIAutomation(); } private static void InitializeUIAutomation() { Assembly assembly = null; try { assembly = Assembly.Load("UIAutomationWinforms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f4ceacb585d99812"); } catch { } if (assembly == null) { return; } try { Type type = assembly.GetType("Mono.UIAutomation.Winforms.Global", throwOnError: false); if (type != null) { MethodInfo method = type.GetMethod("Initialize", BindingFlags.Static | BindingFlags.Public); if (method != null) { method.Invoke(null, new object[0]); return; } throw new Exception(string.Format("Method {0} not found in type {1}.", "Initialize", "Mono.UIAutomation.Winforms.Global")); } throw new Exception(string.Format("Type {0} not found in assembly {1}.", "Mono.UIAutomation.Winforms.Global", "UIAutomationWinforms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f4ceacb585d99812")); } catch (Exception ex) { Console.Error.WriteLine("Error setting up UIA: " + ex); } } internal static void CloseForms(Thread thread) { ArrayList arrayList = new ArrayList(); lock (forms) { foreach (Form form in forms) { if (thread == null || thread == form.creator_thread) { arrayList.Add(form); } } foreach (Form item in arrayList) { item.Dispose(); } } } public static void AddMessageFilter(IMessageFilter value) { lock (message_filters) { message_filters.Add(value); } } internal static void AddKeyFilter(IKeyFilter value) { XplatUI.AddKeyFilter(value); } public static void DoEvents() { XplatUI.DoEvents(); } public static void EnableVisualStyles() { visual_styles_enabled = true; XplatUI.EnableThemes(); } [EditorBrowsable(EditorBrowsableState.Advanced)] public static bool FilterMessage(ref Message message) { lock (message_filters) { for (int i = 0; i < message_filters.Count; i++) { if (((IMessageFilter)message_filters[i]).PreFilterMessage(ref message)) { return true; } } } return false; } public static void SetCompatibleTextRenderingDefault(bool defaultValue) { use_compatible_text_rendering = defaultValue; } [EditorBrowsable(EditorBrowsableState.Advanced)] [MonoNotSupported("Only applies when Winforms is being hosted by an unmanaged app.")] public static void RegisterMessageLoop(MessageLoopCallback callback) { } [MonoNotSupported("Empty stub.")] public static bool SetSuspendState(PowerState state, bool force, bool disableWakeEvent) { return false; } [MonoNotSupported("Empty stub.")] public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode) { } [MonoNotSupported("Empty stub.")] public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode, bool threadScope) { } [MonoNotSupported("Only applies when Winforms is being hosted by an unmanaged app.")] [EditorBrowsable(EditorBrowsableState.Advanced)] public static void UnregisterMessageLoop() { } [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RaiseIdle(EventArgs e) { XplatUI.RaiseIdle(e); } public static void Restart() { if (Assembly.GetEntryAssembly() == null) { throw new NotSupportedException("The method 'Restart' is not supported by this application type."); } string mono = MonoToolsLocator.Mono; StringBuilder stringBuilder = new StringBuilder(); string[] commandLineArgs = Environment.GetCommandLineArgs(); for (int i = 0; i < commandLineArgs.Length; i++) { stringBuilder.Append($"\"{commandLineArgs[i]}\" "); } string text = stringBuilder.ToString(); ProcessStartInfo startInfo = Process.GetCurrentProcess().StartInfo; if (mono == null) { startInfo.FileName = commandLineArgs[0]; startInfo.Arguments = text.Remove(0, commandLineArgs[0].Length + 3); } else { startInfo.Arguments = text; startInfo.FileName = mono; } startInfo.WorkingDirectory = Environment.CurrentDirectory; Exit(); Process.Start(startInfo); } public static void Exit() { Exit(new CancelEventArgs()); } [EditorBrowsable(EditorBrowsableState.Advanced)] public static void Exit(CancelEventArgs e) { lock (forms) { foreach (Form item in new ArrayList(forms)) { e.Cancel = item.FireClosingEvents(CloseReason.ApplicationExitCall, cancel: false); if (e.Cancel) { return; } item.suppress_closing_events = true; item.Close(); item.Dispose(); } } XplatUI.PostQuitMessage(0); } public static void ExitThread() { CloseForms(Thread.CurrentThread); XplatUI.PostQuitMessage(0); } public static ApartmentState OleRequired() { return ApartmentState.Unknown; } public static void OnThreadException(Exception t) { if (MWFThread.Current.HandlingException) { Console.WriteLine(t); Environment.Exit(1); } try { MWFThread.Current.HandlingException = true; if (Application.ThreadException != null) { Application.ThreadException(null, new ThreadExceptionEventArgs(t)); return; } if (SystemInformation.UserInteractive) { new ThreadExceptionDialog(t).ShowDialog(); return; } Console.WriteLine(t.ToString()); Exit(); } finally { MWFThread.Current.HandlingException = false; } } public static void RemoveMessageFilter(IMessageFilter value) { lock (message_filters) { message_filters.Remove(value); } } public static void Run() { Run(new ApplicationContext()); } public static void Run(Form mainForm) { Run(new ApplicationContext(mainForm)); } internal static void FirePreRun() { Application.PreRun?.Invoke(null, EventArgs.Empty); } public static void Run(ApplicationContext context) { if (SynchronizationContext.Current == null) { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); } RunLoop(Modal: false, context); if (SynchronizationContext.Current is WindowsFormsSynchronizationContext) { WindowsFormsSynchronizationContext.Uninstall(); } } private static void DisableFormsForModalLoop(Queue toplevels, ApplicationContext context) { lock (forms) { IEnumerator enumerator = forms.GetEnumerator(); while (enumerator.MoveNext()) { Form form = (Form)enumerator.Current; if (form == context.MainForm) { continue; } Control control = form; bool flag = false; do { if (control.Parent == context.MainForm) { flag = true; break; } control = control.Parent; } while (control != null); if (!flag && form.IsHandleCreated && XplatUI.IsEnabled(form.Handle)) { XplatUI.EnableWindow(form.Handle, Enable: false); toplevels.Enqueue(form); } } } } private static void EnableFormsForModalLoop(Queue toplevels, ApplicationContext context) { while (toplevels.Count > 0) { Form form = (Form)toplevels.Dequeue(); if (form.IsHandleCreated) { XplatUI.EnableWindow(form.window.Handle, Enable: true); context.MainForm = form; } } } internal static void RunLoop(bool Modal, ApplicationContext context) { MWFThread current = MWFThread.Current; MSG msg = default(MSG); if (context == null) { context = new ApplicationContext(); } ApplicationContext context2 = current.Context; current.Context = context; if (context.MainForm != null) { context.MainForm.is_modal = Modal; context.MainForm.context = context; context.MainForm.closing = false; context.MainForm.Visible = true; if (context.MainForm != null) { context.MainForm.Activate(); } } Queue toplevels; if (Modal) { toplevels = new Queue(); DisableFormsForModalLoop(toplevels, context); if (context.MainForm != null) { XplatUI.EnableWindow(context.MainForm.Handle, Enable: true); XplatUI.SetModal(context.MainForm.Handle, Modal: true); } } else { toplevels = null; } object queue_id = XplatUI.StartLoop(Thread.CurrentThread); current.MessageLoop = true; bool flag = false; while (!flag && XplatUI.GetMessage(queue_id, ref msg, IntPtr.Zero, 0, 0)) { Message message = Message.Create(msg.hwnd, (int)msg.message, msg.wParam, msg.lParam); if (FilterMessage(ref message)) { continue; } Msg message2 = msg.message; if (message2 <= Msg.WM_SYSCHAR) { if (message2 == Msg.WM_QUIT) { flag = true; goto IL_0307; } if ((uint)(message2 - 256) <= 2u || (uint)(message2 - 260) <= 2u) { Control control = Control.FromHandle(msg.hwnd); if (keyboard_capture != null) { if (message.Msg == 260 && message.WParam.ToInt32() == 18) { keyboard_capture.GetTopLevelToolStrip().Dismiss(ToolStripDropDownCloseReason.Keyboard); continue; } message.HWnd = keyboard_capture.Handle; PreProcessControlState preProcessControlState = keyboard_capture.PreProcessControlMessageInternal(ref message); if (preProcessControlState == PreProcessControlState.MessageProcessed) { continue; } if ((uint)(preProcessControlState - 1) <= 1u) { if ((message.Msg != 256 && message.Msg != 258) || keyboard_capture.ProcessControlMnemonic((char)(int)message.WParam) || control == null || !ControlOnToolStrip(control)) { continue; } message.HWnd = msg.hwnd; } } if ((control == null || control.PreProcessControlMessageInternal(ref message) == PreProcessControlState.MessageProcessed) && control != null) { goto IL_0307; } } } else if ((message2 == Msg.WM_LBUTTONDOWN || message2 == Msg.WM_RBUTTONDOWN || message2 == Msg.WM_MBUTTONDOWN) && keyboard_capture != null) { Control control2 = Control.FromHandle(
deps/System.Xml.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using System.Diagnostics; using System.Diagnostics.SymbolStore; using System.Globalization; using System.IO; using System.Net; using System.Net.Cache; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.Serialization.Advanced; using System.Xml.Serialization.Configuration; using System.Xml.Utils; using System.Xml.XPath; using System.Xml.XmlConfiguration; using System.Xml.Xsl; using System.Xml.Xsl.IlGen; using System.Xml.Xsl.Qil; using System.Xml.Xsl.Runtime; using System.Xml.Xsl.XPath; using System.Xml.Xsl.Xslt; using System.Xml.Xsl.XsltOld; using System.Xml.Xsl.XsltOld.Debugger; using MS.Internal.Xml.Cache; using MS.Internal.Xml.XPath; using Microsoft.CSharp; using Microsoft.VisualBasic; using Microsoft.Win32; using Unity; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("System.Data.SqlXml, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.Xml.Linq, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.ServiceModel.Friend, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: AssemblyTitle("System.Xml.dll")] [assembly: AssemblyDescription("System.Xml.dll")] [assembly: AssemblyDefaultAlias("System.Xml.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../ecma.pub")] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("System.Xml.Linq, PublicKey=00000000000000000400000000000000", AllInternalsVisible = false)] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class AssemblyRef { internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string EcmaPublicKey = "b77a5c561934e089"; public const string FrameworkPublicKeyFull = "00000000000000000400000000000000"; public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000"; public const string MicrosoftPublicKey = "b03f5f7f11d50a3a"; public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal static class SR { public const string Xml_UserException = "{0}"; public const string Xml_DefaultException = "An XML error has occurred."; public const string Xml_InvalidOperation = "Operation is not valid due to the current state of the object."; public const string Xml_ErrorFilePosition = "An error occurred at {0}, ({1}, {2})."; public const string Xml_StackOverflow = "Stack overflow."; public const string Xslt_NoStylesheetLoaded = "No stylesheet was loaded."; public const string Xslt_NotCompiledStylesheet = "Type '{0}' is not a compiled stylesheet class."; public const string Xslt_IncompatibleCompiledStylesheetVersion = "Executing a stylesheet that was compiled using a later version of the framework is not supported. Stylesheet Version: {0}. Current Framework Version: {1}."; public const string Xml_AsyncIsRunningException = "An asynchronous operation is already in progress."; public const string Xml_ReaderAsyncNotSetException = "Set XmlReaderSettings.Async to true if you want to use Async Methods."; public const string Xml_UnclosedQuote = "There is an unclosed literal string."; public const string Xml_UnexpectedEOF = "Unexpected end of file while parsing {0} has occurred."; public const string Xml_UnexpectedEOF1 = "Unexpected end of file has occurred."; public const string Xml_UnexpectedEOFInElementContent = "Unexpected end of file has occurred. The following elements are not closed: {0}"; public const string Xml_BadStartNameChar = "Name cannot begin with the '{0}' character, hexadecimal value {1}."; public const string Xml_BadNameChar = "The '{0}' character, hexadecimal value {1}, cannot be included in a name."; public const string Xml_BadDecimalEntity = "Invalid syntax for a decimal numeric entity reference."; public const string Xml_BadHexEntity = "Invalid syntax for a hexadecimal numeric entity reference."; public const string Xml_MissingByteOrderMark = "There is no Unicode byte order mark. Cannot switch to Unicode."; public const string Xml_UnknownEncoding = "System does not support '{0}' encoding."; public const string Xml_InternalError = "An internal error has occurred."; public const string Xml_InvalidCharInThisEncoding = "Invalid character in the given encoding."; public const string Xml_ErrorPosition = "Line {0}, position {1}."; public const string Xml_MessageWithErrorPosition = "{0} Line {1}, position {2}."; public const string Xml_UnexpectedTokenEx = "'{0}' is an unexpected token. The expected token is '{1}'."; public const string Xml_UnexpectedTokens2 = "'{0}' is an unexpected token. The expected token is '{1}' or '{2}'."; public const string Xml_ExpectingWhiteSpace = "'{0}' is an unexpected token. Expecting whitespace."; public const string Xml_TagMismatchEx = "The '{0}' start tag on line {1} position {2} does not match the end tag of '{3}'."; public const string Xml_UnexpectedEndTag = "Unexpected end tag."; public const string Xml_UnknownNs = "'{0}' is an undeclared prefix."; public const string Xml_BadAttributeChar = "'{0}', hexadecimal value {1}, is an invalid attribute character."; public const string Xml_ExpectExternalOrClose = "Expecting external ID, '[' or '>'."; public const string Xml_MissingRoot = "Root element is missing."; public const string Xml_MultipleRoots = "There are multiple root elements."; public const string Xml_InvalidRootData = "Data at the root level is invalid."; public const string Xml_XmlDeclNotFirst = "Unexpected XML declaration. The XML declaration must be the first node in the document, and no whitespace characters are allowed to appear before it."; public const string Xml_InvalidXmlDecl = "Syntax for an XML declaration is invalid."; public const string Xml_InvalidNodeType = "'{0}' is an invalid XmlNodeType."; public const string Xml_InvalidPIName = "'{0}' is an invalid name for processing instructions."; public const string Xml_InvalidXmlSpace = "'{0}' is an invalid xml:space value."; public const string Xml_InvalidVersionNumber = "Version number '{0}' is invalid."; public const string Xml_DupAttributeName = "'{0}' is a duplicate attribute name."; public const string Xml_BadDTDLocation = "Unexpected DTD declaration."; public const string Xml_ElementNotFound = "Element '{0}' was not found."; public const string Xml_ElementNotFoundNs = "Element '{0}' with namespace name '{1}' was not found."; public const string Xml_PartialContentNodeTypeNotSupportedEx = "XmlNodeType {0} is not supported for partial content parsing."; public const string Xml_MultipleDTDsProvided = "Cannot have multiple DTDs."; public const string Xml_CanNotBindToReservedNamespace = "Cannot bind to the reserved namespace."; public const string Xml_InvalidCharacter = "'{0}', hexadecimal value {1}, is an invalid character."; public const string Xml_InvalidBinHexValue = "'{0}' is not a valid BinHex text sequence."; public const string Xml_InvalidBinHexValueOddCount = "'{0}' is not a valid BinHex text sequence. The sequence must contain an even number of characters."; public const string Xml_InvalidTextDecl = "Invalid text declaration."; public const string Xml_InvalidBase64Value = "'{0}' is not a valid Base64 text sequence."; public const string Xml_UndeclaredEntity = "Reference to undeclared entity '{0}'."; public const string Xml_RecursiveParEntity = "Parameter entity '{0}' references itself."; public const string Xml_RecursiveGenEntity = "General entity '{0}' references itself."; public const string Xml_ExternalEntityInAttValue = "External entity '{0}' reference cannot appear in the attribute value."; public const string Xml_UnparsedEntityRef = "Reference to unparsed entity '{0}'."; public const string Xml_NotSameNametable = "Not the same name table."; public const string Xml_NametableMismatch = "XmlReaderSettings.XmlNameTable must be the same name table as in XmlParserContext.NameTable or XmlParserContext.NamespaceManager.NameTable, or it must be null."; public const string Xml_BadNamespaceDecl = "Invalid namespace declaration."; public const string Xml_ErrorParsingEntityName = "An error occurred while parsing EntityName."; public const string Xml_InvalidNmToken = "Invalid NmToken value '{0}'."; public const string Xml_EntityRefNesting = "Entity replacement text must nest properly within markup declarations."; public const string Xml_CannotResolveEntity = "Cannot resolve entity reference '{0}'."; public const string Xml_CannotResolveEntityDtdIgnored = "Cannot resolve entity reference '{0}' because the DTD has been ignored. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method."; public const string Xml_CannotResolveExternalSubset = "Cannot resolve external DTD subset - public ID = '{0}', system ID = '{1}'."; public const string Xml_CannotResolveUrl = "Cannot resolve '{0}'."; public const string Xml_CDATAEndInText = "']]>' is not allowed in character data."; public const string Xml_ExternalEntityInStandAloneDocument = "Standalone document declaration must have a value of 'no' because an external entity '{0}' is referenced."; public const string Xml_DtdAfterRootElement = "DTD must be defined before the document root element."; public const string Xml_ReadOnlyProperty = "The '{0}' property is read only and cannot be set."; public const string Xml_DtdIsProhibited = "DTD is prohibited in this XML document."; public const string Xml_DtdIsProhibitedEx = "For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method."; public const string Xml_ReadSubtreeNotOnElement = "ReadSubtree() can be called only if the reader is on an element node."; public const string Xml_DtdNotAllowedInFragment = "DTD is not allowed in XML fragments."; public const string Xml_CannotStartDocumentOnFragment = "WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment."; public const string Xml_ErrorOpeningExternalDtd = "An error has occurred while opening external DTD '{0}': {1}"; public const string Xml_ErrorOpeningExternalEntity = "An error has occurred while opening external entity '{0}': {1}"; public const string Xml_ReadBinaryContentNotSupported = "{0} method is not supported on this XmlReader. Use CanReadBinaryContent property to find out if a reader implements it."; public const string Xml_ReadValueChunkNotSupported = "ReadValueChunk method is not supported on this XmlReader. Use CanReadValueChunk property to find out if an XmlReader implements it."; public const string Xml_InvalidReadContentAs = "The {0} method is not supported on node type {1}. If you want to read typed content of an element, use the ReadElementContentAs method."; public const string Xml_InvalidReadElementContentAs = "The {0} method is not supported on node type {1}."; public const string Xml_MixedReadElementContentAs = "ReadElementContentAs() methods cannot be called on an element that has child elements."; public const string Xml_MixingReadValueChunkWithBinary = "ReadValueChunk calls cannot be mixed with ReadContentAsBase64 or ReadContentAsBinHex."; public const string Xml_MixingBinaryContentMethods = "ReadContentAsBase64 and ReadContentAsBinHex method calls cannot be mixed with calls to ReadElementContentAsBase64 and ReadElementContentAsBinHex."; public const string Xml_MixingV1StreamingWithV2Binary = "ReadContentAsBase64 and ReadContentAsBinHex method calls cannot be mixed with calls to ReadChars, ReadBase64, and ReadBinHex."; public const string Xml_InvalidReadValueChunk = "The ReadValueAsChunk method is not supported on node type {0}."; public const string Xml_ReadContentAsFormatException = "Content cannot be converted to the type {0}."; public const string Xml_DoubleBaseUri = "BaseUri must be specified either as an argument of XmlReader.Create or on the XmlParserContext. If it is specified on both, it must be the same base URI."; public const string Xml_NotEnoughSpaceForSurrogatePair = "The buffer is not large enough to fit a surrogate pair. Please provide a buffer of size at least 2 characters."; public const string Xml_EmptyUrl = "The URL cannot be empty."; public const string Xml_UnexpectedNodeInSimpleContent = "Unexpected node type {0}. {1} method can only be called on elements with simple or empty content."; public const string Xml_InvalidWhitespaceCharacter = "The Whitespace or SignificantWhitespace node can contain only XML whitespace characters. '{0}' is not an XML white space character."; public const string Xml_IncompatibleConformanceLevel = "Cannot change conformance checking to {0}. Make sure the ConformanceLevel in XmlReaderSettings is set to Auto for wrapping scenarios."; public const string Xml_LimitExceeded = "The input document has exceeded a limit set by {0}."; public const string Xml_ClosedOrErrorReader = "The XmlReader is closed or in error state."; public const string Xml_CharEntityOverflow = "Invalid value of a character entity reference."; public const string Xml_BadNameCharWithPos = "The '{0}' character, hexadecimal value {1}, at position {2} within the name, cannot be included in a name."; public const string Xml_XmlnsBelongsToReservedNs = "The 'xmlns' attribute is bound to the reserved namespace 'http://www.w3.org/2000/xmlns/'."; public const string Xml_UndeclaredParEntity = "Reference to undeclared parameter entity '{0}'."; public const string Xml_InvalidXmlDocument = "Invalid XML document. {0}"; public const string Xml_NoDTDPresent = "No DTD found."; public const string Xml_MultipleValidaitonTypes = "Unsupported combination of validation types."; public const string Xml_NoValidation = "No validation occurred."; public const string Xml_WhitespaceHandling = "Expected WhitespaceHandling.None, or WhitespaceHandling.All, or WhitespaceHandling.Significant."; public const string Xml_InvalidResetStateCall = "Cannot call ResetState when parsing an XML fragment."; public const string Xml_EntityHandling = "Expected EntityHandling.ExpandEntities or EntityHandling.ExpandCharEntities."; public const string Xml_AttlistDuplEnumValue = "'{0}' is a duplicate enumeration value."; public const string Xml_AttlistDuplNotationValue = "'{0}' is a duplicate notation value."; public const string Xml_EncodingSwitchAfterResetState = "'{0}' is an invalid value for the 'encoding' attribute. The encoding cannot be switched after a call to ResetState."; public const string Xml_UnexpectedNodeType = "Unexpected XmlNodeType: '{0}'."; public const string Xml_InvalidConditionalSection = "A conditional section is not allowed in an internal subset."; public const string Xml_UnexpectedCDataEnd = "']]>' is not expected."; public const string Xml_UnclosedConditionalSection = "There is an unclosed conditional section."; public const string Xml_ExpectDtdMarkup = "Expected DTD markup was not found."; public const string Xml_IncompleteDtdContent = "Incomplete DTD content."; public const string Xml_EnumerationRequired = "Enumeration data type required."; public const string Xml_InvalidContentModel = "Invalid content model."; public const string Xml_FragmentId = "Fragment identifier '{0}' cannot be part of the system identifier '{1}'."; public const string Xml_ExpectPcData = "Expecting 'PCDATA'."; public const string Xml_ExpectNoWhitespace = "Whitespace not allowed before '?', '*', or '+'."; public const string Xml_ExpectOp = "Expecting '?', '*', or '+'."; public const string Xml_InvalidAttributeType = "'{0}' is an invalid attribute type."; public const string Xml_InvalidAttributeType1 = "Invalid attribute type."; public const string Xml_ExpectAttType = "Expecting an attribute type."; public const string Xml_ColonInLocalName = "'{0}' is an unqualified name and cannot contain the character ':'."; public const string Xml_InvalidParEntityRef = "A parameter entity reference is not allowed in internal markup."; public const string Xml_ExpectSubOrClose = "Expecting an internal subset or the end of the DOCTYPE declaration."; public const string Xml_ExpectExternalOrPublicId = "Expecting a system identifier or a public identifier."; public const string Xml_ExpectExternalIdOrEntityValue = "Expecting an external identifier or an entity value."; public const string Xml_ExpectIgnoreOrInclude = "Conditional sections must specify the keyword 'IGNORE' or 'INCLUDE'."; public const string Xml_UnsupportedClass = "Object type is not supported."; public const string Xml_NullResolver = "Resolving of external URIs was prohibited."; public const string Xml_RelativeUriNotSupported = "Relative URIs are not supported."; public const string Xml_WriterAsyncNotSetException = "Set XmlWriterSettings.Async to true if you want to use Async Methods."; public const string Xml_PrefixForEmptyNs = "Cannot use a prefix with an empty namespace."; public const string Xml_InvalidCommentChars = "An XML comment cannot contain '--', and '-' cannot be the last character."; public const string Xml_UndefNamespace = "The '{0}' namespace is not defined."; public const string Xml_EmptyName = "The empty string '' is not a valid name."; public const string Xml_EmptyLocalName = "The empty string '' is not a valid local name."; public const string Xml_InvalidNameCharsDetail = "Invalid name character in '{0}'. The '{1}' character, hexadecimal value {2}, cannot be included in a name."; public const string Xml_NoStartTag = "There was no XML start tag open."; public const string Xml_ClosedOrError = "The Writer is closed or in error state."; public const string Xml_WrongToken = "Token {0} in state {1} would result in an invalid XML document."; public const string Xml_XmlPrefix = "Prefix \"xml\" is reserved for use by XML and can be mapped only to namespace name \"http://www.w3.org/XML/1998/namespace\"."; public const string Xml_XmlnsPrefix = "Prefix \"xmlns\" is reserved for use by XML."; public const string Xml_NamespaceDeclXmlXmlns = "Prefix '{0}' cannot be mapped to namespace name reserved for \"xml\" or \"xmlns\"."; public const string Xml_NonWhitespace = "Only whitespace characters should be used."; public const string Xml_DupXmlDecl = "Cannot write XML declaration. WriteStartDocument method has already written it."; public const string Xml_CannotWriteXmlDecl = "Cannot write XML declaration. XML declaration can be only at the beginning of the document."; public const string Xml_NoRoot = "Document does not have a root element."; public const string Xml_InvalidPosition = "The current position on the Reader is neither an element nor an attribute."; public const string Xml_IncompleteEntity = "Incomplete entity contents."; public const string Xml_InvalidSurrogateHighChar = "Invalid high surrogate character (0x{0}). A high surrogate character must have a value from range (0xD800 - 0xDBFF)."; public const string Xml_InvalidSurrogateMissingLowChar = "The surrogate pair is invalid. Missing a low surrogate character."; public const string Xml_InvalidSurrogatePairWithArgs = "The surrogate pair (0x{0}, 0x{1}) is invalid. A high surrogate character (0xD800 - 0xDBFF) must always be paired with a low surrogate character (0xDC00 - 0xDFFF)."; public const string Xml_RedefinePrefix = "The prefix '{0}' cannot be redefined from '{1}' to '{2}' within the same start element tag."; public const string Xml_DtdAlreadyWritten = "The DTD has already been written out."; public const string Xml_InvalidCharsInIndent = "XmlWriterSettings.{0} can contain only valid XML text content characters when XmlWriterSettings.CheckCharacters is true. {1}"; public const string Xml_IndentCharsNotWhitespace = "XmlWriterSettings.{0} can contain only valid XML whitespace characters when XmlWriterSettings.CheckCharacters and XmlWriterSettings.NewLineOnAttributes are true."; public const string Xml_ConformanceLevelFragment = "Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment. "; public const string Xml_InvalidQuote = "Invalid XML attribute quote character. Valid attribute quote characters are ' and \"."; public const string Xml_UndefPrefix = "An undefined prefix is in use."; public const string Xml_NoNamespaces = "Cannot set the namespace if Namespaces is 'false'."; public const string Xml_InvalidCDataChars = "Cannot have ']]>' inside an XML CDATA block."; public const string Xml_NotTheFirst = "WriteStartDocument needs to be the first call."; public const string Xml_InvalidPiChars = "Cannot have '?>' inside an XML processing instruction."; public const string Xml_InvalidNameChars = "Invalid name character in '{0}'."; public const string Xml_Closed = "The Writer is closed."; public const string Xml_InvalidPrefix = "Prefixes beginning with \"xml\" (regardless of whether the characters are uppercase, lowercase, or some combination thereof) are reserved for use by XML."; public const string Xml_InvalidIndentation = "Indentation value must be greater than 0."; public const string Xml_NotInWriteState = "NotInWriteState."; public const string Xml_SurrogatePairSplit = "The second character surrogate pair is not in the input buffer to be written."; public const string Xml_NoMultipleRoots = "Document cannot have multiple document elements."; public const string XmlBadName = "A node of type '{0}' cannot have the name '{1}'."; public const string XmlNoNameAllowed = "A node of type '{0}' cannot have a name."; public const string XmlConvert_BadUri = "The string was not recognized as a valid Uri."; public const string XmlConvert_BadFormat = "The string '{0}' is not a valid {1} value."; public const string XmlConvert_Overflow = "Value '{0}' was either too large or too small for {1}."; public const string XmlConvert_TypeBadMapping = "Xml type '{0}' does not support Clr type '{1}'."; public const string XmlConvert_TypeBadMapping2 = "Xml type '{0}' does not support a conversion from Clr type '{1}' to Clr type '{2}'."; public const string XmlConvert_TypeListBadMapping = "Xml type 'List of {0}' does not support Clr type '{1}'."; public const string XmlConvert_TypeListBadMapping2 = "Xml type 'List of {0}' does not support a conversion from Clr type '{1}' to Clr type '{2}'."; public const string XmlConvert_TypeToString = "Xml type '{0}' cannot convert from Clr type '{1}' unless the destination type is String or XmlAtomicValue."; public const string XmlConvert_TypeFromString = "Xml type '{0}' cannot convert to Clr type '{1}' unless the source value is a String or an XmlAtomicValue."; public const string XmlConvert_TypeNoPrefix = "The QName '{0}' cannot be represented as a String. A prefix for namespace '{1}' cannot be found."; public const string XmlConvert_TypeNoNamespace = "The String '{0}' cannot be represented as an XmlQualifiedName. A namespace for prefix '{1}' cannot be found."; public const string XmlConvert_NotOneCharString = "String must be exactly one character long."; public const string Sch_ParEntityRefNesting = "The parameter entity replacement text must nest properly within markup declarations."; public const string Sch_NotTokenString = "line-feed (#xA) or tab (#x9) characters, leading or trailing spaces and sequences of one or more spaces (#x20) are not allowed in 'xs:token'."; public const string Sch_InvalidDateTimeOption = "The '{0}' value for the 'dateTimeOption' parameter is not an allowed value for the 'XmlDateTimeSerializationMode' enumeration."; public const string Sch_StandAloneNormalization = "StandAlone is 'yes' and the value of the attribute '{0}' contains a definition in an external document that changes on normalization."; public const string Sch_UnSpecifiedDefaultAttributeInExternalStandalone = "Markup for unspecified default attribute '{0}' is external and standalone='yes'."; public const string Sch_DefaultException = "A schema error occurred."; public const string Sch_DupElementDecl = "The '{0}' element has already been declared."; public const string Sch_IdAttrDeclared = "The attribute of type ID is already declared on the '{0}' element."; public const string Sch_RootMatchDocType = "Root element name must match the DocType name."; public const string Sch_DupId = "'{0}' is already used as an ID."; public const string Sch_UndeclaredElement = "The '{0}' element is not declared."; public const string Sch_UndeclaredAttribute = "The '{0}' attribute is not declared."; public const string Sch_UndeclaredNotation = "The '{0}' notation is not declared."; public const string Sch_UndeclaredId = "Reference to undeclared ID is '{0}'."; public const string Sch_SchemaRootExpected = "Expected schema root. Make sure the root element is <schema> and the namespace is 'http://www.w3.org/2001/XMLSchema' for an XSD schema or 'urn:schemas-microsoft-com:xml-data' for an XDR schema."; public const string Sch_XSDSchemaRootExpected = "The root element of a W3C XML Schema should be <schema> and its namespace should be 'http://www.w3.org/2001/XMLSchema'."; public const string Sch_UnsupportedAttribute = "The '{0}' attribute is not supported in this context."; public const string Sch_UnsupportedElement = "The '{0}' element is not supported in this context."; public const string Sch_MissAttribute = "The '{0}' attribute is either invalid or missing."; public const string Sch_AnnotationLocation = "The 'annotation' element cannot appear at this location."; public const string Sch_DataTypeTextOnly = "Content must be \"textOnly\" when using DataType on an ElementType."; public const string Sch_UnknownModel = "The model attribute must have a value of open or closed, not '{0}'."; public const string Sch_UnknownOrder = "The order attribute must have a value of 'seq', 'one', or 'many', not '{0}'."; public const string Sch_UnknownContent = "The content attribute must have a value of 'textOnly', 'eltOnly', 'mixed', or 'empty', not '{0}'."; public const string Sch_UnknownRequired = "The required attribute must have a value of yes or no."; public const string Sch_UnknownDtType = "Reference to an unknown data type, '{0}'."; public const string Sch_MixedMany = "The order must be many when content is mixed."; public const string Sch_GroupDisabled = "The group is not allowed when ElementType has empty or textOnly content."; public const string Sch_MissDtvalue = "The DataType value cannot be empty."; public const string Sch_MissDtvaluesAttribute = "The dt:values attribute is missing."; public const string Sch_DupDtType = "Data type has already been declared."; public const string Sch_DupAttribute = "The '{0}' attribute has already been declared for this ElementType."; public const string Sch_RequireEnumeration = "Data type should be enumeration when the values attribute is present."; public const string Sch_DefaultIdValue = "An attribute or element of type xs:ID or derived from xs:ID, should not have a value constraint."; public const string Sch_ElementNotAllowed = "Element is not allowed when the content is empty or textOnly."; public const string Sch_ElementMissing = "There is a missing element."; public const string Sch_ManyMaxOccurs = "When the order is many, the maxOccurs attribute must have a value of '*'."; public const string Sch_MaxOccursInvalid = "The maxOccurs attribute must have a value of 1 or *."; public const string Sch_MinOccursInvalid = "The minOccurs attribute must have a value of 0 or 1."; public const string Sch_DtMaxLengthInvalid = "The value '{0}' is invalid for dt:maxLength."; public const string Sch_DtMinLengthInvalid = "The value '{0}' is invalid for dt:minLength."; public const string Sch_DupDtMaxLength = "The value of maxLength has already been declared."; public const string Sch_DupDtMinLength = "The value of minLength has already been declared."; public const string Sch_DtMinMaxLength = "The maxLength value must be equal to or greater than the minLength value."; public const string Sch_DupElement = "The '{0}' element already exists in the content model."; public const string Sch_DupGroupParticle = "The content model can only have one of the following; 'all', 'choice', or 'sequence'."; public const string Sch_InvalidValue = "The value '{0}' is invalid according to its data type."; public const string Sch_InvalidValueDetailed = "The value '{0}' is invalid according to its schema type '{1}' - {2}"; public const string Sch_InvalidValueDetailedAttribute = "The attribute '{0}' has an invalid value '{1}' according to its schema type '{2}' - {3}"; public const string Sch_MissRequiredAttribute = "The required attribute '{0}' is missing."; public const string Sch_FixedAttributeValue = "The value of the '{0}' attribute does not equal its fixed value."; public const string Sch_FixedElementValue = "The value of the '{0}' element does not equal its fixed value."; public const string Sch_AttributeValueDataTypeDetailed = "The '{0}' attribute is invalid - The value '{1}' is invalid according to its datatype '{2}' - {3}"; public const string Sch_AttributeDefaultDataType = "The default value of '{0}' attribute is invalid according to its datatype."; public const string Sch_IncludeLocation = "The 'include' element cannot appear at this location."; public const string Sch_ImportLocation = "The 'import' element cannot appear at this location."; public const string Sch_RedefineLocation = "The 'redefine' element cannot appear at this location."; public const string Sch_InvalidBlockDefaultValue = "The values 'list' and 'union' are invalid for the blockDefault attribute."; public const string Sch_InvalidFinalDefaultValue = "The value 'substitution' is invalid for the finalDefault attribute."; public const string Sch_InvalidElementBlockValue = "The values 'list' and 'union' are invalid for the block attribute on element."; public const string Sch_InvalidElementFinalValue = "The values 'substitution', 'list', and 'union' are invalid for the final attribute on element."; public const string Sch_InvalidSimpleTypeFinalValue = "The values 'substitution' and 'extension' are invalid for the final attribute on simpleType."; public const string Sch_InvalidComplexTypeBlockValue = "The values 'substitution', 'list', and 'union' are invalid for the block attribute on complexType."; public const string Sch_InvalidComplexTypeFinalValue = "The values 'substitution', 'list', and 'union' are invalid for the final attribute on complexType."; public const string Sch_DupIdentityConstraint = "The identity constraint '{0}' has already been declared."; public const string Sch_DupGlobalElement = "The global element '{0}' has already been declared."; public const string Sch_DupGlobalAttribute = "The global attribute '{0}' has already been declared."; public const string Sch_DupSimpleType = "The simpleType '{0}' has already been declared."; public const string Sch_DupComplexType = "The complexType '{0}' has already been declared."; public const string Sch_DupGroup = "The group '{0}' has already been declared."; public const string Sch_DupAttributeGroup = "The attributeGroup '{0}' has already been declared."; public const string Sch_DupNotation = "The notation '{0}' has already been declared."; public const string Sch_DefaultFixedAttributes = "The fixed and default attributes cannot both be present."; public const string Sch_FixedInRef = "The fixed value constraint on the '{0}' attribute reference must match the fixed value constraint on the declaration."; public const string Sch_FixedDefaultInRef = "The default value constraint cannot be present on the '{0}' attribute reference if the fixed value constraint is present on the declaration."; public const string Sch_DupXsdElement = "'{0}' is a duplicate XSD element."; public const string Sch_ForbiddenAttribute = "The '{0}' attribute cannot be present."; public const string Sch_AttributeIgnored = "The '{0}' attribute is ignored, because the value of 'prohibited' for attribute use only prevents inheritance of an identically named attribute from the base type definition."; public const string Sch_ElementRef = "When the ref attribute is present, the type attribute and complexType, simpleType, key, keyref, and unique elements cannot be present."; public const string Sch_TypeMutualExclusive = "The type attribute cannot be present with either simpleType or complexType."; public const string Sch_ElementNameRef = "For element declaration, either the name or the ref attribute must be present."; public const string Sch_AttributeNameRef = "For attribute '{0}', either the name or the ref attribute must be present, but not both."; public const string Sch_TextNotAllowed = "The following text is not allowed in this context: '{0}'."; public const string Sch_UndeclaredType = "Type '{0}' is not declared."; public const string Sch_UndeclaredSimpleType = "Type '{0}' is not declared, or is not a simple type."; public const string Sch_UndeclaredEquivClass = "Substitution group refers to '{0}', an undeclared element."; public const string Sch_AttListPresence = "An attribute of type ID must have a declared default of either #IMPLIED or #REQUIRED."; public const string Sch_NotationValue = "'{0}' is not in the notation list."; public const string Sch_EnumerationValue = "'{0}' is not in the enumeration list."; public const string Sch_EmptyAttributeValue = "The attribute value cannot be empty."; public const string Sch_InvalidLanguageId = "'{0}' is an invalid language identifier."; public const string Sch_XmlSpace = "Invalid xml:space syntax."; public const string Sch_InvalidXsdAttributeValue = "'{1}' is an invalid value for the '{0}' attribute."; public const string Sch_InvalidXsdAttributeDatatypeValue = "The value for the '{0}' attribute is invalid - {1}"; public const string Sch_ElementValueDataTypeDetailed = "The '{0}' element is invalid - The value '{1}' is invalid according to its datatype '{2}' - {3}"; public const string Sch_InvalidElementDefaultValue = "The default value '{0}' of element '{1}' is invalid according to the type specified by xsi:type."; public const string Sch_NonDeterministic = "Multiple definition of element '{0}' causes the content model to become ambiguous. A content model must be formed such that during validation of an element information item sequence, the particle contained directly, indirectly or implicitly therein with which to attempt to validate each item in the sequence in turn can be uniquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence."; public const string Sch_NonDeterministicAnyEx = "Wildcard '{0}' allows element '{1}', and causes the content model to become ambiguous. A content model must be formed such that during validation of an element information item sequence, the particle contained directly, indirectly or implicitly therein with which to attempt to validate each item in the sequence in turn can be uniquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence."; public const string Sch_NonDeterministicAnyAny = "Wildcards '{0}' and '{1}' have not empty intersection, and causes the content model to become ambiguous. A content model must be formed such that during validation of an element information item sequence, the particle contained directly, indirectly or implicitly therein with which to attempt to validate each item in the sequence in turn can be uniquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence."; public const string Sch_StandAlone = "The standalone document declaration must have a value of 'no'."; public const string Sch_XmlNsAttribute = "The value 'xmlns' cannot be used as the name of an attribute declaration."; public const string Sch_AllElement = "Element '{0}' cannot appear more than once if content model type is \"all\"."; public const string Sch_MismatchTargetNamespaceInclude = "The targetNamespace '{0}' of included/redefined schema should be the same as the targetNamespace '{1}' of the including schema."; public const string Sch_MismatchTargetNamespaceImport = "The namespace attribute '{0}' of an import should be the same value as the targetNamespace '{1}' of the imported schema."; public const string Sch_MismatchTargetNamespaceEx = "The targetNamespace parameter '{0}' should be the same value as the targetNamespace '{1}' of the schema."; public const string Sch_XsiTypeNotFound = "This is an invalid xsi:type '{0}'."; public const string Sch_XsiTypeAbstract = "The xsi:type '{0}' cannot be abstract."; public const string Sch_ListFromNonatomic = "A list data type must be derived from an atomic or union data type."; public const string Sch_UnionFromUnion = "It is an error if a union type has a member with variety union and this member cannot be substituted with its own members. This may be due to the fact that the union member is a restriction of a union with facets."; public const string Sch_DupLengthFacet = "This is a duplicate Length constraining facet."; public const string Sch_DupMinLengthFacet = "This is a duplicate MinLength constraining facet."; public const string Sch_DupMaxLengthFacet = "This is a duplicate MaxLength constraining facet."; public const string Sch_DupWhiteSpaceFacet = "This is a duplicate WhiteSpace constraining facet."; public const string Sch_DupMaxInclusiveFacet = "This is a duplicate MaxInclusive constraining facet."; public const string Sch_DupMaxExclusiveFacet = "This is a duplicate MaxExclusive constraining facet."; public const string Sch_DupMinInclusiveFacet = "This is a duplicate MinInclusive constraining facet."; public const string Sch_DupMinExclusiveFacet = "This is a duplicate MinExclusive constraining facet."; public const string Sch_DupTotalDigitsFacet = "This is a duplicate TotalDigits constraining facet."; public const string Sch_DupFractionDigitsFacet = "This is a duplicate FractionDigits constraining facet."; public const string Sch_LengthFacetProhibited = "The length constraining facet is prohibited for '{0}'."; public const string Sch_MinLengthFacetProhibited = "The MinLength constraining facet is prohibited for '{0}'."; public const string Sch_MaxLengthFacetProhibited = "The MaxLength constraining facet is prohibited for '{0}'."; public const string Sch_PatternFacetProhibited = "The Pattern constraining facet is prohibited for '{0}'."; public const string Sch_EnumerationFacetProhibited = "The Enumeration constraining facet is prohibited for '{0}'."; public const string Sch_WhiteSpaceFacetProhibited = "The WhiteSpace constraining facet is prohibited for '{0}'."; public const string Sch_MaxInclusiveFacetProhibited = "The MaxInclusive constraining facet is prohibited for '{0}'."; public const string Sch_MaxExclusiveFacetProhibited = "The MaxExclusive constraining facet is prohibited for '{0}'."; public const string Sch_MinInclusiveFacetProhibited = "The MinInclusive constraining facet is prohibited for '{0}'."; public const string Sch_MinExclusiveFacetProhibited = "The MinExclusive constraining facet is prohibited for '{0}'."; public const string Sch_TotalDigitsFacetProhibited = "The TotalDigits constraining facet is prohibited for '{0}'."; public const string Sch_FractionDigitsFacetProhibited = "The FractionDigits constraining facet is prohibited for '{0}'."; public const string Sch_LengthFacetInvalid = "The Length constraining facet is invalid - {0}"; public const string Sch_MinLengthFacetInvalid = "The MinLength constraining facet is invalid - {0}"; public const string Sch_MaxLengthFacetInvalid = "The MaxLength constraining facet is invalid - {0}"; public const string Sch_MaxInclusiveFacetInvalid = "The MaxInclusive constraining facet is invalid - {0}"; public const string Sch_MaxExclusiveFacetInvalid = "The MaxExclusive constraining facet is invalid - {0}"; public const string Sch_MinInclusiveFacetInvalid = "The MinInclusive constraining facet is invalid - {0}"; public const string Sch_MinExclusiveFacetInvalid = "The MinExclusive constraining facet is invalid - {0}"; public const string Sch_TotalDigitsFacetInvalid = "The TotalDigits constraining facet is invalid - {0}"; public const string Sch_FractionDigitsFacetInvalid = "The FractionDigits constraining facet is invalid - {0}"; public const string Sch_PatternFacetInvalid = "The Pattern constraining facet is invalid - {0}"; public const string Sch_EnumerationFacetInvalid = "The Enumeration constraining facet is invalid - {0}"; public const string Sch_InvalidWhiteSpace = "The whitespace character, '{0}', is invalid."; public const string Sch_UnknownFacet = "This is an unknown facet."; public const string Sch_LengthAndMinMax = "It is an error for both length and minLength or maxLength to be present."; public const string Sch_MinLengthGtMaxLength = "MinLength is greater than MaxLength."; public const string Sch_FractionDigitsGtTotalDigits = "FractionDigits is greater than TotalDigits."; public const string Sch_LengthConstraintFailed = "The actual length is not equal to the specified length."; public const string Sch_MinLengthConstraintFailed = "The actual length is less than the MinLength value."; public const string Sch_MaxLengthConstraintFailed = "The actual length is greater than the MaxLength value."; public const string Sch_PatternConstraintFailed = "The Pattern constraint failed."; public const string Sch_EnumerationConstraintFailed = "The Enumeration constraint failed."; public const string Sch_MaxInclusiveConstraintFailed = "The MaxInclusive constraint failed."; public const string Sch_MaxExclusiveConstraintFailed = "The MaxExclusive constraint failed."; public const string Sch_MinInclusiveConstraintFailed = "The MinInclusive constraint failed."; public const string Sch_MinExclusiveConstraintFailed = "The MinExclusive constraint failed."; public const string Sch_TotalDigitsConstraintFailed = "The TotalDigits constraint failed."; public const string Sch_FractionDigitsConstraintFailed = "The FractionDigits constraint failed."; public const string Sch_UnionFailedEx = "The value '{0}' is not valid according to any of the memberTypes of the union."; public const string Sch_NotationRequired = "NOTATION cannot be used directly in a schema; only data types derived from NOTATION by specifying an enumeration value can be used in a schema. All enumeration facet values must match the name of a notation declared in the current schema."; public const string Sch_DupNotationAttribute = "No element type can have more than one NOTATION attribute specified."; public const string Sch_MissingPublicSystemAttribute = "NOTATION must have either the Public or System attribute present."; public const string Sch_NotationAttributeOnEmptyElement = "An attribute of type NOTATION must not be declared on an element declared EMPTY."; public const string Sch_RefNotInScope = "The Keyref '{0}' cannot find the referred key or unique in scope."; public const string Sch_UndeclaredIdentityConstraint = "The '{0}' identity constraint is not declared."; public const string Sch_RefInvalidIdentityConstraint = "Reference to an invalid identity constraint, '{0}'."; public const string Sch_RefInvalidCardin = "Keyref '{0}' has different cardinality as the referred key or unique element."; public const string Sch_ReftoKeyref = "The '{0}' Keyref can refer to key or unique only."; public const string Sch_EmptyXPath = "The XPath for selector or field cannot be empty."; public const string Sch_UnresolvedPrefix = "The prefix '{0}' in XPath cannot be resolved."; public const string Sch_UnresolvedKeyref = "The key sequence '{0}' in '{1}' Keyref fails to refer to some key."; public const string Sch_ICXpathError = "'{0}' is an invalid XPath for selector or field."; public const string Sch_SelectorAttr = "'{0}' is an invalid XPath for selector. Selector cannot have an XPath selection with an attribute node."; public const string Sch_FieldSimpleTypeExpected = "The field '{0}' is expecting an element or attribute with simple type or simple content."; public const string Sch_FieldSingleValueExpected = "The field '{0}' is expecting at the most one value."; public const string Sch_MissingKey = "The identity constraint '{0}' validation has failed. Either a key is missing or the existing key has an empty node."; public const string Sch_DuplicateKey = "There is a duplicate key sequence '{0}' for the '{1}' key or unique identity constraint."; public const string Sch_TargetNamespaceXsi = "The target namespace of an attribute declaration, whether local or global, must not match http://www.w3.org/2001/XMLSchema-instance."; public const string Sch_UndeclaredEntity = "Reference to an undeclared entity, '{0}'."; public const string Sch_UnparsedEntityRef = "Reference to an unparsed entity, '{0}'."; public const string Sch_MaxOccursInvalidXsd = "The value for the 'maxOccurs' attribute must be xsd:nonNegativeInteger or 'unbounded'."; public const string Sch_MinOccursInvalidXsd = "The value for the 'minOccurs' attribute must be xsd:nonNegativeInteger."; public const string Sch_MaxInclusiveExclusive = "'maxInclusive' and 'maxExclusive' cannot both be specified for the same data type."; public const string Sch_MinInclusiveExclusive = "'minInclusive' and 'minExclusive' cannot both be specified for the same data type."; public const string Sch_MinInclusiveGtMaxInclusive = "The value specified for 'minInclusive' cannot be greater than the value specified for 'maxInclusive' for the same data type."; public const string Sch_MinExclusiveGtMaxExclusive = "The value specified for 'minExclusive' cannot be greater than the value specified for 'maxExclusive' for the same data type."; public const string Sch_MinInclusiveGtMaxExclusive = "The value specified for 'minInclusive' cannot be greater than the value specified for 'maxExclusive' for the same data type."; public const string Sch_MinExclusiveGtMaxInclusive = "The value specified for 'minExclusive' cannot be greater than the value specified for 'maxInclusive' for the same data type."; public const string Sch_SimpleTypeRestriction = "'simpleType' should be the first child of restriction."; public const string Sch_InvalidFacetPosition = "Facet should go before 'attribute', 'attributeGroup', or 'anyAttribute'."; public const string Sch_AttributeMutuallyExclusive = "'{0}' and content model are mutually exclusive."; public const string Sch_AnyAttributeLastChild = "'anyAttribute' must be the last child."; public const string Sch_ComplexTypeContentModel = "The content model of a complex type must consist of 'annotation' (if present); followed by zero or one of the following: 'simpleContent', 'complexContent', 'group', 'choice', 'sequence', or 'all'; followed by zero or more 'attribute' or 'attributeGroup'; followed by zero or one 'anyAttribute'."; public const string Sch_ComplexContentContentModel = "Complex content restriction or extension should consist of zero or one of 'group', 'choice', 'sequence', or 'all'; followed by zero or more 'attribute' or 'attributeGroup'; followed by zero or one 'anyAttribute'."; public const string Sch_NotNormalizedString = "Carriage return (#xD), line feed (#xA), and tab (#x9) characters are not allowed in xs:normalizedString."; public const string Sch_FractionDigitsNotOnDecimal = "FractionDigits should be equal to 0 on types other then decimal."; public const string Sch_ContentInNill = "Element '{0}' must have no character or element children."; public const string Sch_NoElementSchemaFound = "Could not find schema information for the element '{0}'."; public const string Sch_NoAttributeSchemaFound = "Could not find schema information for the attribute '{0}'."; public const string Sch_InvalidNamespace = "The Namespace '{0}' is an invalid URI."; public const string Sch_InvalidTargetNamespaceAttribute = "The targetNamespace attribute cannot have empty string as its value."; public const string Sch_InvalidNamespaceAttribute = "The namespace attribute cannot have empty string as its value."; public const string Sch_InvalidSchemaLocation = "The SchemaLocation '{0}' is an invalid URI."; public const string Sch_ImportTargetNamespace = "Namespace attribute of an import must not match the real value of the enclosing targetNamespace of the <schema>."; public const string Sch_ImportTargetNamespaceNull = "The enclosing <schema> must have a targetNamespace, if the Namespace attribute is absent on the import element."; public const string Sch_GroupDoubleRedefine = "Double redefine for group."; public const string Sch_ComponentRedefineNotFound = "Cannot find a {0} with name '{1}' to redefine."; public const string Sch_GroupRedefineNotFound = "No group to redefine."; public const string Sch_AttrGroupDoubleRedefine = "Double redefine for attribute group."; public const string Sch_AttrGroupRedefineNotFound = "No attribute group to redefine."; public const string Sch_ComplexTypeDoubleRedefine = "Double redefine for complex type."; public const string Sch_ComplexTypeRedefineNotFound = "No complex type to redefine."; public const string Sch_SimpleToComplexTypeRedefine = "Cannot redefine a simple type as complex type."; public const string Sch_SimpleTypeDoubleRedefine = "Double redefine for simple type."; public const string Sch_ComplexToSimpleTypeRedefine = "Cannot redefine a complex type as simple type."; public const string Sch_SimpleTypeRedefineNotFound = "No simple type to redefine."; public const string Sch_MinMaxGroupRedefine = "When group is redefined, the real value of both minOccurs and maxOccurs attribute must be 1 (or absent)."; public const string Sch_MultipleGroupSelfRef = "Multiple self-reference within a group is redefined."; public const string Sch_MultipleAttrGroupSelfRef = "Multiple self-reference within an attribute group is redefined."; public const string Sch_InvalidTypeRedefine = "If type is being redefined, the base type has to be self-referenced."; public const string Sch_InvalidElementRef = "If ref is present, all of <complexType>, <simpleType>, <key>, <keyref>, <unique>, nillable, default, fixed, form, block, and type must be absent."; public const string Sch_MinGtMax = "minOccurs value cannot be greater than maxOccurs value."; public const string Sch_DupSelector = "Selector cannot appear twice in one identity constraint."; public const string Sch_IdConstraintNoSelector = "Selector must be present."; public const string Sch_IdConstraintNoFields = "At least one field must be present."; public const string Sch_IdConstraintNoRefer = "The referring attribute must be present."; public const string Sch_SelectorBeforeFields = "Cannot define fields before selector."; public const string Sch_NoSimpleTypeContent = "SimpleType content is missing."; public const string Sch_SimpleTypeRestRefBase = "SimpleType restriction should have either the base attribute or a simpleType child, but not both."; public const string Sch_SimpleTypeRestRefBaseNone = "SimpleType restriction should have either the base attribute or a simpleType child to indicate the base type for the derivation."; public const string Sch_SimpleTypeListRefBase = "SimpleType list should have either the itemType attribute or a simpleType child, but not both."; public const string Sch_SimpleTypeListRefBaseNone = "SimpleType list should have either the itemType attribute or a simpleType child to indicate the itemType of the list. "; public const string Sch_SimpleTypeUnionNoBase = "Either the memberTypes attribute must be non-empty or there must be at least one simpleType child."; public const string Sch_NoRestOrExtQName = "'restriction' or 'extension' child is required for complexType '{0}' in namespace '{1}', because it has a simpleContent or complexContent child."; public const string Sch_NoRestOrExt = "'restriction' or 'extension' child is required for complexType with simpleContent or complexContent child."; public const string Sch_NoGroupParticle = "'sequence', 'choice', or 'all' child is required."; public const string Sch_InvalidAllMin = "'all' must have 'minOccurs' value of 0 or 1."; public const string Sch_InvalidAllMax = "'all' must have {max occurs}=1."; public const string Sch_InvalidFacet = "The 'value' attribute must be present in facet."; public const string Sch_AbstractElement = "The element '{0}' is abstract or its type is abstract."; public const string Sch_XsiTypeBlockedEx = "The xsi:type attribute value '{0}' is not valid for the element '{1}', either because it is not a type validly derived from the type in the schema, or because it has xsi:type derivation blocked."; public const string Sch_InvalidXsiNill = "If the 'nillable' attribute is false in the schema, the 'xsi:nil' attribute must not be present in the instance."; public const string Sch_SubstitutionNotAllowed = "Element '{0}' cannot substitute in place of head element '{1}' because it has block='substitution'."; public const string Sch_SubstitutionBlocked = "Member element {0}'s type cannot be derived by restriction or extension from head element {1}'s type, because it has block='restriction' or 'extension'."; public const string Sch_InvalidElementInEmptyEx = "The element '{0}' cannot contain child element '{1}' because the parent element's content model is empty."; public const string Sch_InvalidElementInTextOnlyEx = "The element '{0}' cannot contain child element '{1}' because the parent element's content model is text only."; public const string Sch_InvalidTextInElement = "The element {0} cannot contain text."; public const string Sch_InvalidElementContent = "The element {0} has invalid child element {1}."; public const string Sch_InvalidElementContentComplex = "The element {0} has invalid child element {1} - {2}"; public const string Sch_IncompleteContent = "The element {0} has incomplete content."; public const string Sch_IncompleteContentComplex = "The element {0} has incomplete content - {2}"; public const string Sch_InvalidTextInElementExpecting = "The element {0} cannot contain text. List of possible elements expected: {1}."; public const string Sch_InvalidElementContentExpecting = "The element {0} has invalid child element {1}. List of possible elements expected: {2}."; public const string Sch_InvalidElementContentExpectingComplex = "The element {0} has invalid child element {1}. List of possible elements expected: {2}. {3}"; public const string Sch_IncompleteContentExpecting = "The element {0} has incomplete content. List of possible elements expected: {1}."; public const string Sch_IncompleteContentExpectingComplex = "The element {0} has incomplete content. List of possible elements expected: {1}. {2}"; public const string Sch_InvalidElementSubstitution = "The element {0} cannot substitute for a local element {1} expected in that position."; public const string Sch_ElementNameAndNamespace = "'{0}' in namespace '{1}'"; public const string Sch_ElementName = "'{0}'"; public const string Sch_ContinuationString = "{0}as well as "; public const string Sch_AnyElementNS = "any element in namespace '{0}'"; public const string Sch_AnyElement = "any element"; public const string Sch_InvalidTextInEmpty = "The element cannot contain text. Content model is empty."; public const string Sch_InvalidWhitespaceInEmpty = "The element cannot contain whitespace. Content model is empty."; public const string Sch_InvalidPIComment = "The element cannot contain comment or processing instruction. Content model is empty."; public const string Sch_InvalidAttributeRef = "If ref is present, all of 'simpleType', 'form', 'type', and 'use' must be absent."; public const string Sch_OptionalDefaultAttribute = "The 'use' attribute must be optional (or absent) if the default attribute is present."; public const string Sch_AttributeCircularRef = "Circular attribute reference."; public const string Sch_IdentityConstraintCircularRef = "Circular identity constraint reference."; public const string Sch_SubstitutionCircularRef = "Circular substitution group affiliation."; public const string Sch_InvalidAnyAttribute = "Invalid namespace in 'anyAttribute'."; public const string Sch_DupIdAttribute = "Duplicate ID attribute."; public const string Sch_InvalidAllElementMax = "The {max occurs} of all the particles in the {particles} of an all group must be 0 or 1."; public const string Sch_InvalidAny = "Invalid namespace in 'any'."; public const string Sch_InvalidAnyDetailed = "The value of the namespace attribute of the element or attribute wildcard is invalid - {0}"; public const string Sch_InvalidExamplar = "Cannot be nominated as the {substitution group affiliation} of any other declaration."; public const string Sch_NoExamplar = "Reference to undeclared substitution group affiliation."; public const string Sch_InvalidSubstitutionMember = "'{0}' cannot be a member of substitution group with head element '{1}'."; public const string Sch_RedefineNoSchema = "'SchemaLocation' must successfully resolve if <redefine> contains any child other than <annotation>."; public const string Sch_ProhibitedAttribute = "The '{0}' attribute is not allowed."; public const string Sch_TypeCircularRef = "Circular type reference."; public const string Sch_TwoIdAttrUses = "Two distinct members of the attribute uses must not have type definitions which are both xs:ID or are derived from xs:ID."; public const string Sch_AttrUseAndWildId = "It is an error if there is a member of the attribute uses of a type definition with type xs:ID or derived from xs:ID and another attribute with type xs:ID matches an attribute wildcard."; public const string Sch_MoreThanOneWildId = "It is an error if more than one attribute whose type is xs:ID or is derived from xs:ID, matches an attribute wildcard on an element."; public const string Sch_BaseFinalExtension = "The base type is the final extension."; public const string Sch_NotSimpleContent = "The content type of the base type must be a simple type definition or it must be mixed, and simpleType child must be present."; public const string Sch_NotComplexContent = "The content type of the base type must not be a simple type definition."; public const string Sch_BaseFinalRestriction = "The base type is final restriction."; public const string Sch_BaseFinalList = "The base type is the final list."; public const string Sch_BaseFinalUnion = "The base type is the final union."; public const string Sch_UndefBaseRestriction = "Undefined complexType '{0}' is used as a base for complex type restriction."; public const string Sch_UndefBaseExtension = "Undefined complexType '{0}' is used as a base for complex type extension."; public const string Sch_DifContentType = "The derived type and the base type must have the same content type."; public const string Sch_InvalidContentRestriction = "Invalid content type derivation by restriction."; public const string Sch_InvalidContentRestrictionDetailed = "Invalid content type derivation by restriction. {0}"; public const string Sch_InvalidBaseToEmpty = "If the derived content type is Empty, then the base content type should also be Empty or Mixed with Emptiable particle according to rule 5.3 of Schema Component Constraint: Derivation Valid (Restriction, Complex)."; public const string Sch_InvalidBaseToMixed = "If the derived content type is Mixed, then the base content type should also be Mixed according to rule 5.4 of Schema Component Constraint: Derivation Valid (Restriction, Complex)."; public const string Sch_DupAttributeUse = "The attribute '{0}' already exists."; public const string Sch_InvalidParticleRestriction = "Invalid particle derivation by restriction."; public const string Sch_InvalidParticleRestrictionDetailed = "Invalid particle derivation by restriction - '{0}'."; public const string Sch_ForbiddenDerivedParticleForAll = "'Choice' or 'any' is forbidden as derived particle when the base particle is 'all'."; public const string Sch_ForbiddenDerivedParticleForElem = "Only 'element' is valid as derived particle when the base particle is 'element'."; public const string Sch_ForbiddenDerivedParticleForChoice = "'All' or 'any' is forbidden as derived particle when the base particle is 'choice'."; public const string Sch_ForbiddenDerivedParticleForSeq = "'All', 'any', and 'choice' are forbidden as derived particles when the base particle is 'sequence'."; public const string Sch_ElementFromElement = "Derived element '{0}' is not a valid restriction of base element '{1}' according to Elt:Elt -- NameAndTypeOK."; public const string Sch_ElementFromAnyRule1 = "The namespace of element '{0}'is not valid with respect to the wildcard's namespace constraint in the base, Elt:Any -- NSCompat Rule 1."; public const string Sch_ElementFromAnyRule2 = "The occurrence range of element '{0}'is not a valid restriction of the wildcard's occurrence range in the base, Elt:Any -- NSCompat Rule2."; public const string Sch_AnyFromAnyRule1 = "The derived wildcard's occurrence range is not a valid restriction of the base wildcard's occurrence range, Any:Any -- NSSubset Rule 1."; public const string Sch_AnyFromAnyRule2 = "The derived wildcard's namespace constraint must be an intensional subset of the base wildcard's namespace constraint, Any:Any -- NSSubset Rule2."; public const string Sch_AnyFromAnyRule3 = "The derived wildcard's 'processContents' must be identical to or stronger than the base wildcard's 'processContents', where 'strict' is stronger than 'lax' and 'lax' is stronger than 'skip', Any:Any -- NSSubset Rule 3."; public const string Sch_GroupBaseFromAny1 = "Every member of the derived group particle must be a valid restriction of the base wildcard, NSRecurseCheckCardinality Rule 1."; public const string Sch_GroupBaseFromAny2 = "The derived particle's occurrence range at ({0}, {1}) is not a valid restriction of the base wildcard's occurrence range at ({2}, {3}), NSRecurseCheckCardinality Rule 2."; public const string Sch_ElementFromGroupBase1 = "The derived element {0} at ({1}, {2}) is not a valid restriction of the base sequence particle at ({3}, {4}) according to Elt:All/Choice/Sequence -- RecurseAsIfGroup."; public const string Sch_ElementFromGroupBase2 = "The derived element {0} at ({1}, {2}) is not a valid restriction of the base choice particle at ({3}, {4}) according to Elt:All/Choice/Sequence -- RecurseAsIfGroup."; public const string Sch_ElementFromGroupBase3 = "The derived element {0} at ({1}, {2}) is not a valid restriction of the base all particle at ({3}, {4}) according to Elt:All/Choice/Sequence -- RecurseAsIfGroup."; public const string Sch_GroupBaseRestRangeInvalid = "The derived particle's range is not a valid restriction of the base particle's range according to All:All,Sequence:Sequence -- Recurse Rule 1 or Choice:Choice -- RecurseLax."; public const string Sch_GroupBaseRestNoMap = "The derived particle cannot have more members than the base particle - All:All,Sequence:Sequence -- Recurse Rule 2 / Choice:Choice -- RecurseLax."; public const string Sch_GroupBaseRestNotEmptiable = "All particles in the {particles} of the base particle which are not mapped to by any particle in the {particles} of the derived particle should be emptiable - All:All,Sequence:Sequence -- Recurse Rule 2 / Choice:Choice -- RecurseLax."; public const string Sch_SeqFromAll = "The derived sequence particle at ({0}, {1}) is not a valid restriction of the base all particle at ({2}, {3}) according to Sequence:All -- RecurseUnordered."; public const string Sch_SeqFromChoice = "The derived sequence particle at ({0}, {1}) is not a valid restriction of the base choice particle at ({2}, {3}) according to Sequence:Choice -- MapAndSum."; public const string Sch_UndefGroupRef = "Reference to undeclared model group '{0}'."; public const string Sch_GroupCircularRef = "Circular group reference."; public const string Sch_AllRefNotRoot = "The group ref to 'all' is not the root particle, or it is being used as an extension."; public const string Sch_AllRefMinMax = "The group ref to 'all' must have {min occurs}= 0 or 1 and {max occurs}=1."; public const string Sch_NotAllAlone = "'all' is not the only particle in a group, or is being used as an extension."; public const string Sch_AttributeGroupCircularRef = "Circular attribute group reference."; public const string Sch_UndefAttributeGroupRef = "Reference to undeclared attribute group '{0}'."; public const string Sch_InvalidAttributeExtension = "Invalid attribute extension."; public const string Sch_InvalidAnyAttributeRestriction = "The base any attribute must be a superset of the derived 'anyAttribute'."; public const string Sch_AttributeRestrictionProhibited = "Invalid attribute restriction. Attribute restriction is prohibited in base type."; public const string Sch_AttributeRestrictionInvalid = "Invalid attribute restriction. Derived attribute's type is not a valid restriction of the base attribute's type."; public const string Sch_AttributeFixedInvalid = "Invalid attribute restriction. Derived attribute's fixed value must be the same as the base attribute's fixed value. "; public const string Sch_AttributeUseInvalid = "Derived attribute's use has to be required if base attribute's use is required."; public const string Sch_AttributeRestrictionInvalidFromWildcard = "The {base type definition} must have an {attribute wildcard} and the {target namespace} of the R's {attribute declaration} must be valid with respect to that wildcard."; public const string Sch_NoDerivedAttribute = "The base attribute '{0}' whose use = 'required' does not have a corresponding derived attribute while redefining attribute group '{1}'."; public const string Sch_UnexpressibleAnyAttribute = "The 'anyAttribute' is not expressible."; public const string Sch_RefInvalidAttribute = "Reference to invalid attribute '{0}'."; public const string Sch_ElementCircularRef = "Circular element reference."; public const string Sch_RefInvalidElement = "Reference to invalid element '{0}'."; public const string Sch_ElementCannotHaveValue = "Element's type does not allow fixed or default value constraint."; public const string Sch_ElementInMixedWithFixed = "Although the '{0}' element's content type is mixed, it cannot have element children, because it has a fixed value constraint in the schema."; public const string Sch_ElementTypeCollision = "Elements with the same name and in the same scope must have the same type."; public const string Sch_InvalidIncludeLocation = "Cannot resolve the 'schemaLocation' attribute."; public const string Sch_CannotLoadSchema = "Cannot load the schema for the namespace '{0}' - {1}"; public const string Sch_CannotLoadSchemaLocation = "Cannot load the schema from the location '{0}' - {1}"; public const string Sch_LengthGtBaseLength = "It is an error if 'length' is among the members of {facets} of {base type definition} and {value} is greater than the {value} of the parent 'length'."; public const string Sch_MinLengthGtBaseMinLength = "It is an error if 'minLength' is among the members of {facets} of {base type definition} and {value} is less than the {value} of the parent 'minLength'."; public const string Sch_MaxLengthGtBaseMaxLength = "It is an error if 'maxLength' is among the members of {facets} of {base type definition} and {value} is greater than the {value} of the parent 'maxLength'."; public const string Sch_MaxMinLengthBaseLength = "It is an error for both 'length' and either 'minLength' or 'maxLength' to be members of {facets}, unless they are specified in different derivation steps. In which case the following must be true: the {value} of 'minLength' <= the {value} of 'length' <= the {value} of 'maxLength'."; public const string Sch_MaxInclusiveMismatch = "It is an error if the derived 'maxInclusive' facet value is greater than the parent 'maxInclusive' facet value."; public const string Sch_MaxExclusiveMismatch = "It is an error if the derived 'maxExclusive' facet value is greater than the parent 'maxExclusive' facet value."; public const string Sch_MinInclusiveMismatch = "It is an error if the derived 'minInclusive' facet value is less than the parent 'minInclusive' facet value."; public const string Sch_MinExclusiveMismatch = "It is an error if the derived 'minExclusive' facet value is less than the parent 'minExclusive' facet value."; public const string Sch_MinExlIncMismatch = "It is an error if the derived 'minExclusive' facet value is less than or equal to the parent 'minInclusive' facet value."; public const string Sch_MinExlMaxExlMismatch = "It is an error if the derived 'minExclusive' facet value is greater than or equal to the parent 'maxExclusive' facet value."; public const string Sch_MinIncMaxExlMismatch = "It is an error if the derived 'minInclusive' facet value is greater than or equal to the parent 'maxExclusive' facet value."; public const string Sch_MinIncExlMismatch = "It is an error if the derived 'minInclusive' facet value is less than or equal to the parent 'minExclusive' facet value."; public const string Sch_MaxIncExlMismatch = "It is an error if the derived 'maxInclusive' facet value is greater than or equal to the parent 'maxExclusive' facet value."; public const string Sch_MaxExlIncMismatch = "It is an error if the derived 'maxExclusive' facet value is greater than or equal to the parent 'maxInclusive' facet value."; public const string Sch_TotalDigitsMismatch = "It is an error if the derived 'totalDigits' facet value is greater than the parent 'totalDigits' facet value."; public const string Sch_FacetBaseFixed = "Values that are declared as {fixed} in a base type can not be changed in a derived type."; public const string Sch_WhiteSpaceRestriction1 = "It is an error if 'whiteSpace' is among the members of {facets} of {base type definition}, {value} is 'replace' or 'preserve', and the {value} of the parent 'whiteSpace' is 'collapse'."; public const string Sch_WhiteSpaceRestriction2 = "It is an error if 'whiteSpace' is among the members of {facets} of {base type definition}, {value} is 'preserve', and the {value} of the parent 'whiteSpace' is 'replace'."; public const string Sch_XsiNilAndFixed = "There must be no fixed value when an attribute is 'xsi:nil' and has a value of 'true'."; public const string Sch_MixSchemaTypes = "Different schema types cannot be mixed."; public const string Sch_XSDSchemaOnly = "'XmlSchemaSet' can load only W3C XML Schemas."; public const string Sch_InvalidPublicAttribute = "Public attribute '{0}' is an invalid URI."; public const string Sch_InvalidSystemAttribute = "System attribute '{0}' is an invalid URI."; public const string Sch_TypeAfterConstraints = "'simpleType' or 'complexType' cannot follow 'unique', 'key' or 'keyref'."; public const string Sch_XsiNilAndType = "There can be no type value when attribute is 'xsi:nil' and has value 'true'."; public const string Sch_DupSimpleTypeChild = "'simpleType' should have only one child 'union', 'list', or 'restriction'."; public const string Sch_InvalidIdAttribute = "Invalid 'id' attribute value: {0}"; public const string Sch_InvalidNameAttributeEx = "Invalid 'name' attribute value '{0}': '{1}'."; public const string Sch_InvalidAttribute = "Invalid '{0}' attribute: '{1}'."; public const string Sch_EmptyChoice = "Empty choice cannot be satisfied if 'minOccurs' is not equal to 0."; public const string Sch_DerivedNotFromBase = "The data type of the simple content is not a valid restriction of the base complex type."; public const string Sch_NeedSimpleTypeChild = "Simple content restriction must have a simple type child if the content type of the base type is not a simple type definition."; public const string Sch_InvalidCollection = "The schema items collection cannot contain an object of type 'XmlSchemaInclude', 'XmlSchemaImport', or 'XmlSchemaRedefine'."; public const string Sch_UnrefNS = "Namespace '{0}' is not available to be referenced in this schema."; public const string Sch_InvalidSimpleTypeRestriction = "Restriction of 'anySimpleType' is not allowed."; public const string Sch_MultipleRedefine = "Multiple redefines of the same schema will be ignored."; public const string Sch_NullValue = "Value cannot be null."; public const string Sch_ComplexContentModel = "Content model validation resulted in a large number of states, possibly due to large occurrence ranges. Therefore, content model may not be validated accurately."; public const string Sch_SchemaNotPreprocessed = "All schemas in the set should be successfully preprocessed prior to compilation."; public const string Sch_SchemaNotRemoved = "The schema could not be removed because other schemas in the set have dependencies on this schema or its imports."; public const string Sch_ComponentAlreadySeenForNS = "An element or attribute information item has already been validated from the '{0}' namespace. It is an error if 'xsi:schemaLocation', 'xsi:noNamespaceSchemaLocation', or an inline schema occurs for that namespace."; public const string Sch_DefaultAttributeNotApplied = "Default attribute '{0}' for element '{1}' could not be applied as the attribute namespace is not mapped to a prefix in the instance document."; public const string Sch_NotXsiAttribute = "The attribute '{0}' does not match one of the four allowed attributes in the 'xsi' namespace."; public const string Sch_SchemaDoesNotExist = "Schema does not exist in the set."; public const string XmlDocument_ValidateInvalidNodeType = "Validate method can be called only on nodes of type Document, DocumentFragment, Element, or Attribute."; public const string XmlDocument_NodeNotFromDocument = "Cannot validate '{0}' because its owner document is not the current document. "; public const string XmlDocument_NoNodeSchemaInfo = "Schema information could not be found for the node passed into Validate. The node may be invalid in its current position. Navigate to the ancestor that has schema information, then call Validate again."; public const string XmlDocument_NoSchemaInfo = "The XmlSchemaSet on the document is either null or has no schemas in it. Provide schema information before calling Validate."; public const string Sch_InvalidStartTransition = "It is invalid to call the '{0}' method in the current state of the validator. The '{1}' method must be called before proceeding with validation."; public const string Sch_InvalidStateTransition = "The transition from the '{0}' method to the '{1}' method is not allowed."; public const string Sch_InvalidEndValidation = "The 'EndValidation' method cannot not be called when all the elements have not been validated. 'ValidateEndElement' calls corresponding to 'ValidateElement' calls might be missing."; public const string Sch_InvalidEndElementCall = "It is invalid to call the 'ValidateEndElement' overload that takes in a 'typedValue' after 'ValidateText' or 'ValidateWhitespace' methods have been called."; public const string Sch_InvalidEndElementCallTyped = "It is invalid to call the 'ValidateEndElement' overload that takes in a 'typedValue' for elements with complex content."; public const string Sch_InvalidEndElementMultiple = "The call to the '{0}' method does not match a corresponding call to 'ValidateElement' method."; public const string Sch_DuplicateAttribute = "The '{0}' attribute has already been validated and is a duplicate attribute."; public const string Sch_InvalidPartialValidationType = "The partial validation type has to be 'XmlSchemaElement', 'XmlSchemaAttribute', or 'XmlSchemaType'."; public const string Sch_SchemaElementNameMismatch = "The element name '{0}' does not match the name '{1}' of the 'XmlSchemaElement' set as a partial validation type. "; public const string Sch_SchemaAttributeNameMismatch = "The attribute name '{0}' does not match the name '{1}' of the 'XmlSchemaAttribute' set as a partial validation type. "; public const string Sch_ValidateAttributeInvalidCall = "If the partial validation type is 'XmlSchemaElement' or 'XmlSchemaType', the 'ValidateAttribute' method cannot be called."; public const string Sch_ValidateElementInvalidCall = "If the partial validation type is 'XmlSchemaAttribute', the 'ValidateElement' method cannot be called."; public const string Sch_EnumNotStarted = "Enumeration has not started. Call MoveNext."; public const string Sch_EnumFinished = "Enumeration has already finished."; public const string SchInf_schema = "The supplied xml instance is a schema or contains an inline schema. This class cannot infer a schema for a schema."; public const string SchInf_entity = "Inference cannot handle entity references. Pass in an 'XmlReader' that expands entities."; public const string SchInf_simplecontent = "Expected simple content. Schema was not created using this tool."; public const string SchInf_extension = "Expected 'Extension' within 'SimpleContent'. Schema was not created using this tool."; public const string SchInf_particle = "Particle cannot exist along with 'ContentModel'."; public const string SchInf_ct = "Complex type expected to exist with at least one 'Element' at this point."; public const string SchInf_seq = "sequence expected to contain elements only. Schema was not created using this tool."; public const string SchInf_noseq = "The supplied schema contains particles other than Sequence and Choice. Only schemas generated by this tool are supported."; public const string SchInf_noct = "Expected ComplexType. Schema was not generated using this tool."; public const string SchInf_UnknownParticle = "Expected Element. Schema was not generated using this tool."; public const string SchInf_schematype = "Inference can only handle simple built-in types for 'SchemaType'."; public const string SchInf_NoElement = "There is no element to infer schema."; public const string Xp_UnclosedString = "This is an unclosed string."; public const string Xp_ExprExpected = "'{0}' is an invalid expression."; public const string Xp_InvalidArgumentType = "The argument to function '{0}' in '{1}' cannot be converted to a node-set."; public const string Xp_InvalidNumArgs = "Function '{0}' in '{1}' has an invalid number of arguments."; public const string Xp_InvalidName = "'{0}' has an invalid qualified name."; public const string Xp_InvalidToken = "'{0}' has an invalid token."; public const string Xp_NodeSetExpected = "Expression must evaluate to a node-set."; public const string Xp_NotSupported = "The XPath query '{0}' is not supported."; public const string Xp_InvalidPattern = "'{0}' is an invalid XSLT pattern."; public const string Xp_InvalidKeyPattern = "'{0}' is an invalid key pattern. It either contains a variable reference or 'key()' function."; public const string Xp_BadQueryObject = "This is an invalid object. Only objects returned from Compile() can be passed as input."; public const string Xp_UndefinedXsltContext = "XsltContext is needed for this query because of an unknown function."; public const string Xp_NoContext = "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function."; public const string Xp_UndefVar = "The variable '{0}' is undefined."; public const string Xp_UndefFunc = "The function '{0}()' is undefined."; public const string Xp_FunctionFailed = "Function '{0}()' has failed."; public const string Xp_CurrentNotAllowed = "The 'current()' function cannot be used in a pattern."; public const string Xp_QueryTooComplex = "The xpath query is too complex."; public const string Xdom_DualDocumentTypeNode = "This document already has a 'DocumentType' node."; public const string Xdom_DualDocumentElementNode = "This document already has a 'DocumentElement' node."; public const string Xdom_DualDeclarationNode = "This document already has an 'XmlDeclaration' node."; public const string Xdom_Import = "Cannot import nodes of type '{0}'."; public const string Xdom_Import_NullNode = "Cannot import a null node."; public const string Xdom_NoRootEle = "The document does not have a root element."; public const string Xdom_Attr_Name = "The attribute local name cannot be empty."; public const string Xdom_AttrCol_Object = "An 'Attributes' collection can only contain 'Attribute' objects."; public const string Xdom_AttrCol_Insert = "The reference node must be a child of the current node."; public const string Xdom_NamedNode_Context = "The named node is from a different document context."; public const string Xdom_Version = "Wrong XML version information. The XML must match production \"VersionNum ::= '1.' [0-9]+\"."; public const string Xdom_standalone = "Wrong value for the XML declaration standalone attribute of '{0}'."; public const string Xdom_Ent_Innertext = "The 'InnerText' of an 'Entity' node is read-only and cannot be set."; public const string Xdom_EntRef_SetVal = "'EntityReference' nodes have no support for setting value."; public const string Xdom_WS_Char = "The string for whitespace contains an invalid character."; public const string Xdom_Node_SetVal = "Cannot set a value on node type '{0}'."; public const string Xdom_Empty_LocalName = "The local name for elements or attributes cannot be null or an empty string."; public const string Xdom_Set_InnerXml = "Cannot set the 'InnerXml' for the current node because it is either read-only or cannot have children."; public const string Xdom_Attr_InUse = "The 'Attribute' node cannot be inserted because it is already an attribute of another element."; public const string Xdom_Enum_ElementList = "The element list has changed. The enumeration operation failed to continue."; public const string Xdom_Invalid_NT_String = "'{0}' does not represent any 'XmlNodeType'."; public const string Xdom_InvalidCharacter_EntityReference = "Cannot create an 'EntityReference' node with a name starting with '#'."; public const string Xdom_IndexOutOfRange = "The index being passed in is out of range."; public const string Xdom_Document_Innertext = "The 'InnerText' of a 'Document' node is read-only and cannot be set."; public const string Xpn_BadPosition = "Operation is not valid due to the current position of the navigator."; public const string Xpn_MissingParent = "The current position of the navigator is missing a valid parent."; public const string Xpn_NoContent = "No content generated as the result of the operation."; public const string Xdom_Load_NoDocument = "The document to be loaded could not be found."; public const string Xdom_Load_NoReader = "There is no reader from which to load the document."; public const string Xdom_Node_Null_Doc = "Cannot create a node without an owner document."; public const string Xdom_Node_Insert_Child = "Cannot insert a node or any ancestor of that node as a child of itself."; public const string Xdom_Node_Insert_Contain = "The current node cannot contain other nodes."; public const string Xdom_Node_Insert_Path = "The reference node is not a child of this node."; public const string Xdom_Node_Insert_Context = "The node to be inserted is from a different document context."; public const string Xdom_Node_Insert_Location = "Cannot insert the node in the specified location."; public const string Xdom_Node_Insert_TypeConflict = "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."; public const string Xdom_Node_Remove_Contain = "The current node cannot contain other nodes, so the node to be removed is not its child."; public const string Xdom_Node_Remove_Child = "The node to be removed is not a child of this node."; public const string Xdom_Node_Modify_ReadOnly = "This node is read-only. It cannot be modified."; public const string Xdom_TextNode_SplitText = "The 'Text' node is not connected in the DOM live tree. No 'SplitText' operation could be performed."; public const string Xdom_Attr_Reserved_XmlNS = "The namespace declaration attribute has an incorrect 'namespaceURI': '{0}'."; public const string Xdom_Node_Cloning = "'Entity' and 'Notation' nodes cannot be cloned."; public const string Xnr_ResolveEntity = "The node is not an expandable 'EntityReference' node."; public const string XPathDocument_MissingSchemas = "An XmlSchemaSet must be provided to validate the document."; public const string XPathDocument_NotEnoughSchemaInfo = "Element should have prior schema information to call this method."; public const string XPathDocument_ValidateInvalidNodeType = "Validate and CheckValidity are only allowed on Root or Element nodes."; public const string XPathDocument_SchemaSetNotAllowed = "An XmlSchemaSet is only allowed as a parameter on the Root node."; public const string XmlBin_MissingEndCDATA = "CDATA end token is missing."; public const string XmlBin_InvalidQNameID = "Invalid QName ID."; public const string XmlBinary_UnexpectedToken = "Unexpected BinaryXml token."; public const string XmlBinary_InvalidSqlDecimal = "Unable to parse data as SQL_DECIMAL."; public const string XmlBinary_InvalidSignature = "Invalid BinaryXml signature."; public const string XmlBinary_InvalidProtocolVersion = "Invalid BinaryXml protocol version."; public const string XmlBinary_UnsupportedCodePage = "Unsupported BinaryXml codepage."; public const string XmlBinary_InvalidStandalone = "Invalid BinaryXml standalone token."; public const string XmlBinary_NoParserContext = "BinaryXml Parser does not support initialization with XmlParserContext."; public const string XmlBinary_ListsOfValuesNotSupported = "Lists of BinaryXml value tokens not supported."; public const string XmlBinary_CastNotSupported = "Token '{0}' does not support a conversion to Clr type '{1}'."; public const string XmlBinary_NoRemapPrefix = "Prefix '{0}' is already assigned to namespace '{1}' and cannot be reassigned to '{2}' on this tag."; public const string XmlBinary_AttrWithNsNoPrefix = "Attribute '{0}' has namespace '{1}' but no prefix."; public const string XmlBinary_ValueTooBig = "The value is too big to fit into an Int32. The arithmetic operation resulted in an overflow."; public const string SqlTypes_ArithOverflow = "Arithmetic Overflow."; public const string XmlMissingType = "Invalid serialization assembly: Required type {0} cannot be found in the generated assembly '{1}'."; public const string XmlSerializerUnsupportedType = "{0} is an unsupported type. Please use [XmlIgnore] attribute to exclude members of this type from serialization graph."; public const string XmlSerializerUnsupportedMember = "Cannot serialize member '{0}' of type '{1}', see inner exception for more details."; public const string XmlUnsupportedTypeKind = "The type {0} may not be serialized."; public const string XmlUnsupportedSoapTypeKind = "The type {0} may not be serialized with SOAP-encoded messages. Set the Use for your message to Literal."; public const string XmlUnsupportedIDictionary = "The type {0} is not supported because it implements IDictionary."; public const string XmlUnsupportedIDictionaryDetails = "Cannot serialize member {0} of type {1}, because it implements IDictionary."; public const string XmlDuplicateTypeName = "A type with the name {0} has already been added in namespace {1}."; public const string XmlSerializableNameMissing1 = "Schema Id is missing. The schema returned from {0}.GetSchema() must have an Id."; public const string XmlConstructorInaccessible = "{0} cannot be serialized because it does not have a parameterless constructor."; public const string XmlTypeInaccessible = "{0} is inaccessible due to its protection level. Only public types can be processed."; public const string XmlTypeStatic = "{0} cannot be serialized. Static types cannot be used as parameters or return types."; public const string XmlNoDefaultAccessors = "You must implement a default accessor on {0} because it inherits from ICollection."; public const string XmlNoAddMethod = "To be XML serializable, types which inherit from {2} must have an implementation of Add({1}) at all levels of their inheritance hierarchy. {0} does not implement Add({1})."; public const string XmlReadOnlyPropertyError = "Cannot deserialize type '{0}' because it contains property '{1}' which has no public setter."; public const string XmlAttributeSetAgain = "'{0}.{1}' already has attributes."; public const string XmlIllegalWildcard = "Cannot use wildcards at the top level of a schema."; public const string XmlIllegalArrayElement = "An element declared at the top level of a schema cannot have maxOccurs > 1. Provide a wrapper element for '{0}' by using XmlArray or XmlArrayItem instead of XmlElementAttribute, or by using the Wrapped parameter style."; public const string XmlIllegalForm = "There was an error exporting '{0}': elements declared at the top level of a schema cannot be unqualified."; public const string XmlBareTextMember = "There was an error exporting '{0}': bare members cannot contain text content."; public const string XmlBareAttributeMember = "There was an error exporting '{0}': bare members cannot be attributes."; public const string XmlReflectionError = "There was an error reflecting '{0}'."; public const string XmlTypeReflectionError = "There was an error reflecting type '{0}'."; public const string XmlPropertyReflectionError = "There was an error reflecting property '{0}'."; public const string XmlFieldReflectionError = "There was an error reflecting field '{0}'."; public const string XmlInvalidDataTypeUsage = "'{0}' is an invalid value for the {1} property. The property may only be specified for primitive types."; public const string XmlInvalidXsdDataType = "Value '{0}' cannot be used for the {1} property. The datatype '{2}' is missing."; public const string XmlDataTypeMismatch = "'{0}' is an invalid value for the {1} property. {0} cannot be converted to {2}."; public const string XmlIllegalTypeContext = "{0} cannot be used as: 'xml {1}'."; public const string XmlUdeclaredXsdType = "The type, {0}, is undeclared."; public const string XmlInvalidConstantAttribute = "Only XmlEnum may be used on enumerated constants."; public const string XmlIllegalAttributesArrayAttribute = "XmlAttribute and XmlAnyAttribute cannot be used in conjunction with XmlElement, XmlText, XmlAnyElement, XmlArray, or XmlArrayItem."; public const string XmlIllegalElementsArrayAttribute = "XmlElement, XmlText, and XmlAnyElement cannot be used in conjunction with XmlAttribute, XmlAnyAttribute, XmlArray, or XmlArrayItem."; public const string XmlIllegalArrayArrayAttribute = "XmlArray and XmlArrayItem cannot be used in conjunction with XmlAttribute, XmlAnyAttribute, XmlElement, XmlText, or XmlAnyElement."; public const string XmlIllegalAttribute = "For non-array types, you may use the following attributes: XmlAttribute, XmlText, XmlElement, or XmlAnyElement."; public const string XmlIllegalType = "The type for {0} may not be specified for primitive types."; public const string XmlIllegalAttrOrText = "Cannot serialize member '{0}' of type {1}. XmlAttribute/XmlText cannot be used to encode complex types."; public const string XmlIllegalSoapAttribute = "Cannot serialize member '{0}' of type {1}. SoapAttribute cannot be used to encode complex types."; public const string XmlIllegalAttrOrTextInterface = "Cannot serialize member '{0}' of type {1}. XmlAttribute/XmlText cannot be used to encode types implementing {2}."; public const string XmlIllegalAttributeFlagsArray = "XmlAttribute cannot be used to encode array of {1}, because it is marked with FlagsAttribute."; public const string XmlIllegalAnyElement = "Cannot serialize member of type {0}: XmlAnyElement can only be used with classes of type XmlNode or a type deriving from XmlNode."; public const string XmlInvalidIsNullable = "IsNullable may not be 'true' for value type {0}. Please consider using Nullable<{0}> instead."; public const string XmlInvalidNotNullable = "IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the {1} attribute."; public const string XmlInvalidFormUnqualified = "The Form property may not be 'Unqualified' when an explicit Namespace property is present."; public const string XmlDuplicateNamespace = "The namespace, {0}, is a duplicate."; public const string XmlElementHasNoName = "This element has no name. Please review schema type '{0}' from namespace '{1}'."; public const string XmlAttributeHasNoName = "This attribute has no name."; public const string XmlElementImportedTwice = "The element, {0}, from namespace, {1}, was imported in two different contexts: ({2}, {3})."; public const string XmlHiddenMember = "Member {0}.{1} of type {2} hides base class member {3}.{4} of type {5}. Use XmlElementAttribute or XmlAttributeAttribute to specify a new name."; public const string XmlInvalidXmlOverride = "Member '{0}.{1}' hides inherited member '{2}.{3}', but has different custom attributes."; public const string XmlMembersDeriveError = "These members may not be derived."; public const string XmlTypeUsedTwice = "The type '{0}' from namespace '{1}' was used in two different ways."; public const string XmlMissingGroup = "Group {0} is missing."; public const string XmlMissingAttributeGroup = "The attribute group {0} is missing."; public const string XmlMissingDataType = "The datatype '{0}' is missing."; public const string XmlInvalidEncoding = "Referenced type '{0}' is only valid for encoded SOAP."; public const string XmlMissingElement = "The element '{0}' is missing."; public const string XmlMissingAttribute = "The attribute {0} is missing."; public const string XmlMissingMethodEnum = "The method for enum {0} is missing."; public const string XmlNoAttributeHere = "Cannot write a node of type XmlAttribute as an element value. Use XmlAnyAttributeAttribute with an array of XmlNode or XmlAttribute to write the
deps/System.Xml.Linq.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using System.Xml.Schema; using System.Xml.Serialization; using Unity; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Xml.Linq.dll")] [assembly: AssemblyDescription("System.Xml.Linq.dll")] [assembly: AssemblyDefaultAlias("System.Xml.Linq.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../ecma.pub")] [assembly: AllowPartiallyTrustedCallers] [assembly: ComVisible(false)] [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class SR { public const string Argument_AddAttribute = "An attribute cannot be added to content."; public const string Argument_AddNode = "A node of type {0} cannot be added to content."; public const string Argument_AddNonWhitespace = "Non-whitespace characters cannot be added to content."; public const string Argument_ConvertToString = "The argument cannot be converted to a string."; public const string Argument_InvalidExpandedName = "'{0}' is an invalid expanded name."; public const string Argument_InvalidPIName = "'{0}' is an invalid name for a processing instruction."; public const string Argument_InvalidPrefix = "'{0}' is an invalid prefix."; public const string Argument_MustBeDerivedFrom = "The argument must be derived from {0}."; public const string Argument_NamespaceDeclarationPrefixed = "The prefix '{0}' cannot be bound to the empty namespace name."; public const string Argument_NamespaceDeclarationXml = "The prefix 'xml' is bound to the namespace name 'http://www.w3.org/XML/1998/namespace'. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace."; public const string Argument_NamespaceDeclarationXmlns = "The prefix 'xmlns' is bound to the namespace name 'http://www.w3.org/2000/xmlns/'. It must not be declared. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace."; public const string Argument_XObjectValue = "An XObject cannot be used as a value."; public const string InvalidOperation_DeserializeInstance = "This instance cannot be deserialized."; public const string InvalidOperation_DocumentStructure = "This operation would create an incorrectly structured document."; public const string InvalidOperation_DuplicateAttribute = "Duplicate attribute."; public const string InvalidOperation_ExpectedEndOfFile = "The XmlReader state should be EndOfFile after this operation."; public const string InvalidOperation_ExpectedInteractive = "The XmlReader state should be Interactive."; public const string InvalidOperation_ExpectedNodeType = "The XmlReader must be on a node of type {0} instead of a node of type {1}."; public const string InvalidOperation_ExternalCode = "This operation was corrupted by external code."; public const string InvalidOperation_MissingAncestor = "A common ancestor is missing."; public const string InvalidOperation_MissingParent = "The parent is missing."; public const string InvalidOperation_MissingRoot = "The root element is missing."; public const string InvalidOperation_UnexpectedNodeType = "The XmlReader should not be on a node of type {0}."; public const string InvalidOperation_UnresolvedEntityReference = "The XmlReader cannot resolve entity references."; public const string InvalidOperation_WriteAttribute = "An attribute cannot be written after content."; public const string NotSupported_WriteBase64 = "This XmlWriter does not support base64 encoded data."; public const string NotSupported_WriteEntityRef = "This XmlWriter does not support entity references."; public const string Argument_CreateNavigator = "This XPathNavigator cannot be created on a node of type {0}."; public const string InvalidOperation_BadNodeType = "This operation is not valid on a node of type {0}."; public const string InvalidOperation_UnexpectedEvaluation = "The XPath expression evaluated to unexpected type {0}."; public const string NotSupported_MoveToId = "This XPathNavigator does not support IDs."; internal static string GetString(string name, params object[] args) { return GetString(CultureInfo.InvariantCulture, name, args); } internal static string GetString(CultureInfo culture, string name, params object[] args) { return string.Format(culture, name, args); } internal static string GetString(string name) { return name; } internal static string GetString(CultureInfo culture, string name) { return name; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2); } internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2) { return string.Format(ci, resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3); } internal static string GetResourceString(string str) { return str; } } namespace System.Runtime.CompilerServices { internal class FriendAccessAllowedAttribute : Attribute { } } namespace System.Xml.XPath { internal static class XAttributeExtensions { public static string GetPrefixOfNamespace(this XAttribute attribute, XNamespace ns) { string namespaceName = ns.NamespaceName; if (namespaceName.Length == 0) { return string.Empty; } if (attribute.GetParent() != null) { return ((XElement)attribute.GetParent()).GetPrefixOfNamespace(ns); } if ((object)namespaceName == XNodeNavigator.xmlPrefixNamespace) { return "xml"; } if ((object)namespaceName == XNodeNavigator.xmlnsPrefixNamespace) { return "xmlns"; } return null; } } internal class XNodeNavigator : XPathNavigator, IXmlLineInfo { internal static readonly string xmlPrefixNamespace = XNamespace.Xml.NamespaceName; internal static readonly string xmlnsPrefixNamespace = XNamespace.Xmlns.NamespaceName; private const int DocumentContentMask = 386; private static readonly int[] s_ElementContentMasks = new int[10] { 0, 2, 0, 0, 24, 0, 0, 128, 256, 410 }; private const int TextMask = 24; private static XAttribute s_XmlNamespaceDeclaration; private XObject _source; private XElement _parent; private XmlNameTable _nameTable; public override string BaseURI { get { if (_source != null) { return _source.BaseUri; } if (_parent != null) { return _parent.BaseUri; } return string.Empty; } } public override bool HasAttributes { get { if (_source is XElement xElement) { foreach (XAttribute item in xElement.Attributes()) { if (!item.IsNamespaceDeclaration) { return true; } } } return false; } } public override bool HasChildren { get { if (_source is XContainer xContainer) { foreach (XNode item in xContainer.Nodes()) { if (IsContent(xContainer, item)) { return true; } } } return false; } } public override bool IsEmptyElement { get { if (_source is XElement xElement) { return xElement.IsEmpty; } return false; } } public override string LocalName => _nameTable.Add(GetLocalName()); public override string Name { get { string prefix = GetPrefix(); if (prefix.Length == 0) { return _nameTable.Add(GetLocalName()); } return _nameTable.Add(prefix + ":" + GetLocalName()); } } public override string NamespaceURI => _nameTable.Add(GetNamespaceURI()); public override XmlNameTable NameTable => _nameTable; public override XPathNodeType NodeType { get { if (_source != null) { switch (_source.NodeType) { case XmlNodeType.Element: return XPathNodeType.Element; case XmlNodeType.Attribute: if (!((XAttribute)_source).IsNamespaceDeclaration) { return XPathNodeType.Attribute; } return XPathNodeType.Namespace; case XmlNodeType.Document: return XPathNodeType.Root; case XmlNodeType.Comment: return XPathNodeType.Comment; case XmlNodeType.ProcessingInstruction: return XPathNodeType.ProcessingInstruction; default: return XPathNodeType.Text; } } return XPathNodeType.Text; } } public override string Prefix => _nameTable.Add(GetPrefix()); public override object UnderlyingObject => _source; public override string Value { get { if (_source != null) { switch (_source.NodeType) { case XmlNodeType.Element: return ((XElement)_source).Value; case XmlNodeType.Attribute: return ((XAttribute)_source).Value; case XmlNodeType.Document: { XElement root = ((XDocument)_source).Root; if (root == null) { return string.Empty; } return root.Value; } case XmlNodeType.Text: case XmlNodeType.CDATA: return CollectText((XText)_source); case XmlNodeType.Comment: return ((XComment)_source).Value; case XmlNodeType.ProcessingInstruction: return ((XProcessingInstruction)_source).Data; default: return string.Empty; } } return string.Empty; } } int IXmlLineInfo.LineNumber => ((IXmlLineInfo)_source)?.LineNumber ?? 0; int IXmlLineInfo.LinePosition => ((IXmlLineInfo)_source)?.LinePosition ?? 0; public XNodeNavigator(XNode node, XmlNameTable nameTable) { _source = node; _nameTable = ((nameTable != null) ? nameTable : CreateNameTable()); } public XNodeNavigator(XNodeNavigator other) { _source = other._source; _parent = other._parent; _nameTable = other._nameTable; } private string GetLocalName() { if (_source is XElement xElement) { return xElement.Name.LocalName; } if (_source is XAttribute xAttribute) { if (_parent != null && xAttribute.Name.NamespaceName.Length == 0) { return string.Empty; } return xAttribute.Name.LocalName; } if (_source is XProcessingInstruction xProcessingInstruction) { return xProcessingInstruction.Target; } return string.Empty; } private string GetNamespaceURI() { if (_source is XElement xElement) { return xElement.Name.NamespaceName; } if (_source is XAttribute xAttribute) { if (_parent != null) { return string.Empty; } return xAttribute.Name.NamespaceName; } return string.Empty; } private string GetPrefix() { if (_source is XElement xElement) { string prefixOfNamespace = xElement.GetPrefixOfNamespace(xElement.Name.Namespace); if (prefixOfNamespace != null) { return prefixOfNamespace; } return string.Empty; } if (_source is XAttribute xAttribute) { if (_parent != null) { return string.Empty; } string prefixOfNamespace2 = xAttribute.GetPrefixOfNamespace(xAttribute.Name.Namespace); if (prefixOfNamespace2 != null) { return prefixOfNamespace2; } } return string.Empty; } public override XPathNavigator Clone() { return new XNodeNavigator(this); } public override bool IsSamePosition(XPathNavigator navigator) { if (!(navigator is XNodeNavigator n)) { return false; } return IsSamePosition(this, n); } public override bool MoveTo(XPathNavigator navigator) { if (navigator is XNodeNavigator xNodeNavigator) { _source = xNodeNavigator._source; _parent = xNodeNavigator._parent; return true; } return false; } public override bool MoveToAttribute(string localName, string namespaceName) { if (_source is XElement xElement) { foreach (XAttribute item in xElement.Attributes()) { if (item.Name.LocalName == localName && item.Name.NamespaceName == namespaceName && !item.IsNamespaceDeclaration) { _source = item; return true; } } } return false; } public override bool MoveToChild(string localName, string namespaceName) { if (_source is XContainer xContainer) { foreach (XElement item in xContainer.Elements()) { if (item.Name.LocalName == localName && item.Name.NamespaceName == namespaceName) { _source = item; return true; } } } return false; } public override bool MoveToChild(XPathNodeType type) { if (_source is XContainer xContainer) { int num = GetElementContentMask(type); if ((0x18u & (uint)num) != 0 && xContainer.GetParent() == null && xContainer is XDocument) { num &= -25; } foreach (XNode item in xContainer.Nodes()) { if (((1 << (int)item.NodeType) & num) != 0) { _source = item; return true; } } } return false; } public override bool MoveToFirstAttribute() { if (_source is XElement xElement) { foreach (XAttribute item in xElement.Attributes()) { if (!item.IsNamespaceDeclaration) { _source = item; return true; } } } return false; } public override bool MoveToFirstChild() { if (_source is XContainer xContainer) { foreach (XNode item in xContainer.Nodes()) { if (IsContent(xContainer, item)) { _source = item; return true; } } } return false; } public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { if (_source is XElement xElement) { XAttribute xAttribute = null; switch (scope) { case XPathNamespaceScope.Local: xAttribute = GetFirstNamespaceDeclarationLocal(xElement); break; case XPathNamespaceScope.ExcludeXml: xAttribute = GetFirstNamespaceDeclarationGlobal(xElement); while (xAttribute != null && xAttribute.Name.LocalName == "xml") { xAttribute = GetNextNamespaceDeclarationGlobal(xAttribute); } break; case XPathNamespaceScope.All: xAttribute = GetFirstNamespaceDeclarationGlobal(xElement); if (xAttribute == null) { xAttribute = GetXmlNamespaceDeclaration(); } break; } if (xAttribute != null) { _source = xAttribute; _parent = xElement; return true; } } return false; } public override bool MoveToId(string id) { throw new NotSupportedException("This XPathNavigator does not support IDs."); } public override bool MoveToNamespace(string localName) { if (_source is XElement xElement) { if (localName == "xmlns") { return false; } if (localName != null && localName.Length == 0) { localName = "xmlns"; } for (XAttribute xAttribute = GetFirstNamespaceDeclarationGlobal(xElement); xAttribute != null; xAttribute = GetNextNamespaceDeclarationGlobal(xAttribute)) { if (xAttribute.Name.LocalName == localName) { _source = xAttribute; _parent = xElement; return true; } } if (localName == "xml") { _source = GetXmlNamespaceDeclaration(); _parent = xElement; return true; } } return false; } public override bool MoveToNext() { if (_source is XNode xNode) { XContainer parent = xNode.GetParent(); if (parent != null) { XNode xNode2 = null; for (XNode xNode3 = xNode; xNode3 != null; xNode3 = xNode2) { xNode2 = xNode3.NextNode; if (xNode2 == null) { break; } if (IsContent(parent, xNode2) && (!(xNode3 is XText) || !(xNode2 is XText))) { _source = xNode2; return true; } } } } return false; } public override bool MoveToNext(string localName, string namespaceName) { if (_source is XNode xNode) { foreach (XElement item in xNode.ElementsAfterSelf()) { if (item.Name.LocalName == localName && item.Name.NamespaceName == namespaceName) { _source = item; return true; } } } return false; } public override bool MoveToNext(XPathNodeType type) { if (_source is XNode xNode) { XContainer parent = xNode.GetParent(); if (parent != null) { int num = GetElementContentMask(type); if ((0x18u & (uint)num) != 0 && parent.GetParent() == null && parent is XDocument) { num &= -25; } XNode xNode2 = null; for (XNode xNode3 = xNode; xNode3 != null; xNode3 = xNode2) { xNode2 = xNode3.NextNode; if (((1 << (int)xNode2.NodeType) & num) != 0 && (!(xNode3 is XText) || !(xNode2 is XText))) { _source = xNode2; return true; } } } } return false; } public override bool MoveToNextAttribute() { if (_source is XAttribute xAttribute && _parent == null && (XElement)xAttribute.GetParent() != null) { for (XAttribute nextAttribute = xAttribute.NextAttribute; nextAttribute != null; nextAttribute = nextAttribute.NextAttribute) { if (!nextAttribute.IsNamespaceDeclaration) { _source = nextAttribute; return true; } } } return false; } public override bool MoveToNextNamespace(XPathNamespaceScope scope) { XAttribute xAttribute = _source as XAttribute; if (xAttribute != null && _parent != null && !IsXmlNamespaceDeclaration(xAttribute)) { switch (scope) { case XPathNamespaceScope.Local: if (xAttribute.GetParent() != _parent) { return false; } xAttribute = GetNextNamespaceDeclarationLocal(xAttribute); break; case XPathNamespaceScope.ExcludeXml: do { xAttribute = GetNextNamespaceDeclarationGlobal(xAttribute); } while (xAttribute != null && (xAttribute.Name.LocalName == "xml" || HasNamespaceDeclarationInScope(xAttribute, _parent))); break; case XPathNamespaceScope.All: do { xAttribute = GetNextNamespaceDeclarationGlobal(xAttribute); } while (xAttribute != null && HasNamespaceDeclarationInScope(xAttribute, _parent)); if (xAttribute == null && !HasNamespaceDeclarationInScope(GetXmlNamespaceDeclaration(), _parent)) { xAttribute = GetXmlNamespaceDeclaration(); } break; } if (xAttribute != null) { _source = xAttribute; return true; } } return false; } public override bool MoveToParent() { if (_parent != null) { _source = _parent; _parent = null; return true; } XNode parent = _source.GetParent(); if (parent != null) { _source = parent; return true; } return false; } public override bool MoveToPrevious() { if (_source is XNode xNode) { XContainer parent = xNode.GetParent(); if (parent != null) { XNode xNode2 = null; foreach (XNode item in parent.Nodes()) { if (item == xNode) { if (xNode2 != null) { _source = xNode2; return true; } return false; } if (IsContent(parent, item)) { xNode2 = item; } } } } return false; } public override XmlReader ReadSubtree() { return ((_source as XContainer) ?? throw new InvalidOperationException(SR.Format("This operation is not valid on a node of type {0}.", NodeType))).CreateReader(); } bool IXmlLineInfo.HasLineInfo() { return ((IXmlLineInfo)_source)?.HasLineInfo() ?? false; } private static string CollectText(XText n) { string text = n.Value; if (n.GetParent() != null) { using IEnumerator<XNode> enumerator = n.NodesAfterSelf().GetEnumerator(); while (enumerator.MoveNext() && enumerator.Current is XText xText) { text += xText.Value; } } return text; } private static XmlNameTable CreateNameTable() { NameTable nameTable = new NameTable(); nameTable.Add(string.Empty); nameTable.Add(xmlnsPrefixNamespace); nameTable.Add(xmlPrefixNamespace); return nameTable; } private static bool IsContent(XContainer c, XNode n) { if (c.GetParent() != null || c is XElement) { return true; } return ((1 << (int)n.NodeType) & 0x182) != 0; } private static bool IsSamePosition(XNodeNavigator n1, XNodeNavigator n2) { if (n1._source == n2._source) { return n1._source.GetParent() == n2._source.GetParent(); } return false; } private static bool IsXmlNamespaceDeclaration(XAttribute a) { return a == GetXmlNamespaceDeclaration(); } private static int GetElementContentMask(XPathNodeType type) { return s_ElementContentMasks[(int)type]; } private static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e) { do { XAttribute firstNamespaceDeclarationLocal = GetFirstNamespaceDeclarationLocal(e); if (firstNamespaceDeclarationLocal != null) { return firstNamespaceDeclarationLocal; } e = e.Parent; } while (e != null); return null; } private static XAttribute GetFirstNamespaceDeclarationLocal(XElement e) { foreach (XAttribute item in e.Attributes()) { if (item.IsNamespaceDeclaration) { return item; } } return null; } private static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a) { XElement xElement = (XElement)a.GetParent(); if (xElement == null) { return null; } XAttribute nextNamespaceDeclarationLocal = GetNextNamespaceDeclarationLocal(a); if (nextNamespaceDeclarationLocal != null) { return nextNamespaceDeclarationLocal; } xElement = xElement.Parent; if (xElement == null) { return null; } return GetFirstNamespaceDeclarationGlobal(xElement); } private static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a) { if (a.Parent == null) { return null; } for (a = a.NextAttribute; a != null; a = a.NextAttribute) { if (a.IsNamespaceDeclaration) { return a; } } return null; } private static XAttribute GetXmlNamespaceDeclaration() { if (s_XmlNamespaceDeclaration == null) { Interlocked.CompareExchange(ref s_XmlNamespaceDeclaration, new XAttribute(XNamespace.Xmlns.GetName("xml"), xmlPrefixNamespace), null); } return s_XmlNamespaceDeclaration; } private static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e) { XName name = a.Name; while (e != null && e != a.GetParent()) { if (e.Attribute(name) != null) { return true; } e = e.Parent; } return false; } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal readonly struct XPathEvaluator { public object Evaluate<T>(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class { object obj = node.CreateNavigator().Evaluate(expression, resolver); if (obj is XPathNodeIterator result) { return EvaluateIterator<T>(result); } if (!(obj is T)) { throw new InvalidOperationException(SR.Format("The XPath expression evaluated to unexpected type {0}.", obj.GetType())); } return (T)obj; } private IEnumerable<T> EvaluateIterator<T>(XPathNodeIterator result) { foreach (XPathNavigator item in result) { object r = item.UnderlyingObject; if (!(r is T)) { throw new InvalidOperationException(SR.Format("The XPath expression evaluated to unexpected type {0}.", r.GetType())); } yield return (T)r; XText t = r as XText; if (t == null || t.GetParent() == null) { continue; } do { t = t.NextNode as XText; if (t == null) { break; } yield return (T)(object)t; } while (t != t.GetParent().LastNode); } } } public static class Extensions { public static XPathNavigator CreateNavigator(this XNode node) { return node.CreateNavigator(null); } public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable) { if (node == null) { throw new ArgumentNullException("node"); } if (node is XDocumentType) { throw new ArgumentException(SR.Format("This XPathNavigator cannot be created on a node of type {0}.", XmlNodeType.DocumentType)); } if (node is XText xText) { if (xText.GetParent() is XDocument) { throw new ArgumentException(SR.Format("This XPathNavigator cannot be created on a node of type {0}.", XmlNodeType.Whitespace)); } node = CalibrateText(xText); } return new XNodeNavigator(node, nameTable); } public static object XPathEvaluate(this XNode node, string expression) { return node.XPathEvaluate(expression, null); } public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver) { if (node == null) { throw new ArgumentNullException("node"); } return default(XPathEvaluator).Evaluate<object>(node, expression, resolver); } public static XElement XPathSelectElement(this XNode node, string expression) { return node.XPathSelectElement(expression, null); } public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver) { return node.XPathSelectElements(expression, resolver).FirstOrDefault(); } public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression) { return node.XPathSelectElements(expression, null); } public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver) { if (node == null) { throw new ArgumentNullException("node"); } return (IEnumerable<XElement>)default(XPathEvaluator).Evaluate<XElement>(node, expression, resolver); } private static XText CalibrateText(XText n) { XContainer parent = n.GetParent(); if (parent == null) { return n; } foreach (XNode item in parent.Nodes()) { if (item is XText result && item == n) { return result; } } return null; } } internal static class XObjectExtensions { public static XContainer GetParent(this XObject obj) { XContainer xContainer = obj.Parent; if (xContainer == null) { xContainer = obj.Document; } if (xContainer == obj) { return null; } return xContainer; } } public static class XDocumentExtensions { private class XDocumentNavigable : IXPathNavigable { private XNode _node; public XDocumentNavigable(XNode n) { _node = n; } public XPathNavigator CreateNavigator() { return _node.CreateNavigator(); } } public static IXPathNavigable ToXPathNavigable(this XNode node) { return new XDocumentNavigable(node); } } } namespace System.Xml.Schema { internal class XNodeValidator { private XmlSchemaSet schemas; private ValidationEventHandler validationEventHandler; private XObject source; private bool addSchemaInfo; private XmlNamespaceManager namespaceManager; private XmlSchemaValidator validator; private Dictionary<XmlSchemaInfo, XmlSchemaInfo> schemaInfos; private ArrayList defaultAttributes; private XName xsiTypeName; private XName xsiNilName; public XNodeValidator(XmlSchemaSet schemas, ValidationEventHandler validationEventHandler) { this.schemas = schemas; this.validationEventHandler = validationEventHandler; XNamespace xNamespace = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance"); xsiTypeName = xNamespace.GetName("type"); xsiNilName = xNamespace.GetName("nil"); } public void Validate(XObject source, XmlSchemaObject partialValidationType, bool addSchemaInfo) { this.source = source; this.addSchemaInfo = addSchemaInfo; XmlSchemaValidationFlags xmlSchemaValidationFlags = XmlSchemaValidationFlags.AllowXmlAttributes; XmlNodeType nodeType = source.NodeType; if (nodeType != XmlNodeType.Element) { if (nodeType != XmlNodeType.Attribute) { if (nodeType != XmlNodeType.Document) { goto IL_007a; } source = ((XDocument)source).Root; if (source == null) { throw new InvalidOperationException(SR.Format("The root element is missing.")); } xmlSchemaValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints; } else { if (((XAttribute)source).IsNamespaceDeclaration) { goto IL_007a; } if (source.Parent == null) { throw new InvalidOperationException(SR.Format("The parent is missing.")); } } } namespaceManager = new XmlNamespaceManager(schemas.NameTable); PushAncestorsAndSelf(source.Parent); validator = new XmlSchemaValidator(schemas.NameTable, schemas, namespaceManager, xmlSchemaValidationFlags); validator.ValidationEventHandler += ValidationCallback; validator.XmlResolver = null; if (partialValidationType != null) { validator.Initialize(partialValidationType); } else { validator.Initialize(); } IXmlLineInfo originalLineInfo = SaveLineInfo(source); if (nodeType == XmlNodeType.Attribute) { ValidateAttribute((XAttribute)source); } else { ValidateElement((XElement)source); } validator.EndValidation(); RestoreLineInfo(originalLineInfo); return; IL_007a: throw new InvalidOperationException(SR.Format("This operation is not valid on a node of type {0}.", nodeType)); } private XmlSchemaInfo GetDefaultAttributeSchemaInfo(XmlSchemaAttribute sa) { XmlSchemaInfo xmlSchemaInfo = new XmlSchemaInfo(); xmlSchemaInfo.IsDefault = true; xmlSchemaInfo.IsNil = false; xmlSchemaInfo.SchemaAttribute = sa; XmlSchemaSimpleType xmlSchemaSimpleType = (XmlSchemaSimpleType)(xmlSchemaInfo.SchemaType = sa.AttributeSchemaType); if (xmlSchemaSimpleType.Datatype.Variety == XmlSchemaDatatypeVariety.Union) { string defaultValue = GetDefaultValue(sa); XmlSchemaSimpleType[] baseMemberTypes = ((XmlSchemaSimpleTypeUnion)xmlSchemaSimpleType.Content).BaseMemberTypes; foreach (XmlSchemaSimpleType xmlSchemaSimpleType2 in baseMemberTypes) { object obj = null; try { obj = xmlSchemaSimpleType2.Datatype.ParseValue(defaultValue, schemas.NameTable, namespaceManager); } catch (XmlSchemaException) { } if (obj != null) { xmlSchemaInfo.MemberType = xmlSchemaSimpleType2; break; } } } xmlSchemaInfo.Validity = XmlSchemaValidity.Valid; return xmlSchemaInfo; } private string GetDefaultValue(XmlSchemaAttribute sa) { XmlQualifiedName refName = sa.RefName; if (!refName.IsEmpty) { sa = schemas.GlobalAttributes[refName] as XmlSchemaAttribute; if (sa == null) { return null; } } string fixedValue = sa.FixedValue; if (fixedValue != null) { return fixedValue; } return sa.DefaultValue; } private string GetDefaultValue(XmlSchemaElement se) { XmlQualifiedName refName = se.RefName; if (!refName.IsEmpty) { se = schemas.GlobalElements[refName] as XmlSchemaElement; if (se == null) { return null; } } string fixedValue = se.FixedValue; if (fixedValue != null) { return fixedValue; } return se.DefaultValue; } private void ReplaceSchemaInfo(XObject o, XmlSchemaInfo schemaInfo) { if (schemaInfos == null) { schemaInfos = new Dictionary<XmlSchemaInfo, XmlSchemaInfo>(new XmlSchemaInfoEqualityComparer()); } XmlSchemaInfo value = o.Annotation<XmlSchemaInfo>(); if (value != null) { if (!schemaInfos.ContainsKey(value)) { schemaInfos.Add(value, value); } o.RemoveAnnotations<XmlSchemaInfo>(); } if (!schemaInfos.TryGetValue(schemaInfo, out value)) { value = schemaInfo; schemaInfos.Add(value, value); } o.AddAnnotation(value); } private void PushAncestorsAndSelf(XElement e) { while (e != null) { XAttribute xAttribute = e.lastAttr; if (xAttribute != null) { do { xAttribute = xAttribute.next; if (xAttribute.IsNamespaceDeclaration) { string text = xAttribute.Name.LocalName; if (text == "xmlns") { text = string.Empty; } if (!namespaceManager.HasNamespace(text)) { namespaceManager.AddNamespace(text, xAttribute.Value); } } } while (xAttribute != e.lastAttr); } e = e.parent as XElement; } } private void PushElement(XElement e, ref string xsiType, ref string xsiNil) { namespaceManager.PushScope(); XAttribute xAttribute = e.lastAttr; if (xAttribute == null) { return; } do { xAttribute = xAttribute.next; if (xAttribute.IsNamespaceDeclaration) { string text = xAttribute.Name.LocalName; if (text == "xmlns") { text = string.Empty; } namespaceManager.AddNamespace(text, xAttribute.Value); continue; } XName name = xAttribute.Name; if (name == xsiTypeName) { xsiType = xAttribute.Value; } else if (name == xsiNilName) { xsiNil = xAttribute.Value; } } while (xAttribute != e.lastAttr); } private IXmlLineInfo SaveLineInfo(XObject source) { IXmlLineInfo lineInfoProvider = validator.LineInfoProvider; validator.LineInfoProvider = source; return lineInfoProvider; } private void RestoreLineInfo(IXmlLineInfo originalLineInfo) { validator.LineInfoProvider = originalLineInfo; } private void ValidateAttribute(XAttribute a) { IXmlLineInfo originalLineInfo = SaveLineInfo(a); XmlSchemaInfo schemaInfo = (addSchemaInfo ? new XmlSchemaInfo() : null); source = a; validator.ValidateAttribute(a.Name.LocalName, a.Name.NamespaceName, a.Value, schemaInfo); if (addSchemaInfo) { ReplaceSchemaInfo(a, schemaInfo); } RestoreLineInfo(originalLineInfo); } private void ValidateAttributes(XElement e) { XAttribute xAttribute = e.lastAttr; IXmlLineInfo originalLineInfo = SaveLineInfo(xAttribute); if (xAttribute != null) { do { xAttribute = xAttribute.next; if (!xAttribute.IsNamespaceDeclaration) { ValidateAttribute(xAttribute); } } while (xAttribute != e.lastAttr); source = e; } if (addSchemaInfo) { if (defaultAttributes == null) { defaultAttributes = new ArrayList(); } else { defaultAttributes.Clear(); } validator.GetUnspecifiedDefaultAttributes(defaultAttributes); foreach (XmlSchemaAttribute defaultAttribute in defaultAttributes) { xAttribute = new XAttribute(XNamespace.Get(defaultAttribute.QualifiedName.Namespace).GetName(defaultAttribute.QualifiedName.Name), GetDefaultValue(defaultAttribute)); ReplaceSchemaInfo(xAttribute, GetDefaultAttributeSchemaInfo(defaultAttribute)); e.Add(xAttribute); } } RestoreLineInfo(originalLineInfo); } private void ValidateElement(XElement e) { XmlSchemaInfo xmlSchemaInfo = (addSchemaInfo ? new XmlSchemaInfo() : null); string xsiType = null; string xsiNil = null; PushElement(e, ref xsiType, ref xsiNil); IXmlLineInfo originalLineInfo = SaveLineInfo(e); source = e; validator.ValidateElement(e.Name.LocalName, e.Name.NamespaceName, xmlSchemaInfo, xsiType, xsiNil, null, null); ValidateAttributes(e); validator.ValidateEndOfAttributes(xmlSchemaInfo); ValidateNodes(e); validator.ValidateEndElement(xmlSchemaInfo); if (addSchemaInfo) { if (xmlSchemaInfo.Validity == XmlSchemaValidity.Valid && xmlSchemaInfo.IsDefault) { e.Value = GetDefaultValue(xmlSchemaInfo.SchemaElement); } ReplaceSchemaInfo(e, xmlSchemaInfo); } RestoreLineInfo(originalLineInfo); namespaceManager.PopScope(); } private void ValidateNodes(XElement e) { XNode xNode = e.content as XNode; IXmlLineInfo originalLineInfo = SaveLineInfo(xNode); if (xNode != null) { do { xNode = xNode.next; if (xNode is XElement e2) { ValidateElement(e2); } else if (xNode is XText xText) { string value = xText.Value; if (value.Length > 0) { validator.LineInfoProvider = xText; validator.ValidateText(value); } } } while (xNode != e.content); source = e; } else if (e.content is string text && text.Length > 0) { validator.ValidateText(text); } RestoreLineInfo(originalLineInfo); } private void ValidationCallback(object sender, ValidationEventArgs e) { if (validationEventHandler != null) { validationEventHandler(source, e); } else if (e.Severity == XmlSeverityType.Error) { throw e.Exception; } } } internal class XmlSchemaInfoEqualityComparer : IEqualityComparer<XmlSchemaInfo> { public bool Equals(XmlSchemaInfo si1, XmlSchemaInfo si2) { if (si1 == si2) { return true; } if (si1 == null || si2 == null) { return false; } if (si1.ContentType == si2.ContentType && si1.IsDefault == si2.IsDefault && si1.IsNil == si2.IsNil && si1.MemberType == si2.MemberType && si1.SchemaAttribute == si2.SchemaAttribute && si1.SchemaElement == si2.SchemaElement && si1.SchemaType == si2.SchemaType) { return si1.Validity == si2.Validity; } return false; } public int GetHashCode(XmlSchemaInfo si) { if (si == null) { return 0; } int num = (int)si.ContentType; if (si.IsDefault) { num ^= 1; } if (si.IsNil) { num ^= 1; } XmlSchemaSimpleType memberType = si.MemberType; if (memberType != null) { num ^= memberType.GetHashCode(); } XmlSchemaAttribute schemaAttribute = si.SchemaAttribute; if (schemaAttribute != null) { num ^= schemaAttribute.GetHashCode(); } XmlSchemaElement schemaElement = si.SchemaElement; if (schemaElement != null) { num ^= schemaElement.GetHashCode(); } XmlSchemaType schemaType = si.SchemaType; if (schemaType != null) { num ^= schemaType.GetHashCode(); } return num ^ (int)si.Validity; } } public static class Extensions { public static IXmlSchemaInfo GetSchemaInfo(this XElement source) { if (source == null) { throw new ArgumentNullException("source"); } return source.Annotation<IXmlSchemaInfo>(); } public static IXmlSchemaInfo GetSchemaInfo(this XAttribute source) { if (source == null) { throw new ArgumentNullException("source"); } return source.Annotation<IXmlSchemaInfo>(); } public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler) { source.Validate(schemas, validationEventHandler, addSchemaInfo: false); } public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo) { if (source == null) { throw new ArgumentNullException("source"); } if (schemas == null) { throw new ArgumentNullException("schemas"); } new XNodeValidator(schemas, validationEventHandler).Validate(source, null, addSchemaInfo); } public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler) { source.Validate(partialValidationType, schemas, validationEventHandler, addSchemaInfo: false); } public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo) { if (source == null) { throw new ArgumentNullException("source"); } if (partialValidationType == null) { throw new ArgumentNullException("partialValidationType"); } if (schemas == null) { throw new ArgumentNullException("schemas"); } new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo); } public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler) { source.Validate(partialValidationType, schemas, validationEventHandler, addSchemaInfo: false); } public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo) { if (source == null) { throw new ArgumentNullException("source"); } if (partialValidationType == null) { throw new ArgumentNullException("partialValidationType"); } if (schemas == null) { throw new ArgumentNullException("schemas"); } new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo); } } } namespace System.Xml.Linq { internal class BaseUriAnnotation { internal string baseUri; public BaseUriAnnotation(string baseUri) { this.baseUri = baseUri; } } public static class Extensions { public static IEnumerable<XAttribute> Attributes(this IEnumerable<XElement> source) { if (source == null) { throw new ArgumentNullException("source"); } return GetAttributes(source, null); } public static IEnumerable<XAttribute> Attributes(this IEnumerable<XElement> source, XName name) { if (source == null) { throw new ArgumentNullException("source"); } if (!(name != null)) { return XAttribute.EmptySequence; } return GetAttributes(source, name); } public static IEnumerable<XElement> Ancestors<T>(this IEnumerable<T> source) where T : XNode { if (source == null) { throw new ArgumentNullException("source"); } return GetAncestors(source, null, self: false); } public static IEnumerable<XElement> Ancestors<T>(this IEnumerable<T> source, XName name) where T : XNode { if (source == null) { throw new ArgumentNullException("source"); } if (!(name != null)) { return XElement.EmptySequence; } return GetAncestors(source, name, self: false); } public static IEnumerable<XElement> AncestorsAndSelf(this IEnumerable<XElement> source) { if (source == null) { throw new ArgumentNullException("source"); } return GetAncestors(source, null, self: true); } public static IEnumerable<XElement> AncestorsAndSelf(this IEnumerable<XElement> source, XName name) { if (source == null) { throw new ArgumentNullException("source"); } if (!(name != null)) { return XElement.EmptySequence; } return GetAncestors(source, name, self: true); } public static IEnumerable<XNode> Nodes<T>(this IEnumerable<T> source) where T : XContainer { if (source == null) { throw new ArgumentNullException("source"); } return NodesIterator(source); } private static IEnumerable<XNode> NodesIterator<T>(IEnumerable<T> source) where T : XContainer { foreach (T root in source) { if (root == null) { continue; } XNode i = root.LastNode; if (i != null) { do { i = i.next; yield return i; } while (i.parent == root && i != root.content); } } } public static IEnumerable<XNode> DescendantNodes<T>(this IEnumerable<T> source) where T : XContainer { if (source == null) { throw new ArgumentNullException("source"); } return GetDescendantNodes(source, self: false); } public static IEnumerable<XElement> Descendants<T>(this IEnumerable<T> source) where T : XContainer { if (source == null) { throw new ArgumentNullException("source"); } return GetDescendants(source, null, self: false); } public static IEnumerable<XElement> Descendants<T>(this IEnumerable<T> source, XName name) where T : XContainer { if (source == null) { throw new ArgumentNullException("source"); } if (!(name != null)) { return XElement.EmptySequence; } return GetDescendants(source, name, self: false); } public static IEnumerable<XNode> DescendantNodesAndSelf(this IEnumerable<XElement> source) { if (source == null) { throw new ArgumentNullException("source"); } return GetDescendantNodes(source, self: true); } public static IEnumerable<XElement> DescendantsAndSelf(this IEnumerable<XElement> source) { if (source == null) { throw new ArgumentNullException("source"); } return GetDescendants(source, null, self: true); } public static IEnumerable<XElement> DescendantsAndSelf(this IEnumerable<XElement> source, XName name) { if (source == null) { throw new ArgumentNullException("source"); } if (!(name != null)) { return XElement.EmptySequence; } return GetDescendants(source, name, self: true); } public static IEnumerable<XElement> Elements<T>(this IEnumerable<T> source) where T : XContainer { if (source == null) { throw new ArgumentNullException("source"); } return GetElements(source, null); } public static IEnumerable<XElement> Elements<T>(this IEnumerable<T> source, XName name) where T : XContainer { if (source == null) { throw new ArgumentNullException("source"); } if (!(name != null)) { return XElement.EmptySequence; } return GetElements(source, name); } public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : XNode { if (source == null) { throw new ArgumentNullException("source"); } return DocumentOrderIterator(source); } private static IEnumerable<T> DocumentOrderIterator<T>(IEnumerable<T> source) where T : XNode { int count; T[] items = System.Collections.Generic.EnumerableHelpers.ToArray(source, out count); if (count > 0) { Array.Sort(items, 0, count, XNode.DocumentOrderComparer); int i = 0; while (i != count) { yield return items[i]; int num = i + 1; i = num; } } } public static void Remove(this IEnumerable<XAttribute> source) { if (source == null) { throw new ArgumentNullException("source"); } int length; XAttribute[] array = System.Collections.Generic.EnumerableHelpers.ToArray(source, out length); for (int i = 0; i < length; i++) { array[i]?.Remove(); } } public static void Remove<T>(this IEnumerable<T> source) where T : XNode { if (source == null) { throw new ArgumentNullException("source"); } int length; T[] array = System.Collections.Generic.EnumerableHelpers.ToArray(source, out length); for (int i = 0; i < length; i++) { array[i]?.Remove(); } } private static IEnumerable<XAttribute> GetAttributes(IEnumerable<XElement> source, XName name) { foreach (XElement e in source) { if (e == null) { continue; } XAttribute a = e.lastAttr; if (a == null) { continue; } do { a = a.next; if (name == null || a.name == name) { yield return a; } } while (a.parent == e && a != e.lastAttr); } } private static IEnumerable<XElement> GetAncestors<T>(IEnumerable<T> source, XName name, bool self) where T : XNode { foreach (T item in source) { if (item == null) { continue; } for (XElement e = (self ? ((XNode)item) : ((XNode)item.parent)) as XElement; e != null; e = e.parent as XElement) { if (name == null || e.name == name) { yield return e; } } } } private static IEnumerable<XNode> GetDescendantNodes<T>(IEnumerable<T> source, bool self) where T : XContainer { foreach (T root in source) { if (root == null) { continue; } if (self) { yield return root; } XNode i = root; while (true) { XNode firstNode; if (i is XContainer xContainer && (firstNode = xContainer.FirstNode) != null) { i = firstNode; } else { while (i != null && i != root && i == i.parent.content) { i = i.parent; } if (i == null || i == root) { break; } i = i.next; } yield return i; } } } private static IEnumerable<XElement> GetDescendants<T>(IEnumerable<T> source, XName name, bool self) where T : XContainer { foreach (T root in source) { if (root == null) { continue; } if (self) { XElement xElement = (XElement)(object)root; if (name == null || xElement.name == name) { yield return xElement; } } XNode i = root; XContainer xContainer = root; while (true) { if (xContainer != null && xContainer.content is XNode) { i = ((XNode)xContainer.content).next; } else { while (i != null && i != root && i == i.parent.content) { i = i.parent; } if (i == null || i == root) { break; } i = i.next; } XElement e = i as XElement; if (e != null && (name == null || e.name == name)) { yield return e; } xContainer = e; } } } private static IEnumerable<XElement> GetElements<T>(IEnumerable<T> source, XName name) where T : XContainer { foreach (T root in source) { if (root == null) { continue; } XNode i = root.content as XNode; if (i == null) { continue; } do { i = i.next; if (i is XElement xElement && (name == null || xElement.name == name)) { yield return xElement; } } while (i.parent == root && i != root.content); } } } internal class LineInfoAnnotation { internal int lineNumber; internal int linePosition; public LineInfoAnnotation(int lineNumber, int linePosition) { this.lineNumber = lineNumber; this.linePosition = linePosition; } } internal class LineInfoEndElementAnnotation : LineInfoAnnotation { public LineInfoEndElementAnnotation(int lineNumber, int linePosition) : base(lineNumber, linePosition) { } } public class XAttribute : XObject { internal XAttribute next; internal XName name; internal string value; public static IEnumerable<XAttribute> EmptySequence => Array.Empty<XAttribute>(); public bool IsNamespaceDeclaration { get { string namespaceName = name.NamespaceName; if (namespaceName.Length == 0) { return name.LocalName == "xmlns"; } return (object)namespaceName == "http://www.w3.org/2000/xmlns/"; } } public XName Name => name; public XAttribute NextAttribute { get { if (parent == null || ((XElement)parent).lastAttr == this) { return null; } return next; } } public override XmlNodeType NodeType => XmlNodeType.Attribute; public XAttribute PreviousAttribute { get { if (parent == null) { return null; } XAttribute lastAttr = ((XElement)parent).lastAttr; while (lastAttr.next != this) { lastAttr = lastAttr.next; } if (lastAttr == ((XElement)parent).lastAttr) { return null; } return lastAttr; } } public string Value { get { return value; } set { if (value == null) { throw new ArgumentNullException("value"); } ValidateAttribute(name, value); bool num = NotifyChanging(this, XObjectChangeEventArgs.Value); this.value = value; if (num) { NotifyChanged(this, XObjectChangeEventArgs.Value); } } } public XAttribute(XName name, object value) { if (name == null) { throw new ArgumentNullException("name"); } if (value == null) { throw new ArgumentNullException("value"); } string stringValue = XContainer.GetStringValue(value); ValidateAttribute(name, stringValue); this.name = name; this.value = stringValue; } public XAttribute(XAttribute other) { if (other == null) { throw new ArgumentNullException("other"); } name = other.name; value = other.value; } public void Remove() { if (parent == null) { throw new InvalidOperationException("The parent is missing."); } ((XElement)parent).RemoveAttribute(this); } public void SetValue(object value) { if (value == null) { throw new ArgumentNullException("value"); } Value = XContainer.GetStringValue(value); } public override string ToString() { using StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.ConformanceLevel = ConformanceLevel.Fragment; using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings)) { xmlWriter.WriteAttributeString(GetPrefixOfNamespace(name.Namespace), name.LocalName, name.NamespaceName, value); } return stringWriter.ToString().Trim(); } [CLSCompliant(false)] public static explicit operator string(XAttribute attribute) { return attribute?.value; } [CLSCompliant(false)] public static explicit operator bool(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant()); } [CLSCompliant(false)] public static explicit operator bool?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant()); } [CLSCompliant(false)] public static explicit operator int(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToInt32(attribute.value); } [CLSCompliant(false)] public static explicit operator int?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToInt32(attribute.value); } [CLSCompliant(false)] public static explicit operator uint(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToUInt32(attribute.value); } [CLSCompliant(false)] public static explicit operator uint?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToUInt32(attribute.value); } [CLSCompliant(false)] public static explicit operator long(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToInt64(attribute.value); } [CLSCompliant(false)] public static explicit operator long?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToInt64(attribute.value); } [CLSCompliant(false)] public static explicit operator ulong(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToUInt64(attribute.value); } [CLSCompliant(false)] public static explicit operator ulong?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToUInt64(attribute.value); } [CLSCompliant(false)] public static explicit operator float(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToSingle(attribute.value); } [CLSCompliant(false)] public static explicit operator float?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToSingle(attribute.value); } [CLSCompliant(false)] public static explicit operator double(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToDouble(attribute.value); } [CLSCompliant(false)] public static explicit operator double?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToDouble(attribute.value); } [CLSCompliant(false)] public static explicit operator decimal(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToDecimal(attribute.value); } [CLSCompliant(false)] public static explicit operator decimal?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToDecimal(attribute.value); } [CLSCompliant(false)] public static explicit operator DateTime(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); } [CLSCompliant(false)] public static explicit operator DateTime?(XAttribute attribute) { if (attribute == null) { return null; } return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); } [CLSCompliant(false)] public static explicit operator DateTimeOffset(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToDateTimeOffset(attribute.value); } [CLSCompliant(false)] public static explicit operator DateTimeOffset?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToDateTimeOffset(attribute.value); } [CLSCompliant(false)] public static explicit operator TimeSpan(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToTimeSpan(attribute.value); } [CLSCompliant(false)] public static explicit operator TimeSpan?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToTimeSpan(attribute.value); } [CLSCompliant(false)] public static explicit operator Guid(XAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } return XmlConvert.ToGuid(attribute.value); } [CLSCompliant(false)] public static explicit operator Guid?(XAttribute attribute) { if (attribute == null) { return null; } return XmlConvert.ToGuid(attribute.value); } internal int GetDeepHashCode() { return name.GetHashCode() ^ value.GetHashCode(); } internal string GetPrefixOfNamespace(XNamespace ns) { string namespaceName = ns.NamespaceName; if (namespaceName.Length == 0) { return string.Empty; } if (parent != null) { return ((XElement)parent).GetPrefixOfNamespace(ns); } if ((object)namespaceName == "http://www.w3.org/XML/1998/namespace") { return "xml"; } if ((object)namespaceName == "http://www.w3.org/2000/xmlns/") { return "xmlns"; } return null; } private static void ValidateAttribute(XName name, string value) { string namespaceName = name.NamespaceName; if ((object)namespaceName == "http://www.w3.org/2000/xmlns/") { if (value.Length == 0) { throw new ArgumentException(SR.Format("The prefix '{0}' cannot be bound to the empty namespace name.", name.LocalName)); } if (value == "http://www.w3.org/XML/1998/namespace") { if (name.LocalName != "xml") { throw new ArgumentException("The prefix 'xml' is bound to the namespace name 'http://www.w3.org/XML/1998/namespace'. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace."); } return; } if (value == "http://www.w3.org/2000/xmlns/") { throw new ArgumentException("The prefix 'xmlns' is bound to the namespace name 'http://www.w3.org/2000/xmlns/'. It must not be declared. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace."); } string localName = name.LocalName; if (localName == "xml") { throw new ArgumentException("The prefix 'xml' is bound to the namespace name 'http://www.w3.org/XML/1998/namespace'. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace."); } if (localName == "xmlns") { throw new ArgumentException("The prefix 'xmlns' is bound to the namespace name 'http://www.w3.org/2000/xmlns/'. It must not be declared. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace."); } } else if (namespaceName.Length == 0 && name.LocalName == "xmlns") { if (value == "http://www.w3.org/XML/1998/namespace") { throw new ArgumentException("The prefix 'xml' is bound to the namespace name 'http://www.w3.org/XML/1998/namespace'. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace."); } if (value == "http://www.w3.org/2000/xmlns/") { throw new ArgumentException("The prefix 'xmlns' is bound to the namespace name 'http://www.w3.org/2000/xmlns/'. It must not be declared. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace."); } } } } public class XCData : XText { public override XmlNodeType NodeType => XmlNodeType.CDATA; public XCData(string value) : base(value) { } public XCData(XCData other) : base(other) { } internal XCData(XmlReader r) : base(r) { } public override void WriteTo(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } writer.WriteCData(text); } public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { if (writer == null) { throw new ArgumentNullException("writer"); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } return writer.WriteCDataAsync(text); } internal override XNode CloneNode() { return new XCData(this); } } public class XComment : XNode { internal string value; public override XmlNodeType NodeType => XmlNodeType.Comment; public string Value { get { return value; } set { if (value == null) { throw new ArgumentNullException("value"); } bool num = NotifyChanging(this, XObjectChangeEventArgs.Value); this.value = value; if (num) { NotifyChanged(this, XObjectChangeEventArgs.Value); } } } public XComment(string value) { if (value == null) { throw new ArgumentNullException("value"); } this.value = value; } public XComment(XComment other) { if (other == null) { throw new ArgumentNullException("other"); } value = other.value; } internal XComment(XmlReader r) { value = r.Value; r.Read(); } public override void WriteTo(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } writer.WriteComment(value); } public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { if (writer == null) { throw new ArgumentNullException("writer"); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } return writer.WriteCommentAsync(value); } internal override XNode CloneNode() { return new XComment(this); } internal override bool DeepEquals(XNode node) { if (node is XComment xComment) { return value == xComment.value; } return false; } internal override int GetDeepHashCode() { return value.GetHashCode(); } } public abstract class XContainer : XNode { private sealed class ContentReader { private readonly NamespaceCache _eCache; private readonly NamespaceCache _aCache; private readonly IXmlLineInfo _lineInfo; private XContainer _currentContainer; private string _baseUri; public ContentReader(XContainer rootContainer) { _currentContainer = rootContainer; } public ContentReader(XContainer rootContainer, XmlReader r, LoadOptions o) { _currentContainer = rootContainer; _baseUri = (((o & LoadOptions.SetBaseUri) != 0) ? r.BaseURI : null); _lineInfo = (((o & LoadOptions.SetLineInfo) != 0) ? (r as IXmlLineInfo) : null); } public bool ReadContentFrom(XContainer rootContainer, XmlReader r) { switch (r.NodeType) { case XmlNodeType.Element: { XElement xElement = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName)); if (r.MoveToFirstAttribute()) { do { xElement.AppendAttributeSkipNotify(new XAttribute(_aCache.Get((r.Prefix.Length == 0) ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value)); } while (r.MoveToNextAttribute()); r.MoveToElement(); } _currentContainer.AddNodeSkipNotify(xElement); if (!r.IsEmptyElement) { _currentContainer = xElement; } break; } case XmlNodeType.EndElement: if (_currentContainer.content == null) { _currentContainer.content = string.Empty; } if (_currentContainer == rootContainer) { return false; } _currentContainer = _currentContainer.parent; break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: _currentContainer.AddStringSkipNotify(r.Value); break; case XmlNodeType.CDATA: _currentContainer.AddNodeSkipNotify(new XCData(r.Value)); break; case XmlNodeType.Comment: _currentContainer.AddNodeSkipNotify(new XComment(r.Value)); break; case XmlNodeType.ProcessingInstruction: _currentContainer.AddNodeSkipNotify(new XProcessingInstruction(r.Name, r.Value)); break; case XmlNodeType.DocumentType: _currentContainer.AddNodeSkipNotify(new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value)); break; case XmlNodeType.EntityReference: if (!r.CanResolveEntity) { throw new InvalidOperationException("The XmlReader cannot resolve entity references."); } r.ResolveEntity(); break; default: throw new InvalidOperationException(SR.Format("The XmlReader should not be on a node of type {0}.", r.NodeType)); case XmlNodeType.EndEntity: break; } return true; } public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o) { XNode xNode = null; string baseURI = r.BaseURI; switch (r.NodeType) { case XmlNodeType.Element: { XElement xElement2 = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName)); if (_baseUri != null && _baseUri != baseURI) { xElement2.SetBaseUri(baseURI); } if (_lineInfo != null && _lineInfo.HasLineInfo()) { xElement2.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition); } if (r.MoveToFirstAttribute()) { do { XAttribute xAttribute = new XAttribute(_aCache.Get((r.Prefix.Length == 0) ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value); if (_lineInfo != null && _lineInfo.HasLineInfo()) { xAttribute.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition); } xElement2.AppendAttributeSkipNotify(xAttribute); } while (r.MoveToNextAttribute()); r.MoveToElement(); } _currentContainer.AddNodeSkipNotify(xElement2); if (!r.IsEmptyElement) { _currentContainer = xElement2; if (_baseUri != null) { _baseUri = baseURI; } } break; } case XmlNodeType.EndElement: if (_currentContainer.content == null) { _currentContainer.content = string.Empty; } if (_currentContainer is XElement xElement && _lineInfo != null && _lineInfo.HasLineInfo()) { xElement.SetEndElementLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition); } if (_currentContainer == rootContainer) { return false; } if (_baseUri != null && _currentContainer.HasBaseUri) { _baseUri = _currentContainer.parent.BaseUri; } _currentContainer = _currentContainer.parent; break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if ((_baseUri != null && _baseUri != baseURI) || (_lineInfo != null && _lineInfo.HasLineInfo())) { xNode = new XText(r.Value); } else { _currentContainer.AddStringSkipNotify(r.Value); } break; case XmlNodeType.CDATA: xNode = new XCData(r.Value); break; case XmlNodeType.Comment: xNode = new XComment(r.Value); break; case XmlNodeType.ProcessingInstruction: xNode = new XProcessingInstruction(r.Name, r.Value); break; case XmlNodeType.DocumentType: xNode = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value); break; case XmlNodeType.EntityReference: if (!r.CanResolveEntity) { throw new InvalidOperationException("The XmlReader cannot resolve entity references."); } r.ResolveEntity(); break; default: throw new InvalidOperationException(SR.Format("The XmlReader should not be on a node of type {0}.", r.NodeType)); case XmlNodeType.EndEntity: break; } if (xNode != null) { if (_baseUri != null && _baseUri != baseURI) { xNode.SetBaseUri(baseURI); } if (_lineInfo != null && _lineInfo.HasLineInfo()) { xNode.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition); } _currentContainer.AddNodeSkipNotify(xNode); xNode = null; } return true; } } internal object content; public XNode FirstNode => LastNode?.next; public XNode LastNode { get { if (content == null) { return null; } if (content is XNode result) { return result; } if (content is string text) { if (text.Length == 0) { return null; } XText xText = new XText(text); xText.parent = this; xText.next = xText; Interlocked.CompareExchange<object>(ref content, (object)xText, (object)text); } return (XNode)content; } } internal XContainer() { } internal XContainer(XContainer other) { if (other == null) { throw new ArgumentNullException("other"); } if (other.content is string) { content = other.content; return; } XNode xNode = (XNode)other.content; if (xNode != null) { do { xNode = xNode.next; AppendNodeSkipNotify(xNode.CloneNode()); } while (xNode != other.content); } } public void Add(object content) { if (SkipNotify()) { AddContentSkipNotify(content); } else { if (content == null) { return; } if (content is XNode n) { AddNode(n); return; } if (content is string s) { AddString(s); return; } if (content is XAttribute a) { AddAttribute(a); return; } if (content is XStreamingElement other) { AddNode(new XElement(other)); return; } if (content is object[] array) { object[] array2 = array; foreach (object obj in array2) { Add(obj); } return; } if (content is IEnumerable enumerable) { { foreach (object item in enumerable) { Add(item); } return; } } AddString(GetStringValue(content)); } } public void Add(params object[] content) { Add((object)content); } public void AddFirst(object content) { new Inserter(this, null).Add(content); } public void AddFirst(params object[] content) { AddFirst((object)content); } public XmlWriter CreateWriter() { XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.ConformanceLevel = ((!(this is XDocument)) ? ConformanceLevel.Fragment : ConformanceLevel.Document); return XmlWriter.Create(new XNodeBuilder(this), xmlWriterSettings); } public IEnumerable<XNode> DescendantNodes() { return GetDescendantNodes(self: false); } public IEnumerable<XElement> Descendants() { return GetDescendants(null, self: false); } public IEnumerable<XElement> Descendants(XName name) { if (!(name != null)) { return XElement.EmptySequence; } return GetDescendants(name, self: false); } public XElement Element(XName name) { XNode xNode = content as XNode; if (xNode != null) { do { xNode = xNode.next; if (xNode is XElement xElement && xElement.name == name) { return xElement; } } while (xNode != content); } return null; } public IEnumerable<XElement> Elements() { return GetElements(null); } public IEnumerable<XElement> Elements(XName name) { if (!(name != null)) { return XElement.EmptySequence; } return GetElements(name); } public IEnumerable<XNode> Nodes() { XNode i = LastNode; if (i != null) { do { i = i.next; yield return i; } while (i.parent == this && i != content); } } public void RemoveNodes() { if (SkipNotify()) { RemoveNodesSkipNotify(); return; } while (content != null) { if (content is string text) { if (text.Length > 0) { ConvertTextToNode(); } else if (this is XElement) { NotifyChanging(this, XObjectChangeEventArgs.Value); if (text != content) { throw new InvalidOperationException("This operation was corrupted by external code."); } content = null; NotifyChanged(this, XObjectChangeEventArgs.Value); } else { content = null; } } if (content is XNode xNode) { XNode xNode2 = xNode.next; NotifyChanging(xNode2, XObjectChangeEventArgs.Remove); if (xNode != content || xNode2 != xNode.next) { throw new InvalidOperationException("This operation was corrupted by external code."); } if (xNode2 != xNode) { xNode.next = xNode2.next; } else { content = null; } xNode2.parent = null; xNode2.next = null; NotifyChanged(xNode2, XObjectChangeEventArgs.Remove); } } } public void ReplaceNodes(object content) { content = GetContentSnapshot(content); RemoveNodes(); Add(content); } public void ReplaceNodes(params object[] content) { ReplaceNodes((object)content); } internal virtual void AddAttribute(XAttribute a) { } internal virtual void AddAttributeSkipNotify(XAttribute a) { } internal void AddContentSkipNotify(object content) { if (content == null) { return; } if (content is XNode n) { AddNodeSkipNotify(n); return; } if (content is string s) { AddStringSkipNotify(s); return; } if (content is XAttribute a) { AddAttributeSkipNotify(a); return; } if (content is XStreamingElement other) { AddNodeSkipNotify(new XElement(other)); return; } if (content is object[] array) { object[] array2 = array; foreach (object obj in array2) { AddContentSkipNotify(obj); } return; } if (content is IEnumerable enumerable) { { foreach (object item in enumerable) { AddContentSkipNotify(item); } return; } } AddStringSkipNotify(GetStringValue(content)); } internal void AddNode(XNode n) { ValidateNode(n, this); if (n.parent != null) { n = n.CloneNode(); } else { XNode xNode = this; while (xNode.parent != null) { xNode = xNode.parent; } if (n == xNode) { n = n.CloneNode(); } } ConvertTextToNode(); AppendNode(n); } internal void AddNodeSkipNotify(XNode n) { ValidateNode(n, this); if (n.parent != null) { n = n.CloneNode(); } else { XNode xNode = this; while (xNode.parent != null) { xNode = xNode.parent; } if (n == xNode) { n = n.CloneNode(); } } ConvertTextToNode(); AppendNodeSkipNotify(n); } internal void AddString(string s) { ValidateString(s); if (content == null) { if (s.Length > 0) { AppendNode(new XText(s)); } else if (this is XElement) { NotifyChanging(this, XObjectChangeEventArgs.Value); if (content != null) { throw new InvalidOperationException("This operation was corrupted by external code."); } content = s; NotifyChanged(this, XObjectChangeEventArgs.Value); } else { content = s; } } else if (s.Length > 0) { ConvertTextToNode(); if (content is XText xText && !(xText is XCData)) { xText.Value += s; } else { AppendNode(new XText(s)); } } } internal void AddStringSkipNotify(string s) { ValidateString(s); if (content == null) { content = s; } else if (s.Length > 0) { if (content is string text) { content = text + s; } else if (content is XText xText && !(xText is XCData)) { xText.text += s; } else { AppendNodeSkipNotify(new XText(s)); } } } internal void AppendNode(XNode n) { bool num = NotifyChanging(n, XObjectChangeEventArgs.Add); if (n.parent != null) { throw new InvalidOperationException("This operation was corrupted by external code."); } AppendNodeSkipNotify(n); if (num) { NotifyChanged(n, XObjectChangeEventArgs.Add); } } internal void AppendNodeSkipNotify(XNode n) { n.parent = this; if (content == null || content is string) { n.next = n; } else { XNode xNode = (XNode)content; n.next = xNode.next; xNode.next = n; } content = n; } internal override void AppendText(StringBuilder sb) { if (content is string value) { sb.Append(value); return; } XNode xNode = (XNode)content; if (xNode != null) { do { xNode = xNode.next; xNode.AppendText(sb); } while (xNode != content); } } private string GetTextOnly() { if (content == null) { return null; } string text = content as string; if (text == null) { XNode xNode = (XNode)content; do { xNode = xNode.next; if (xNode.NodeType != XmlNodeType.Text) { return null; } text += ((XText)xNode).Value; } while (xNode != content); } return text; } private string CollectText(ref XNode n) { string text = ""; while (n != null && n.NodeType == XmlNodeType.Text) { text += ((XText)n).Value; n = ((n != content) ? n.next : null); } return text; } internal bool ContentsEqual(XContainer e) { if (content == e.content) { return true; } string textOnly = GetTextOnly(); if (textOnly != null) { return textOnly == e.GetTextOnly(); } XNode xNode = content as XNode; XNode xNode2 = e.content as XNode; if (xNode != null && xNode2 != null) { xNode = xNode.next; xNode2 = xNode2.next; while (!(CollectText(ref xNode) != e.CollectText(ref xNode2))) { if (xNode == null && xNode2 == null) { return true; } if (xNode == null || xNode2 == null || !xNode.DeepEquals(xNode2)) { break; } xNode = ((xNode != content) ? xNode.next : null); xNode2 = ((xNode2 != e.content) ? xNode2.next : null); } } return false; } internal int ContentsHashCode() { string textOnly = GetTextOnly(); if (textOnly != null) { return textOnly.GetHashCode(); } int num = 0; XNode n = content as XNode; if (n != null) { do { n = n.next; string text = CollectText(ref n); if (text.Length > 0) { num ^= text.GetHashCode(); } if (n == null) { break; } num ^= n.GetDeepHashCode(); } while (n != content); } return num; } internal void ConvertTextToNode() { string value = content as string; if (!string.IsNullOrEmpty(value)) { XText xText = new XText(value); xText.parent = this; xText.next = xText; content = xText; } } internal IEnumerable<XNode> GetDescendantNodes(bool self) { if (self) { yield return this; } XNode i = this; while (true) { XNode firstNode; if (i is XContainer xContainer && (firstNode = xContainer.FirstNode) != null) { i = firstNode; } else { while (i != null && i != this && i == i.parent.content) { i = i.parent; } if (i == null || i == this) { break; } i = i.next; } yield return i; } } internal IEnumerable<XElement> GetDescendants(XName name, bool self) { if (self) { XElement xElement = (XElement)this; if (name == null || xElement.name == name) { yield return xElement; } } XNode i = this; XContainer xContainer = this; while (true) { if (xContainer != null && xContainer.content is XNode) { i = ((XNode)xContainer.content).next; } else { while (i != this && i == i.parent.content) { i = i.parent; } if (i == this) { break; } i = i.next; } XElement e = i as XElement; if (e != null && (name == null || e.name == name)) { yield return e; } xContainer = e; } } private IEnumerable<XElement> GetElements(XName name) { XNode i = content as XNode; if (i == null) { yield break; } do { i = i.next; if (i is XElement xElement && (name == null || xElement.name == name)) { yield return xElement; } } while (i.parent == this && i != content); } internal static string GetStringValue(object value) { if (value is string result) { return result; } string text; if (value is double) { text = XmlConvert.ToString((double)value); } else if (value is float) { text = XmlConvert.ToString((float)value); } else if (value is decimal) { text = XmlConvert.ToString((decimal)value); } else if (value is bool) { text = XmlConvert.ToString((bool)value); } else if (value is DateTime) { text = XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind); } else if (value is DateTimeOffset) { text = XmlConvert.ToString((DateTimeOffset)value); } else if (value is TimeSpan) { text = XmlConvert.ToString((TimeSpan)value); } else { if (value is XObject) { throw new ArgumentException("An XObject cannot be used as a value."); } text = value.ToString(); } if (text == null) { throw new ArgumentException("The argument cannot be converted to a string."); } return text; } internal void ReadContentFrom(XmlReader r) { if (r.ReadState != ReadState.Interactive) { throw new InvalidOperationException("The XmlReader state should be Interactive."); } ContentReader contentReader = new ContentReader(this); while (contentReader.ReadContentFrom(this, r) && r.Read()) { } } internal void ReadContentFrom(XmlReader r, LoadOptions o) { if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0) { ReadContentFrom(r); return; } if (r.ReadState != ReadState.Interactive) { throw new InvalidOperationException("The XmlReader state should be Interactive."); } ContentReader contentReader = new ContentReader(this, r, o); while (contentReader.ReadContentFrom(this, r, o) && r.Read()) { } } internal async Task ReadContentFromAsync(XmlReader r, CancellationToken cancellationToken) { if (r.ReadState != ReadState.Interactive) { throw new InvalidOperationException("The XmlReader state should be Interactive."); } ContentReader cr = new ContentReader(this); bool flag; do { cancellationToken.ThrowIfCancellationRequested(); flag = cr.ReadContentFrom(this, r); if (flag) { flag = await r.ReadAsync().ConfigureAwait(continueOnCapturedContext: false); } } while (flag); } internal async Task ReadContentFromAsync(XmlReader r, LoadOptions o, CancellationToken cancellationToken) { if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0) { await ReadContentFromAsync(r, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); return; } if (r.ReadState != ReadState.Interactive) { throw new InvalidOperationException("The XmlReader state should be Interactive."); } ContentReader cr = new ContentReader(this, r, o); bool flag; do { cancellationToken.ThrowIfCancellationRequested(); flag = cr.ReadContentFrom(this, r, o); if (flag) { flag = await r.ReadAsync().ConfigureAwait(continueOnCapturedContext: false); } } while (flag); } internal void RemoveNode(XNode n) { bool flag = NotifyChanging(n, XObjectChangeEventArgs.Remove); if (n.parent != this) { throw new InvalidOperationException("This operation was corrupted by external code."); } XNode xNode = (XNode)content; while (xNode.next != n) { xNode = xNode.next; } if (xNode == n) { content = null; } else { if (content == n) { content = xNode; } xNode.next = n.next; } n.parent = null; n.next = null; if (flag) { NotifyChanged(n, XObjectChangeEventArgs.Remove); } } private void RemoveNodesSkipNotify() { XNode xNode = content as XNode; if (xNode != null) { do { XNode xNode2 = xNode.next; xNode.parent = null; xNode.next = null; xNode = xNode2; } while (xNode != content); } content = null; } internal virtual void ValidateNode(XNode node, XNode previous) { } internal virtual void ValidateString(string s) { } internal void WriteContentTo(XmlWriter writer) { if (content == null) { return; } if (content is string text) { if (this is XDocument) { writer.WriteWhitespace(text); } else { writer.WriteString(text); } return; } XNode xNode = (XNode)content; do { xNode = xNode.next; xNode.WriteTo(writer); } while (xNode != content); } internal async Task WriteContentToAsync(XmlWriter writer, CancellationToken cancellationToken) { if (content == null) { return; } if (content is string text) { cancellationToken.ThrowIfCancellationRequested(); Task task = ((!(this is XDocument)) ? writer.WriteStringAsync(text) : writer.WriteWhitespaceAsync(text)); await task.ConfigureAwait(continueOnCapturedContext: false); return; } XNode i = (XNode)content; do { i = i.next; await i.WriteToAsync(writer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } while (i != content); } private static void AddContentToList(List<object> list, object content) { IEnumerable enumerable = ((content is string) ? null : (content as IEnumerable)); if (enumerable == null) { list.Add(content); return; } foreach (object item in enumerable) { if (item != null) { AddContentToList(list, item); } } } internal static object GetContentSnapshot(object content) { if (content is string || !(content is IEnumerable)) { return content; } List<object> list = new List<object>(); AddContentToList(list, content); return list; } } public class XDeclaration { private string _version; private string _encoding; private string _standalone; public string Encoding { get { return _encoding; } set { _encoding = value; } } public string Standalone { get { return _standalone; } set { _standalone = value; } } public string Version { get { return _version; } set { _version = value; } } public XDeclaration(string version, string encoding, string standalone) { _version = version; _encoding = encoding; _standalone = standalone; } public XDeclaration(XDeclaration other) { if (other == null) { throw new ArgumentNullException("other"); } _version = other._version; _encoding = other._encoding; _standalone = other._standalone; } internal XDeclaration(XmlReader r) { _version = r.GetAttribute("version"); _encoding = r.GetAttribute("encoding"); _standalone = r.GetAttribute("standalone"); r.Read(); } public override string ToString() { StringBuilder stringBuilder = System.Text.StringBuilderCache.Acquire(); stringBuilder.Append("<?xml"); if (_version != null) { stringBuilder.Append(" version=\""); stringBuilder.Append(_version); stringBuilder.Append('"'); } if (_encoding != null) { stringBuilder.Append(" encoding=\""); stringBuilder.Append(_encoding); stringBuilder.Append('"'); } if (_standalone != null) { stringBuilder.Append(" standalone=\""); stringBuilder.Append(_standalone); stringBuilder.Append('"'); } stringBuilder.Append("?>"); return System.Text.StringBuilderCache.GetStringAndRelease(stringBuilder); } } public class XDocument : XContainer { private XDeclaration _declaration; public XDeclaration Declaration { get { return _declaration; } set { _declaration = value; } } public XDocumentType DocumentType => GetFirstNode<XDocumentType>(); public override XmlNodeType NodeType => XmlNodeType.Document; public XElement Root => GetFirstNode<XElement>(); public XDocument() { } public XDocument(params object[] content) : this() { AddContentSkipNotify(content); } public XDocument(XDeclaration declaration, params object[] content) : this(content) { _declaration = declaration; } public XDocument(XDocument other) : base(other) { if (other._declaration != null) { _declaration = new XDeclaration(other._declaration); } } public static XDocument Load(string uri) { return Load(uri, LoadOptions.None); } public static XDocument Load(string uri, LoadOptions options) { XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options); using XmlReader reader = XmlReader.Create(uri, xmlReaderSettings); return Load(reader, options); } public static XDocument Load(Stream stream) { return Load(stream, LoadOptions.None); } public static XDocument Load(Stream stream, LoadOptions options) { XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options); using XmlReader reader = XmlReader.Create(stream, xmlReaderSettings); return Load(reader, options); } public static async Task<XDocument> LoadAsync(Stream stream, LoadOptions options, CancellationToken cancellationToken) { XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options); xmlReaderSettings.Async = true; using XmlReader r = XmlReader.Create(stream, xmlReaderSettings); return await LoadAsync(r, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static XDocument Load(TextReader textReader) { return Load(textReader, LoadOptions.None); } public static XDocument Load(TextReader textReader, LoadOptions options) { XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options); using XmlReader reader = XmlReader.Create(textReader, xmlReaderSettings); return Load(reader, options); } public static async Task<XDocument> LoadAsync(TextReader textReader, LoadOptions options, CancellationToken cancellationToken) { XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options); xmlReaderSettings.Async = true; using XmlReader r = XmlReader.Create(textReader, xmlReaderSettings); return await LoadAsync(r, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public static XDocument Load(XmlReader reader) { return Load(reader, LoadOptions.None); } public static XDocument Load(XmlReader reader, LoadOptions options) { if (reader == null) { throw new ArgumentNullException("reader"); } if (reader.ReadState == ReadState.Initial) { reader.Read(); } XDocument xDocument = InitLoad(reader, options); xDocument.ReadContentFrom(reader, options); if (!reader.EOF) { throw new InvalidOperationException("The XmlReader state should be EndOfFile after this operation."); } if (xDocument.Root == null) { throw new InvalidOperationException("The root element is missing."); } return xDocument; } public static Task<XDocument> LoadAsync(XmlReader reader, LoadOptions options, CancellationToken cancellationToken) { if (reader == null) { throw new ArgumentNullException("reader"); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<XDocument>(cancellationToken); } return LoadAsyncInternal(reader, options, cancellationToken); } private static async Task<XDocument> LoadAsyncInternal(XmlReader reader, LoadOptions options, CancellationToken cancellationToken) { if (reader.ReadState == ReadState.Initial) { await reader.ReadAsync().ConfigureAwait(continueOnCapturedContext: false); } XDocument d = InitLoad(reader, options); await d.ReadContentFromAsync(reader, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (!reader.EOF) { throw new InvalidOperationException("The XmlReader state should be EndOfFile after this operation."); } if (d.Root == null) { throw new InvalidOperationException("The root element is missing."); } return d; } private static XDocument InitLoad(XmlReader reader, LoadOptions options) { XDocument xDocument = new XDocument(); if ((options & LoadOptions.SetBaseUri) != 0) { string baseURI = reader.BaseURI; if (!string.IsNullOrEmpty(baseURI)) { xDocument.SetBaseUri(baseURI); } } if ((options & LoadOptions.SetLineInfo) != 0 && reader is IXmlLineInfo xmlLineInfo && xmlLineInfo.HasLineInfo()) { xDocument.SetLineInfo(xmlLineInfo.LineNumber, xmlLineInfo.LinePosition); } if (reader.NodeType == XmlNodeType.XmlDeclaration) { xDocument.Declaration = new XDeclaration(reader); } return xDocument; } public static XDocument Parse(string text) { return Parse(text, LoadOptions.None); } public static XDocument Parse(string text, LoadOptions options) { using StringReader input = new StringReader(text); XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options); using XmlReader reader = XmlReader.Create(input, xmlReaderSettings); return Load(reader, options); } public void Save(Stream stream) { Save(stream, GetSaveOptionsFromAnnotations()); } public void Save(Stream stream, SaveOptions options) { XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options); if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding)) { try { xmlWriterSettings.Encoding = Encoding.GetEncoding(_declaration.Encoding); } catch (ArgumentException) { } } using XmlWriter writer = XmlWriter.Create(stream, xmlWriterSettings); Save(writer); } public async Task SaveAsync(Stream stream, SaveOptions options, CancellationToken cancellationToken) { XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options); xmlWriterSettings.Async = true; if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding)) { try { xmlWriterSettings.Encoding = Encoding.GetEncoding(_declaration.Encoding); } catch (ArgumentException) { } } using XmlWriter w = XmlWriter.Create(stream, xmlWriterSettings); await WriteToAsync(w, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public void Save(TextWriter textWriter) { Save(textWriter, GetSaveOptionsFromAnnotations()); } public void Save(TextWriter textWriter, SaveOptions options) { XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options); using XmlWriter writer = XmlWriter.Create(textWriter, xmlWriterSettings); Save(writer); } public void Save(XmlWriter writer) { WriteTo(writer); } public async Task SaveAsync(TextWriter textWriter, SaveOptions options, CancellationToken cancellationToken) { XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options); xmlWriterSettings.Async = true; using XmlWriter w = XmlWriter.Create(textWriter, xmlWriterSettings); await WriteToAsync(w, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public void Save(string fileName) { Save(fileName, GetSaveOptionsFromAnnotations()); } public Task SaveAsync(XmlWriter writer, CancellationToken cancellationToken) { return WriteToAsync(writer, cancellationToken); } public void Save(string fileName, SaveOptions options) { XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options); if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding)) { try { xmlWriterSettings.Encoding = Encoding.GetEncoding(_declaration.Encoding); } catch (ArgumentException) { } } using XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings); Save(writer); } public override void WriteTo(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } if (_declaration != null && _declaration.Standalone == "yes") { writer.WriteStartDocument(standalone: true); } else if (_declaration != null && _declaration.Standalone == "no") { writer.WriteStartDocument(standalone: false); } else { writer.WriteStartDocument(); } WriteContentTo(writer); writer.WriteEndDocument(); } public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { if (writer == null) { throw new ArgumentNullException("writer"); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } return WriteToAsyncInternal(writer, cancellationToken); } private async Task WriteToAsyncInternal(XmlWriter writer, CancellationToken cancellationToken) { Task task = ((_declaration != null && _declaration.Standalone == "yes") ? writer.WriteStartDocumentAsync(standalone: true) : ((_declaration == null || !(_declaration.Standalone == "no")) ? writer.WriteStartDocumentAsync() : writer.WriteStartDocumentAsync(standalone: false))); await task.ConfigureAwait(continueOnCapturedContext: false); await WriteContentToAsync(writer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); await writer.WriteEndDocumentAsync().ConfigureAwait(continueOnCapturedContext: false); } internal override void AddAttribute(XAttribute a) { throw new ArgumentException("An attribute cannot be added to content."); } internal override void AddAttributeSkipNotify(XAttribute a) { throw new ArgumentException("An attribute cannot be added to content."); } internal override XNode CloneNode() { return new XDocument(this); } internal override bool DeepEquals(XNode node) { if (node is XDocument e) { return ContentsEqual(e); } return false; } internal override int GetDeepHashCode() { return ContentsHashCode(); } private T GetFirstNode<T>() where T : XNode { XNode xNode = content as XNode; if (xNode != null) { do { xNode = xNode.next; if (xNode is T result) { return result; } } while (xNode != content); } return null; } internal static bool IsWhitespace(string s) { foreach (char c in s) { if (c != ' ' && c != '\t' && c != '\r' && c != '\n') { return false; } } return true; } internal override void ValidateNode(XNode node, XNode previous) { switch (node.NodeType) { case XmlNodeType.Text: ValidateString(((XText)node).Value); break; case XmlNodeType.Element: ValidateDocument(previous, XmlNodeType.DocumentType, XmlNodeType.None); break; case XmlNodeType.DocumentType: ValidateDocument(previous, XmlNodeType.None, XmlNodeType.Element); break; case XmlNodeType.CDATA