Decompiled source of VoiceBox v0.3.4
VoiceBoxModLib.Core.dll
Decompiled a month 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.MediaFoundation; 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("0.3.4.0")] [assembly: AssemblyInformationalVersion("0.3.4+8df47c835b89e3c9278a4984060ef6efbdf76fe6")] [assembly: AssemblyProduct("VoiceBoxModLib.Core")] [assembly: AssemblyTitle("VoiceBoxModLib.Core")] [assembly: AssemblyVersion("0.3.4.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 2!", 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) { if (e.Result.Reason == STTUtils.VoiceBoxResultReason.RecognizedSpeech) { if (e.Result.Text.Length > 0) { Debug.Log((object)("API Tester: Recognized: " + e.Result.Text)); } } else if (e.Result.Reason == STTUtils.VoiceBoxResultReason.RecognizedSpeechWithTimestamps && e.Result.Text.Length > 0) { Debug.Log((object)("API Tester: Recognized with timestamps: " + 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 bool requestWordLevelTimestamps; 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 enum ElevenlabsSTTCommitStrategy { Manual, Vad } [CreateAssetMenu(fileName = "ElevenlabsSTTServiceConfig", menuName = "VoiceBox/STT/ElevenlabsSTTService Configuration")] public class ElevenlabsSTTServiceConfig : GenericSTTServiceConfig { public string language_code = "eng"; public string audioInputDeviceName = "Default"; public string[] audioInputEndpointNames = new string[1] { "Default" }; public bool include_timestamps = true; public bool include_language_detection; public ElevenlabsSTTCommitStrategy commit_strategy = ElevenlabsSTTCommitStrategy.Vad; public double vad_silence_threshold_secs = 0.65; public double vad_threshold = 0.4; public int min_speech_duration_ms = 250; public int min_silence_duration_ms = 550; public ElevenlabsSTTServiceConfig() { serviceManagerType = typeof(ElevenlabsSTTServiceManager); apiKeyJSONString = "ELEVENLABS_API_KEY"; } public void OnValidate() { audioInputEndpointNames = STTUtils.GetAudioInputEndpoints().Keys.ToArray(); } } [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 = 0.5f; [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 = 0.75f; [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 = true; [Tooltip("A float between 0.7 and 1.2. A higher value will exaggerate the speed of the voice.")] [Range(0.7f, 1.2f)] public float speed = 1f; } [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_flash_v2_5.")] public string modelID = "eleven_flash_v2_5"; [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(); private CancellationTokenSource internalTtsCancellationTokenSource = 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(); internalTtsCancellationTokenSource.Cancel(); UnloadAPIKeys(); Instance = null; } 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)"[AI Manager] 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); if (internalTtsCancellationTokenSource.IsCancellationRequested) { internalTtsCancellationTokenSource = new CancellationTokenSource(); } audioStreamer.ConnectAndStream(prompt, TextToSpeechService, isFinalSegment: true, internalTtsCancellationTokenSource.Token); } else { Debug.LogError((object)"[AI Manager] Audio Streamer is null."); } } public void RequestAudioAndStream(string promptChunk, bool isFinalSegment, AudioStreamer audioStreamer, CancellationToken token = default(CancellationToken)) { if (Object.op_Implicit((Object)(object)audioStreamer)) { audioStreamer.InitStreaming(TextToSpeechService); if (internalTtsCancellationTokenSource.IsCancellationRequested) { internalTtsCancellationTokenSource = new CancellationTokenSource(); } audioStreamer.ConnectAndStream(promptChunk, TextToSpeechService, isFinalSegment, internalTtsCancellationTokenSource.Token); } else { Debug.LogError((object)"[AI Manager] Audio Streamer is null."); } } public async Task<string> CloneVoiceAndGetVoiceIDAsync(AudioFileSource filePaths, string voiceName, string description = "", bool removeBackgroundNoise = false) { return await TextToSpeechService.CloneVoiceAndGetVoiceIDAsync(filePaths.Paths, voiceName, description, removeBackgroundNoise); } public async Task<string> CloneVoiceAndGetVoiceIDAsync(AudioDataSource audioDataList, string voiceName, string description = "", bool removeBackgroundNoise = false, string mediaType = "mpeg") { return await TextToSpeechService.CloneVoiceAndGetVoiceIDAsync(audioDataList.Data, voiceName, description, removeBackgroundNoise, mediaType); } } 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<STTUtils.VoiceBoxSpeechRecognitionCanceledEventArgs> 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 { event EventHandler<byte[]> OnAudioDataReceived; 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, StreamingAudioDecoder audioDecoder, CancellationToken token); Task ConnectAndStream(string text, ClientWebSocket _webSocket, bool isFinalSegment, CancellationToken token); void StopStreamingAndDisconnect(ClientWebSocket websocket, CancellationToken token = default(CancellationToken)); Task<string> CloneVoiceAndGetVoiceIDAsync(IEnumerable<byte[]> audioDataList, string voiceName, string description = "", bool removeBackgroundNoise = false, string mediaType = "mpeg"); Task<string> CloneVoiceAndGetVoiceIDAsync(IEnumerable<string> filePaths, string voiceName, string description = "", bool removeBackgroundNoise = false); } 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 enum VoiceBoxResultReason { NoMatch, Canceled, RecognizingSpeech, RecognizedSpeech, RecognizingIntent, RecognizedIntent, TranslatingSpeech, TranslatedSpeech, SynthesizingAudio, SynthesizingAudioCompleted, RecognizingKeyword, RecognizedKeyword, SynthesizingAudioStarted, TranslatingParticipantSpeech, TranslatedParticipantSpeech, TranslatedInstantMessage, TranslatedParticipantInstantMessage, EnrollingVoiceProfile, EnrolledVoiceProfile, RecognizedSpeakers, RecognizedSpeaker, ResetVoiceProfile, DeletedVoiceProfile, VoicesListRetrieved, RecognizedSpeechWithTimestamps } public class RecognitionResult { public VoiceBoxResultReason Reason { get; set; } public string Text { get; set; } public TimeSpan Duration { get; set; } public long OffsetInTicks { get; set; } } public class VoiceBoxSpeechRecognitionEventArgs { public RecognitionResult Result { get; set; } public string Text => Result.Text; public VoiceBoxSpeechRecognitionEventArgs() { Result = new RecognitionResult(); } public VoiceBoxSpeechRecognitionEventArgs(VoiceBoxResultReason reason, string text, TimeSpan duration, long offsetInTicks) { Result = new RecognitionResult(); Result.Reason = reason; Result.Text = text; Result.Duration = duration; Result.OffsetInTicks = offsetInTicks; } public static explicit operator VoiceBoxSpeechRecognitionEventArgs(SpeechRecognitionEventArgs args) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected I4, but got Unknown return new VoiceBoxSpeechRecognitionEventArgs((VoiceBoxResultReason)((RecognitionResult)args.Result).Reason, ((RecognitionResult)args.Result).Text, ((RecognitionResult)args.Result).Duration, ((RecognitionResult)args.Result).OffsetInTicks); } } public class VoiceBoxSpeechRecognitionCanceledEventArgs : EventArgs { public CancellationReason Reason { get; private set; } public string ErrorCode { get; private set; } public string ErrorDetails { get; private set; } public VoiceBoxSpeechRecognitionCanceledEventArgs(CancellationReason reason, string errorCode, string errorDetails) { Reason = reason; ErrorCode = errorCode; ErrorDetails = errorDetails; } public static explicit operator VoiceBoxSpeechRecognitionCanceledEventArgs(SpeechRecognitionCanceledEventArgs args) { //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_000e: 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_0022: Expected I4, but got Unknown //IL_002f: 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) if (args == null) { return null; } CancellationReason reason = CancellationReason.Error; CancellationReason reason2 = args.Reason; switch (reason2 - 1) { case 0: reason = CancellationReason.Error; break; case 1: reason = CancellationReason.EndOfStream; break; case 2: reason = CancellationReason.User; break; } CancellationErrorCode errorCode = args.ErrorCode; string errorCode2 = ((object)(CancellationErrorCode)(ref errorCode)).ToString(); return new VoiceBoxSpeechRecognitionCanceledEventArgs(reason, errorCode2, args.ErrorDetails); } } public enum CancellationReason { Error, EndOfStream, User } 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 readonly struct AudioFileSource { public IEnumerable<string> Paths { get; } public AudioFileSource(string path) { Paths = new string[1] { path }; } public AudioFileSource(IEnumerable<string> paths) { Paths = paths; } public static implicit operator AudioFileSource(string path) { return new AudioFileSource(path); } public static implicit operator AudioFileSource(List<string> paths) { return new AudioFileSource(paths); } public static implicit operator AudioFileSource(string[] paths) { return new AudioFileSource(paths); } } public readonly struct AudioDataSource { public IEnumerable<byte[]> Data { get; } public AudioDataSource(byte[] singleItem) { Data = new byte[1][] { singleItem }; } public AudioDataSource(IEnumerable<byte[]> collection) { Data = collection; } public static implicit operator AudioDataSource(byte[] data) { return new AudioDataSource(data); } public static implicit operator AudioDataSource(List<byte[]> data) { return new AudioDataSource(data); } public static implicit operator AudioDataSource(byte[][] data) { return new AudioDataSource(data); } } public class AzureSTTServiceManager : ISpeechToTextService { public SpeechRecognizer speechRecognizer; private Dictionary<string, string> audioEndpoints; private AzureSTTServiceConfig _config; public event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognizing; public event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognized; public event EventHandler<STTUtils.VoiceBoxSpeechRecognitionCanceledEventArgs> 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_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown _config = config as AzureSTTServiceConfig; if (_config.apiKey.Length == 0) { Debug.Log((object)"No API key. STT disabled."); return; } audioEndpoints = STTUtils.GetAudioInputEndpoints(); AudioConfig val; try { val = ((_config.audioInputDeviceName == "Default") ? AudioConfig.FromDefaultMicrophoneInput() : AudioConfig.FromMicrophoneInput(audioEndpoints[_config.audioInputDeviceName])); } catch (Exception ex) { Debug.LogWarning((object)("Azure Service Manager: AudioConfig error: " + ex.Message + " -- Using default microphone.")); val = AudioConfig.FromDefaultMicrophoneInput(); } SpeechConfig val2 = SpeechConfig.FromSubscription(_config.apiKey, _config.region); val2.SpeechRecognitionLanguage = _config.language; if (_config.requestWordLevelTimestamps) { val2.RequestWordLevelTimestamps(); } 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."); } STTUtils.VoiceBoxSpeechRecognitionEventArgs voiceBoxSpeechRecognitionEventArgs = (STTUtils.VoiceBoxSpeechRecognitionEventArgs)e; if (_config.requestWordLevelTimestamps && voiceBoxSpeechRecognitionEventArgs.Result.Reason == STTUtils.VoiceBoxResultReason.RecognizedSpeech) { voiceBoxSpeechRecognitionEventArgs.Result.Reason = STTUtils.VoiceBoxResultReason.RecognizedSpeechWithTimestamps; } this.OnRecognized?.Invoke(this, voiceBoxSpeechRecognitionEventArgs); }; 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} Details={e.ErrorDetails}"); this.OnCanceled?.Invoke(this, (STTUtils.VoiceBoxSpeechRecognitionCanceledEventArgs)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
BepInEx/core/Accessibility.dll
Decompiled a month 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); }
BepInEx/core/Azure.Core.dll
Decompiled a month 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.5000.25.55604")] [assembly: AssemblyInformationalVersion("1.50.0+724366b17b92e657d2136d470077c769e89818c7")] [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.50.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; } [RequiresDynamicCode("This method uses reflection.")] [RequiresUnreferencedCode("This method uses reflection.")] 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); } [RequiresDynamicCode("This method uses reflection.")] [RequiresUnreferencedCode("This method uses reflection.")] 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> { [CompilerGenerated] private sealed class <AsPages>d__2 : IEnumerable<Page<T>>, IEnumerable, IEnumerator<Page<T>>, IEnumerator, IDisposable { private int <>1__state; private Page<T> <>2__current; private int <>l__initialThreadId; private string continuationToken; public string <>3__continuationToken; public Pageable<T>.StaticPageable <>4__this; private bool <shouldReturnPages>5__2; private IEnumerator<Page<T>> <>7__wrap2; Page<T> IEnumerator<Page<T>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <AsPages>d__2(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; Pageable<T>.StaticPageable staticPageable = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <shouldReturnPages>5__2 = continuationToken == null; <>7__wrap2 = staticPageable._pages.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } while (<>7__wrap2.MoveNext()) { Page<T> current = <>7__wrap2.Current; if (<shouldReturnPages>5__2) { <>2__current = current; <>1__state = 1; return true; } if (continuationToken == current.ContinuationToken) { <shouldReturnPages>5__2 = true; } } <>m__Finally1(); <>7__wrap2 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<Page<T>> IEnumerable<Page<T>>.GetEnumerator() { <AsPages>d__2 <AsPages>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <AsPages>d__ = this; } else { <AsPages>d__ = new <AsPages>d__2(0) { <>4__this = <>4__this }; } <AsPages>d__.continuationToken = <>3__continuationToken; return <AsPages>d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<Page<T>>)this).GetEnumerator(); } } private readonly IEnumerable<Page<T>> _pages; public StaticPageable(IEnumerable<Page<T>> pages) { _pages = pages; } [IteratorStateMachine(typeof(Pageable<>.StaticPageable.<AsPages>d__2))] public override IEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <AsPages>d__2(-2) { <>4__this = this, <>3__continuationToken = continuationToken }; } } [CompilerGenerated] private sealed class <GetEnumerator>d__8 : IEnumerator<T>, IEnumerator, IDisposable { private int <>1__state; private T <>2__current; public Pageable<T> <>4__this; private IEnumerator<Page<T>> <>7__wrap1; private IEnumerator<T> <>7__wrap2; T IEnumerator<T>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__8(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if ((uint)(num - -4) <= 1u || num == 1) { try { if (num == -4 || num == 1) { try { } finally { <>m__Finally2(); } } } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; Pageable<T> pageable = <>4__this; if (num != 0) { if (num != 1) { return false; } <>1__state = -4; goto IL_0099; } <>1__state = -1; <>7__wrap1 = pageable.AsPages().GetEnumerator(); <>1__state = -3; goto IL_00b3; IL_0099: if (<>7__wrap2.MoveNext()) { T current = <>7__wrap2.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally2(); <>7__wrap2 = null; goto IL_00b3; IL_00b3: if (<>7__wrap1.MoveNext()) { Page<T> current2 = <>7__wrap1.Current; <>7__wrap2 = current2.Values.GetEnumerator(); <>1__state = -4; goto IL_0099; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } private void <>m__Finally2() { <>1__state = -3; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } 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(); } [IteratorStateMachine(typeof(Pageable<>.<GetEnumerator>d__8))] public virtual IEnumerator<T> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__8(0) { <>4__this = this }; } 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,
BepInEx/core/Microsoft.Bcl.AsyncInterfaces.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; 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: AssemblyMetadata("IsAotCompatible", "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.")] [assembly: AssemblyFileVersion("10.0.125.57005")] [assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")] [assembly: AssemblyVersion("10.0.0.1")] [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; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace System { internal static class ExceptionPolyfills { [SpecialName] public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B { [SpecialName] public static class <M>$96F0261AC622664B8B003966835C0332 { } [ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")] public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { throw null; } } [SpecialName] public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9 { [SpecialName] public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC { } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { throw null; } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { throw null; } } public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { ThrowArgumentNullException(paramName); } } [DoesNotReturn] private static void ThrowArgumentNullException(string paramName) { throw new ArgumentNullException(paramName); } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { if (condition) { ThrowObjectDisposedException(instance); } } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { if (condition) { ThrowObjectDisposedException(type); } } [DoesNotReturn] private static void ThrowObjectDisposedException(object instance) { throw new ObjectDisposedException(instance?.GetType().FullName); } [DoesNotReturn] private static void ThrowObjectDisposedException(Type type) { throw new ObjectDisposedException(type?.FullName); } } } 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.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.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 } }
BepInEx/core/Microsoft.Bcl.Numerics.dll
Decompiled a month agousing System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; 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.Numerics")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyMetadata("IsAotCompatible", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides the System.MathF for .NET Standard 2.0")] [assembly: AssemblyFileVersion("10.0.125.57005")] [assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Bcl.Numerics")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("10.0.0.1")] [assembly: TypeForwardedTo(typeof(MathF))] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace System { internal static class ExceptionPolyfills { [SpecialName] public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B { [SpecialName] public static class <M>$96F0261AC622664B8B003966835C0332 { } [ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")] public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { throw null; } } [SpecialName] public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9 { [SpecialName] public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC { } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { throw null; } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { throw null; } } public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { ThrowArgumentNullException(paramName); } } [DoesNotReturn] private static void ThrowArgumentNullException(string paramName) { throw new ArgumentNullException(paramName); } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { if (condition) { ThrowObjectDisposedException(instance); } } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { if (condition) { ThrowObjectDisposedException(type); } } [DoesNotReturn] private static void ThrowObjectDisposedException(object instance) { throw new ObjectDisposedException(instance?.GetType().FullName); } [DoesNotReturn] private static void ThrowObjectDisposedException(Type type) { throw new ObjectDisposedException(type?.FullName); } } } 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.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.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 } }
BepInEx/core/Microsoft.CognitiveServices.Speech.csharp.dll
Decompiled a month 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
BepInEx/core/Microsoft.Extensions.AI.Abstractions.dll
Decompiled a month 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.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("10.100.125.61202")] [assembly: AssemblyInformationalVersion("10.1.1+8a57aae6b42651573f06fd3904b9a0d1023f9aeb")] [assembly: AssemblyProduct("Microsoft.Extensions.AI.Abstractions")] [assembly: AssemblyTitle("Microsoft.Extensions.AI.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/extensions")] [assembly: AssemblyVersion("10.1.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] [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 ResponseContinuationToken? 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 ResponseContinuationToken? 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; } } private static void CoalesceImageResultContent(IList<AIContent> contents) { Dictionary<string, int> dictionary = null; bool flag = false; for (int i = 0; i < contents.Count; i++) { if (contents[i] is ImageGenerationToolResultContent imageGenerationToolResultContent && !string.IsNullOrEmpty(imageGenerationToolResultContent.ImageId)) { if (dictionary == null) { dictionary = new Dictionary<string, int>(StringComparer.Ordinal); } if (dictionary.TryGetValue(imageGenerationToolResultContent.ImageId, out var value)) { contents[value] = imageGenerationToolResultContent; contents[i] = null; flag = true; } else { dictionary[imageGenerationToolResultContent.ImageId] = i; } } } if (flag) { RemoveNullContents(contents); } } internal static void CoalesceContent(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), delegate(IList<AIContent> contents, int start, int end) { TextReasoningContent textReasoningContent = new TextReasoningContent(MergeText(contents, start, end)) { AdditionalProperties = contents[start].AdditionalProperties?.Clone() }; string protectedData = ((TextReasoningContent)contents[end - 1]).ProtectedData; if (protectedData != null) { textReasoningContent.ProtectedData = protectedData; } return textReasoningContent; }); CoalesceImageResultContent(contents); Coalesce<DataContent>(contents, mergeSingle: false, (DataContent r1, DataContent r2) => r1.MediaType == r2.MediaType && r1.HasTopLevelMediaType("text") && r1.Name == r2.Name, delegate(IList<AIContent> contents, int start, int end) { MemoryStream memoryStream = new MemoryStream(); for (int l = start; l < end; l++) { DataContent dataContent = (DataContent)contents[l]; if (!MemoryMarshal.TryGetArray(dataContent.Data, out var segment)) { segment = new ArraySegment<byte>(dataContent.Data.ToArray()); } memoryStream.Write(segment.Array, segment.Offset, segment.Count); } DataContent dataContent2 = (DataContent)contents[start]; return new DataContent(new ReadOnlyMemory<byte>(memoryStream.GetBuffer(), 0, (int)memoryStream.Length), dataContent2.MediaType) { Name = dataContent2.Name }; }); Coalesce<CodeInterpreterToolCallContent>(contents, mergeSingle: true, (CodeInterpreterToolCallContent r1, CodeInterpreterToolCallContent r2) => r1.CallId == r2.CallId, delegate(IList<AIContent> contents, int start, int end) { CodeInterpreterToolCallContent codeInterpreterToolCallContent = (CodeInterpreterToolCallContent)contents[start]; if (start == end - 1) { if (codeInterpreterToolCallContent.Inputs != null) { CoalesceContent(codeInterpreterToolCallContent.Inputs); } return codeInterpreterToolCallContent; } List<AIContent> list2 = null; for (int k = start; k < end; k++) { (list2 ?? (list2 = new List<AIContent>())).AddRange(((CodeInterpreterToolCallContent)contents[k]).Inputs ?? new List<AIContent>()); } if (list2 != null) { CoalesceContent(list2); } return new CodeInterpreterToolCallContent { CallId = codeInterpreterToolCallContent.CallId, Inputs = list2, AdditionalProperties = codeInterpreterToolCallContent.AdditionalProperties?.Clone() }; }); Coalesce<CodeInterpreterToolResultContent>(contents, mergeSingle: true, (CodeInterpreterToolResultContent r1, CodeInterpreterToolResultContent r2) => r1.CallId != null && r2.CallId != null && r1.CallId == r2.CallId, delegate(IList<AIContent> contents, int start, int end) { CodeInterpreterToolResultContent codeInterpreterToolResultContent = (CodeInterpreterToolResultContent)contents[start]; if (start == end - 1) { if (codeInterpreterToolResultContent.Outputs != null) { CoalesceContent(codeInterpreterToolResultContent.Outputs); } return codeInterpreterToolResultContent; } List<AIContent> list = null; for (int j = start; j < end; j++) { (list ?? (list = new List<AIContent>())).AddRange(((CodeInterpreterToolResultContent)contents[j]).Outputs ?? new List<AIContent>()); } if (list != null) { CoalesceContent(list); } return new CodeInterpreterToolResultContent { CallId = codeInterpreterToolResultContent.CallId, Outputs = list, AdditionalProperties = codeInterpreterToolResultContent.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; } } } } RemoveNullContents(contents); } static string MergeText(IList<AIContent> contents, int start, int end) { StringBuilder stringBuilder = new StringBuilder(); for (int i = start; i < end; i++) { stringBuilder.Append(contents[i]); } 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 RemoveNullContents<T>(IList<T> contents) where T : class { if (contents is List<AIContent> list) { list.RemoveAll((AIContent u) => u == null); return; } int num = 0; int count = contents.Count; for (int i = 0; i < count; i++) { T val = contents[i]; if (val != null) { contents[num++] = val; } } for (int num2 = count - 1; num2 >= num; num2--) { contents.RemoveAt(num2); } } private static void FinalizeResponse(ChatResponse response) { int count = response.Messages.Count; for (int i = 0; i < count; i++) { CoalesceContent((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 ?? schemaType.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? 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 ResponseContinuationToken? 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 ChatResponseUpdate Clone() { return new ChatResponseUpdate { AdditionalProperties = AdditionalProperties, AuthorName = AuthorName, Contents = Contents, CreatedAt = CreatedAt, ConversationId = ConversationId, FinishReason = FinishReason, MessageId = MessageId, ModelId = ModelId, RawRepresentation = RawRepresentation, ResponseId = ResponseId, Role = Role }; } 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; } } [Experimental("MEAI001")] public sealed class CodeInterpreterToolCallContent : AIContent { public string? CallId { get; set; } public IList<AIContent>? Inputs { get; set; } } [Experimental("MEAI001")] public sealed class CodeInterpreterToolResultContent : AIContent { public string? CallId { get; set; } public IList<AIContent>? Outputs { 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 { if (HasTopLevelMediaType("text")) { return "MediaType = " + MediaType + ", Text = \"" + Encoding.UTF8.GetString(Data.ToArray()) + "\""; } if ("application/json".Equals(MediaType, StringComparison.OrdinalIgnoreCase)) { return "JSON = " + Encoding.UTF8.GetString(Data.ToArray()); } 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("{DebuggerDisplay,nq}")] public sealed class HostedFileContent : AIContent { [CompilerGenerated] private string <FileId>k__BackingField; [CompilerGenerated] private string? <MediaType>k__BackingField; public string FileId { get { return <FileId>k__BackingField; } set { <FileId>k__BackingField = Throw.IfNullOrWhitespace(value, "value"); } } public string? MediaType { [CompilerGenerated] get { return <MediaType>k__BackingField; } set { <MediaType>k__BackingField = ((value != null) ? DataUriParser.ThrowIfInvalidMediaType(value, "value") : value); } } public string? Name { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { string text = "FileId = " + FileId; string mediaType = MediaType; if (mediaType != null) { text = text + ", MediaType = " + mediaType; } string name = Name; if (name != null) { text = text + ", Name = \"" + name + "\""; } return text; } } public HostedFileContent(string fileId) { FileId = Throw.IfNullOrWhitespace(fileId, "fileId"); } public bool HasTopLevelMediaType(string topLevelType) { if (MediaType != null) { return DataUriParser.HasTopLevelMediaType(MediaType, topLevelType); } return false; } } [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 ImageGenerationToolCallContent : AIContent { public string? ImageId { get; set; } } [Experimental("MEAI001")] public sealed class ImageGenerationToolResultContent : AIContent { public string? ImageId { get; set; } public IList<AIContent>? Outputs { get; set; } } [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 = 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")] [JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] [JsonDerivedType(typeof(FunctionApprovalRequestContent), "functionApprovalRequest")] [JsonDerivedType(typeof(McpServerToolApprovalRequestContent), "mcpServerToolApprovalRequest")] public class UserInputRequestContent : AIContent { public string Id { get; } protected UserInputRequestContent(string id) { Id = Throw.IfNullOrWhitespace(id, "id"); } } [Experimental("MEAI001")] [JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")] [JsonDerivedType(typeof(FunctionApprovalResponseContent), "functionApprovalResponse")] [JsonDerivedType(typeof(McpServerToolApprovalResponseContent), "mcpServerToolApprovalResponse")] 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 ?? key.Method.GetCustomAttribute<DisplayNameAttribute>(inherit: true)?.DisplayName ?? 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(NormalizeReturnType(returnType, serializerOptions), 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(T
BepInEx/core/Microsoft.Extensions.AI.dll
Decompiled a month 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.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Metrics; using System.Drawing; using System.IO; using System.Linq; using System.Numerics.Tensors; 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 System.Threading.Tasks.Sources; 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("10.100.125.61202")] [assembly: AssemblyInformationalVersion("10.1.1+8a57aae6b42651573f06fd3904b9a0d1023f9aeb")] [assembly: AssemblyProduct("Microsoft.Extensions.AI")] [assembly: AssemblyTitle("Microsoft.Extensions.AI")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/extensions")] [assembly: AssemblyVersion("10.1.0.0")] [assembly: TypeForwardedTo(typeof(IChatReducer))] [module: RefSafetyRules(11)] [CompilerGenerated] internal delegate TResult <>f__AnonymousDelegate0<T1, T2, TResult>(T1 arg1, T2 arg2 = default(T2)); [CompilerGenerated] internal delegate TResult <>f__AnonymousDelegate1<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3 = default(T3)); 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 { [CompilerGenerated] private sealed class <GetCachedStreamingResponseAsync>d__10 : 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 CachingChatClient <>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 <cacheKey>5__2; private TaskAwaiter<ChatResponse?> <>u__1; private ChatResponseUpdate[] <>7__wrap2; private int <>7__wrap3; private List<ChatResponseUpdate> <capturedItems>5__5; private IAsyncEnumerator<ChatResponseUpdate> <>7__wrap5; private object <>7__wrap6; private ValueTaskAwaiter<bool> <>u__2; private ValueTaskAwaiter <>u__3; private TaskAwaiter <>u__4; private TaskAwaiter<IReadOnlyList<ChatResponseUpdate>?> <>u__5; private string <conversationId>5__8; private IEnumerator<ChatResponseUpdate> <>7__wrap8; ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetCachedStreamingResponseAsync>d__10(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; CachingChatClient cachingChatClient = <>4__this; try { TaskAwaiter<ChatResponse> awaiter6; TaskAwaiter<IReadOnlyList<ChatResponseUpdate>> awaiter3; ValueTaskAwaiter awaiter5; TaskAwaiter awaiter4; ValueTaskAwaiter awaiter2; TaskAwaiter awaiter; object obj; ChatResponse result; ChatResponse val; IReadOnlyList<ChatResponseUpdate> result2; IReadOnlyList<ChatResponseUpdate> readOnlyList; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); if (cachingChatClient.CoalesceStreamingUpdates) { <cacheKey>5__2 = cachingChatClient.GetCacheKey(messages, options, new ReadOnlySpan<object>(new object[1] { _boxedTrue })); <>2__current = null; awaiter6 = cachingChatClient.ReadCacheAsync(<cacheKey>5__2, cancellationToken).GetAwaiter(); if (!awaiter6.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter6; <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter6, ref stateMachine); return; } goto IL_010d; } <cacheKey>5__2 = cachingChatClient.GetCacheKey(messages, options, new ReadOnlySpan<object>(new object[1] { _boxedTrue })); <>2__current = null; awaiter3 = cachingChatClient.ReadCacheStreamingAsync(<cacheKey>5__2, cancellationToken).GetAwaiter(); if (!awaiter3.IsCompleted) { num = (<>1__state = 4); <>u__5 = awaiter3; <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine); return; } goto IL_04aa; } goto end_IL_000e; case 0: awaiter6 = <>u__1; <>u__1 = default(TaskAwaiter<ChatResponse>); num = (<>1__state = -1); goto IL_010d; case -4: num = (<>1__state = -1); if (!<>w__disposeMode) { <>7__wrap3++; goto IL_0179; } goto end_IL_000e; case -5: case 1: try { ValueTaskAwaiter<bool> awaiter7; if (num != -5) { if (num != 1) { goto IL_0231; } awaiter7 = <>u__2; <>u__2 = default(ValueTaskAwaiter<bool>); num = (<>1__state = -1); goto IL_029c; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_0231; } goto end_IL_01dc; IL_0231: <>2__current = null; awaiter7 = <>7__wrap5.MoveNextAsync().GetAwaiter(); if (!awaiter7.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter7; <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter7, ref stateMachine); return; } goto IL_029c; IL_029c: if (awaiter7.GetResult()) { ChatResponseUpdate current2 = <>7__wrap5.Current; <capturedItems>5__5.Add(current2); <>2__current = current2; num = (<>1__state = -5); goto IL_08c7; } end_IL_01dc:; } catch (object obj2) { <>7__wrap6 = obj2; } if (<>7__wrap5 != null) { <>2__current = null; awaiter5 = <>7__wrap5.DisposeAsync().GetAwaiter(); if (!awaiter5.IsCompleted) { num = (<>1__state = 2); <>u__3 = awaiter5; <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter5, ref stateMachine); return; } goto IL_032d; } goto IL_0334; case 2: awaiter5 = <>u__3; <>u__3 = default(ValueTaskAwaiter); num = (<>1__state = -1); goto IL_032d; case 3: awaiter4 = <>u__4; <>u__4 = default(TaskAwaiter); num = (<>1__state = -1); goto IL_03f7; case 4: awaiter3 = <>u__5; <>u__5 = default(TaskAwaiter<IReadOnlyList<ChatResponseUpdate>>); num = (<>1__state = -1); goto IL_04aa; case -6: try { if (num != -6) { goto IL_0524; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_0524; } goto end_IL_04d3; IL_0524: if (<>7__wrap8.MoveNext()) { ChatResponseUpdate current = <>7__wrap8.Current; if (<conversationId>5__8 == null) { <conversationId>5__8 = current.ConversationId; } <>2__current = current; num = (<>1__state = -6); goto IL_08c7; } end_IL_04d3:; } finally { if (num == -1 && <>7__wrap8 != null) { <>7__wrap8.Dispose(); } } if (!<>w__disposeMode) { <>7__wrap8 = null; <conversationId>5__8 = null; break; } goto end_IL_000e; case -7: case 5: try { ValueTaskAwaiter<bool> awaiter8; if (num != -7) { if (num != 5) { goto IL_0607; } awaiter8 = <>u__2; <>u__2 = default(ValueTaskAwaiter<bool>); num = (<>1__state = -1); goto IL_0672; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_0607; } goto end_IL_05b2; IL_0607: <>2__current = null; awaiter8 = <>7__wrap5.MoveNextAsync().GetAwaiter(); if (!awaiter8.IsCompleted) { num = (<>1__state = 5); <>u__2 = awaiter8; <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter8, ref stateMachine); return; } goto IL_0672; IL_0672: if (awaiter8.GetResult()) { ChatResponseUpdate current3 = <>7__wrap5.Current; <capturedItems>5__5.Add(current3); <>2__current = current3; num = (<>1__state = -7); goto IL_08c7; } end_IL_05b2:; } catch (object obj2) { <>7__wrap6 = obj2; } if (<>7__wrap5 != null) { <>2__current = null; awaiter2 = <>7__wrap5.DisposeAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 6); <>u__3 = awaiter2; <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_0703; } goto IL_070a; case 6: awaiter2 = <>u__3; <>u__3 = default(ValueTaskAwaiter); num = (<>1__state = -1); goto IL_0703; case 7: { awaiter = <>u__4; <>u__4 = default(TaskAwaiter); num = (<>1__state = -1); goto IL_07c8; } IL_070a: obj = <>7__wrap6; if (obj != null) { if (!(obj is Exception source)) { throw obj; } ExceptionDispatchInfo.Capture(source).Throw(); } _ = <>7__wrap3; if (!<>w__disposeMode) { <>7__wrap6 = null; <>7__wrap5 = null; <>2__current = null; awaiter = cachingChatClient.WriteCacheStreamingAsync(<cacheKey>5__2, <capturedItems>5__5, cancellationToken).GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 7); <>u__4 = awaiter; <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_07c8; } goto end_IL_000e; IL_032d: awaiter5.GetResult(); goto IL_0334; IL_0334: obj = <>7__wrap6; if (obj != null) { if (!(obj is Exception source2)) { throw obj; } ExceptionDispatchInfo.Capture(source2).Throw(); } _ = <>7__wrap3; if (!<>w__disposeMode) { <>7__wrap6 = null; <>7__wrap5 = null; <>2__current = null; awaiter4 = cachingChatClient.WriteCacheAsync(<cacheKey>5__2, ChatResponseExtensions.ToChatResponse((IEnumerable<ChatResponseUpdate>)<capturedItems>5__5), cancellationToken).GetAwaiter(); if (!awaiter4.IsCompleted) { num = (<>1__state = 3); <>u__4 = awaiter4; <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter4, ref stateMachine); return; } goto IL_03f7; } goto end_IL_000e; IL_010d: result = awaiter6.GetResult(); val = result; if (val != null) { <>7__wrap2 = val.ToChatResponseUpdates(); <>7__wrap3 = 0; goto IL_0179; } <capturedItems>5__5 = new List<ChatResponseUpdate>(); <>7__wrap5 = cachingChatClient.<>n__1(messages, options, cancellationToken).GetAsyncEnumerator(); <>7__wrap6 = null; <>7__wrap3 = 0; goto case -5; IL_04aa: result2 = awaiter3.GetResult(); readOnlyList = result2; if (readOnlyList != null) { <conversationId>5__8 = null; <>7__wrap8 = readOnlyList.GetEnumerator(); goto case -6; } <capturedItems>5__5 = new List<ChatResponseUpdate>(); <>7__wrap5 = cachingChatClient.<>n__1(messages, options, cancellationToken).GetAsyncEnumerator(); <>7__wrap6 = null; <>7__wrap3 = 0; goto case -7; IL_0179: if (<>7__wrap3 < <>7__wrap2.Length) { ChatResponseUpdate val2 = <>7__wrap2[<>7__wrap3]; <>2__current = val2; num = (<>1__state = -4); goto IL_08c7; } <>7__wrap2 = null; goto IL_0405; IL_0703: awaiter2.GetResult(); goto IL_070a; IL_03f7: awaiter4.GetResult(); <capturedItems>5__5 = null; goto IL_0405; IL_07c8: awaiter.GetResult(); <capturedItems>5__5 = null; break; IL_0405: <cacheKey>5__2 = null; goto end_IL_000e; } <cacheKey>5__2 = null; end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <cacheKey>5__2 = null; <>7__wrap2 = null; <capturedItems>5__5 = null; <>7__wrap5 = null; <>7__wrap6 = null; <conversationId>5__8 = null; <>7__wrap8 = 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; <cacheKey>5__2 = null; <>7__wrap2 = null; <capturedItems>5__5 = null; <>7__wrap5 = null; <>7__wrap6 = null; <conversationId>5__8 = null; <>7__wrap8 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_08c7: <>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)) { <GetCachedStreamingResponseAsync>d__10 <GetCachedStreamingResponseAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <GetCachedStreamingResponseAsync>d__ = this; } else { <GetCachedStreamingResponseAsync>d__ = new <GetCachedStreamingResponseAsync>d__10(-3) { <>4__this = <>4__this }; } <GetCachedStreamingResponseAsync>d__.messages = <>3__messages; <GetCachedStreamingResponseAsync>d__.options = <>3__options; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <GetCachedStreamingResponseAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <GetCachedStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <GetCachedStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <GetCachedStreamingResponseAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <GetCachedStreamingResponseAsync>d__10 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(); <GetCachedStreamingResponseAsync>d__10 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } 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); } [AsyncIteratorStateMachine(typeof(<GetCachedStreamingResponseAsync>d__10))] private IAsyncEnumerable<ChatResponseUpdate> GetCachedStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { return new <GetCachedStreamingResponseAsync>d__10(-2) { <>4__this = this, <>3__messages = messages, <>3__options = options, <>3__cancellationToken = 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(new ReadOnlySpan<JsonNode>(new JsonNode[1] { "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 = new JsonReaderOptions { AllowMultipleValues = true }; 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 { [CompilerGenerated] private sealed class <GetStreamingResponseAsync>d__3 : 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 ConfigureOptionsChatClient <>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 IAsyncEnumerator<ChatResponseUpdate> <>7__wrap1; private object <>7__wrap2; private int <>7__wrap3; private ValueTaskAwaiter<bool> <>u__1; private ValueTaskAwaiter <>u__2; ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetStreamingResponseAsync>d__3(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { int num = <>1__state; ConfigureOptionsChatClient configureOptionsChatClient = <>4__this; try { ValueTaskAwaiter awaiter; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); <>7__wrap1 = configureOptionsChatClient.<>n__1(messages, configureOptionsChatClient.Configure(options), cancellationToken).GetAsyncEnumerator(); <>7__wrap2 = null; <>7__wrap3 = 0; goto case -4; } goto end_IL_000e; case -4: case 0: try { ValueTaskAwaiter<bool> awaiter2; if (num != -4) { if (num != 0) { goto IL_00cb; } awaiter2 = <>u__1; <>u__1 = default(ValueTaskAwaiter<bool>); num = (<>1__state = -1); goto IL_0136; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_00cb; } goto end_IL_0086; IL_00cb: <>2__current = null; awaiter2 = <>7__wrap1.MoveNextAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; <GetStreamingResponseAsync>d__3 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_0136; IL_0136: if (awaiter2.GetResult()) { ChatResponseUpdate current = <>7__wrap1.Current; <>2__current = current; num = (<>1__state = -4); goto IL_02b9; } end_IL_0086:; } catch (object obj) { <>7__wrap2 = obj; } if (<>7__wrap1 == null) { break; } <>2__current = null; awaiter = <>7__wrap1.DisposeAsync().GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter; <GetStreamingResponseAsync>d__3 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_01c7; case 1: { awaiter = <>u__2; <>u__2 = default(ValueTaskAwaiter); num = (<>1__state = -1); goto IL_01c7; } IL_01c7: awaiter.GetResult(); break; } object obj2 = <>7__wrap2; if (obj2 != null) { if (!(obj2 is Exception source)) { throw obj2; } ExceptionDispatchInfo.Capture(source).Throw(); } _ = <>7__wrap3; if (!<>w__disposeMode) { <>7__wrap2 = null; <>7__wrap1 = null; } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <>7__wrap1 = null; <>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 = null; <>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_02b9: <>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)) { <GetStreamingResponseAsync>d__3 <GetStreamingResponseAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <GetStreamingResponseAsync>d__ = this; } else { <GetStreamingResponseAsync>d__ = new <GetStreamingResponseAsync>d__3(-3) { <>4__this = <>4__this }; } <GetStreamingResponseAsync>d__.messages = <>3__messages; <GetStreamingResponseAsync>d__.options = <>3__options; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <GetStreamingResponseAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <GetStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <GetStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <GetStreamingResponseAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <GetStreamingResponseAsync>d__3 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(); <GetStreamingResponseAsync>d__3 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } 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); } [AsyncIteratorStateMachine(typeof(<GetStreamingResponseAsync>d__3))] public override IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { return new <GetStreamingResponseAsync>d__3(-2) { <>4__this = this, <>3__messages = messages, <>3__options = options, <>3__cancellationToken = cancellationToken }; } 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; [CompilerGenerated] private JsonSerializerOptions <JsonSerializerOptions>k__BackingField = AIJsonUtilities.DefaultOptions; public JsonSerializerOptions JsonSerializerOptions { [CompilerGenerated] get { return <JsonSerializerOptions>k__BackingField; } set { <JsonSerializerOptions>k__BackingField = 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); [CompilerGenerated] private AIFunction <Function>k__BackingField = _nopFunction; [CompilerGenerated] private AIFunctionArguments <Arguments>k__BackingField; [CompilerGenerated] private FunctionCallContent <CallContent>k__BackingField; [CompilerGenerated] private IList<ChatMessage> <Messages>k__BackingField = Array.Empty<ChatMessage>(); public AIFunction Function { [CompilerGenerated] get { return <Function>k__BackingField; } set { <Function>k__BackingField = 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>k__BackingField; if (obj == null) { AIFunctionArguments val = new AIFunctionArguments(); AIFunctionArguments val2 = val; <Arguments>k__BackingField = val; obj = val2; } return obj; } set { <Arguments>k__BackingField = 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>k__BackingField; if (obj == null) { FunctionCallContent val = new FunctionCallContent(string.Empty, ((AITool)_nopFunction).Name, (IDictionary<string, object>)EmptyReadOnlyDictionary<string, object>.Instance); FunctionCallContent val2 = val; <CallContent>k__BackingField = val; obj = val2; } return obj; } set { <CallContent>k__BackingField = Throw.IfNull<FunctionCallContent>(value, "value"); } } public IList<ChatMessage> Messages { [CompilerGenerated] get { return <Messages>k__BackingField; } set { <Messages>k__BackingField = 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; } } [CompilerGenerated] private sealed class <GetStreamingResponseAsync>d__39 : 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; private IEnumerable<ChatMessage> messages; public IEnumerable<ChatMessage> <>3__messages; public FunctionInvokingChatClient <>4__this; private ChatOptions options; public ChatOptions <>3__options; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private Activity <activity>5__2; private UsageDetails <totalUsage>5__3; private List<ChatMessage> <originalMessages>5__4; private AITool[] <approvalRequiredFunctions>5__5; private List<ChatMessage> <augmentedHistory>5__6; private List<FunctionCallContent> <functionCallContents>5__7; private List<ChatMessage> <responseMessages>5__8; private bool <lastIterationHadConversationId>5__9; private List<ChatResponseUpdate> <updates>5__10; private int <consecutiveErrorCount>5__11; private Dictionary<string, AITool> <toolMap>5__12; private bool <anyToolsRequireApproval>5__13; private string <toolMessageId>5__14; private List<ApprovalResultWithRequestMessage> <notInvokedApprovals>5__15; private bool <shouldTerminate>5__16; private List<ChatMessage>.Enumerator <>7__wrap16; private TaskAwaiter<(IList<ChatMessage>? FunctionResultContentMessages, bool ShouldTerminate, int ConsecutiveErrorCount)> <>u__1; private IEnumerator<ChatMessage> <>7__wrap17; private int <iteration>5__19; private int <lastApprovalCheckedFCCIndex>5__20; private int <lastYieldedUpdateIndex>5__21; private ChatResponse <response>5__22; private (bool ShouldTerminate, int NewConsecutiveErrorCount, IList<ChatMessage> MessagesAdded) <modeAndMessages>5__23; private IAsyncEnumerator<ChatResponseUpdate> <>7__wrap23; private object <>7__wrap24; private int <>7__wrap25; private ValueTaskAwaiter<bool> <>u__2; private ValueTaskAwaiter <>u__3; private TaskAwaiter<(bool ShouldTerminate, int NewConsecutiveErrorCount, IList<ChatMessage> MessagesAdded)> <>u__4; ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetStreamingResponseAsync>d__39(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { //IL_00f1: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; FunctionInvokingChatClient functionInvokingChatClient = <>4__this; try { switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); Throw.IfNull(messages, "messages"); <activity>5__2 = (CurrentActivityIsInvokeAgent ? null : functionInvokingChatClient._activitySource?.StartActivity("orchestrate_tools")); break; } goto end_IL_000e; case -9: case -8: case -7: case -6: case -5: case -4: case 0: case 1: case 2: case 3: break; } try { TaskAwaiter<(IList<ChatMessage>, bool, int)> awaiter3; ValueTaskAwaiter awaiter2; TaskAwaiter<(bool, int, IList<ChatMessage>)> awaiter; IList<ChatMessage> list2; object obj5; (bool, int, IList<ChatMessage>) result; ChatResponseUpdate val3; switch (num) { default: { <totalUsage>5__3 = ((<activity>5__2 == null || !<activity>5__2.IsAllDataRequested) ? ((UsageDetails)null) : new UsageDetails()); <originalMessages>5__4 = messages.ToList(); messages = <originalMessages>5__4; <approvalRequiredFunctions>5__5 = null; <augmentedHistory>5__6 = null; <functionCallContents>5__7 = null; <responseMessages>5__8 = null; <lastIterationHadConversationId>5__9 = false; <updates>5__10 = new List<ChatResponseUpdate>(); <consecutiveErrorCount>5__11 = 0; IList<AITool>[] obj2 = new IList<AITool>[2] { functionInvokingChatClient.AdditionalTools, null }; ChatOptions obj3 = options; obj2[1] = ((obj3 != null) ? obj3.Tools : null); (Dictionary<string, AITool>, bool) tuple = CreateToolsMap(new ReadOnlySpan<IList<AITool>>(obj2)); <toolMap>5__12 = tuple.Item1; <anyToolsRequireApproval>5__13 = tuple.Item2; <toolMessageId>5__14 = Guid.NewGuid().ToString("N"); if (HasAnyApprovalContent(<originalMessages>5__4)) { string functionCallContentFallbackMessageId = Guid.NewGuid().ToString("N"); List<ChatMessage> originalMessages = <originalMessages>5__4; ChatOptions obj4 = options; List<ChatMessage> list; (list, <notInvokedApprovals>5__15) = ProcessFunctionApprovalResponses(originalMessages, !string.IsNullOrWhiteSpace((obj4 != null) ? obj4.ConversationId : null), <toolMessageId>5__14, functionCallContentFallbackMessageId); if (list != null) { <>7__wrap16 = list.GetEnumerator(); goto case -4; } goto IL_02bf; } goto IL_0451; } case -4: try { if (num != -4) { goto IL_028f; } num = (<>1__state = -1); if (!<>w__disposeMode) { Activity.Current = <activity>5__2; goto IL_028f; } goto end_IL_022a; IL_028f: if (!<>7__wrap16.MoveNext()) { goto end_IL_022a; } ChatMessage current = <>7__wrap16.Current; ChatOptions obj = options; <>2__current = ConvertToolResultMessageToUpdate(current, (obj != null) ? obj.ConversationId : null, current.MessageId); num = (<>1__state = -4); goto end_IL_009b; end_IL_022a:; } finally { if (num == -1) { ((IDisposable)<>7__wrap16).Dispose(); } } if (!<>w__disposeMode) { goto IL_02bf; } goto IL_0b85; case 0: awaiter3 = <>u__1; <>u__1 = default(TaskAwaiter<(IList<ChatMessage>, bool, int)>); num = (<>1__state = -1); goto IL_0346; case -5: try { if (num != -5) { goto IL_03fd; } num = (<>1__state = -1); if (!<>w__disposeMode) { Activity.Current = <activity>5__2; goto IL_03fd; } goto end_IL_038b; IL_03fd: if (!<>7__wrap17.MoveNext()) { goto end_IL_038b; } ChatMessage current2 = <>7__wrap17.Current; current2.MessageId = <toolMessageId>5__14; ChatOptions obj6 = options; <>2__current = ConvertToolResultMessageToUpdate(current2, (obj6 != null) ? obj6.ConversationId : null, current2.MessageId); num = (<>1__state = -5); goto end_IL_009b; end_IL_038b:; } finally { if (num == -1 && <>7__wrap17 != null) { <>7__wrap17.Dispose(); } } if (!<>w__disposeMode) { <>7__wrap17 = null; if (!<shouldTerminate>5__16) { goto IL_044a; } <>w__disposeMode = true; } goto IL_0b85; case -7: case -6: case 1: try { ValueTaskAwaiter<bool> awaiter4; if (num != -7) { if (num != -6) { if (num != 1) { goto IL_0746; } awaiter4 = <>u__2; <>u__2 = default(ValueTaskAwaiter<bool>); num = (<>1__state = -1); goto IL_07b1; } num = (<>1__state = -1); if (!<>w__disposeMode) { Activity.Current = <activity>5__2; goto IL_0746; } } else { num = (<>1__state = -1); if (!<>w__disposeMode) { Activity.Current = <activity>5__2; <lastYieldedUpdateIndex>5__21++; goto IL_0730; } } goto end_IL_04c5; IL_07b1: if (!awaiter4.GetResult()) { goto end_IL_04c5; } ChatResponseUpdate current3 = <>7__wrap23.Current; if (current3 == null) { Throw.InvalidOperationException("The inner IChatClient streamed a null ChatResponseUpdate."); } <updates>5__10.Add(current3); CopyFunctionCalls(current3.Contents, ref <functionCallContents>5__7); if (<totalUsage>5__3 != null) { IList<AIContent> contents = current3.Contents; int count = contents.Count; for (int i = 0; i < count; i++) { AIContent obj7 = contents[i]; UsageContent val = (UsageContent)(object)((obj7 is UsageContent) ? obj7 : null); if (val != null) { <totalUsage>5__3.Add(val.Details); } } } if (<anyToolsRequireApproval>5__13 && <approvalRequiredFunctions>5__5 == null && <functionCallContents>5__7 != null && <functionCallContents>5__7.Count > 0) { ChatOptions obj8 = options; IEnumerable<AITool> enumerable = ((obj8 != null) ? obj8.Tools : null); IEnumerable<AITool> first = enumerable ?? Enumerable.Empty<AITool>(); enumerable = functionInvokingChatClient.AdditionalTools; <approvalRequiredFunctions>5__5 = (from t in first.Concat(enumerable ?? Enumerable.Empty<AITool>()) where t.GetService<ApprovalRequiredAIFunction>((object)null) != null select t).ToArray(); } if (<approvalRequiredFunctions>5__5 != null && <approvalRequiredFunctions>5__5.Length > 0 && <functionCallContents>5__7 != null && <functionCallContents>5__7.Count > 0) { (<shouldTerminate>5__16, <lastApprovalCheckedFCCIndex>5__20) = CheckForApprovalRequiringFCC(<functionCallContents>5__7, <approvalRequiredFunctions>5__5, <shouldTerminate>5__16, <lastApprovalCheckedFCCIndex>5__20); if (<shouldTerminate>5__16) { goto IL_0730; } goto IL_0746; } <lastYieldedUpdateIndex>5__21++; <>2__current = current3; num = (<>1__state = -6); goto end_IL_009b; IL_0746: <>2__current = null; awaiter4 = <>7__wrap23.MoveNextAsync().GetAwaiter(); if (!awaiter4.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter4; <GetStreamingResponseAsync>d__39 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter4, ref stateMachine); return; } goto IL_07b1; IL_0730: if (<lastYieldedUpdateIndex>5__21 >= <updates>5__10.Count) { goto IL_0746; } ChatResponseUpdate val2 = <updates>5__10[<lastYieldedUpdateIndex>5__21]; if (TryReplaceFunctionCallsWithApprovalRequests(val2.Contents, out List<AIContent> updatedContent)) { val2.Contents = updatedContent; } <>2__current = val2; num = (<>1__state = -7); goto end_IL_009b; end_IL_04c5:; } catch (object obj9) { <>7__wrap24 = obj9; } if (<>7__wrap23 != null) { <>2__current = null; awaiter2 = <>7__wrap23.DisposeAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 2); <>u__3 = awaiter2; <GetStreamingResponseAsync>d__39 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_0842; } goto IL_0849; case 2: awaiter2 = <>u__3; <>u__3 = default(ValueTaskAwaiter); num = (<>1__state = -1); goto IL_0842; case -8: num = (<>1__state = -1); if (!<>w__disposeMode) { Activity.Current = <activity>5__2; <lastYieldedUpdateIndex>5__21++; goto IL_08ee; } goto IL_0b85; case 3: awaiter = <>u__4; <>u__4 = default(TaskAwaiter<(bool, int, IList<ChatMessage>)>); num = (<>1__state = -1); goto IL_0a26; case -9: { try { if (num != -9) { goto IL_0ad2; } num = (<>1__state = -1); if (!<>w__disposeMode) { Activity.Current = <activity>5__2; goto IL_0ad2; } goto end_IL_0a75; IL_0ad2: if (!<>7__wrap17.MoveNext()) { goto end_IL_0a75; } ChatMessage current4 = <>7__wrap17.Current; <>2__current = ConvertToolResultMessageToUpdate(current4, <response>5__22.ConversationId, <toolMessageId>5__14); num = (<>1__state = -9); goto end_IL_009b; end_IL_0a75:; } finally { if (num == -1 && <>7__wrap17 != null) { <>7__wrap17.Dispose(); } } if (!<>w__disposeMode) { <>7__wrap17 = null; if (<modeAndMessages>5__23.ShouldTerminate) { break; } UpdateOptionsForNextIteration(ref options, <response>5__22.ConversationId); <response>5__22 = null; <modeAndMessages>5__23 = default((bool, int, IList<ChatMessage>)); <iteration>5__19++; goto IL_0458; } goto IL_0b85; } IL_0842: awaiter2.GetResult(); goto IL_0849; IL_0346: (list2, <shouldTerminate>5__16, <consecutiveErrorCount>5__11) = awaiter3.GetResult(); if (list2 != null) { <>7__wrap17 = list2.GetEnumerator(); goto case -5; } goto IL_044a; IL_02bf: <>2__current = null; awaiter3 = functionInvokingChatClient.InvokeApprovedFunctionApprovalResponsesAsync(<notInvokedApprovals>5__15, <toolMap>5__12, <originalMessages>5__4, options, <consecutiveErrorCount>5__11, isStreaming: true, cancellationToken).GetAwaiter(); if (!awaiter3.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter3; <GetStreamingResponseAsync>d__39 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine); return; } goto IL_0346; IL_0849: obj5 = <>7__wrap24; if (obj5 != null) { if (!(obj5 is Exception source)) { throw obj5; } ExceptionDispatchInfo.Capture(source).Throw(); } _ = <>7__wrap25; if (!<>w__disposeMode) { <>7__wrap24 = null; <>7__wrap23 = null; goto IL_08ee; } goto IL_0b85; IL_0a26: result = awaiter.GetResult(); <modeAndMessages>5__23 = result; <responseMessages>5__8.AddRange(<modeAndMessages>5__23.MessagesAdded); <consecutiveErrorCount>5__11 = <modeAndMessages>5__23.NewConsecutiveErrorCount; <>7__wrap17 = <modeAndMessages>5__23.MessagesAdded.GetEnumerator(); goto case -9; IL_08ee: if (<lastYieldedUpdateIndex>5__21 >= <updates>5__10.Count) { if (((<iteration>5__19 >= functionInvokingChatClient.MaximumIterationsPerRequest) | <shouldTerminate>5__16) || functionInvokingChatClient.ShouldTerminateLoopBasedOnHandleableFunctions(<functionCallContents>5__7, <toolMap>5__12)) { break; } <response>5__22 = ChatResponseExtensions.ToChatResponse((IEnumerable<ChatResponseUpdate>)<updates>5__10); (<responseMessages>5__8 ?? (<responseMessages>5__8 = new List<ChatMessage>())).AddRange(<response>5__22.Messages); FixupHistories(<originalMessages>5__4, ref messages, ref <augmentedHistory>5__6, <response>5__22, <responseMessages>5__8, ref <lastIterationHadConversationId>5__9); <>2__current = null; awaiter = functionInvokingChatClient.ProcessFunctionCallsAsync(<augmentedHistory>5__6, options, <toolMap>5__12, <functionCallContents>5__7, <iteration>5__19, <consecutiveErrorCount>5__11, isStreaming: true, cancellationToken).GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 3); <>u__4 = awaiter; <GetStreamingResponseAsync>d__39 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } goto IL_0a26; } val3 = <updates>5__10[<lastYieldedUpdateIndex>5__21]; <>2__current = val3; num = (<>1__state = -8); goto end_IL_009b; IL_044a: <notInvokedApprovals>5__15 = null; goto IL_0451; IL_0451: <iteration>5__19 = 0; goto IL_0458; IL_0458: <updates>5__10.Clear(); <functionCallContents>5__7?.Clear(); <shouldTerminate>5__16 = false; <lastApprovalCheckedFCCIndex>5__20 = 0; <lastYieldedUpdateIndex>5__21 = 0; <>7__wrap23 = functionInvokingChatClient.<>n__1(messages, options, cancellationToken).GetAsyncEnumerator(); <>7__wrap24 = null; <>7__wrap25 = 0; goto case -7; } AddUsageTags(<activity>5__2, <totalUsage>5__3); goto end_IL_000e; end_IL_009b:; } finally { if (num == -1 && <activity>5__2 != null) { ((IDisposable)<activity>5__2).Dispose(); } } goto IL_0d4d; IL_0b85: if (!<>w__disposeMode) { <activity>5__2 = null; <totalUsage>5__3 = null; <originalMessages>5__4 = null; <approvalRequiredFunctions>5__5 = null; <augmentedHistory>5__6 = null; <functionCallContents>5__7 = null; <responseMessages>5__8 = null; <updates>5__10 = null; <toolMap>5__12 = null; <toolMessageId>5__14 = null; throw null; } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <activity>5__2 = null; <totalUsage>5__3 = null; <originalMessages>5__4 = null; <approvalRequiredFunctions>5__5 = null; <augmentedHistory>5__6 = null; <functionCallContents>5__7 = null; <responseMessages>5__8 = null; <updates>5__10 = null; <toolMap>5__12 = null; <toolMessageId>5__14 = null; <notInvokedApprovals>5__15 = null; <>7__wrap17 = null; <response>5__22 = null; <modeAndMessages>5__23 = default((bool, int, IList<ChatMessage>)); <>7__wrap23 = null; <>7__wrap24 = 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; <activity>5__2 = null; <totalUsage>5__3 = null; <originalMessages>5__4 = null; <approvalRequiredFunctions>5__5 = null; <augmentedHistory>5__6 = null; <functionCallContents>5__7 = null; <responseMessages>5__8 = null; <updates>5__10 = null; <toolMap>5__12 = null; <toolMessageId>5__14 = null; <notInvokedApprovals>5__15 = null; <>7__wrap17 = null; <response>5__22 = null; <modeAndMessages>5__23 = default((bool, int, IList<ChatMessage>)); <>7__wrap23 = null; <>7__wrap24 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_0d4d: <>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)) { <GetStreamingResponseAsync>d__39 <GetStreamingResponseAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <GetStreamingResponseAsync>d__ = this; } else { <GetStreamingResponseAsync>d__ = new <GetStreamingResponseAsync>d__39(-3) { <>4__this = <>4__this }; } <GetStreamingResponseAsync>d__.messages = <>3__messages; <GetStreamingResponseAsync>d__.options = <>3__options; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <GetStreamingResponseAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <GetStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <GetStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <GetStreamingResponseAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <GetStreamingResponseAsync>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(); <GetStreamingResponseAsync>d__39 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } private static readonly AsyncLocal<FunctionInvocationContext?> _currentContext = new AsyncLocal<FunctionInvocationContext>(); private readonly ILogger _logger; private readonly ActivitySource? _activitySource; [CompilerGenerated] private int <MaximumIterationsPerRequest>k__BackingField = 40; [CompilerGenerated] private int <MaximumConsecutiveErrorsPerRequest>k__BackingField = 3; [GeneratedCode("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")] 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", "10.0.13.7005")] 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", "10.0.13.7005")] 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", "10.0.13.7005")] 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", "10.0.13.7005")] 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", "10.0.13.7005")] 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 { [CompilerGenerated] get { return <MaximumIterationsPerRequest>k__BackingField; } set { if (value < 1) { Throw.ArgumentOutOfRangeException("value"); } <MaximumIterationsPerRequest>k__BackingField = value; } } public int MaximumConsecutiveErrorsPerRequest { [CompilerGenerated] get { return <MaximumConsecutiveErrorsPerRequest>k__BackingField; } set { <MaximumConsecutiveErrorsPerRequest>k__BackingField = 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; } private static bool CurrentActivityIsInvokeAgent => Activity.Current?.DisplayName == "invoke_agent"; 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 = (CurrentActivityIsInvokeAgent ? null : _activitySource?.StartActivity("orchestrate_tools"));
BepInEx/core/Microsoft.Extensions.AI.OpenAI.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; 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.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; 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 System.Threading.Tasks.Sources; 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("10.100.125.61202")] [assembly: AssemblyInformationalVersion("10.1.1-preview.1.25612.2+8a57aae6b42651573f06fd3904b9a0d1023f9aeb")] [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("10.1.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace OpenAI.Responses { public static class MicrosoftExtensionsAIResponsesExtensions { public static FunctionTool AsOpenAIResponseTool(this AIFunctionDeclaration function) { return OpenAIResponsesChatClient.ToResponseTool(Throw.IfNull<AIFunctionDeclaration>(function, "function")); } public static ResponseTool? AsOpenAIResponseTool(this AITool tool) { return OpenAIResponsesChatClient.ToResponseTool(Throw.IfNull<AITool>(tool, "tool")); } 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 ResponseResult response, CreateResponseOptions? options = null) { return OpenAIResponsesChatClient.FromOpenAIResponse(Throw.IfNull<ResponseResult>(response, "response"), options, null); } public static IAsyncEnumerable<ChatResponseUpdate> AsChatResponseUpdatesAsync(this IAsyncEnumerable<StreamingResponseUpdate> responseUpdates, CreateResponseOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) { return OpenAIResponsesChatClient.FromOpenAIStreamingResponseUpdatesAsync(Throw.IfNull(responseUpdates, "responseUpdates"), options, null, null, cancellationToken); } public static ResponseResult AsOpenAIResponseResult(this ChatResponse response, ChatOptions? options = null) { //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_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown Throw.IfNull<ChatResponse>(response, "response"); object rawRepresentation = response.RawRepresentation; ResponseResult val = (ResponseResult)((rawRepresentation is ResponseResult) ? rawRepresentation : null); if (val != null) { return val; } ? val2 = new ResponseResult(); ? val3 = val2; object obj; if (!OpenAIClientExtensions.IsConversationId(response.ConversationId)) { obj = null; val2 = obj; obj = (object)val2; } else { val2 = new ResponseConversationOptions(response.ConversationId); obj = (object)val2; } ((ResponseResult)val3).ConversationOptions = (ResponseConversationOptions)val2; ((ResponseResult)obj).CreatedAt = response.CreatedAt.GetValueOrDefault(); ((ResponseResult)obj).Id = response.ResponseId; ((ResponseResult)obj).Instructions = ((options != null) ? options.Instructions : null); ((ResponseResult)obj).MaxOutputTokenCount = ((options != null) ? options.MaxOutputTokens : null); ((ResponseResult)obj).Model = response.ModelId ?? ((options != null) ? options.ModelId : null); ((ResponseResult)obj).ParallelToolCallsEnabled = ((options != null) ? options.AllowMultipleToolCalls : null).GetValueOrDefault(true); ((ResponseResult)obj).Status = (ResponseStatus)1; ((ResponseResult)obj).Temperature = ((options != null) ? options.Temperature : null); ((ResponseResult)obj).TopP = ((options != null) ? options.TopP : null); ((ResponseResult)obj).Usage = OpenAIResponsesChatClient.ToResponseTokenUsage(response.Usage); ResponseResult val4 = (ResponseResult)obj; foreach (ResponseItem item in OpenAIResponsesChatClient.ToOpenAIResponseItems(response.Messages, options)) { val4.OutputItems.Add(item); } return val4; } 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 { [CompilerGenerated] private sealed class <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d : IEnumerable<ChatMessageAnnotation>, IEnumerable, IEnumerator<ChatMessageAnnotation>, IEnumerator, IDisposable { private int <>1__state; private ChatMessageAnnotation <>2__current; private int <>l__initialThreadId; private IEnumerable<AIContent> contents; public IEnumerable<AIContent> <>3__contents; private IEnumerator<AIContent> <>7__wrap1; private IEnumerator<AIAnnotation> <>7__wrap2; private CitationAnnotation <citation>5__4; private TextSpanAnnotatedRegion[] <>7__wrap4; private int <>7__wrap5; ChatMessageAnnotation IEnumerator<ChatMessageAnnotation>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if ((uint)(num - -4) <= 1u || (uint)(num - 1) <= 1u) { try { if (num == -4 || (uint)(num - 1) <= 1u) { try { } finally { <>m__Finally2(); } } } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>7__wrap2 = null; <citation>5__4 = null; <>7__wrap4 = null; <>1__state = -2; } private bool MoveNext() { try { TextSpanAnnotatedRegion[] array; AIContent current; switch (<>1__state) { default: return false; case 0: <>1__state = -1; if (contents == null) { return false; } <>7__wrap1 = contents.GetEnumerator(); <>1__state = -3; goto IL_01d6; case 1: <>1__state = -4; <>7__wrap5++; goto IL_0160; case 2: { <>1__state = -4; goto IL_01b2; } IL_00ac: array = ((AIAnnotation)<citation>5__4).AnnotatedRegions?.OfType<TextSpanAnnotatedRegion>().ToArray(); if (array == null || array.Length <= 0) { break; } <>7__wrap4 = array; <>7__wrap5 = 0; goto IL_0160; IL_01b2: <citation>5__4 = null; goto IL_01b9; IL_01d6: do { if (<>7__wrap1.MoveNext()) { current = <>7__wrap1.Current; continue; } <>m__Finally1(); <>7__wrap1 = null; return false; } while (current.Annotations == null); <>7__wrap2 = current.Annotations.GetEnumerator(); <>1__state = -4; goto IL_01b9; IL_0160: if (<>7__wrap5 < <>7__wrap4.Length) { TextSpanAnnotatedRegion val = <>7__wrap4[<>7__wrap5]; <>2__current = OpenAIChatModelFactory.ChatMessageAnnotation(val.StartIndex.GetValueOrDefault(), val.EndIndex.GetValueOrDefault(), <citation>5__4.Url, <citation>5__4.Title); <>1__state = 1; return true; } <>7__wrap4 = null; goto IL_01b2; IL_01b9: while (<>7__wrap2.MoveNext()) { AIAnnotation current2 = <>7__wrap2.Current; <citation>5__4 = (CitationAnnotation)(object)((current2 is CitationAnnotation) ? current2 : null); if (<citation>5__4 == null) { continue; } goto IL_00ac; } <>m__Finally2(); <>7__wrap2 = null; goto IL_01d6; } <>2__current = OpenAIChatModelFactory.ChatMessageAnnotation(0, 0, <citation>5__4.Url, <citation>5__4.Title); <>1__state = 2; return true; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } private void <>m__Finally2() { <>1__state = -3; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<ChatMessageAnnotation> IEnumerable<ChatMessageAnnotation>.GetEnumerator() { <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d = this; } else { <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d = new <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d(0); } <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d.contents = <>3__contents; return <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<ChatMessageAnnotation>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <AsChatMessages>d__5 : IEnumerable<ChatMessage>, IEnumerable, IEnumerator<ChatMessage>, IEnumerator, IDisposable { private int <>1__state; private ChatMessage <>2__current; private int <>l__initialThreadId; private IEnumerable<ChatMessage> messages; public IEnumerable<ChatMessage> <>3__messages; private IEnumerator<ChatMessage> <>7__wrap1; ChatMessage IEnumerator<ChatMessage>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <AsChatMessages>d__5(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { //IL_005a: 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_0067: Expected O, but got Unknown //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_0144: 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_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: 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_0200: Expected O, but got Unknown try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; Throw.IfNull(messages, "messages"); <>7__wrap1 = messages.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { ChatMessage current = <>7__wrap1.Current; ChatMessage val = new ChatMessage { RawRepresentation = current }; AssistantChatMessage val2 = (AssistantChatMessage)(object)((current is AssistantChatMessage) ? current : null); if (val2 == null) { UserChatMessage val3 = (UserChatMessage)(object)((current is UserChatMessage) ? current : null); if (val3 == null) { DeveloperChatMessage val4 = (DeveloperChatMessage)(object)((current is DeveloperChatMessage) ? current : null); if (val4 == null) { SystemChatMessage val5 = (SystemChatMessage)(object)((current is SystemChatMessage) ? current : null); if (val5 == null) { ToolChatMessage val6 = (ToolChatMessage)(object)((current is ToolChatMessage) ? current : null); if (val6 != null) { val.Role = ChatRole.Tool; val.Contents.Add((AIContent)new FunctionResultContent(val6.ToolCallId, <AsChatMessages>g__ToToolResult|5_0(((ChatMessage)val6).Content)) { RawRepresentation = val6 }); } } else { val.Role = ChatRole.System; val.AuthorName = val5.ParticipantName; OpenAIChatClient.ConvertContentParts(((ChatMessage)val5).Content, val.Contents); } } else { val.Role = ChatRole.System; val.AuthorName = val4.ParticipantName; OpenAIChatClient.ConvertContentParts(((ChatMessage)val4).Content, val.Contents); } } else { val.Role = ChatRole.User; val.AuthorName = val3.ParticipantName; OpenAIChatClient.ConvertContentParts(((ChatMessage)val3).Content, val.Contents); } } else { val.Role = ChatRole.Assistant; 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); } } <>2__current = val; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<ChatMessage> IEnumerable<ChatMessage>.GetEnumerator() { <AsChatMessages>d__5 <AsChatMessages>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <AsChatMessages>d__ = this; } else { <AsChatMessages>d__ = new <AsChatMessages>d__5(0); } <AsChatMessages>d__.messages = <>3__messages; return <AsChatMessages>d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<ChatMessage>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 : IAsyncEnumerable<StreamingChatCompletionUpdate>, IAsyncEnumerator<StreamingChatCompletionUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine { public int <>1__state; public AsyncIteratorMethodBuilder <>t__builder; public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd; private StreamingChatCompletionUpdate <>2__current; private bool <>w__disposeMode; private CancellationTokenSource <>x__combinedTokens; private int <>l__initialThreadId; private IAsyncEnumerable<ChatResponseUpdate> responseUpdates; public IAsyncEnumerable<ChatResponseUpdate> <>3__responseUpdates; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private ConfiguredCancelableAsyncEnumerable<ChatResponseUpdate>.Enumerator <>7__wrap1; private object <>7__wrap2; private int <>7__wrap3; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2; StreamingChatCompletionUpdate IAsyncEnumerator<StreamingChatCompletionUpdate>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Expected O, but got Unknown int num = <>1__state; try { ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); Throw.IfNull(responseUpdates, "responseUpdates"); <>7__wrap1 = responseUpdates.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap2 = null; <>7__wrap3 = 0; goto case -5; } goto end_IL_0007; case -5: case -4: case 0: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2; if (num != -5) { if (num != -4) { if (num != 0) { goto IL_02a4; } awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_030f; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_02a4; } } else { num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_02a4; } } goto end_IL_008a; IL_030f: if (awaiter2.GetResult()) { ChatResponseUpdate current = <>7__wrap1.Current; object rawRepresentation = current.RawRepresentation; StreamingChatCompletionUpdate val = (StreamingChatCompletionUpdate)((rawRepresentation is StreamingChatCompletionUpdate) ? rawRepresentation : null); if (val != null) { <>2__current = val; num = (<>1__state = -4); } else { AIContent? obj = ((IEnumerable<AIContent>)current.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 = current.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 = current.ResponseId; ChatMessageContent val4 = new ChatMessageContent((IEnumerable<ChatMessageContentPart>)OpenAIChatClient.ToOpenAIChatContent(current.Contents)); ChatMessageRole? val5 = ToChatMessageRole(current.Role); ChatFinishReason? val6 = ToChatFinishReason(current.FinishReason); DateTimeOffset valueOrDefault = current.CreatedAt.GetValueOrDefault(); string modelId = current.ModelId; ChatTokenUsage val7 = val3; <>2__current = 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); num = (<>1__state = -5); } goto IL_0499; } goto end_IL_008a; IL_02a4: <>2__current = null; awaiter2 = <>7__wrap1.MoveNextAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_030f; end_IL_008a:; } catch (object obj2) { <>7__wrap2 = obj2; } <>2__current = null; awaiter = <>7__wrap1.DisposeAsync().GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter; <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 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 obj3 = <>7__wrap2; if (obj3 != null) { if (!(obj3 is Exception source)) { throw obj3; } ExceptionDispatchInfo.Capture(source).Throw(); } _ = <>7__wrap3; if (!<>w__disposeMode) { <>7__wrap2 = null; <>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseUpdate>.Enumerator); } end_IL_0007:; } catch (Exception exception) { <>1__state = -2; <>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseUpdate>.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<ChatResponseUpdate>.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_0499: <>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<StreamingChatCompletionUpdate> IAsyncEnumerable<StreamingChatCompletionUpdate>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 <AsOpenAIStreamingChatCompletionUpdatesAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <AsOpenAIStreamingChatCompletionUpdatesAsync>d__ = this; } else { <AsOpenAIStreamingChatCompletionUpdatesAsync>d__ = new <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4(-3); } <AsOpenAIStreamingChatCompletionUpdatesAsync>d__.responseUpdates = <>3__responseUpdates; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <AsOpenAIStreamingChatCompletionUpdatesAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <AsOpenAIStreamingChatCompletionUpdatesAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <AsOpenAIStreamingChatCompletionUpdatesAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <AsOpenAIStreamingChatCompletionUpdatesAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<StreamingChatCompletionUpdate>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 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(); <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } 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); [IteratorStateMachine(typeof(<<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d))] static IEnumerable<ChatMessageAnnotation> ConvertAnnotations(IEnumerable<AIContent>? contents) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d(-2) { <>3__contents = contents }; } } [AsyncIteratorStateMachine(typeof(<AsOpenAIStreamingChatCompletionUpdatesAsync>d__4))] public static IAsyncEnumerable<StreamingChatCompletionUpdate> AsOpenAIStreamingChatCompletionUpdatesAsync(this IAsyncEnumerable<ChatResponseUpdate> responseUpdates, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { return new <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4(-2) { <>3__responseUpdates = responseUpdates, <>3__cancellationToken = cancellationToken }; } [IteratorStateMachine(typeof(<AsChatMessages>d__5))] public static IEnumerable<ChatMessage> AsChatMessages(this IEnumerable<ChatMessage> messages) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <AsChatMessages>d__5(-2) { <>3__messages = messages }; } 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, }); } [CompilerGenerated] internal static object <AsChatMessages>g__ToToolResult|5_0(ChatMessageContent content) { if (((Collection<ChatMessageContentPart>)(object)content).Count == 1) { ChatMessageContentPart val = ((Collection<ChatMessageContentPart>)(object)content)[0]; if (val != null) { string text = val.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 JsonElement.Parse((ReadOnlySpan<byte>)memoryStream.GetBuffer().AsSpan(0, (int)memoryStream.Position), default(JsonDocumentOptions)); } } } 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 sealed class ToolDefinitionNameEqualityComparer : IEqualityComparer<ToolDefinition> { public static ToolDefinitionNameEqualityComparer Instance { get; } = new ToolDefinitionNameEqualityComparer(); public bool Equals(ToolDefinition? x, ToolDefinition? y) { FunctionToolDefinition val = (FunctionToolDefinition)(object)((x is FunctionToolDefinition) ? x : null); if (val != null) { FunctionToolDefinition val2 = (FunctionToolDefinition)(object)((y is FunctionToolDefinition) ? y : null); if (val2 != null) { return val.FunctionName.Equals(val2.FunctionName, StringComparison.Ordinal); } } return EqualityComparer<ToolDefinition>.Default.Equals(x, y); } public int GetHashCode(ToolDefinition obj) { FunctionToolDefinition val = (FunctionToolDefinition)(object)((obj is FunctionToolDefinition) ? obj : null); if (val == null) { return EqualityComparer<ToolDefinition>.Default.GetHashCode(obj); } return StringHash.GetHashCode(val.FunctionName, StringComparison.Ordinal); } } [CompilerGenerated] private sealed class <GetStreamingResponseAsync>d__9 : 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; private IEnumerable<ChatMessage> messages; public IEnumerable<ChatMessage> <>3__messages; public OpenAIAssistantsChatClient <>4__this; private ChatOptions options; public ChatOptions <>3__options; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private RunCreationOptions <runOptions>5__2; private ToolResources <toolResources>5__3; private List<FunctionResultContent> <toolResults>5__4; private string <threadId>5__5; private ThreadRun <threadRun>5__6; private string <responseId>5__7; private ConfiguredValueTaskAwaitable<(RunCreationOptions RunOptions, ToolResources? Resources, List<FunctionResultContent>? ToolResults)>.ConfiguredValueTaskAwaiter <>u__1; private ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator <>7__wrap7; private object <>7__wrap8; private int <>7__wrap9; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__2; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__3; private ConfiguredTaskAwaitable<ClientResult<AssistantThread>>.ConfiguredTaskAwaiter <>u__4; private ConfiguredTaskAwaitable<ClientResult<ThreadRun>>.ConfiguredTaskAwaiter <>u__5; private ConfiguredCancelableAsyncEnumerable<StreamingUpdate>.Enumerator <>7__wrap10; private StreamingUpdate <update>5__12; private RunStepDetailsUpdate <details>5__13; ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetStreamingResponseAsync>d__9(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_096b: Unknown result type (might be due to invalid IL or missing references) //IL_0970: Unknown result type (might be due to invalid IL or missing references) //IL_0981: Unknown result type (might be due to invalid IL or missing references) //IL_098f: Expected O, but got Unknown //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Expected O, but got Unknown //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_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03fd: Expected O, but got Unknown //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0c8a: Unknown result type (might be due to invalid IL or missing references) //IL_0c8f: Unknown result type (might be due to invalid IL or missing references) //IL_0c9b: Unknown result type (might be due to invalid IL or missing references) //IL_0ca7: Unknown result type (might be due to invalid IL or missing references) //IL_0cb3: Unknown result type (might be due to invalid IL or missing references) //IL_0cbf: Unknown result type (might be due to invalid IL or missing references) //IL_0ccb: Unknown result type (might be due to invalid IL or missing references) //IL_0ccc: Unknown result type (might be due to invalid IL or missing references) //IL_0ce0: Expected O, but got Unknown //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_06d7: Unknown result type (might be due to invalid IL or missing references) //IL_06dc: Unknown result type (might be due to invalid IL or missing references) //IL_06e8: Unknown result type (might be due to invalid IL or missing references) //IL_06f4: Unknown result type (might be due to invalid IL or missing references) //IL_070b: Unknown result type (might be due to invalid IL or missing references) //IL_0717: Unknown result type (might be due to invalid IL or missing references) //IL_0729: Unknown result type (might be due to invalid IL or missing references) //IL_0731: Unknown result type (might be due to invalid IL or missing references) //IL_073d: Unknown result type (might be due to invalid IL or missing references) //IL_073e: Unknown result type (might be due to invalid IL or missing references) //IL_074f: Expected O, but got Unknown //IL_086c: Unknown result type (might be due to invalid IL or missing references) //IL_0871: Unknown result type (might be due to invalid IL or missing references) //IL_0882: Unknown result type (might be due to invalid IL or missing references) //IL_08a9: Unknown result type (might be due to invalid IL or missing references) //IL_08b3: Expected O, but got Unknown //IL_08b8: Unknown result type (might be due to invalid IL or missing references) //IL_08c6: Expected O, but got Unknown //IL_08c7: Unknown result type (might be due to invalid IL or missing references) //IL_08df: Unknown result type (might be due to invalid IL or missing references) //IL_08e4: Unknown result type (might be due to invalid IL or missing references) //IL_08f0: Unknown result type (might be due to invalid IL or missing references) //IL_08fc: Unknown result type (might be due to invalid IL or missing references) //IL_0908: Unknown result type (might be due to invalid IL or missing references) //IL_0914: Unknown result type (might be due to invalid IL or missing references) //IL_0925: Expected O, but got Unknown //IL_0ae9: Unknown result type (might be due to invalid IL or missing references) //IL_0aed: Unknown result type (might be due to invalid IL or missing references) //IL_0af2: Unknown result type (might be due to invalid IL or missing references) //IL_09df: Unknown result type (might be due to invalid IL or missing references) //IL_09e4: Unknown result type (might be due to invalid IL or missing references) //IL_09f4: Expected O, but got Unknown //IL_0a59: Unknown result type (might be due to invalid IL or missing references) //IL_0a71: Unknown result type (might be due to invalid IL or missing references) //IL_0a76: Unknown result type (might be due to invalid IL or missing references) //IL_0a82: Unknown result type (might be due to invalid IL or missing references) //IL_0a8e: Unknown result type (might be due to invalid IL or missing references) //IL_0a9a: Unknown result type (might be due to invalid IL or missing references) //IL_0aa6: Unknown result type (might be due to invalid IL or missing references) //IL_0ab7: Expected O, but got Unknown //IL_0768: Unknown result type (might be due to invalid IL or missing references) //IL_076d: Unknown result type (might be due to invalid IL or missing references) //IL_0780: Unknown result type (might be due to invalid IL or missing references) //IL_0793: Unknown result type (might be due to invalid IL or missing references) //IL_07ab: Expected O, but got Unknown //IL_07a6: Unknown result type (might be due to invalid IL or missing references) //IL_07b0: Expected O, but got Unknown //IL_0b07: Unknown result type (might be due to invalid IL or missing references) //IL_0b00: Unknown result type (might be due to invalid IL or missing references) //IL_0a23: Unknown result type (might be due to invalid IL or missing references) //IL_0a2d: Expected O, but got Unknown //IL_0b18: Unknown result type (might be due to invalid IL or missing references) //IL_0b1d: Unknown result type (might be due to invalid IL or missing references) //IL_0b29: Unknown result type (might be due to invalid IL or missing references) //IL_0b35: Unknown result type (might be due to invalid IL or missing references) //IL_0b41: Unknown result type (might be due to invalid IL or missing references) //IL_0b49: Unknown result type (might be due to invalid IL or missing references) //IL_0b57: Expected O, but got Unknown //IL_0be3: Unknown result type (might be due to invalid IL or missing references) //IL_0bea: Expected O, but got Unknown //IL_0bcc: Unknown result type (might be due to invalid IL or missing references) //IL_0bd6: Expected O, but got Unknown //IL_0c06: Unknown result type (might be due to invalid IL or missing references) //IL_0c0b: Unknown result type (might be due to invalid IL or missing references) //IL_0c13: Unknown result type (might be due to invalid IL or missing references) //IL_0c1b: Unknown result type (might be due to invalid IL or missing references) //IL_0c20: Unknown result type (might be due to invalid IL or missing references) //IL_0c2d: Unknown result type (might be due to invalid IL or missing references) //IL_0c3f: Expected O, but got Unknown //IL_0c44: Unknown result type (might be due to invalid IL or missing references) //IL_0c4c: Unknown result type (might be due to invalid IL or missing references) //IL_0c59: Expected O, but got Unknown int num = <>1__state; OpenAIAssistantsChatClient openAIAssistantsChatClient = <>4__this; try { ConfiguredValueTaskAwaitable<(RunCreationOptions, ToolResources, List<FunctionResultContent>)>.ConfiguredValueTaskAwaiter awaiter5; ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter4; ConfiguredTaskAwaitable<ClientResult<AssistantThread>>.ConfiguredTaskAwaiter awaiter3; ConfiguredTaskAwaitable<ClientResult<ThreadRun>>.ConfiguredTaskAwaiter awaiter2; ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter; IAsyncEnumerable<StreamingUpdate> source; (RunCreationOptions, ToolResources, List<FunctionResultContent>) result; (RunCreationOptions, ToolResources, List<FunctionResultContent>) tuple; ChatOptions obj2; ThreadCreationOptions val; IEnumerator<ThreadInitializationMessage> enumerator; ClientResult<AssistantThread> result2; ClientResult<AssistantThread> val12; ClientResult<ThreadRun> result3; object obj3; switch (num) { default: if (!<>w__disposeMode) { num = (<>1__state = -1); Throw.IfNull(messages, "messages"); <>2__current = null; awaiter5 = openAIAssistantsChatClient.CreateRunOptionsAsync(messages, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter5.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter5; <GetStreamingResponseAsync>d__9 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter5, ref stateMachine); return; } goto IL_00fc; } goto end_IL_000e; case 0: awaiter5 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaitable<(RunCreationOptions, ToolResources, List<FunctionResultContent>)>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_00fc; case 1: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter6; if (num != 1) { <>2__current = null; awaiter6 = <>7__wrap7.MoveNextAsync().GetAwaiter(); if (!awaiter6.IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter6; <GetStreamingResponseAsync>d__9 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter6, ref stateMachine); return; } } else { awaiter6 = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); } if (awaiter6.GetResult()) { ThreadRun current = <>7__wrap7.Current; if (current.Status != RunStatus.Completed && current.Status != RunStatus.Cancelled && current.Status != RunStatus.Failed && current.Status != RunStatus.Expired) { <threadRun>5__6 = current; } } } catch (object obj) { <>7__wrap8 = obj; } <>2__current = null; awaiter4 = <>7__wrap7.DisposeAsync().GetAwaiter(); if (!awaiter4.IsCompleted) { num = (<>1__state = 2); <>u__3 = awaiter4; <GetStreamingResponseAsync>d__9 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter4, ref stateMachine); return; } goto IL_032c; case 2: awaiter4 = <>u__3; <>u__3 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_032c; case 3: awaiter3 = <>u__4; <>u__4 = default(ConfiguredTaskAwaitable<ClientResult<AssistantThread>>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_04d9; case 4: awaiter2 = <>u__5; <>u__5 = default(ConfiguredTaskAwaitable<ClientResult<ThreadRun>>.ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_0590; case -8: case -7: case -6: case -5: case -4: case 5: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter7; StreamingUpdate obj4; ThreadUpdate val2; StreamingUpdate obj5; RunUpdate val3; IReadOnlyList<RunStepUpdateCodeInterpreterOutput> codeInterpreterOutputs; CodeInterpreterToolResultContent val10; IEnumerator<RunStepUpdateCodeInterpreterOutput> enumerator2; switch (num) { case -4: num = (<>1__state = -1); if (<>w__disposeMode) { break; } goto IL_0d05; case -5: num = (<>1__state = -1); if (<>w__disposeMode) { break; } goto IL_094a; case -6: num = (<>1__state = -1); if (<>w__disposeMode) { break; } goto IL_0d05; case -7: num = (<>1__state = -1); if (<>w__disposeMode) { break; } goto IL_0d05; case -8: num = (<>1__state = -1); if (<>w__disposeMode) { break; } goto IL_0d05; default: <>2__current = null; awaiter7 = <>7__wrap10.MoveNextAsync().GetAwaiter(); if (!awaiter7.IsCompleted) { num = (<>1__state = 5); <>u__2 = awaiter7; <GetStreamingResponseAsync>d__9 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter7, ref stateMachine); return; } goto IL_0d7e; case 5: { awaiter7 = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_0d7e; } IL_0d05: <details>5__13 = null; <update>5__12 = null; goto default; IL_0c89: <>2__current = new ChatResponseUpdate { AuthorName = openAIAssistantsChatClient._assistantId, ConversationId = <threadId>5__5, MessageId = <responseId>5__7, RawRepresentation = <update>5__12, ResponseId = <responseId>5__7, Role = ChatRole.Assistant }; num = (<>1__state = -8); goto IL_0f99; IL_0d7e: if (!awaiter7.GetResult()) { break; } <update>5__12 = <>7__wrap10.Current; obj4 = <update>5__12; val2 = (ThreadUpdate)(object)((obj4 is ThreadUpdate) ? obj4 : null); if (val2 != null) { if (<threadId>5__5 == null) { <threadId>5__5 = ((StreamingUpdate<AssistantThread>)(object)val2).Value.Id; } goto IL_0c89; } obj5 = <update>5__12; val3 = (RunUpdate)(object)((obj5 is RunUpdate) ? obj5 : null); if (val3 == null) { ref RunStepDetailsUpdate reference = ref <details>5__13; StreamingUpdate obj6 = <update>5__12; reference = (RunStepDetailsUpdate)(object)((obj6 is RunStepDetailsUpdate) ? obj6 : null); if (<details>5__13 == null) { StreamingUpdate obj7 = <update>5__12; MessageContentUpdate val4 = (MessageContentUpdate)(object)((obj7 is MessageContentUpdate) ? obj7 : null); if (val4 == null) { goto IL_0c89; } ChatResponseUpdate val5 = new ChatResponseUpdate((ChatRole?)((val4.Role == (MessageRole?)0) ? ChatRole.User : ChatRole.Assistant), val4.Text) { AuthorName = openAIAssistantsChatClient._assistantId, ConversationId = <threadId>5__5, MessageId = <responseId>5__7, RawRepresentation = val4, ResponseId = <responseId>5__7 }; TextAnnotationUpdate textAnnotation = val4.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 (val5.Contents.Count == 0) { val5.Contents.Add((AIContent)new TextContent(string.Empty)); } TextContent val6 = (TextContent)val5.Contents[0]; (((AIContent)val6).Annotations ?? (((AIContent)val6).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 }); } } <>2__current = val5; num = (<>1__state = -7); } else { if (string.IsNullOrEmpty(<details>5__13.CodeInterpreterInput)) { goto IL_094a; } CodeInterpreterToolCallContent item = new CodeInterpreterToolCallContent { CallId = <details>5__13.ToolCallId, Inputs = new List<AIContent>(1) { (AIContent)new DataContent((ReadOnlyMemory<byte>)Encoding.UTF8.GetBytes(<details>5__13.CodeInterpreterInput), "text/x-python") }, RawRepresentation = <details>5__13 }; <>2__current = new ChatResponseUpdate((ChatRole?)ChatRole.Assistant, (IList<AIContent>)new List<AIContent>(1) { (AIContent)(object)item }) { AuthorName = openAIAssistantsChatClient._assistantId, ConversationId = <threadId>5__5, MessageId = <responseId>5__7, RawRepresentation = <update>5__12, ResponseId = <responseId>5__7 }; num = (<>1__state = -5); } } else { if (<threadId>5__5 == null) { <threadId>5__5 = ((StreamingUpdate<ThreadRun>)(object)val3).Value.ThreadId; } if (<responseId>5__7 == null) { <responseId>5__7 = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Id; } ChatResponseUpdate val7 = new ChatResponseUpdate { AuthorName = openAIAssistantsChatClient._assistantId, ConversationId = <threadId>5__5, CreatedAt = ((StreamingUpdate<ThreadRun>)(object)val3).Value.CreatedAt, MessageId = <responseId>5__7, ModelId = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Model, RawRepresentation = val3, ResponseId = <responseId>5__7, Role = ChatRole.Assistant }; RunTokenUsage usage = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Usage; if (usage != null) { val7.Contents.Add((AIContent)new UsageContent(new UsageDetails { InputTokenCount = usage.InputTokenCount, OutputTokenCount = usage.OutputTokenCount, TotalTokenCount = usage.TotalTokenCount })); } RequiredActionUpdate val8 = (RequiredActionUpdate)(object)((val3 is RequiredActionUpdate) ? val3 : null); if (val8 != null) { string toolCallId = val8.ToolCallId; if (toolCallId != null) { string functionName = val8.FunctionName; if (functionName != null) { FunctionCallContent val9 = OpenAIClientExtensions.ParseCallContent(val8.FunctionArguments, JsonSerializer.Serialize(new string[2] { ((StreamingUpdate<ThreadRun>)(object)val3).Value.Id, toolCallId }, OpenAIJsonContext.Default.StringArray), functionName); ((AIContent)val9).RawRepresentation = val3; val7.Contents.Add((AIContent)(object)val9); } } } <>2__current = val7; num = (<>1__state = -4); } goto IL_0f99; IL_094a: codeInterpreterOutputs = <details>5__13.CodeInterpreterOutputs; if (codeInterpreterOutputs == null || codeInterpreterOutputs.Count <= 0) { goto IL_0d05; } val10 = new CodeInterpreterToolResultContent { CallId = <details>5__13.ToolCallId, RawRepresentation = <details>5__13 }; enumerator2 = <details>5__13.CodeInterpreterOutputs.GetEnumerator(); try { while (enumerator2.MoveNext()) { RunStepUpdateCodeInterpreterOutput current3 = enumerator2.Current; if (current3.ImageFileId != null) { CodeInterpreterToolResultContent val11 = val10; (val11.Outputs ?? (val11.Outputs = new List<AIContent>())).Add((AIContent)new HostedFileContent(current3.ImageFileId) { MediaType = "image/*" }); } string logs = current3.Logs; if (logs != null) { CodeInterpreterToolResultContent val11 = val10; (val11.Outputs ?? (val11.Outputs = new List<AIContent>())).Add((AIContent)new TextContent(logs)); } } } finally { if (num == -1) { enumerator2?.Dispose(); } } if (<>w__disposeMode) { break; } <>2__current = new ChatResponseUpdate((ChatRole?)ChatRole.Assistant, (IList<AIContent>)new List<AIContent>(1) { (AIContent)(object)val10 }) { AuthorName = openAIAssistantsChatClient._assistantId, ConversationId = <threadId>5__5, MessageId = <responseId>5__7, RawRepresentation = <update>5__12, ResponseId = <responseId>5__7 }; num = (<>1__state = -6); goto IL_0f99; } } catch (object obj) { <>7__wrap8 = obj; } <>2__current = null; awaiter = <>7__wrap10.DisposeAsync().GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 6); <>u__3 = awaiter; <GetStreamingResponseAsync>d__9 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); return; } break; case 6: { awaiter = <>u__3; <>u__3 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); break; } IL_05c4: <responseId>5__7 = null; <>7__wrap10 = source.ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap8 = null; <>7__wrap9 = 0; goto case -8; IL_00fc: result = awaiter5.GetResult(); tuple = result; <runOptions>5__2 = tuple.Item1; <toolResources>5__3 = tuple.Item2; <toolResults>5__4 = tuple.Item3; obj2 = options; <threadId>5__5 = ((obj2 != null) ? obj2.ConversationId : null) ?? openAIAssistantsChatClient._defaultThreadId; <threadRun>5__6 = null; if (<threadId>5__5 != null) { <>7__wrap7 = ((IAsyncEnumerable<ThreadRun>)openAIAssistantsChatClient._client.GetRunsAsync(<threadId>5__5, new RunCollectionOptions { Order = RunCollectionOrder.Descending, PageSizeLimit = 1 }, cancellationToken)).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap8 = null; <>7__wrap9 = 0; goto case 1; } goto IL_0382; IL_032c: awaiter4.GetResult(); obj3 = <>7__wrap8; if (obj3 != null) { if (!(obj3 is Exception source2)) { throw obj3; } ExceptionDispatchInfo.Capture(source2).Throw(); } _ = <>7__wrap9; if (!<>w__disposeMode) { <>7__wrap8 = null; <>7__wrap7 = default(ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator); goto IL_0382; } goto end_IL_000e; IL_05a0: source = (IAsyncEnumerable<StreamingUpdate>)openAIAssistantsChatClient._client.CreateRunStreamingAsync(<threadId>5__5, openAIAssistantsChatClient._assistantId, <runOptions>5__2, cancellationToken); goto IL_05c4; IL_0382: if (<threadRun>5__6 != null) { List<ToolOutput> toolOutputs; string text = ConvertFunctionResultsToToolOutput(<toolResults>5__4, out toolOutputs); if (text != null && text == <threadRun>5__6.Id) { source = (IAsyncEnumerable<StreamingUpdate>)openAIAssistantsChatClient._client.SubmitToolOutputsToRunStreamingAsync(<threadRun>5__6.ThreadId, <threadRun>5__6.Id, (IEnumerable<ToolOutput>)toolOutputs, cancellationToken); goto IL_05c4; } } if (<threadId>5__5 != null) { if (<threadRun>5__6 != null) { <>2__current = null; awaiter2 = openAIAssistantsChatClient._client.CancelRunAsync(<threadId>5__5, <threadRun>5__6.Id, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 4); <>u__5 = awaiter2; <GetStreamingResponseAsync>d__9 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_0590; } goto IL_05a0; } val = new ThreadCreationOptions { ToolResources = <toolResources>5__3 }; enumerator = <runOptions>5__2.AdditionalMessages.GetEnumerator(); try { while (enumerator.MoveNext()) { ThreadInitializationMessage current2 = enumerator.Current; val.InitialMessages.Add(current2); } } finally { if (num == -1) { enumerator?.Dispose(); } } if (!<>w__disposeMode) { <runOptions>5__2.AdditionalMessages.Clear(); <>2__current = null; awaiter3 = openAIAssistantsChatClient._client.CreateThreadAsync(val, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter(); if (!awaiter3.IsCompleted) { num = (<>1__state = 3); <>u__4 = awaiter3; <GetStreamingResponseAsync>d__9 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine); return; } goto IL_04d9; } goto end_IL_000e; IL_04d9: result2 = awaiter3.GetResult(); val12 = result2; <threadId>5__5 = val12.Value.Id; goto IL_05a0; IL_0590: result3 = awaiter2.GetResult(); <threadRun>5__6 = null; goto IL_05a0; } awaiter.GetResult(); obj3 = <>7__wrap8; if (obj3 != null) { if (!(obj3 is Exception source3)) { throw obj3; } ExceptionDispatchInfo.Capture(source3).Throw(); } _ = <>7__wrap9; if (!<>w__disposeMode) { <>7__wrap8 = null; <>7__wrap10 = default(ConfiguredCancelableAsyncEnumerable<StreamingUpdate>.Enumerator); } end_IL_000e:; } catch (Exception exception) { <>1__state = -2; <runOptions>5__2 = null; <toolResources>5__3 = null; <toolResults>5__4 = null; <threadId>5__5 = null; <threadRun>5__6 = null; <responseId>5__7 = null; <>7__wrap7 = default(ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator); <>7__wrap8 = null; <>7__wrap10 = default(ConfiguredCancelableAsyncEnumerable<StreamingUpdate>.Enumerator); <update>5__12 = null; <details>5__13 = 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; <runOptions>5__2 = null; <toolResources>5__3 = null; <toolResults>5__4 = null; <threadId>5__5 = null; <threadRun>5__6 = null; <responseId>5__7 = null; <>7__wrap7 = default(ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator); <>7__wrap8 = null; <>7__wrap10 = default(ConfiguredCancelableAsyncEnumerable<StreamingUpdate>.Enumerator); <update>5__12 = null; <details>5__13 = null; if (<>x__combinedTokens != null) { <>x__combinedTokens.Dispose(); <>x__combinedTokens = null; } <>2__current = null; <>t__builder.Complete(); <>v__promiseOfValueOrEnd.SetResult(result: false); return; IL_0f99: <>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)) { <GetStreamingResponseAsync>d__9 <GetStreamingResponseAsync>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = -3; <>t__builder = AsyncIteratorMethodBuilder.Create(); <>w__disposeMode = false; <GetStreamingResponseAsync>d__ = this; } else { <GetStreamingResponseAsync>d__ = new <GetStreamingResponseAsync>d__9(-3) { <>4__this = <>4__this }; } <GetStreamingResponseAsync>d__.messages = <>3__messages; <GetStreamingResponseAsync>d__.options = <>3__options; if (<>3__cancellationToken.Equals(default(CancellationToken))) { <GetStreamingResponseAsync>d__.cancellationToken = cancellationToken; } else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken))) { <GetStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken; } else { <>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken); <GetStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token; } return <GetStreamingResponseAsync>d__; } [DebuggerHidden] ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync() { if (<>1__state == -2) { return default(ValueTask<bool>); } <>v__promiseOfValueOrEnd.Reset(); <GetStreamingResponseAsync>d__9 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(); <GetStreamingResponseAsync>d__9 stateMachine = this; <>t__builder.MoveNext(ref stateMachine); return new ValueTask(this, <>v__promiseOfValueOrEnd.Version); } } 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); } [AsyncIteratorStateMachine(typeof(<GetStreamingResponseAsync>d__9))] public IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken)) { return new <GetStreamingResponseAsync>d__9(-2) { <>4__this = this, <>3__messages = messages, <>3__options = options, <>3__cancellationToken = cancellationToken }; } 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) { HashSet<ToolDefinition> toolsOverride = new HashSet<ToolDefinition>(ToolDefinitionNameEqualityComparer.Instance); if (runOptions.ToolsOverride.Count == 0) { if (_assistantTools == null) { _assistantTools = (await _client.GetAssistantAsync(_assistantId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Value.Tools; } toolsOverride.UnionWith(_assistantTools); } 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; } FileSearchToolDefinition val5 = ToolDefinition.CreateFileSearch(val4.MaximumResultCount); val5.RankingOptions = ((AITool)(object)val4).GetProperty<FileSearchRankingOptions>("RankingOptions"); toolsOverride.Add((ToolDefinition)(object)val5); IList<AIContent> inputs = val4.Inputs; if (inputs == null || inputs.Count <= 0) { continue; } foreach (AIContent item3 in inputs) { HostedVectorStoreContent val6 = (HostedVectorStoreContent)(object)((item3 is HostedVectorStoreContent) ? item3 : null); if (val6 != null) { ToolResources obj2 = resources; if (obj2 == null) { ToolResources val7 = new ToolResources(); ToolResources val8 = val7; resources = val7; obj2 = val8; } ToolResources val9 = obj2; if (val9.FileSearch == null) { val9.FileSearch = new FileSearchToolResources(); } resources.FileSearch.VectorStoreIds.Add(val6.VectorStoreId); } } continue; } CodeInterpreterToolDefinition item = ToolDefinition.CreateCodeInterpreter(); toolsOverride.Add((ToolDefinition)(object)item); int? num = val3.Inputs?.Count; if (!num.HasValue || num.GetValueOrDefault() <= 0) { continue; } ThreadInitializationMessage val10 = null; foreach (AIContent input in val3.Inputs) { HostedFileContent val11 = (HostedFileContent)(object)((input is HostedFileContent) ? input : null); if (val11 != null) { if (val10 == null) { val10 = new ThreadInitializationMessage((MessageRole)0, (IEnumerable<MessageContent>)new <>z__ReadOnlySingleElementList<MessageContent>(MessageContent.FromText("attachments"))); } ((MessageCreationOptions)val10).Attachments.Add(new MessageCreationAttachment(val11.FileId, (IEnumerable<ToolDefinition>)new <>z__ReadOnlySingleElementList<ToolDefinition>((ToolDefinition)(object)item))); } } if (val10 != null) { runOptions.AdditionalMessages.Add(val10); } } else { toolsOverride.Add((ToolDefinition)(object)ToOpenAIAssistantsFunctionToolDefinition(val2, options)); } } foreach (ToolDefinition item4 in toolsOverride) { runOptions.ToolsOverride.Add(item4); } } if (runOptions.ToolConstraint == null) { ChatToolMode toolMode = options.ToolMode; if (!(toolMode is NoneChatToolMode)) { if (!(toolMode is AutoChatToolMode)) { RequiredChatToolMode val12 = (RequiredChatToolMode)(object)((toolMode is RequiredChatToolMode) ? toolMode : null); if (val12 != null) { string requiredFunctionName = val12.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 val13 = (ChatResponseFormatJson)(object)((responseFormat is ChatResponseFormatJson) ? responseFormat : null); if (val13 != null) { JsonElement? orCreateTransformedSchema = OpenAIClientExtensions.StrictSchemaTransformCache.GetOrCreateTransformedSchema(val13); if (orCreateTransformedSchema.HasValue) { JsonElement valueOrDefault = orCreateTransformedSchema.GetValueOrDefault(); runOptions.ResponseFormat = AssistantResponseFormat.CreateJsonSchemaFormat(val13.SchemaName, BinaryData.FromBytes(JsonSerializer.SerializeToUtf8Bytes(valueOrDefault, OpenAIJsonContext.Default.JsonElement)), val13.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 item5 in message.Contents.OfType<TextContent>()) { AppendSystemInstructions(item5.Text); } continue; } foreach (AIContent content in message.Contents) { AIContent val14 = content; if (val14 == null) { continue; } object rawRepresentation = content.RawRepresentation; MessageContent val15 = (MessageContent)((rawRepresentation is MessageContent) ? rawRepresentation : null); if (val15 == null) { TextContent val16 = (TextContent)(object)((val14 is TextContent) ? val14 : null); if (val16 == null) { UriContent val17 = (UriContent)(object)((val14 is UriContent) ? val14 : null); if (val17 == null) { FunctionResultContent val18 = (FunctionResultContent)(object)((val14 is FunctionResultContent) ? val14 : null); if (val18 != null && message.Role == ChatRole.Tool) { (list ?? (list = new List<FunctionResultContent>())).Add(val18); } } else if (val17.HasTopLevelMediaType("image")) { list2.Add(MessageContent.FromImageUri(val17.Uri, (MessageImageDetail?)null)); } } else { list2.Add(MessageContent.FromText(val16.Text)); } } else { list2.Add(val15); } } 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; } [CompilerGenerated] private sealed class <FromOpenAIStreamingChatCompletionAsync>d__14 : 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; private IAsyncEnumerable<StreamingChatCompletionUpdate> updates; public IAsyncEnumerable<StreamingChatCompletionUpdate> <>3__updates; private CancellationToken cancellationToken; public CancellationToken <>3__cancellationToken; private ChatCompletionOptions options; public ChatCompletionOptions <>3__options; private Dictionary<int, FunctionCallInfo> <functionCallInfos>5__2; private ChatRole? <streamedRole>5__3; private ChatFinishReason? <finishReason>5__4; private StringBuilder <refusal>5__5; private string <responseId>5__6; private DateTimeOffset? <createdAt>5__7; private string <modelId>5__8; private ConfiguredCancelableAsyncEnumerable<StreamingChatCompletionUpdate>.Enumerator <>7__wrap8; private object <>7__wrap9; private int <>7__wrap10; private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1; private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2; ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <FromOpenAIStreamingChatCompletionAsync>d__14(int <>1__state) { <>t__builder = AsyncIteratorMethodBuilder.Create(); this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } private void MoveNext() { //IL_0581: Unknown result type (might be due to invalid IL or missing references) //IL_0586: Unknown result type (might be due to invalid IL or missing references) //IL_0592: Unknown result type (might be due to invalid IL or missing references) //IL_059e: Unknown result type (might be due to invalid IL or missing references) //IL_05aa: Unknown result type (might be due to invalid IL or missing references) //IL_05b6: Unknown result type (might be due to invalid IL or missing references) //IL_05c2: Unknown result type (might be due to invalid IL or missing references) //IL_05d0: Expected O, but got Unknown //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: 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_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0682: Unknown result type (might be due to invalid IL or missing references) //IL_0687: Unknown result type (might be due to invalid IL or missing references) //IL_0697: Expected O, but got Unknown //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Expected O, but got Unknown //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Expected O, but got Unknown //IL_03ed: Unknown result type (might be due to invalid IL or missing references) //IL_03f2: Unknown result type (might be due to invalid IL or missing references) //IL_03ff: Expected O, but got Unknown int num = <>1__state; try { ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter; object obj; ChatResponseUpdate val; Dictionary<int, FunctionCallInfo>.Enumerator enumerator; switch (num) { default: if (<>w__disposeMode) { break; } num = (<>1__state = -1); <functionCallInfos>5__2 = null; <streamedRole>5__3 = null; <finishReason>5__4 = null; <refusal>5__5 = null; <responseId>5__6 = null; <createdAt>5__7 = null; <modelId>5__8 = null; <>7__wrap8 = updates.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator(); <>7__wrap9 = null; <>7__wrap10 = 0; goto case -4; case -4: case 0: try { ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2; if (num != -4) { if (num != 0) { goto IL_042c; } awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_0497; } num = (<>1__state = -1); if (!<>w__disposeMode) { goto IL_042c; } goto end_IL_00b9; IL_042c: <>2__current = null; awaiter2 = <>7__wrap8.MoveNextAsync().GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; <FromOpenAIStreamingChatCompletionAsync>d__14 stateMachine = this; <>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine); return; } goto IL_0497; IL_0497: StreamingChatCompletionUpdate current; ChatResponseUpdate val4; if (awaiter2.GetResult()) { current = <>7__wrap8.Current; ChatRole? val2 = <streamedRole>5__3; if (!val2.HasValue) { ChatMessageRole? role = current.Role; ChatRole? obj2; if (role.HasValue) { ChatMessageRole valueOrDefault = role.GetValueOrDefault(); obj2 = FromOpenAIChatRole(valueOrDefault); } else { obj2 = null; } <streamedRole>5__3 = obj2; } ChatFinishReason? val3 = <finishReason>5__4; if (!val3.HasValue) { ChatFinishReason? finishReason = current.FinishReason; ChatFinishReason? obj3; if (finishReason.HasValue) { ChatFinishReason valueOrDefault2 = finishReason.GetValueOrDefault(); obj3 = FromOpenAIFinishReason(valueOrDefault2); } else { obj3 = null; } <finishReason>5__4 = obj3; } if (<responseId>5__6 == null) { <responseId>5__6 = current.CompletionId; } DateTimeOffset valueOrDefault3 = <createdAt>5__7.GetValueOrDefault(); if (!<createdAt>5__7.HasValue) { valueOrDefault3 = current.CreatedAt; <createdAt>5__7 = valueOrDefault3; } if (<modelId>5__8 == null) { <modelId>5__8 = current.Model; } val4 = new ChatResponseUpdate { ResponseId = current.CompletionId, MessageId = current.CompletionId, CreatedAt = current.CreatedAt, FinishReason = <finishReason>5__4, ModelId = <modelId>5__8, RawRepresentation = current, Role = <streamedRole>5__3 }; ChatMessageContent contentUpdate = current.ContentUpdate; if (contentUpdate != null && ((Collection<ChatMessageContentPart>)(object)contentUpdate).Count > 0) { ConvertContentParts(current.ContentUpdate, val4.Contents); } StreamingChatOutputAudioUpdate outputAudioUpdate = current.OutputAudioUpdate; if (outputAudioUpdate != null) { val4.Contents.Add((AIContent)new DataContent(outputAudioUpdate.AudioBytesUpdate.ToMemory(), GetOutputAudioMimeType(options)) { RawRepresentation = outputAudioUpdate }); } if (current.RefusalUpdate != null) { (<refusal>5__5 ?? (<refusal>5__5 = new StringBuilder())).Append(current.RefusalUpdate); } IReadOnlyList<StreamingChatToolCallUpdate> toolCallUpdates = current.ToolCallUpdates; if (toolCallUpdates == null || toolCallUpdates.Count <= 0) { goto IL_03d3; } IEnumerator<StreamingChatToolCallUpdate> enumerator2 = toolCallUpdates.GetEnumerator(); try { while (enumerator2.MoveNext()) { StreamingChatToolCallUpdate current2 = enumerator2.Current; if (<functionCallInfos>5__2 == null) { <functionCallInfos>5__2 = new Dictionary<int, FunctionCallInfo>(); } if (!<functionCallInfos>5__2.TryGetValue(current2.Index, out FunctionCallInfo value2)) { value2 = (<functionCallInfos>5__2[current2.Index] = new FunctionCallInfo()); } FunctionCallInfo functionCallInfo2 = value2; if (functionCallInfo2.CallId == null) { functionCallInfo2.CallId = current2.ToolCallId; } functionCallInfo2 = value2; if (functionCallInfo2.Name == null) { functionCallInfo2.Name = current2.FunctionName; } BinaryData functionArgumentsUpdate = current2.FunctionArgumentsUpdate; if (functionArgumentsUpdate != null && !functionArgumentsUpdate.ToMemory().IsEmpty) { functionCallInfo2 = value2; (functionCallInfo2.Arguments ?? (functionCallInfo2.Arguments = new StringBuilder())).Append(((object)functionArgumentsUpdate).ToString()); } } } finally { if (num == -1) { enumerator2?.Dispose(); } } if (
BepInEx/core/Microsoft.Extensions.Caching.Abstractions.dll
Decompiled a month agousing System; using System.Buffers; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; 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.Caching.Distributed; 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: AssemblyMetadata("IsAotCompatible", "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("10.0.125.57005")] [assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Caching.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")] [assembly: AssemblyVersion("10.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] 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; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace System { internal static class ExceptionPolyfills { [SpecialName] public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B { [SpecialName] public static class <M>$96F0261AC622664B8B003966835C0332 { } [ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")] public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { throw null; } } [SpecialName] public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9 { [SpecialName] public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC { } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { throw null; } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { throw null; } } public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { ThrowArgumentNullException(paramName); } } [DoesNotReturn] private static void ThrowArgumentNullException(string paramName) { throw new ArgumentNullException(paramName); } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { if (condition) { ThrowObjectDisposedException(instance); } } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { if (condition) { ThrowObjectDisposedException(type); } } [DoesNotReturn] private static void ThrowObjectDisposedException(object instance) { throw new ObjectDisposedException(instance?.GetType().FullName); } [DoesNotReturn] private static void ThrowObjectDisposedException(Type type) { throw new ObjectDisposedException(type?.FullName); } } } 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 { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } [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 { public interface ISystemClock { DateTimeOffset UtcNow { get; } } public class SystemClock : ISystemClock { public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; } } namespace Microsoft.Extensions.Caching.Hybrid { public abstract class HybridCache { private static class WrappedCallbackCache<T> { public static readonly Func<Func<CancellationToken, ValueTask<T>>, CancellationToken, ValueTask<T>> Instance = (Func<CancellationToken, ValueTask<T>> callback, CancellationToken ct) => callback(ct); } public abstract ValueTask<T> GetOrCreateAsync<TState, T>(string key, TState state, Func<TState, CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default(CancellationToken)); public ValueTask<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOrCreateAsync<Func<CancellationToken, ValueTask<T>>, T>(key, factory, WrappedCallbackCache<T>.Instance, options, tags, cancellationToken); } public abstract ValueTask SetAsync<T>(string key, T value, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default(CancellationToken)); public abstract ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default(CancellationToken)); public virtual ValueTask RemoveAsync(IEnumerable<string> keys, CancellationToken cancellationToken = default(CancellationToken)) { if (keys != null) { if (keys is ICollection<string> collection) { int count = collection.Count; if (count == 0) { goto IL_001d; } if (count == 1) { return RemoveAsync(keys.First(), cancellationToken); } } return ForEachAsync(this, keys, cancellationToken); } goto IL_001d; IL_001d: return default(ValueTask); static async ValueTask ForEachAsync(HybridCache @this, IEnumerable<string> keys, CancellationToken cancellationToken) { foreach (string key in keys) { await @this.RemoveAsync(key, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } } public virtual ValueTask RemoveByTagAsync(IEnumerable<string> tags, CancellationToken cancellationToken = default(CancellationToken)) { if (tags != null) { if (tags is ICollection<string> collection) { int count = collection.Count; if (count == 0) { goto IL_001d; } if (count == 1) { return RemoveByTagAsync(tags.Single(), cancellationToken); } } return ForEachAsync(this, tags, cancellationToken); } goto IL_001d; IL_001d: return default(ValueTask); static async ValueTask ForEachAsync(HybridCache @this, IEnumerable<string> keys, CancellationToken cancellationToken) { foreach (string key in keys) { await @this.RemoveByTagAsync(key, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } } public abstract ValueTask RemoveByTagAsync(string tag, CancellationToken cancellationToken = default(CancellationToken)); } [Flags] public enum HybridCacheEntryFlags { None = 0, DisableLocalCacheRead = 1, DisableLocalCacheWrite = 2, DisableLocalCache = 3, DisableDistributedCacheRead = 4, DisableDistributedCacheWrite = 8, DisableDistributedCache = 0xC, DisableUnderlyingData = 0x10, DisableCompression = 0x20 } public sealed class HybridCacheEntryOptions { private DistributedCacheEntryOptions _dc; public TimeSpan? Expiration { get; init; } public TimeSpan? LocalCacheExpiration { get; init; } public HybridCacheEntryFlags? Flags { get; init; } internal DistributedCacheEntryOptions ToDistributedCacheEntryOptions() { object obj; if (Expiration.HasValue) { obj = _dc; if (obj == null) { DistributedCacheEntryOptions obj2 = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = Expiration }; DistributedCacheEntryOptions result = obj2; _dc = obj2; return result; } } else { obj = null; } return (DistributedCacheEntryOptions)obj; } } public interface IHybridCacheSerializer<T> { T Deserialize(ReadOnlySequence<byte> source); void Serialize(T value, IBufferWriter<byte> target); } public interface IHybridCacheSerializerFactory { bool TryCreateSerializer<T>([NotNullWhen(true)] out IHybridCacheSerializer<T>? serializer); } } 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 bool _absoluteExpirationSet; private TimeSpan _absoluteExpirationRelativeToNow; private bool _absoluteExpirationRelativeToNowSet; private TimeSpan _slidingExpiration; private bool _slidingExpirationSet; private bool _frozen; public DateTimeOffset? AbsoluteExpiration { get { if (!_absoluteExpirationSet) { return null; } return _absoluteExpiration; } set { Set(ref _absoluteExpiration, ref _absoluteExpirationSet, in value); } } public TimeSpan? AbsoluteExpirationRelativeToNow { get { if (!_absoluteExpirationRelativeToNowSet) { return null; } return _absoluteExpirationRelativeToNow; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("AbsoluteExpirationRelativeToNow", value, "The relative expiration value must be positive."); } Set(ref _absoluteExpirationRelativeToNow, ref _absoluteExpirationRelativeToNowSet, in value); } } public TimeSpan? SlidingExpiration { get { if (!_slidingExpirationSet) { return null; } return _slidingExpiration; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException("SlidingExpiration", value, "The sliding expiration value must be positive."); } Set(ref _slidingExpiration, ref _slidingExpirationSet, in value); } } internal DistributedCacheEntryOptions Freeze() { _frozen = true; return this; } private void Set<T>(ref T field, ref bool isSet, in T? value) where T : struct { if (_frozen) { ThrowFrozen(); } field = value.GetValueOrDefault(); isSet = value.HasValue; static void ThrowFrozen() { throw new InvalidOperationException("This instance has been frozen and cannot be mutated"); } } } public static class DistributedCacheExtensions { private static readonly DistributedCacheEntryOptions DefaultOptions = new DistributedCacheEntryOptions().Freeze(); public static void Set(this IDistributedCache cache, string key, byte[] value) { ExceptionPolyfills.ThrowIfNull(key, "key"); ExceptionPolyfills.ThrowIfNull(value, "value"); cache.Set(key, value, DefaultOptions); } public static Task SetAsync(this IDistributedCache cache, string key, byte[] value, CancellationToken token = default(CancellationToken)) { ExceptionPolyfills.ThrowIfNull(key, "key"); ExceptionPolyfills.ThrowIfNull(value, "value"); return cache.SetAsync(key, value, DefaultOptions, token); } public static void SetString(this IDistributedCache cache, string key, string value) { cache.SetString(key, value, DefaultOptions); } public static void SetString(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options) { ExceptionPolyfills.ThrowIfNull(key, "key"); ExceptionPolyfills.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, DefaultOptions, token); } public static Task SetStringAsync(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) { ExceptionPolyfills.ThrowIfNull(key, "key"); ExceptionPolyfills.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 IBufferDistributedCache : IDistributedCache { bool TryGet(string key, IBufferWriter<byte> destination); ValueTask<bool> TryGetAsync(string key, IBufferWriter<byte> destination, CancellationToken token = default(CancellationToken)); void Set(string key, ReadOnlySequence<byte> value, DistributedCacheEntryOptions options); ValueTask SetAsync(string key, ReadOnlySequence<byte> value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)); } 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) { ExceptionPolyfills.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) { return entry.RegisterPostEvictionCallback(callback, null); } public static ICacheEntry RegisterPostEvictionCallback(this ICacheEntry entry, PostEvictionDelegate callback, object? state) { ExceptionPolyfills.ThrowIfNull(callback, "callback"); 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) { ExceptionPolyfills.ThrowIfNull(options, "options"); entry.AbsoluteExpiration = options.AbsoluteExpiration; entry.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow; entry.SlidingExpiration = options.SlidingExpiration; entry.Priority = options.Priority; entry.Size = options.Size; List<IChangeToken> expirationTokensDirect = options.ExpirationTokensDirect; if (expirationTokensDirect != null) { foreach (IChangeToken item in expirationTokensDirect) { entry.AddExpirationToken(item); } } List<PostEvictionCallbackRegistration> postEvictionCallbacksDirect = options.PostEvictionCallbacksDirect; if (postEvictionCallbacksDirect != null) { for (int i = 0; i < postEvictionCallbacksDirect.Count; i++) { PostEvictionCallbackRegistration postEvictionCallbackRegistration = postEvictionCallbacksDirect[i]; if (postEvictionCallbackRegistration.EvictionCallback == null) { ThrowNullCallback(i, "options"); } entry.PostEvictionCallbacks.Add(postEvictionCallbackRegistration); } } return entry; } [DoesNotReturn] private static void ThrowNullCallback(int index, string paramName) { throw new ArgumentException($"MemoryCacheEntryOptions.PostEvictionCallbacks contains a PostEvictionCallbackRegistration with a null EvictionCallback at index {index}.", 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) { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(callback, "callback"); return options.RegisterPostEvictionCallback(callback, null); } public static MemoryCacheEntryOptions RegisterPostEvictionCallback(this MemoryCacheEntryOptions options, PostEvictionDelegate callback, object? state) { ExceptionPolyfills.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; private List<IChangeToken> _expirationTokens; private List<PostEvictionCallbackRegistration> _postEvictionCallbacks; 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 => _expirationTokens ?? (_expirationTokens = new List<IChangeToken>()); internal List<IChangeToken>? ExpirationTokensDirect => _expirationTokens; public IList<PostEvictionCallbackRegistration> PostEvictionCallbacks => _postEvictionCallbacks ?? (_postEvictionCallbacks = new List<PostEvictionCallbackRegistration>()); internal List<PostEvictionCallbackRegistration>? PostEvictionCallbacksDirect => _postEvictionCallbacks; 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) { cache.TryGetValue(key, out object value); if (value != null) { return (TItem)value; } return 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) { ICacheEntry cacheEntry = cache.CreateEntry(key); cacheEntry.Value = value; cacheEntry.Dispose(); 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) { return cache.GetOrCreate(key, factory, null); } public static TItem? GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory, MemoryCacheEntryOptions? createOptions) { if (!cache.TryGetValue(key, out object value)) { using ICacheEntry cacheEntry = cache.CreateEntry(key); if (createOptions != null) { cacheEntry.SetOptions(createOptions); } value = (cacheEntry.Value = factory(cacheEntry)); } return (TItem)value; } public static Task<TItem?> GetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory) { return cache.GetOrCreateAsync(key, factory, null); } public static async Task<TItem?> GetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory, MemoryCacheEntryOptions? createOptions) { if (!cache.TryGetValue(key, out object value)) { using ICacheEntry entry = cache.CreateEntry(key); if (createOptions != null) { entry.SetOptions(createOptions); } 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); }
BepInEx/core/Microsoft.Extensions.DependencyInjection.Abstractions.dll
Decompiled a month 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.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; 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.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: AssemblyMetadata("IsAotCompatible", "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("10.0.125.57005")] [assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")] [assembly: AssemblyVersion("10.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; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace FxResources.Microsoft.Extensions.DependencyInjection.Abstractions { 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 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"); 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; } } internal static class ExceptionPolyfills { [SpecialName] public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B { [SpecialName] public static class <M>$96F0261AC622664B8B003966835C0332 { } [ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")] public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { throw null; } } [SpecialName] public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9 { [SpecialName] public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC { } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { throw null; } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { throw null; } } public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { ThrowArgumentNullException(paramName); } } [DoesNotReturn] private static void ThrowArgumentNullException(string paramName) { throw new ArgumentNullException(paramName); } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { if (condition) { ThrowObjectDisposedException(instance); } } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { if (condition) { ThrowObjectDisposedException(type); } } [DoesNotReturn] private static void ThrowObjectDisposedException(object instance) { throw new ObjectDisposedException(instance?.GetType().FullName); } [DoesNotReturn] private static void ThrowObjectDisposedException(Type type) { throw new ObjectDisposedException(type?.FullName); } } } 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.Class, Inherited = false)] internal sealed class CompilerLoweringPreserveAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } } namespace System.Diagnostics.CodeAnalysis { [CompilerLoweringPreserve] [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, NonPublicConstructorsWithInherited = 0x4004, NonPublicMethodsWithInherited = 0x8010, NonPublicFieldsWithInherited = 0x10040, NonPublicNestedTypesWithInherited = 0x20100, NonPublicPropertiesWithInherited = 0x40400, NonPublicEventsWithInherited = 0x81000, PublicConstructorsWithInherited = 0x100003, PublicNestedTypesWithInherited = 0x200080, AllConstructors = 0x104007, AllMethods = 0x8018, AllFields = 0x10060, AllNestedTypes = 0x220180, AllProperties = 0x40600, AllEvents = 0x81800, [EditorBrowsable(EditorBrowsableState.Never)] All = -1 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public bool ExcludeStatics { get; set; } public string Message { get; } public string? Url { get; set; } public RequiresDynamicCodeAttribute(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.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 Microsoft.Extensions.Internal { internal static class ParameterDefaultValue { public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue) { bool tryToGetDefaultValue; bool num = CheckHasDefaultValue(parameter, out tryToGetDefaultValue); defaultValue = null; if (num) { if (tryToGetDefaultValue) { defaultValue = parameter.DefaultValue; } bool flag = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>); if (defaultValue == null && parameter.ParameterType.IsValueType && !flag) { defaultValue = CreateValueType(parameter.ParameterType); } if (defaultValue != null && flag) { Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType != null && underlyingType.IsEnum) { defaultValue = Enum.ToObject(underlyingType, defaultValue); } } } return num; [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 ref struct ConstructorMatcher { private readonly ConstructorInfoEx _constructor; private readonly object[] _parameterValues; public ConstructorInfoEx ConstructorInfo => _constructor; public ConstructorMatcher(ConstructorInfoEx constructor, object[] parameterValues) { _constructor = constructor; _parameterValues = parameterValues; } 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; } } try { return _constructor.Info.Invoke(_parameterValues); } catch (TargetInvocationException ex) when (ex.InnerException != null) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } 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 = new Func<IServiceProvider, Type, Type, bool, object, object>(GetService).Method; public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); if (instanceType.IsAbstract) { throw new InvalidOperationException(System.SR.CannotCreateAbstractClasses); } ConstructorInfoEx[] array = CreateConstructorInfoExs(instanceType); object[] ctorArgs2 = null; object[] array2 = null; ConstructorMatcher constructorMatcher = default(ConstructorMatcher); IServiceProviderIsService service = provider.GetService<IServiceProviderIsService>(); ConstructorInfoEx constructorInfoEx; if (service != null) { for (int i = 0; i < array.Length; i++) { constructorInfoEx = array[i]; if (!constructorInfoEx.IsPreferred) { continue; } for (int j = i + 1; j < array.Length; j++) { if (array[j].IsPreferred) { ThrowMultipleCtorsMarkedWithAttributeException(); } } InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length); constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2); if (constructorMatcher.Match(parameters, service) == -1) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } return constructorMatcher.CreateInstance(provider); } int num = -1; ConstructorMatcher constructorMatcher2 = default(ConstructorMatcher); bool flag = false; for (int k = 0; k < array.Length; k++) { constructorInfoEx = array[k]; InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length); constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2); int num2 = constructorMatcher.Match(parameters, service); if (num < num2) { num = num2; if (k == array.Length - 1) { array2 = ctorArgs2; } else { array2 = new object[num2]; ctorArgs2.CopyTo(array2, 0); } constructorMatcher2 = new ConstructorMatcher(constructorMatcher.ConstructorInfo, array2); flag = false; } else if (num == num2) { flag = true; } } if (num != -1) { if (flag) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFoundWithBestLength, instanceType, num)); } return constructorMatcher2.CreateInstance(provider); } } Type[] array3; if (parameters.Length == 0) { array3 = Type.EmptyTypes; } else { array3 = new Type[parameters.Length]; for (int l = 0; l < array3.Length; l++) { array3[l] = parameters[l]?.GetType(); } } FindApplicableConstructor(instanceType, array3, array, out var matchingConstructor, out var matchingParameterMap); constructorInfoEx = FindConstructorEx(matchingConstructor, array); InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length); constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2); constructorMatcher.MapParameters(matchingParameterMap, parameters); return constructorMatcher.CreateInstance(provider); static void InitializeCtorArgValues(ref object[] ctorArgs, int length) { if (ctorArgs != null && ctorArgs.Length == length) { Array.Clear(ctorArgs, 0, length); } else { ctorArgs = new object[length]; } } } 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); return Expression.Lambda<ObjectFactory>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }).Compile(); } 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); return Expression.Lambda<ObjectFactory<T>>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }).Compile(); } private static void CreateFactoryInternal([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ParameterExpression provider, out ParameterExpression argumentArray, out Expression factoryExpressionBody) { FindApplicableConstructor(instanceType, argumentTypes, null, 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 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, typeof(object)) }; 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)); } private static ObjectFactory CreateFactoryReflection([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes) { FindApplicableConstructor(instanceType, argumentTypes, null, 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].GetValueOrDefault(-1), fromKeyedServicesAttribute?.Key); } return array; } } private static void FindApplicableConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, ConstructorInfoEx[] constructors, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap) { if (!TryFindPreferredConstructor(instanceType, argumentTypes, constructors, 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 ConstructorInfoEx FindConstructorEx(ConstructorInfo constructorInfo, ConstructorInfoEx[] constructorExs) { for (int i = 0; i < constructorExs.Length; i++) { if ((object)constructorExs[i].Info == constructorInfo) { return constructorExs[i]; } } return null; } 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, ConstructorInfoEx[] constructors, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap) { bool flag = false; matchingConstructor = null; parameterMap = null; if (constructors == null) { constructors = CreateConstructorInfoExs(instanceType); } ConstructorInfoEx[] array = constructors; foreach (ConstructorInfoEx constructorInfoEx in array) { if (constructorInfoEx.IsPreferred) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (!TryCreateParameterMap(constructorInfoEx.Info.GetParameters(), argumentTypes, out var parameterMap2)) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } matchingConstructor = constructorInfoEx.Info; 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) { ExceptionPolyfills.ThrowIfNull(serviceProvider, "serviceProvider"); 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) { ExceptionPolyfills.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) { ExceptionPolyfills.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 ServiceKeyLookupMode LookupMode { get; } public FromKeyedServicesAttribute(object? key) { Key = key; LookupMode = ((key == null) ? ServiceKeyLookupMode.NullKey : ServiceKeyLookupMode.ExplicitKey); } public FromKeyedServicesAttribute() { Key = null; LookupMode = ServiceKeyLookupMode.InheritKey; } } 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<out 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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddTransient(serviceType, serviceType); } public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService)); } public static IServiceCollection AddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddScoped(serviceType, serviceType); } public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService)); } public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddSingleton(serviceType, serviceType); } public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService)); } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, object implementationInstance) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, object implementationInstance) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(instance, "instance"); _implementationInstance = instance; } public ServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime) : this(serviceType, (object)null, lifetime) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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) { MethodInfo method = KeyedImplementationFactory.Method; string text2 = method.DeclaringType?.FullName; string name = method.Name; return text + "KeyedImplementationFactory: " + text2 + "." + name; } return text + string.Format("{0}: {1}", "KeyedImplementationInstance", KeyedImplementationInstance); } if (ImplementationType != null) { return text + string.Format("{0}: {1}", "ImplementationType", ImplementationType); } if (ImplementationFactory != null) { MethodInfo method2 = ImplementationFactory.Method; string text3 = method2.DeclaringType?.FullName; string name2 = method2.Name; return text + "ImplementationFactory: " + text3 + "." + name2; } 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) { return ImplementationFactory.GetType().GenericTypeArguments[1]; } } else { if (KeyedImplementationType != null) { return KeyedImplementationType; } if (KeyedImplementationInstance != null) { return KeyedImplementationInstance.GetType(); } if (KeyedImplementationFactory != null) { return KeyedImplementationFactory.GetType().GenericTypeArguments[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) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type serviceType, Func<IServiceProvider, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(TService implementationInstance) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return Singleton(typeof(TService), implementationInstance); } public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, TService implementationInstance) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return KeyedSingleton(typeof(TService), serviceKey, implementationInstance); } public static ServiceDescriptor Singleton(Type serviceType, object implementationInstance) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, implementationInstance); } public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, object implementationInstance) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.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 ServiceKeyLookupMode { InheritKey, NullKey, ExplicitKey } public enum ServiceLifetime { Singleton, Scoped, Transient } public static class ServiceProviderKeyedServiceExtensions { public static T? GetKeyedService<T>(this IServiceProvider provider, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return (T)keyedServiceProvider.GetKeyedService(typeof(T), serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static object? GetKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetKeyedService(serviceType, serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static object GetRequiredKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey); } public static IEnumerable<T> GetKeyedServices<T>(this IServiceProvider provider, object? serviceKey) { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); return (T)provider.GetService(typeof(T)); } public static object GetRequiredService(this IServiceProvider provider, Type serviceType) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); if (provider is ISupportRequiredService supportRequiredService) { return supportRequiredService.GetRequiredService(serviceType); } return provider.GetService(serviceType) ?? throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType)); } public static T GetRequiredService<T>(this IServiceProvider provider) where T : notnull { ExceptionPolyfills.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredService(typeof(T)); } public static IEnumerable<T> GetServices<T>(this IServiceProvider provider) { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor"); collection.Add(descriptor); return collection; } public static IServiceCollection Add(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.Add(descriptor); } return collection; } public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.TryAdd(descriptor); } } public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.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 { ExceptionPolyfills.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 { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TImplementation)); } public static void TryAddSingleton<TService>(this IServiceCollection collection, TService instance) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { services.TryAddEnumerable(descriptor); } } public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.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(th
BepInEx/core/Microsoft.Extensions.Logging.Abstractions.dll
Decompiled a month 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: AssemblyMetadata("IsAotCompatible", "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("10.0.125.57005")] [assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("10.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; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace FxResources.Microsoft.Extensions.Logging.Abstractions { 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 UnexpectedNumberOfNamedParameters => GetResourceString("UnexpectedNumberOfNamedParameters"); 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; } } internal static class ExceptionPolyfills { [SpecialName] public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B { [SpecialName] public static class <M>$96F0261AC622664B8B003966835C0332 { } [ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")] public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { throw null; } } [SpecialName] public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9 { [SpecialName] public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC { } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { throw null; } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { throw null; } } public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { ThrowArgumentNullException(paramName); } } [DoesNotReturn] private static void ThrowArgumentNullException(string paramName) { throw new ArgumentNullException(paramName); } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { if (condition) { ThrowObjectDisposedException(instance); } } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { if (condition) { ThrowObjectDisposedException(type); } } [DoesNotReturn] private static void ThrowObjectDisposedException(object instance) { throw new ObjectDisposedException(instance?.GetType().FullName); } [DoesNotReturn] private static void ThrowObjectDisposedException(Type type) { throw new ObjectDisposedException(type?.FullName); } } } 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.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.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 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 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); return ProcessType(ref builder, type, in options) ?? 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 struct FormattedLogValues : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>> { [CompilerGenerated] private sealed class <GetEnumerator>d__15 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public FormattedLogValues <>4__this; private int <i>5__2; KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__15(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <i>5__2 = 0; break; case 1: { <>1__state = -1; int num = <i>5__2 + 1; <i>5__2 = num; break; } } if (<i>5__2 < <>4__this.Count) { <>2__current = <>4__this[<i>5__2]; <>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(); } } 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; private string _cachedToString; 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; _cachedToString = null; } [IteratorStateMachine(typeof(<GetEnumerator>d__15))] public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__15(0) { <>4__this = this }; } public override string ToString() { if (_formatter == null) { return _originalMessage; } return _cachedToString ?? (_cachedToString = _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) { ExceptionPolyfills.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) { ExceptionPolyfills.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) { ExceptionPolyfills.ThrowIfNull(factory, "factory"); return new Logger<T>(factory); } public static ILogger CreateLogger(this ILoggerFactory factory, Type type) { ExceptionPolyfills.ThrowIfNull(factory, "factory"); ExceptionPolyfills.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>> { [CompilerGenerated] private sealed class <GetEnumerator>d__7 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues <>4__this; KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__7(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>2__current = <>4__this[0]; <>1__state = 1; return true; case 1: <>1__state = -1; return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } public static 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; } [IteratorStateMachine(typeof(<GetEnumerator>d__7))] public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__7(0) { <>4__this = this }; } 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>> { [CompilerGenerated] private sealed class <GetEnumerator>d__8 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues<T0> <>4__this; private int <i>5__2; KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__8(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <i>5__2 = 0; break; case 1: { <>1__state = -1; int num = <i>5__2 + 1; <i>5__2 = num; break; } } if (<i>5__2 < <>4__this.Count) { <>2__current = <>4__this[<i>5__2]; <>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(); } } 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; } [IteratorStateMachine(typeof(LogValues<>.<GetEnumerator>d__8))] public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__8(0) { <>4__this = this }; } 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>> { [CompilerGenerated] private sealed class <GetEnumerator>d__9 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues<T0, T1> <>4__this; private int <i>5__2; KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__9(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <i>5__2 = 0; break; case 1: { <>1__state = -1; int num = <i>5__2 + 1; <i>5__2 = num; break; } } if (<i>5__2 < <>4__this.Count) { <>2__current = <>4__this[<i>5__2]; <>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(); } } 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; } [IteratorStateMachine(typeof(LogValues<, >.<GetEnumerator>d__9))] public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__9(0) { <>4__this = this }; } 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>> { [CompilerGenerated] private sealed class <GetEnumerator>d__11 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues<T0, T1, T2> <>4__this; private int <i>5__2; KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__11(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <i>5__2 = 0; break; case 1: { <>1__state = -1; int num = <i>5__2 + 1; <i>5__2 = num; break; } } if (<i>5__2 < <>4__this.Count) { <>2__current = <>4__this[<i>5__2]; <>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(); } } 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); } [IteratorStateMachine(typeof(LogValues<, , >.<GetEnumerator>d__11))] public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__11(0) { <>4__this = this }; } 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>> { [CompilerGenerated] private sealed class <GetEnumerator>d__13 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues<T0, T1, T2, T3> <>4__this; private int <i>5__2; KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__13(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <i>5__2 = 0; break; case 1: { <>1__state = -1; int num = <i>5__2 + 1; <i>5__2 = num; break; } } if (<i>5__2 < <>4__this.Count) { <>2__current = <>4__this[<i>5__2]; <>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(); } } 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()); } [IteratorStateMachine(typeof(LogValues<, , , >.<GetEnumerator>d__13))] public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__13(0) { <>4__this = this }; } 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>> { [CompilerGenerated] private sealed class <GetEnumerator>d__14 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues<T0, T1, T2, T3, T4> <>4__this; private int <i>5__2; KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__14(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <i>5__2 = 0; break; case 1: { <>1__state = -1; int num = <i>5__2 + 1; <i>5__2 = num; break; } } if (<i>5__2 < <>4__this.Count) { <>2__current = <>4__this[<i>5__2]; <>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(); } } 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()); } [IteratorStateMachine(typeof(LogValues<, , , , >.<GetEnumerator>d__14))] public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__14(0) { <>4__this = this }; } 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>> { [CompilerGenerated] private sealed class <GetEnumerator>d__15 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues<T0, T1, T2, T3, T4, T5> <>4__this; private int <i>5__2; KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__15(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <i>5__2 = 0; break; case 1: { <>1__state = -1; int num = <i>5__2 + 1; <i>5__2 = num; break; } } if (<i>5__2 < <>4__this.Count) { <>2__current = <>4__this[<i>5__2]; <>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(); } } 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()); } [IteratorStateMachine(typeof(LogValues<, , , , , >.<GetEnumerator>d__15))] public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <GetEnumerator>d__15(0) { <>4__this = this }; } 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) { ExceptionPolyfills.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 readonly List<string> _valueNames = new List<string>(); private readonly string _format; public string OriginalFormat { get; } public List<string> ValueNames => _valueNames; public LogValuesFormatter(string format) { ExceptionPolyfills.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 = format.AsSpan(num2, num3 - num2).IndexOfAny(',', ':'); num4 = ((num4 < 0) ? num3 : (num4 + num2)); valueStringBuilder.Append(format.AsSpan(num, num2 - num + 1)); valueStringBuilder.Append(_valueNames.Count.ToString(CultureInfo.InvariantCulture)); _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; } 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 is IFormattable formattable) ? formattable.ToString(null, CultureInfo.InvariantCulture) : ((item != null) ? item.ToString() : "(null)")); flag = false; } stringValue = valueStringBuilder.ToString(); return true; } stringValue = null; return false; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ProviderAliasAttribute : Attribute { public string Alias { get; } public ProviderAliasAttribute(string alias) { Alias = alias; } } 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) { object obj = global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6; if (obj == null) { obj = new int[6] { 5, 4, 3, 2, 1, 0 }; global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6 = (int[])obj; } ReadOnlySpan<LogLevel> readOnlySpan = new ReadOnlySpan<LogLevel>((LogLevel[]?)obj); 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 abstract class BufferedLogRecord { public abstract DateTimeOffset Timestamp { get; } public abstract LogLevel LogLevel { get; } public abstract EventId EventId { get; } public virtual string? Exception => null; public virtual ActivitySpanId? ActivitySpanId => null; public virtual ActivityTraceId? ActivityTraceId => null; public virtual int? ManagedThreadId => null; public virtual string? FormattedMessage => null; public virtual string? MessageTemplate => null; public virtual IReadOnlyList<KeyValuePair<string, object?>> Attributes => Array.Empty<KeyValuePair<string, object>>(); } public interface IBufferedLogger { void LogRecords(IEnumerable<BufferedLogRecord> records); } 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 sealed 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 sealed 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; } } }
BepInEx/core/Microsoft.Extensions.Primitives.dll
Decompiled a month 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: AssemblyMetadata("IsAotCompatible", "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("10.0.125.57005")] [assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Primitives")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("10.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.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; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace FxResources.Microsoft.Extensions.Primitives { 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 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"); 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; } } internal static class ExceptionPolyfills { [SpecialName] public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B { [SpecialName] public static class <M>$96F0261AC622664B8B003966835C0332 { } [ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")] public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { throw null; } } [SpecialName] public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9 { [SpecialName] public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC { } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { throw null; } [ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { throw null; } } public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { ThrowArgumentNullException(paramName); } } [DoesNotReturn] private static void ThrowArgumentNullException(string paramName) { throw new ArgumentNullException(paramName); } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { if (condition) { ThrowObjectDisposedException(instance); } } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { if (condition) { ThrowObjectDisposedException(type); } } [DoesNotReturn] private static void ThrowObjectDisposedException(object instance) { throw new ObjectDisposedException(instance?.GetType().FullName); } [DoesNotReturn] private static void ThrowObjectDisposedException(Type type) { throw new ObjectDisposedException(type?.FullName); } } } 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