Decompiled source of AuriePack v1.0.1
AuriePack/AurieInstaller/AurieInstaller.dll
Decompiled a year agousing System; 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.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Resources; using System.Windows.Threading; using AurieInstaller.Services; using AurieInstaller.ViewModels.Pages; using AurieInstaller.ViewModels.Windows; using AurieInstaller.Views.Pages; using AurieInstaller.Views.Windows; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel.__Internals; using CommunityToolkit.Mvvm.Input; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Win32; using Wpf.Ui.Appearance; using Wpf.Ui.Common; using Wpf.Ui.Contracts; using Wpf.Ui.Controls; using Wpf.Ui.Services; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: ThemeInfo(/*Could not decode attribute arguments.*/)] [assembly: AssemblyAssociatedContentFile("wpfui-icon.ico")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyCompany("AurieInstaller")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+f65341a37e751bdd428c64e3ea1725d27ffb292a")] [assembly: AssemblyProduct("AurieInstaller")] [assembly: AssemblyTitle("AurieInstaller")] [assembly: TargetPlatform("Windows7.0")] [assembly: SupportedOSPlatform("Windows7.0")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace CommunityToolkit.Mvvm.ComponentModel.__Internals { [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This type is not intended to be used directly by user code")] internal static class __KnownINotifyPropertyChangingArgs { [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangingEventArgs AppVersion = new PropertyChangingEventArgs("AppVersion"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangingEventArgs CurrentTheme = new PropertyChangingEventArgs("CurrentTheme"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangingEventArgs ApplicationTitle = new PropertyChangingEventArgs("ApplicationTitle"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangingEventArgs MenuItems = new PropertyChangingEventArgs("MenuItems"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangingEventArgs FooterMenuItems = new PropertyChangingEventArgs("FooterMenuItems"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangingEventArgs TrayMenuItems = new PropertyChangingEventArgs("TrayMenuItems"); } [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This type is not intended to be used directly by user code")] internal static class __KnownINotifyPropertyChangedArgs { [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangedEventArgs AppVersion = new PropertyChangedEventArgs("AppVersion"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangedEventArgs CurrentTheme = new PropertyChangedEventArgs("CurrentTheme"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangedEventArgs ApplicationTitle = new PropertyChangedEventArgs("ApplicationTitle"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangedEventArgs MenuItems = new PropertyChangedEventArgs("MenuItems"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangedEventArgs FooterMenuItems = new PropertyChangedEventArgs("FooterMenuItems"); [EditorBrowsable(/*Could not decode attribute arguments.*/)] [Obsolete("This field is not intended to be referenced directly by user code")] public static readonly PropertyChangedEventArgs TrayMenuItems = new PropertyChangedEventArgs("TrayMenuItems"); } } namespace XamlGeneratedNamespace { [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] [EditorBrowsable(/*Could not decode attribute arguments.*/)] public sealed class GeneratedInternalTypeHelper : InternalTypeHelper { protected override object CreateInstance(System.Type type, CultureInfo culture) { return Activator.CreateInstance(type, (BindingFlags)564, (Binder)null, (object[])null, culture); } protected override object GetPropertyValue(PropertyInfo propertyInfo, object target, CultureInfo culture) { return propertyInfo.GetValue(target, (BindingFlags)0, (Binder)null, (object[])null, culture); } protected override void SetPropertyValue(PropertyInfo propertyInfo, object target, object value, CultureInfo culture) { propertyInfo.SetValue(target, value, (BindingFlags)0, (Binder)null, (object[])null, culture); } protected override System.Delegate CreateDelegate(System.Type delegateType, object target, string handler) { return (System.Delegate)target.GetType().InvokeMember("_CreateDelegate", (BindingFlags)292, (Binder)null, target, new object[2] { delegateType, handler }, (CultureInfo)null); } protected override void AddEventHandler(EventInfo eventInfo, object target, System.Delegate handler) { eventInfo.AddEventHandler(target, handler); } } } namespace AurieInstaller { public class App : Application { [StructLayout(3)] [CompilerGenerated] private struct <OnExit>d__3 : IAsyncStateMachine { public int <>1__state; public AsyncVoidMethodBuilder <>t__builder; private TaskAwaiter <>u__1; private void MoveNext() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0017: 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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { TaskAwaiter awaiter; if (num != 0) { awaiter = _host.StopAsync(default(CancellationToken)).GetAwaiter(); if (!((TaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncVoidMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<TaskAwaiter, <OnExit>d__3>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(TaskAwaiter); num = (<>1__state = -1); } ((TaskAwaiter)(ref awaiter)).GetResult(); ((System.IDisposable)_host).Dispose(); } catch (System.Exception exception) { <>1__state = -2; ((AsyncVoidMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncVoidMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncVoidMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } private static readonly IHost _host = HostingHostBuilderExtensions.ConfigureAppConfiguration(Host.CreateDefaultBuilder(), (Action<IConfigurationBuilder>)delegate(IConfigurationBuilder c) { FileConfigurationExtensions.SetBasePath(c, Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); }).ConfigureServices((Action<HostBuilderContext, IServiceCollection>)delegate(HostBuilderContext context, IServiceCollection services) { ServiceCollectionHostedServiceExtensions.AddHostedService<ApplicationHostService>(services); ServiceCollectionServiceExtensions.AddSingleton<MainWindow>(services); ServiceCollectionServiceExtensions.AddSingleton<MainWindowViewModel>(services); ServiceCollectionServiceExtensions.AddSingleton<INavigationService, NavigationService>(services); ServiceCollectionServiceExtensions.AddSingleton<ISnackbarService, SnackbarService>(services); ServiceCollectionServiceExtensions.AddSingleton<IContentDialogService, ContentDialogService>(services); ServiceCollectionServiceExtensions.AddSingleton<DashboardPage>(services); ServiceCollectionServiceExtensions.AddSingleton<DashboardViewModel>(services); ServiceCollectionServiceExtensions.AddSingleton<SettingsPage>(services); ServiceCollectionServiceExtensions.AddSingleton<SettingsViewModel>(services); }).Build(); private bool _contentLoaded; public static T GetService<T>() where T : class { return _host.Services.GetService(typeof(T)) as T; } private void OnStartup(object sender, StartupEventArgs e) { HostingAbstractionsHostExtensions.Start(_host); } [AsyncStateMachine(typeof(<OnExit>d__3))] private void OnExit(object sender, ExitEventArgs e) { //IL_0002: 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) <OnExit>d__3 <OnExit>d__ = default(<OnExit>d__3); <OnExit>d__.<>t__builder = AsyncVoidMethodBuilder.Create(); <OnExit>d__.<>1__state = -1; ((AsyncVoidMethodBuilder)(ref <OnExit>d__.<>t__builder)).Start<<OnExit>d__3>(ref <OnExit>d__); } private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] public void InitializeComponent() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown if (!_contentLoaded) { _contentLoaded = true; ((Application)this).DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(OnDispatcherUnhandledException); ((Application)this).Exit += new ExitEventHandler(OnExit); ((Application)this).Startup += new StartupEventHandler(OnStartup); Uri val = new Uri("/AurieInstaller;component/app.xaml", (UriKind)2); Application.LoadComponent((object)this, val); } } [STAThread] [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] public static void Main() { App app = new App(); app.InitializeComponent(); ((Application)app).Run(); } } } namespace AurieInstaller.Views.Windows { public class MainWindow : FluentWindow, IComponentConnector { internal TitleBar TitleBar; internal NavigationView NavigationView; internal BreadcrumbBar BreadcrumbBar; internal AutoSuggestBox AutoSuggestBox; internal SnackbarPresenter SnackbarPresenter; internal ContentPresenter RootContentDialog; private bool _contentLoaded; [field: CompilerGenerated] public MainWindowViewModel ViewModel { [CompilerGenerated] get; } public MainWindow(MainWindowViewModel viewModel, INavigationService navigationService, IServiceProvider serviceProvider, ISnackbarService snackbarService, IContentDialogService contentDialogService) { Watcher.Watch((Window)(object)this, (WindowBackdropType)2, true, false); ViewModel = viewModel; ((FrameworkElement)this).DataContext = this; InitializeComponent(); navigationService.SetNavigationControl((INavigationView)(object)NavigationView); snackbarService.SetSnackbarPresenter(SnackbarPresenter); contentDialogService.SetContentPresenter(RootContentDialog); NavigationView.SetServiceProvider(serviceProvider); } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] public void InitializeComponent() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (!_contentLoaded) { _contentLoaded = true; Uri val = new Uri("/AurieInstaller;component/views/windows/mainwindow.xaml", (UriKind)2); Application.LoadComponent((object)this, val); } } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] [EditorBrowsable(/*Could not decode attribute arguments.*/)] void IComponentConnector.Connect(int connectionId, object target) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown switch (connectionId) { case 1: TitleBar = (TitleBar)target; break; case 2: NavigationView = (NavigationView)target; break; case 3: BreadcrumbBar = (BreadcrumbBar)target; break; case 4: AutoSuggestBox = (AutoSuggestBox)target; break; case 5: SnackbarPresenter = (SnackbarPresenter)target; break; case 6: RootContentDialog = (ContentPresenter)target; break; default: _contentLoaded = true; break; } } } } namespace AurieInstaller.Views.Pages { public class DashboardPage : Page, INavigableView<DashboardViewModel>, IComponentConnector { private bool _contentLoaded; [field: CompilerGenerated] public DashboardViewModel ViewModel { [CompilerGenerated] get; } public DashboardPage(DashboardViewModel viewModel) { ViewModel = viewModel; ((FrameworkElement)this).DataContext = this; InitializeComponent(); } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] public void InitializeComponent() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (!_contentLoaded) { _contentLoaded = true; Uri val = new Uri("/AurieInstaller;component/views/pages/dashboardpage.xaml", (UriKind)2); Application.LoadComponent((object)this, val); } } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] [EditorBrowsable(/*Could not decode attribute arguments.*/)] void IComponentConnector.Connect(int connectionId, object target) { _contentLoaded = true; } } public class SettingsPage : Page, INavigableView<SettingsViewModel>, IComponentConnector { private bool _contentLoaded; [field: CompilerGenerated] public SettingsViewModel ViewModel { [CompilerGenerated] get; } public SettingsPage(SettingsViewModel viewModel) { ViewModel = viewModel; ((FrameworkElement)this).DataContext = this; InitializeComponent(); } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] public void InitializeComponent() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (!_contentLoaded) { _contentLoaded = true; Uri val = new Uri("/AurieInstaller;component/views/pages/settingspage.xaml", (UriKind)2); Application.LoadComponent((object)this, val); } } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "8.0.0.0")] [EditorBrowsable(/*Could not decode attribute arguments.*/)] void IComponentConnector.Connect(int connectionId, object target) { _contentLoaded = true; } } } namespace AurieInstaller.ViewModels.Windows { public class MainWindowViewModel : ObservableObject { [ObservableProperty] private string _applicationTitle = "Aurie Framework Installer"; [ObservableProperty] private ObservableCollection<object> _menuItems; [ObservableProperty] private ObservableCollection<object> _footerMenuItems; [ObservableProperty] private ObservableCollection<MenuItem> _trayMenuItems; [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public string ApplicationTitle { get { return _applicationTitle; } [MemberNotNull("_applicationTitle")] set { if (!EqualityComparer<string>.Default.Equals(_applicationTitle, value)) { ((ObservableObject)this).OnPropertyChanging(__KnownINotifyPropertyChangingArgs.ApplicationTitle); _applicationTitle = value; ((ObservableObject)this).OnPropertyChanged(__KnownINotifyPropertyChangedArgs.ApplicationTitle); } } } [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public ObservableCollection<object> MenuItems { get { return _menuItems; } [MemberNotNull("_menuItems")] set { if (!EqualityComparer<ObservableCollection<object>>.Default.Equals(_menuItems, value)) { ((ObservableObject)this).OnPropertyChanging(__KnownINotifyPropertyChangingArgs.MenuItems); _menuItems = value; ((ObservableObject)this).OnPropertyChanged(__KnownINotifyPropertyChangedArgs.MenuItems); } } } [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public ObservableCollection<object> FooterMenuItems { get { return _footerMenuItems; } [MemberNotNull("_footerMenuItems")] set { if (!EqualityComparer<ObservableCollection<object>>.Default.Equals(_footerMenuItems, value)) { ((ObservableObject)this).OnPropertyChanging(__KnownINotifyPropertyChangingArgs.FooterMenuItems); _footerMenuItems = value; ((ObservableObject)this).OnPropertyChanged(__KnownINotifyPropertyChangedArgs.FooterMenuItems); } } } [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public ObservableCollection<MenuItem> TrayMenuItems { get { return _trayMenuItems; } [MemberNotNull("_trayMenuItems")] set { if (!EqualityComparer<ObservableCollection<MenuItem>>.Default.Equals(_trayMenuItems, value)) { ((ObservableObject)this).OnPropertyChanging(__KnownINotifyPropertyChangingArgs.TrayMenuItems); _trayMenuItems = value; ((ObservableObject)this).OnPropertyChanged(__KnownINotifyPropertyChangedArgs.TrayMenuItems); } } } public MainWindowViewModel() { //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_0022: 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_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown ObservableCollection<object> obj = new ObservableCollection<object>(); ((Collection<object>)(object)obj).Add((object)new NavigationViewItem { Content = "Main", Icon = (IconElement)new SymbolIcon { Symbol = (SymbolRegular)62593 }, TargetPageType = typeof(DashboardPage) }); _menuItems = obj; ObservableCollection<object> obj2 = new ObservableCollection<object>(); ((Collection<object>)(object)obj2).Add((object)new NavigationViewItem { Content = "About", Icon = (IconElement)new SymbolIcon { Symbol = (SymbolRegular)63146 }, TargetPageType = typeof(SettingsPage) }); _footerMenuItems = obj2; ObservableCollection<MenuItem> obj3 = new ObservableCollection<MenuItem>(); ((Collection<MenuItem>)(object)obj3).Add(new MenuItem { Header = "Home", Tag = "tray_home" }); _trayMenuItems = obj3; ((ObservableObject)this)..ctor(); } } } namespace AurieInstaller.ViewModels.Pages { public class DashboardViewModel : ObservableObject { private static readonly string m_IFEOPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options"; [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "8.2.0.0")] private RelayCommand? uninstallButtonCommand; [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "8.2.0.0")] private RelayCommand? installButtonCommand; [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public IRelayCommand UninstallButtonCommand { get { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0023: Expected O, but got Unknown RelayCommand obj = uninstallButtonCommand; if (obj == null) { RelayCommand val = new RelayCommand(new Action(OnUninstallButton)); RelayCommand val2 = val; uninstallButtonCommand = val; obj = val2; } return (IRelayCommand)(object)obj; } } [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public IRelayCommand InstallButtonCommand { get { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0023: Expected O, but got Unknown RelayCommand obj = installButtonCommand; if (obj == null) { RelayCommand val = new RelayCommand(new Action(OnInstallButton)); RelayCommand val2 = val; installButtonCommand = val; obj = val2; } return (IRelayCommand)(object)obj; } } internal static void ThrowError(string Message) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) MessageBox.Show(Message, "Fatal Error", (MessageBoxButton)0, (MessageBoxImage)16); } internal static OpenFileDialog PickGame(string Title, string Filter) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return new OpenFileDialog { Title = Title, Filter = Filter }; } internal static RegistryKey? GetIFEOKey(bool WriteAccess) { return Registry.LocalMachine.OpenSubKey(m_IFEOPath, WriteAccess); } internal static RegistryKey? GetRunnerKey(string RunnerName, bool WriteAccess) { RegistryKey iFEOKey = GetIFEOKey(WriteAccess); try { return (iFEOKey != null) ? iFEOKey.CreateSubKey(RunnerName, true) : null; } finally { ((System.IDisposable)iFEOKey)?.Dispose(); } } internal static List<RegistryKey> GetAurieInstallerKeys() { List<RegistryKey> val = new List<RegistryKey>(); RegistryKey iFEOKey = GetIFEOKey(WriteAccess: false); try { if (iFEOKey == null) { ThrowError("Failed to get runner IFEO key!"); return val; } string[] subKeyNames = iFEOKey.GetSubKeyNames(); foreach (string text in subKeyNames) { RegistryKey val2 = iFEOKey.OpenSubKey(text, false); if (val2 != null && Enumerable.Contains<string>((System.Collections.Generic.IEnumerable<string>)val2.GetValueNames(), "IsAurieInstallerKey")) { val.Add(val2); } } return val; } finally { ((System.IDisposable)iFEOKey)?.Dispose(); } } [RelayCommand] private void OnUninstallButton() { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) OpenFileDialog val = PickGame("Select the game executable...", "PE Files|*.exe|All Files|*.*"); if (!((CommonDialog)val).ShowDialog().GetValueOrDefault()) { return; } string fileName = ((FileDialog)val).FileName; string safeFileName = ((FileDialog)val).SafeFileName; try { RegistryKey runnerKey = GetRunnerKey(safeFileName, WriteAccess: true); try { if (runnerKey == null) { ThrowError("Failed to get runner IFEO key!"); return; } string text = fileName.Replace('\\', '_'); if (!Enumerable.Contains<string>((System.Collections.Generic.IEnumerable<string>)runnerKey.GetValueNames(), "IsAurieInstallerKey")) { MessageBox.Show("The Aurie Framework registry key is corrupt.\nReinstall the framework and try again.", "Key is corrupt.", (MessageBoxButton)0, (MessageBoxImage)16); return; } if (!Enumerable.Contains<string>((System.Collections.Generic.IEnumerable<string>)runnerKey.GetSubKeyNames(), text)) { MessageBox.Show("The Aurie Framework not installed for this executable!", "Framework not installed", (MessageBoxButton)0, (MessageBoxImage)16); return; } runnerKey.DeleteSubKeyTree(text); if (runnerKey.GetSubKeyNames().Length == 0) { RegistryKey iFEOKey = GetIFEOKey(WriteAccess: true); try { if (iFEOKey != null) { iFEOKey.DeleteSubKeyTree(safeFileName); } } finally { ((System.IDisposable)iFEOKey)?.Dispose(); } } } finally { ((System.IDisposable)runnerKey)?.Dispose(); } MessageBox.Show("Aurie Framework was uninstalled successfully.", "Success!", (MessageBoxButton)0, (MessageBoxImage)64); } catch (System.Exception ex) { ThrowError("Failed to access the required registry keys!\n" + ex.Message); } } [RelayCommand] private void OnInstallButton() { //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) OpenFileDialog val = PickGame("Select the game executable...", "PE Files|*.exe|All Files|*.*"); if (!((CommonDialog)val).ShowDialog().GetValueOrDefault()) { return; } string fileName = ((FileDialog)val).FileName; string safeFileName = ((FileDialog)val).SafeFileName; try { RegistryKey runnerKey = GetRunnerKey(safeFileName, WriteAccess: true); try { if (runnerKey == null) { ThrowError("Failed to get runner IFEO key!"); return; } runnerKey.SetValue("IsAurieInstallerKey", (object)1, (RegistryValueKind)4); runnerKey.SetValue("UseFilter", (object)1, (RegistryValueKind)4); string text = fileName.Replace('\\', '_'); if (Enumerable.Contains<string>((System.Collections.Generic.IEnumerable<string>)runnerKey.GetSubKeyNames(), text)) { MessageBox.Show("The Aurie Framework is already installed for this executable!", "Framework already installed", (MessageBoxButton)0, (MessageBoxImage)48); return; } RegistryKey val2 = runnerKey.CreateSubKey(text, true); try { if (val2 == null) { ThrowError("Failed to create runner filter subkey!"); return; } DirectoryInfo parent = Directory.GetParent(fileName); string text2 = ((parent != null) ? ((FileSystemInfo)parent).FullName : null) ?? ""; if (text2.Equals(string.Empty)) { ThrowError("Failed to get game folder!"); return; } text2 = Path.Combine(text2, "mods", "AurieLoader.exe"); val2.SetValue("Debugger", (object)text2); val2.SetValue("FilterFullPath", (object)fileName); } finally { ((System.IDisposable)val2)?.Dispose(); } } finally { ((System.IDisposable)runnerKey)?.Dispose(); } MessageBox.Show("Aurie Framework was installed successfully.", "Success!", (MessageBoxButton)0, (MessageBoxImage)64); } catch (System.Exception ex) { ThrowError("Failed to access the required registry keys!\n" + ex.Message); } } } public class SettingsViewModel : ObservableObject, INavigationAware { private bool _isInitialized; [ObservableProperty] private string _appVersion = string.Empty; [ObservableProperty] private ThemeType _currentTheme; [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "8.2.0.0")] private RelayCommand<string>? changeThemeCommand; [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public string AppVersion { get { return _appVersion; } [MemberNotNull("_appVersion")] set { if (!EqualityComparer<string>.Default.Equals(_appVersion, value)) { ((ObservableObject)this).OnPropertyChanging(__KnownINotifyPropertyChangingArgs.AppVersion); _appVersion = value; ((ObservableObject)this).OnPropertyChanged(__KnownINotifyPropertyChangedArgs.AppVersion); } } } [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public ThemeType CurrentTheme { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return _currentTheme; } set { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (!EqualityComparer<ThemeType>.Default.Equals(_currentTheme, value)) { ((ObservableObject)this).OnPropertyChanging(__KnownINotifyPropertyChangingArgs.CurrentTheme); _currentTheme = value; ((ObservableObject)this).OnPropertyChanged(__KnownINotifyPropertyChangedArgs.CurrentTheme); } } } [GeneratedCode("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "8.2.0.0")] [ExcludeFromCodeCoverage] public IRelayCommand<string> ChangeThemeCommand => (IRelayCommand<string>)(object)(changeThemeCommand ?? (changeThemeCommand = new RelayCommand<string>((Action<string>)OnChangeTheme))); public void OnNavigatedTo() { if (!_isInitialized) { InitializeViewModel(); } } public void OnNavigatedFrom() { } private void InitializeViewModel() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) CurrentTheme = Theme.GetAppTheme(); AppVersion = "AurieInstaller - " + GetAssemblyVersion(); _isInitialized = true; } private static string GetAssemblyVersion() { return ((object)Assembly.GetExecutingAssembly().GetName().Version)?.ToString() ?? string.Empty; } [RelayCommand] private void OnChangeTheme(string parameter) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 if (parameter == "theme_light") { if ((int)CurrentTheme != 2) { Theme.Apply((ThemeType)2, (WindowBackdropType)2, false, false); CurrentTheme = (ThemeType)2; } } else if ((int)CurrentTheme != 1) { Theme.Apply((ThemeType)1, (WindowBackdropType)2, false, false); CurrentTheme = (ThemeType)1; } } } } namespace AurieInstaller.Services { public class ApplicationHostService : IHostedService { [StructLayout(3)] [CompilerGenerated] private struct <HandleActivationAsync>d__4 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public ApplicationHostService <>4__this; private TaskAwaiter <>u__1; private void MoveNext() { //IL_0049: 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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Expected O, but got Unknown int num = <>1__state; ApplicationHostService applicationHostService = <>4__this; try { TaskAwaiter awaiter; if (num != 0) { awaiter = System.Threading.Tasks.Task.CompletedTask.GetAwaiter(); if (!((TaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<TaskAwaiter, <HandleActivationAsync>d__4>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(TaskAwaiter); num = (<>1__state = -1); } ((TaskAwaiter)(ref awaiter)).GetResult(); if (!Enumerable.Any<MainWindow>(Enumerable.OfType<MainWindow>((System.Collections.IEnumerable)Application.Current.Windows))) { MainWindow requiredService = ServiceProviderServiceExtensions.GetRequiredService<MainWindow>(applicationHostService._serviceProvider); ((FrameworkElement)requiredService).Loaded += new RoutedEventHandler(applicationHostService.OnNavigationWindowLoaded); ((Window)requiredService).Show(); } } catch (System.Exception exception) { <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } [StructLayout(3)] [CompilerGenerated] private struct <StartAsync>d__2 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public ApplicationHostService <>4__this; private TaskAwaiter <>u__1; private void MoveNext() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; ApplicationHostService applicationHostService = <>4__this; try { TaskAwaiter awaiter; if (num != 0) { awaiter = applicationHostService.HandleActivationAsync().GetAwaiter(); if (!((TaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<TaskAwaiter, <StartAsync>d__2>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(TaskAwaiter); num = (<>1__state = -1); } ((TaskAwaiter)(ref awaiter)).GetResult(); } catch (System.Exception exception) { <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } [StructLayout(3)] [CompilerGenerated] private struct <StopAsync>d__3 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; private TaskAwaiter <>u__1; private void MoveNext() { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { TaskAwaiter awaiter; if (num != 0) { awaiter = System.Threading.Tasks.Task.CompletedTask.GetAwaiter(); if (!((TaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<TaskAwaiter, <StopAsync>d__3>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(TaskAwaiter); num = (<>1__state = -1); } ((TaskAwaiter)(ref awaiter)).GetResult(); } catch (System.Exception exception) { <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } private readonly IServiceProvider _serviceProvider; public ApplicationHostService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } [AsyncStateMachine(typeof(<StartAsync>d__2))] public System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken) { //IL_0002: 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) <StartAsync>d__2 <StartAsync>d__ = default(<StartAsync>d__2); <StartAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <StartAsync>d__.<>4__this = this; <StartAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <StartAsync>d__.<>t__builder)).Start<<StartAsync>d__2>(ref <StartAsync>d__); return ((AsyncTaskMethodBuilder)(ref <StartAsync>d__.<>t__builder)).Task; } [AsyncStateMachine(typeof(<StopAsync>d__3))] public System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken) { //IL_0002: 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) <StopAsync>d__3 <StopAsync>d__ = default(<StopAsync>d__3); <StopAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <StopAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <StopAsync>d__.<>t__builder)).Start<<StopAsync>d__3>(ref <StopAsync>d__); return ((AsyncTaskMethodBuilder)(ref <StopAsync>d__.<>t__builder)).Task; } [AsyncStateMachine(typeof(<HandleActivationAsync>d__4))] private System.Threading.Tasks.Task HandleActivationAsync() { //IL_0002: 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) <HandleActivationAsync>d__4 <HandleActivationAsync>d__ = default(<HandleActivationAsync>d__4); <HandleActivationAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <HandleActivationAsync>d__.<>4__this = this; <HandleActivationAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <HandleActivationAsync>d__.<>t__builder)).Start<<HandleActivationAsync>d__4>(ref <HandleActivationAsync>d__); return ((AsyncTaskMethodBuilder)(ref <HandleActivationAsync>d__.<>t__builder)).Task; } private void OnNavigationWindowLoaded(object sender, RoutedEventArgs e) { if (sender is MainWindow mainWindow) { mainWindow.NavigationView.Navigate(typeof(DashboardPage), (object)null); } } } } namespace AurieInstaller.Resources { public class Translations { } } namespace AurieInstaller.Models { public class AppConfig { [field: CompilerGenerated] public string ConfigurationsFolder { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string AppPropertiesFileName { [CompilerGenerated] get; [CompilerGenerated] set; } } public struct DataColor { [field: CompilerGenerated] public Brush Color { [CompilerGenerated] get; [CompilerGenerated] set; } } } namespace AurieInstaller.Helpers { internal class EnumToBooleanConverter : IValueConverter { public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) if (!(parameter is string text)) { throw new ArgumentException("ExceptionEnumToBooleanConverterParameterMustBeAnEnumName"); } if (!System.Enum.IsDefined(typeof(ThemeType), value)) { throw new ArgumentException("ExceptionEnumToBooleanConverterValueMustBeAnEnum"); } return System.Enum.Parse(typeof(ThemeType), text).Equals(value); } public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!(parameter is string text)) { throw new ArgumentException("ExceptionEnumToBooleanConverterParameterMustBeAnEnumName"); } return System.Enum.Parse(typeof(ThemeType), text); } } }
AuriePack/AurieInstaller/CommunityToolkit.Mvvm.dll
Decompiled a year 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.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using CommunityToolkit.Mvvm.Collections.Internals; using CommunityToolkit.Mvvm.ComponentModel.__Internals; using CommunityToolkit.Mvvm.Input.Internals; using CommunityToolkit.Mvvm.Messaging; using CommunityToolkit.Mvvm.Messaging.Internals; using CommunityToolkit.Mvvm.Messaging.Messages; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyFileVersion("8.2.1.1")] [assembly: AssemblyInformationalVersion("8.2.1.1+2258fd3103")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyMetadata("CommitHash", "2258fd310359fb7434d2040b34f04366efbacbf8")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("(c) .NET Foundation and Contributors. All rights reserved.")] [assembly: AssemblyDescription("\r\n This package includes a .NET MVVM library with helpers such as:\r\n - ObservableObject: a base class for objects implementing the INotifyPropertyChanged interface.\r\n - ObservableRecipient: a base class for observable objects with support for the IMessenger service.\r\n - ObservableValidator: a base class for objects implementing the INotifyDataErrorInfo interface.\r\n - RelayCommand: a simple delegate command implementing the ICommand interface.\r\n - AsyncRelayCommand: a delegate command supporting asynchronous operations and cancellation.\r\n - WeakReferenceMessenger: a messaging system to exchange messages through different loosely-coupled objects.\r\n - StrongReferenceMessenger: a high-performance messaging system that trades weak references for speed.\r\n - Ioc: a helper class to configure dependency injection service containers.\r\n ")] [assembly: AssemblyProduct(".NET Community Toolkit")] [assembly: AssemblyTitle("CommunityToolkit.Mvvm")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/CommunityToolkit/dotnet")] [assembly: InternalsVisibleTo("CommunityToolkit.Mvvm.Internals.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010041753AF735AE6140C9508567666C51C6AB929806ADB0D210694B30AB142A060237BC741F9682E7D8D4310364B4BBA4EE89CC9D3D5CE7E5583587E8EA44DCA09977996582875E71FB54FA7B170798D853D5D8010B07219633BDB761D01AC924DA44576D6180CDCEAE537973982BB461C541541D58417A3794E34F45E6F2D129E2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.2.0.0")] [assembly: TypeForwardedTo(typeof(IsExternalInit))] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: SkipLocalsInit] 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; } } } [GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.6.128.36433")] [ExcludeFromCodeCoverage] internal static class ThisAssembly { internal const string AssemblyConfiguration = "Release"; internal const string AssemblyFileVersion = "8.2.1.1"; internal const string AssemblyInformationalVersion = "8.2.1.1+2258fd3103"; internal const string AssemblyName = "CommunityToolkit.Mvvm"; internal const string AssemblyTitle = "CommunityToolkit.Mvvm"; internal const string AssemblyVersion = "8.2.0.0"; internal static readonly DateTime GitCommitDate = new DateTime(638241791050000000L, DateTimeKind.Utc); internal const string GitCommitId = "2258fd310359fb7434d2040b34f04366efbacbf8"; internal const bool IsPrerelease = false; internal const bool IsPublicRelease = true; internal const string PublicKey = "002400000480000094000000060200000024000052534131000400000100010041753af735ae6140c9508567666c51c6ab929806adb0d210694b30ab142a060237bc741f9682e7d8d4310364b4bba4ee89cc9d3d5ce7e5583587e8ea44dca09977996582875e71fb54fa7b170798d853d5d8010b07219633bdb761d01ac924da44576d6180cdceae537973982bb461c541541d58417a3794e34f45e6f2d129e2"; internal const string PublicKeyToken = "4aff67a105548ee2"; internal const string RootNamespace = "CommunityToolkit.Mvvm"; } internal static class Configuration { private const string DisableINotifyPropertyChangingSupport = "MVVMTOOLKIT_DISABLE_INOTIFYPROPERTYCHANGING"; public static readonly bool IsINotifyPropertyChangingDisabled = GetConfigurationValue("MVVMTOOLKIT_DISABLE_INOTIFYPROPERTYCHANGING"); private static bool GetConfigurationValue(string propertyName) { if (AppContext.TryGetSwitch(propertyName, out var isEnabled)) { return isEnabled; } return false; } } namespace System { internal sealed class Gen2GcCallback : CriticalFinalizerObject { private readonly Action<object> callback; private GCHandle handle; private Gen2GcCallback(Action<object> callback, object target) { this.callback = callback; handle = GCHandle.Alloc(target, GCHandleType.Weak); } public static void Register(Action<object> callback, object target) { new System.Gen2GcCallback(callback, target); } ~Gen2GcCallback() { object target = handle.Target; if (target != null) { try { callback(target); } catch { } GC.ReRegisterForFinalize(this); } else { handle.Free(); } } } } namespace System.Runtime.CompilerServices { internal sealed class ConditionalWeakTable2<TKey, TValue> where TKey : class where TValue : class? { public ref struct Enumerator { private ConditionalWeakTable2<TKey, TValue> table; private readonly int maxIndexInclusive; private int currentIndex; private TKey? key; private TValue? value; public Enumerator(ConditionalWeakTable2<TKey, TValue> table) { this.table = table; Container container = table.container; if (container == null || container.FirstFreeEntry == 0) { maxIndexInclusive = -1; } else { maxIndexInclusive = container.FirstFreeEntry - 1; } currentIndex = -1; key = null; value = null; } public void Dispose() { Monitor.Exit(table.lockObject); table = null; key = null; value = null; } public bool MoveNext() { Container container = table.container; int num = currentIndex; int num2 = maxIndexInclusive; while (num < num2) { num++; if (container.TryGetEntry(num, out key, out value)) { currentIndex = num; return true; } } currentIndex = num; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TKey GetKey() { return key; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TValue GetValue() { return value; } } private struct Entry { public DependentHandle depHnd; public int HashCode; public int Next; } private sealed class Container { private readonly ConditionalWeakTable2<TKey, TValue> parent; private int[] buckets; private Entry[] entries; private int firstFreeEntry; private bool invalid; private bool finalized; private volatile object? oldKeepAlive; internal bool HasCapacity => firstFreeEntry < entries.Length; internal int FirstFreeEntry => firstFreeEntry; internal Container(ConditionalWeakTable2<TKey, TValue> parent) { buckets = new int[8]; for (int i = 0; i < buckets.Length; i++) { buckets[i] = -1; } entries = new Entry[8]; this.parent = parent; } private Container(ConditionalWeakTable2<TKey, TValue> parent, int[] buckets, Entry[] entries, int firstFreeEntry) { this.parent = parent; this.buckets = buckets; this.entries = entries; this.firstFreeEntry = firstFreeEntry; } internal void CreateEntryNoResize(TKey key, TValue value) { VerifyIntegrity(); invalid = true; int num = RuntimeHelpers.GetHashCode(key) & 0x7FFFFFFF; int num2 = firstFreeEntry++; entries[num2].HashCode = num; entries[num2].depHnd = new DependentHandle(key, value); int num3 = num & (buckets.Length - 1); entries[num2].Next = buckets[num3]; Volatile.Write(ref buckets[num3], num2); invalid = false; } internal bool TryGetValueWorker(TKey key, [MaybeNullWhen(false)] out TValue value) { object value2; int num = FindEntry(key, out value2); value = Unsafe.As<TValue>(value2); return num != -1; } internal int FindEntry(TKey key, out object? value) { int num = RuntimeHelpers.GetHashCode(key) & 0x7FFFFFFF; int num2 = num & (buckets.Length - 1); for (int num3 = Volatile.Read(ref buckets[num2]); num3 != -1; num3 = entries[num3].Next) { if (entries[num3].HashCode == num) { object obj; (obj, value) = entries[num3].depHnd.TargetAndDependent; if (obj == key) { GC.KeepAlive(this); return num3; } } } GC.KeepAlive(this); value = null; return -1; } internal bool TryGetEntry(int index, [NotNullWhen(true)] out TKey? key, [MaybeNullWhen(false)] out TValue value) { if (index < entries.Length) { var (obj, o) = entries[index].depHnd.TargetAndDependent; GC.KeepAlive(this); if (obj != null) { key = Unsafe.As<TKey>(obj); value = Unsafe.As<TValue>(o); return true; } } key = null; value = null; return false; } internal bool Remove(TKey key) { VerifyIntegrity(); object value; int num = FindEntry(key, out value); if (num != -1) { RemoveIndex(num); return true; } return false; } private void RemoveIndex(int entryIndex) { ref Entry reference = ref entries[entryIndex]; Volatile.Write(ref reference.HashCode, -1); reference.depHnd.Target = null; } internal Container Resize() { bool flag = false; int newSize = buckets.Length; for (int i = 0; i < entries.Length; i++) { ref Entry reference = ref entries[i]; if (reference.HashCode == -1) { flag = true; break; } if (reference.depHnd.IsAllocated && reference.depHnd.Target == null) { flag = true; break; } } if (!flag) { newSize = buckets.Length * 2; } return Resize(newSize); } internal Container Resize(int newSize) { int[] array = new int[newSize]; for (int i = 0; i < array.Length; i++) { array[i] = -1; } Entry[] array2 = new Entry[newSize]; int num = 0; for (int j = 0; j < entries.Length; j++) { ref Entry reference = ref entries[j]; int hashCode = reference.HashCode; DependentHandle depHnd = reference.depHnd; if (hashCode != -1 && depHnd.IsAllocated) { if (depHnd.Target != null) { ref Entry reference2 = ref array2[num]; reference2.HashCode = hashCode; reference2.depHnd = depHnd; int num2 = hashCode & (array.Length - 1); reference2.Next = array[num2]; array[num2] = num; num++; } else { Volatile.Write(ref reference.HashCode, -1); } } } Container result = (Container)(oldKeepAlive = new Container(parent, array, array2, num)); GC.KeepAlive(this); return result; } private void VerifyIntegrity() { if (invalid) { Throw(); } static void Throw() { throw new InvalidOperationException("The current collection is in a corrupted state."); } } ~Container() { if (invalid || parent == null) { return; } if (!finalized) { finalized = true; lock (parent.lockObject) { if (parent.container == this) { parent.container = null; } } GC.ReRegisterForFinalize(this); return; } Entry[] array = entries; invalid = true; entries = null; buckets = null; if (array == null) { return; } int i = 0; for (; i < array.Length; i++) { if (oldKeepAlive == null || array[i].HashCode == -1) { array[i].depHnd.Dispose(); } } } } private const int InitialCapacity = 8; private readonly object lockObject; private volatile Container container; public ConditionalWeakTable2() { lockObject = new object(); container = new Container(this); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { return container.TryGetValueWorker(key, out value); } public bool TryAdd(TKey key, TValue value) { lock (lockObject) { if (container.FindEntry(key, out object _) != -1) { return false; } CreateEntry(key, value); return true; } } public bool Remove(TKey key) { lock (lockObject) { return container.Remove(key); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2091", Justification = "ConditionalWeakTable<TKey, TValue> is only referenced to reuse the callback delegate type, but no value is ever created through reflection.")] public TValue GetValue(TKey key, ConditionalWeakTable<TKey, TValue>.CreateValueCallback createValueCallback) { if (!TryGetValue(key, out var value)) { return GetValueLocked(key, createValueCallback); } return value; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2091", Justification = "ConditionalWeakTable<TKey, TValue> is only referenced to reuse the callback delegate type, but no value is ever created through reflection.")] private TValue GetValueLocked(TKey key, ConditionalWeakTable<TKey, TValue>.CreateValueCallback createValueCallback) { TValue val = createValueCallback(key); lock (lockObject) { if (container.TryGetValueWorker(key, out var value)) { return value; } CreateEntry(key, val); return val; } } public Enumerator GetEnumerator() { Monitor.Enter(lockObject); return new Enumerator(this); } private void CreateEntry(TKey key, TValue value) { Container container = this.container; if (!container.HasCapacity) { container = (this.container = container.Resize()); } container.CreateEntryNoResize(key, value); } } } namespace System.Collections.Generic { [DebuggerDisplay("Count = {Count}")] internal class Dictionary2<TKey, TValue> : IDictionary2<TKey, TValue>, IDictionary2<TKey>, IDictionary2 where TKey : IEquatable<TKey> where TValue : class? { public ref struct Enumerator { private readonly Entry[] entries; private int index; private readonly int count; internal Enumerator(Dictionary2<TKey, TValue> dictionary) { entries = dictionary.entries; index = 0; count = dictionary.count; } public bool MoveNext() { while ((uint)index < (uint)count) { if (entries[index++].Next >= -1) { return true; } } index = count + 1; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TKey GetKey() { return entries[index - 1].Key; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TValue GetValue() { return entries[index - 1].Value; } } private struct Entry { public uint HashCode; public int Next; public TKey Key; public TValue? Value; } private const int StartOfFreeList = -3; private int[] buckets; private Entry[] entries; private ulong fastModMultiplier; private int count; private int freeList; private int freeCount; public int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return count - freeCount; } } public TValue this[TKey key] { get { ref TValue reference = ref FindValue(key); if (!Unsafe.IsNullRef(ref reference)) { return reference; } ThrowArgumentExceptionForKeyNotFound(key); return null; } } public Dictionary2() { Initialize(0); } public void Clear() { int num = count; if (num > 0) { Array.Clear(buckets); count = 0; freeList = -1; freeCount = 0; Array.Clear(entries, 0, num); } } public bool ContainsKey(TKey key) { return !Unsafe.IsNullRef(ref FindValue(key)); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { ref TValue reference = ref FindValue(key); if (!Unsafe.IsNullRef(ref reference)) { value = reference; return true; } value = null; return false; } public bool TryRemove(TKey key) { uint hashCode = (uint)key.GetHashCode(); ref int bucket = ref GetBucket(hashCode); Entry[] array = entries; int num = -1; int num2 = bucket - 1; while (num2 >= 0) { ref Entry reference = ref array[num2]; if (reference.HashCode == hashCode && reference.Key.Equals(key)) { if (num < 0) { bucket = reference.Next + 1; } else { array[num].Next = reference.Next; } reference.Next = -3 - freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { reference.Key = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { reference.Value = null; } freeList = num2; freeCount++; return true; } num = num2; num2 = reference.Next; } return false; } public ref TValue? GetOrAddValueRef(TKey key) { Entry[] array = entries; uint hashCode = (uint)key.GetHashCode(); ref int bucket = ref GetBucket(hashCode); int num = bucket - 1; while ((uint)num < (uint)array.Length) { if (array[num].HashCode == hashCode && array[num].Key.Equals(key)) { return ref array[num].Value; } num = array[num].Next; } int num2; if (freeCount > 0) { num2 = freeList; freeList = -3 - array[freeList].Next; freeCount--; } else { int num3 = count; if (num3 == array.Length) { Resize(); bucket = ref GetBucket(hashCode); } num2 = num3; count = num3 + 1; array = entries; } ref Entry reference = ref array[num2]; reference.HashCode = hashCode; reference.Next = bucket - 1; reference.Key = key; reference.Value = null; bucket = num2 + 1; return ref reference.Value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator GetEnumerator() { return new Enumerator(this); } private unsafe ref TValue FindValue(TKey key) { ref Entry reference = ref *(Entry*)null; uint hashCode = (uint)key.GetHashCode(); int bucket = GetBucket(hashCode); Entry[] array = entries; bucket--; while ((uint)bucket < (uint)array.Length) { reference = ref array[bucket]; if (reference.HashCode != hashCode || !reference.Key.Equals(key)) { bucket = reference.Next; continue; } return ref reference.Value; } return ref *(TValue*)null; } [MemberNotNull(new string[] { "buckets", "entries" })] private void Initialize(int capacity) { int prime = HashHelpers.GetPrime(capacity); int[] array = new int[prime]; Entry[] array2 = new Entry[prime]; freeList = -1; fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)prime); buckets = array; entries = array2; } [MethodImpl(MethodImplOptions.NoInlining)] private void Resize() { int num = HashHelpers.ExpandPrime(count); Entry[] array = new Entry[num]; int num2 = count; Array.Copy(entries, array, num2); buckets = new int[num]; fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)num); for (int i = 0; i < num2; i++) { if (array[i].Next >= -1) { ref int bucket = ref GetBucket(array[i].HashCode); array[i].Next = bucket - 1; bucket = i + 1; } } entries = array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ref int GetBucket(uint hashCode) { int[] array = buckets; return ref array[HashHelpers.FastMod(hashCode, (uint)array.Length, fastModMultiplier)]; } private static void ThrowArgumentExceptionForKeyNotFound(TKey key) { throw new ArgumentException($"The target key {key} was not present in the dictionary"); } } internal static class HashHelpers { private const int MaxPrimeArrayLength = 2147483587; private const int HashPrime = 101; private static readonly int[] primes = new int[72] { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; private static bool IsPrime(int candidate) { if (((uint)candidate & (true ? 1u : 0u)) != 0) { int num = (int)Math.Sqrt(candidate); for (int i = 3; i <= num; i += 2) { if (candidate % i == 0) { return false; } } return true; } return candidate == 2; } public static int GetPrime(int min) { int[] array = primes; foreach (int num in array) { if (num >= min) { return num; } } for (int j = min | 1; j < int.MaxValue; j += 2) { if (IsPrime(j) && (j - 1) % 101 != 0) { return j; } } return min; } public static int ExpandPrime(int oldSize) { int num = 2 * oldSize; if ((uint)num > 2147483587u && 2147483587 > oldSize) { return 2147483587; } return GetPrime(num); } public static ulong GetFastModMultiplier(uint divisor) { return ulong.MaxValue / (ulong)divisor + 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint FastMod(uint value, uint divisor, ulong multiplier) { return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32); } } internal interface IDictionary2 { int Count { get; } void Clear(); } internal interface IDictionary2<in TKey, out TValue> : IDictionary2<TKey>, IDictionary2 where TKey : IEquatable<TKey> where TValue : class? { TValue this[TKey key] { get; } } internal interface IDictionary2<in TKey> : IDictionary2 where TKey : IEquatable<TKey> { bool TryRemove(TKey key); } } namespace CommunityToolkit.Mvvm { internal sealed class ArgumentNullException { public static class For<T> { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull([NotNull] T? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string? paramName) { throw new System.ArgumentNullException(paramName); } } } namespace CommunityToolkit.Mvvm.Messaging { public interface IMessenger { bool IsRegistered<TMessage, TToken>(object recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken>; void Register<TRecipient, TMessage, TToken>(TRecipient recipient, TToken token, MessageHandler<TRecipient, TMessage> handler) where TRecipient : class where TMessage : class where TToken : IEquatable<TToken>; void UnregisterAll(object recipient); void UnregisterAll<TToken>(object recipient, TToken token) where TToken : IEquatable<TToken>; void Unregister<TMessage, TToken>(object recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken>; TMessage Send<TMessage, TToken>(TMessage message, TToken token) where TMessage : class where TToken : IEquatable<TToken>; void Cleanup(); void Reset(); } public static class IMessengerExtensions { private static class MethodInfos { public static readonly MethodInfo RegisterIRecipient = new Action<IMessenger, IRecipient<object>, Unit>(Register).Method.GetGenericMethodDefinition(); } private static class DiscoveredRecipients { public static readonly ConditionalWeakTable<Type, Action<IMessenger, object>?> RegistrationMethods = new ConditionalWeakTable<Type, Action<IMessenger, object>>(); } private static class DiscoveredRecipients<TToken> where TToken : IEquatable<TToken> { public static readonly ConditionalWeakTable<Type, Action<IMessenger, object, TToken>> RegistrationMethods = new ConditionalWeakTable<Type, Action<IMessenger, object, TToken>>(); } private sealed class Observable<TMessage> : IObservable<TMessage> where TMessage : class { private sealed class Recipient : IRecipient<TMessage>, IDisposable { private readonly IMessenger messenger; private readonly IObserver<TMessage> observer; public Recipient(IMessenger messenger, IObserver<TMessage> observer) { this.messenger = messenger; this.observer = observer; messenger.Register(this); } public void Receive(TMessage message) { observer.OnNext(message); } public void Dispose() { messenger.Unregister<TMessage>(this); } } private readonly IMessenger messenger; public Observable(IMessenger messenger) { this.messenger = messenger; } public IDisposable Subscribe(IObserver<TMessage> observer) { return new Recipient(messenger, observer); } } private sealed class Observable<TMessage, TToken> : IObservable<TMessage> where TMessage : class where TToken : IEquatable<TToken> { private sealed class Recipient : IRecipient<TMessage>, IDisposable { private readonly IMessenger messenger; private readonly IObserver<TMessage> observer; private readonly TToken token; public Recipient(IMessenger messenger, IObserver<TMessage> observer, TToken token) { this.messenger = messenger; this.observer = observer; this.token = token; messenger.Register(this, token); } public void Receive(TMessage message) { observer.OnNext(message); } public void Dispose() { messenger.Unregister<TMessage, TToken>(this, token); } } private readonly IMessenger messenger; private readonly TToken token; public Observable(IMessenger messenger, TToken token) { this.messenger = messenger; this.token = token; } public IDisposable Subscribe(IObserver<TMessage> observer) { return new Recipient(messenger, observer, token); } } public static bool IsRegistered<TMessage>(this IMessenger messenger, object recipient) where TMessage : class { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); return messenger.IsRegistered<TMessage, Unit>(recipient, default(Unit)); } [RequiresUnreferencedCode("This method requires the generated CommunityToolkit.Mvvm.Messaging.__Internals.__IMessengerExtensions type not to be removed to use the fast path. If this type is removed by the linker, or if the target recipient was created dynamically and was missed by the source generator, a slower fallback path using a compiled LINQ expression will be used. This will have more overhead in the first invocation of this method for any given recipient type.")] public static void RegisterAll(this IMessenger messenger, object recipient) { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); Action<IMessenger, object> value = DiscoveredRecipients.RegistrationMethods.GetValue(recipient.GetType(), [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] (Type t) => LoadRegistrationMethodsForType(t)); if (value != null) { value(messenger, recipient); } else { messenger.RegisterAll(recipient, default(Unit)); } [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] static Action<IMessenger, object>? LoadRegistrationMethodsForType(Type recipientType) { Type type = recipientType.Assembly.GetType("CommunityToolkit.Mvvm.Messaging.__Internals.__IMessengerExtensions"); if ((object)type != null) { MethodInfo method = type.GetMethod("CreateAllMessagesRegistrator", new Type[1] { recipientType }); if ((object)method != null) { return (Action<IMessenger, object>)method.Invoke(null, new object[1]); } } return null; } } [RequiresUnreferencedCode("This method requires the generated CommunityToolkit.Mvvm.Messaging.__Internals.__IMessengerExtensions type not to be removed to use the fast path. If this type is removed by the linker, or if the target recipient was created dynamically and was missed by the source generator, a slower fallback path using a compiled LINQ expression will be used. This will have more overhead in the first invocation of this method for any given recipient type.")] public static void RegisterAll<TToken>(this IMessenger messenger, object recipient, TToken token) where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); DiscoveredRecipients<TToken>.RegistrationMethods.GetValue(recipient.GetType(), [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] (Type t) => LoadRegistrationMethodsForType(t))(messenger, recipient, token); [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] static Action<IMessenger, object, TToken> LoadRegistrationMethodsForType(Type recipientType) { Type type = recipientType.Assembly.GetType("CommunityToolkit.Mvvm.Messaging.__Internals.__IMessengerExtensions"); if ((object)type != null) { MethodInfo method = type.GetMethod("CreateAllMessagesRegistratorWithToken", new Type[1] { recipientType }); if ((object)method != null) { return (Action<IMessenger, object, TToken>)method.MakeGenericMethod(typeof(TToken)).Invoke(null, new object[1]); } } return LoadRegistrationMethodsForTypeFallback(recipientType); } static Action<IMessenger, object, TToken> LoadRegistrationMethodsForTypeFallback(Type recipientType) { MethodInfo[] array = (from interfaceType in recipientType.GetInterfaces() where interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IRecipient<>) let messageType = interfaceType.GenericTypeArguments[0] select MethodInfos.RegisterIRecipient.MakeGenericMethod(messageType, typeof(TToken))).ToArray(); if (array.Length == 0) { return delegate { }; } ParameterExpression arg0 = Expression.Parameter(typeof(IMessenger)); ParameterExpression parameterExpression = Expression.Parameter(typeof(object)); ParameterExpression arg = Expression.Parameter(typeof(TToken)); UnaryExpression inst1 = Expression.Convert(parameterExpression, recipientType); return Expression.Lambda<Action<IMessenger, object, TToken>>(Expression.Block(array.Select((MethodInfo registrationMethod) => Expression.Call(registrationMethod, new Expression[3] { arg0, inst1, arg }))), new ParameterExpression[3] { arg0, parameterExpression, arg }).Compile(); } } public static void Register<TMessage>(this IMessenger messenger, IRecipient<TMessage> recipient) where TMessage : class { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); if (messenger is WeakReferenceMessenger weakReferenceMessenger) { weakReferenceMessenger.Register(recipient, default(Unit)); return; } if (messenger is StrongReferenceMessenger strongReferenceMessenger) { strongReferenceMessenger.Register(recipient, default(Unit)); return; } messenger.Register(recipient, default(Unit), delegate(IRecipient<TMessage> r, TMessage m) { r.Receive(m); }); } public static void Register<TMessage, TToken>(this IMessenger messenger, IRecipient<TMessage> recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); if (messenger is WeakReferenceMessenger weakReferenceMessenger) { weakReferenceMessenger.Register(recipient, token); return; } if (messenger is StrongReferenceMessenger strongReferenceMessenger) { strongReferenceMessenger.Register(recipient, token); return; } messenger.Register(recipient, token, delegate(IRecipient<TMessage> r, TMessage m) { r.Receive(m); }); } public static void Register<TMessage>(this IMessenger messenger, object recipient, MessageHandler<object, TMessage> handler) where TMessage : class { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.ThrowIfNull(handler, "handler"); messenger.Register(recipient, default(Unit), handler); } public static void Register<TRecipient, TMessage>(this IMessenger messenger, TRecipient recipient, MessageHandler<TRecipient, TMessage> handler) where TRecipient : class where TMessage : class { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.ThrowIfNull(handler, "handler"); messenger.Register(recipient, default(Unit), handler); } public static void Register<TMessage, TToken>(this IMessenger messenger, object recipient, TToken token, MessageHandler<object, TMessage> handler) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); ArgumentNullException.ThrowIfNull(handler, "handler"); messenger.Register(recipient, token, handler); } public static void Unregister<TMessage>(this IMessenger messenger, object recipient) where TMessage : class { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(recipient, "recipient"); messenger.Unregister<TMessage, Unit>(recipient, default(Unit)); } public static TMessage Send<TMessage>(this IMessenger messenger) where TMessage : class, new() { ArgumentNullException.ThrowIfNull(messenger, "messenger"); return messenger.Send(new TMessage(), default(Unit)); } public static TMessage Send<TMessage>(this IMessenger messenger, TMessage message) where TMessage : class { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.ThrowIfNull(message, "message"); return messenger.Send(message, default(Unit)); } public static TMessage Send<TMessage, TToken>(this IMessenger messenger, TToken token) where TMessage : class, new() where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); return messenger.Send(new TMessage(), token); } public static IObservable<TMessage> CreateObservable<TMessage>(this IMessenger messenger) where TMessage : class { ArgumentNullException.ThrowIfNull(messenger, "messenger"); return new Observable<TMessage>(messenger); } public static IObservable<TMessage> CreateObservable<TMessage, TToken>(this IMessenger messenger, TToken token) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(messenger, "messenger"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); return new Observable<TMessage, TToken>(messenger, token); } } public interface IRecipient<in TMessage> where TMessage : class { void Receive(TMessage message); } public delegate void MessageHandler<in TRecipient, in TMessage>(TRecipient recipient, TMessage message) where TRecipient : class where TMessage : class; public sealed class StrongReferenceMessenger : IMessenger { private sealed class Mapping : Dictionary2<Recipient, object?>, IMapping, IDictionary2<Recipient>, IDictionary2 { public Type2 TypeArguments { get; } private Mapping(Type messageType) { TypeArguments = new Type2(messageType, typeof(Unit)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Mapping Create<TMessage>() where TMessage : class { return new Mapping(typeof(TMessage)); } } private sealed class Mapping<TToken> : Dictionary2<Recipient, Dictionary2<TToken, object?>>, IMapping, IDictionary2<Recipient>, IDictionary2 where TToken : IEquatable<TToken> { public Type2 TypeArguments { get; } private Mapping(Type messageType) { TypeArguments = new Type2(messageType, typeof(TToken)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Mapping<TToken> Create<TMessage>() where TMessage : class { return new Mapping<TToken>(typeof(TMessage)); } } private interface IMapping : IDictionary2<Recipient>, IDictionary2 { Type2 TypeArguments { get; } } private readonly struct Recipient : IEquatable<Recipient> { public readonly object Target; [MethodImpl(MethodImplOptions.AggressiveInlining)] public Recipient(object target) { Target = target; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Recipient other) { return Target == other.Target; } public override bool Equals(object? obj) { if (obj is Recipient other) { return Equals(other); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return RuntimeHelpers.GetHashCode(Target); } } private readonly Dictionary2<Recipient, HashSet<IMapping>> recipientsMap = new Dictionary2<Recipient, HashSet<IMapping>>(); private readonly Dictionary2<Type2, IMapping> typesMap = new Dictionary2<Type2, IMapping>(); public static StrongReferenceMessenger Default { get; } = new StrongReferenceMessenger(); public bool IsRegistered<TMessage, TToken>(object recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); lock (recipientsMap) { if (typeof(TToken) == typeof(Unit)) { if (!TryGetMapping<TMessage>(out Mapping mapping)) { return false; } Recipient key = new Recipient(recipient); return mapping.ContainsKey(key); } if (!TryGetMapping<TMessage, TToken>(out Mapping<TToken> mapping2)) { return false; } Recipient key2 = new Recipient(recipient); Dictionary2<TToken, object> value; return mapping2.TryGetValue(key2, out value) && value.ContainsKey(token); } } public void Register<TRecipient, TMessage, TToken>(TRecipient recipient, TToken token, MessageHandler<TRecipient, TMessage> handler) where TRecipient : class where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); ArgumentNullException.ThrowIfNull(handler, "handler"); Register<TMessage, TToken>(recipient, token, new MessageHandlerDispatcher.For<TRecipient, TMessage>(handler)); } internal void Register<TMessage, TToken>(IRecipient<TMessage> recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken> { Register<TMessage, TToken>(recipient, token, null); } private void Register<TMessage, TToken>(object recipient, TToken token, MessageHandlerDispatcher? dispatcher) where TMessage : class where TToken : IEquatable<TToken> { lock (recipientsMap) { Recipient key = new Recipient(recipient); IMapping item; if (typeof(TToken) == typeof(Unit)) { Mapping orAddMapping = GetOrAddMapping<TMessage>(); ref object? orAddValueRef = ref orAddMapping.GetOrAddValueRef(key); if (orAddValueRef != null) { ThrowInvalidOperationExceptionForDuplicateRegistration(); } orAddValueRef = dispatcher; item = orAddMapping; } else { Mapping<TToken> orAddMapping2 = GetOrAddMapping<TMessage, TToken>(); ref Dictionary2<TToken, object> orAddValueRef2 = ref orAddMapping2.GetOrAddValueRef(key); if (orAddValueRef2 == null) { orAddValueRef2 = new Dictionary2<TToken, object>(); } ref object? orAddValueRef3 = ref orAddValueRef2.GetOrAddValueRef(token); if (orAddValueRef3 != null) { ThrowInvalidOperationExceptionForDuplicateRegistration(); } orAddValueRef3 = dispatcher; item = orAddMapping2; } ref HashSet<IMapping> orAddValueRef4 = ref recipientsMap.GetOrAddValueRef(key); if (orAddValueRef4 == null) { orAddValueRef4 = new HashSet<IMapping>(); } orAddValueRef4.Add(item); } } public void UnregisterAll(object recipient) { ArgumentNullException.ThrowIfNull(recipient, "recipient"); lock (recipientsMap) { Recipient key = new Recipient(recipient); if (!recipientsMap.TryGetValue(key, out HashSet<IMapping> value)) { return; } foreach (IMapping item in value) { if (item.TryRemove(key) && item.Count == 0) { typesMap.TryRemove(item.TypeArguments); } } recipientsMap.TryRemove(key); } } public void UnregisterAll<TToken>(object recipient, TToken token) where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); if (typeof(TToken) == typeof(Unit)) { throw new NotImplementedException(); } bool lockTaken = false; object[] array = null; int length = 0; try { Monitor.Enter(recipientsMap, ref lockTaken); Recipient key = new Recipient(recipient); if (!recipientsMap.TryGetValue(key, out HashSet<IMapping> value)) { return; } array = ArrayPool<object>.Shared.Rent(value.Count); foreach (IMapping item in value) { if (item is IDictionary2<Recipient, IDictionary2<TToken>> dictionary) { array[length++] = dictionary; } } Span<object> span = array.AsSpan(0, length); for (int i = 0; i < span.Length; i++) { IDictionary2<Recipient, IDictionary2<TToken>> dictionary2 = Unsafe.As<IDictionary2<Recipient, IDictionary2<TToken>>>(span[i]); IDictionary2<TToken> dictionary3 = dictionary2[key]; if (dictionary3.TryRemove(token) && dictionary3.Count == 0) { dictionary2.TryRemove(key); IMapping mapping = Unsafe.As<IMapping>(dictionary2); value.Remove(mapping); if (value.Count == 0) { recipientsMap.TryRemove(key); } if (dictionary2.Count == 0) { typesMap.TryRemove(mapping.TypeArguments); } } } } finally { if (lockTaken) { Monitor.Exit(recipientsMap); } if (array != null) { array.AsSpan(0, length).Clear(); ArrayPool<object>.Shared.Return(array); } } } public void Unregister<TMessage, TToken>(object recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); lock (recipientsMap) { if (typeof(TToken) == typeof(Unit)) { if (!TryGetMapping<TMessage>(out Mapping mapping)) { return; } Recipient key = new Recipient(recipient); if (mapping.TryRemove(key)) { mapping.TryRemove(key); if (mapping.Count == 0) { typesMap.TryRemove(mapping.TypeArguments); } HashSet<IMapping> hashSet = recipientsMap[key]; hashSet.Remove(mapping); if (hashSet.Count == 0) { recipientsMap.TryRemove(key); } } } else { if (!TryGetMapping<TMessage, TToken>(out Mapping<TToken> mapping2)) { return; } Recipient key2 = new Recipient(recipient); if (mapping2.TryGetValue(key2, out Dictionary2<TToken, object> value) && value.TryRemove(token) && value.Count == 0) { mapping2.TryRemove(key2); if (mapping2.Count == 0) { typesMap.TryRemove(mapping2.TypeArguments); } HashSet<IMapping> hashSet2 = recipientsMap[key2]; hashSet2.Remove(mapping2); if (hashSet2.Count == 0) { recipientsMap.TryRemove(key2); } } } } } public TMessage Send<TMessage, TToken>(TMessage message, TToken token) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(message, "message"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); int num = 0; Span<object> span; object[] array; lock (recipientsMap) { Mapping<TToken> mapping2; if (typeof(TToken) == typeof(Unit)) { if (TryGetMapping<TMessage>(out Mapping mapping)) { int count = mapping.Count; if (count != 0) { span = (array = ArrayPool<object>.Shared.Rent(2 * count)); Dictionary2<Recipient, object>.Enumerator enumerator = mapping.GetEnumerator(); while (enumerator.MoveNext()) { span[2 * num] = enumerator.GetValue(); span[2 * num + 1] = enumerator.GetKey().Target; num++; } goto IL_015d; } } } else if (TryGetMapping<TMessage, TToken>(out mapping2)) { int count2 = mapping2.Count; if (count2 != 0) { span = (array = ArrayPool<object>.Shared.Rent(2 * count2)); Dictionary2<Recipient, Dictionary2<TToken, object>>.Enumerator enumerator2 = mapping2.GetEnumerator(); while (enumerator2.MoveNext()) { if (enumerator2.GetValue().TryGetValue(token, out var value)) { span[2 * num] = value; span[2 * num + 1] = enumerator2.GetKey().Target; num++; } } goto IL_015d; } } } goto IL_0183; IL_015d: try { WeakReferenceMessenger.SendAll(span, num, message); } finally { Array.Clear(array, 0, 2 * num); ArrayPool<object>.Shared.Return(array); } goto IL_0183; IL_0183: return message; } void IMessenger.Cleanup() { } public void Reset() { lock (recipientsMap) { recipientsMap.Clear(); typesMap.Clear(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryGetMapping<TMessage>([NotNullWhen(true)] out Mapping? mapping) where TMessage : class { Type2 key = new Type2(typeof(TMessage), typeof(Unit)); if (typesMap.TryGetValue(key, out IMapping value)) { mapping = Unsafe.As<Mapping>(value); return true; } mapping = null; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryGetMapping<TMessage, TToken>([NotNullWhen(true)] out Mapping<TToken>? mapping) where TMessage : class where TToken : IEquatable<TToken> { Type2 key = new Type2(typeof(TMessage), typeof(TToken)); if (typesMap.TryGetValue(key, out IMapping value)) { mapping = Unsafe.As<Mapping<TToken>>(value); return true; } mapping = null; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private Mapping GetOrAddMapping<TMessage>() where TMessage : class { Type2 key = new Type2(typeof(TMessage), typeof(Unit)); ref IMapping orAddValueRef = ref typesMap.GetOrAddValueRef(key); if (orAddValueRef == null) { orAddValueRef = Mapping.Create<TMessage>(); } return Unsafe.As<Mapping>(orAddValueRef); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private Mapping<TToken> GetOrAddMapping<TMessage, TToken>() where TMessage : class where TToken : IEquatable<TToken> { Type2 key = new Type2(typeof(TMessage), typeof(TToken)); ref IMapping orAddValueRef = ref typesMap.GetOrAddValueRef(key); if (orAddValueRef == null) { orAddValueRef = Mapping<TToken>.Create<TMessage>(); } return Unsafe.As<Mapping<TToken>>(orAddValueRef); } private static void ThrowInvalidOperationExceptionForDuplicateRegistration() { throw new InvalidOperationException("The target recipient has already subscribed to the target message."); } } public sealed class WeakReferenceMessenger : IMessenger { private readonly Dictionary2<Type2, ConditionalWeakTable2<object, object?>> recipientsMap = new Dictionary2<Type2, ConditionalWeakTable2<object, object>>(); public static WeakReferenceMessenger Default { get; } = new WeakReferenceMessenger(); public WeakReferenceMessenger() { System.Gen2GcCallback.Register(Gen2GcCallbackProxy, this); static void Gen2GcCallbackProxy(object target) { ((WeakReferenceMessenger)target).CleanupWithNonBlockingLock(); } } public bool IsRegistered<TMessage, TToken>(object recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); lock (recipientsMap) { Type2 key = new Type2(typeof(TMessage), typeof(TToken)); if (!recipientsMap.TryGetValue(key, out ConditionalWeakTable2<object, object> value)) { return false; } object value2; if (typeof(TToken) == typeof(Unit)) { return value.TryGetValue(recipient, out value2); } object value3; return value.TryGetValue(recipient, out value3) && Unsafe.As<Dictionary2<TToken, object>>(value3).ContainsKey(token); } } public void Register<TRecipient, TMessage, TToken>(TRecipient recipient, TToken token, MessageHandler<TRecipient, TMessage> handler) where TRecipient : class where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); ArgumentNullException.ThrowIfNull(handler, "handler"); Register<TMessage, TToken>(recipient, token, new MessageHandlerDispatcher.For<TRecipient, TMessage>(handler)); } internal void Register<TMessage, TToken>(IRecipient<TMessage> recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken> { Register<TMessage, TToken>(recipient, token, null); } private void Register<TMessage, TToken>(object recipient, TToken token, MessageHandlerDispatcher? dispatcher) where TMessage : class where TToken : IEquatable<TToken> { lock (recipientsMap) { Type2 key = new Type2(typeof(TMessage), typeof(TToken)); ref ConditionalWeakTable2<object, object> orAddValueRef = ref recipientsMap.GetOrAddValueRef(key); if (orAddValueRef == null) { orAddValueRef = new ConditionalWeakTable2<object, object>(); } if (typeof(TToken) == typeof(Unit)) { if (!orAddValueRef.TryAdd(recipient, dispatcher)) { ThrowInvalidOperationExceptionForDuplicateRegistration(); } return; } ref object? orAddValueRef2 = ref Unsafe.As<Dictionary2<TToken, object>>(orAddValueRef.GetValue(recipient, (object _) => new Dictionary2<TToken, object>())).GetOrAddValueRef(token); if (orAddValueRef2 != null) { ThrowInvalidOperationExceptionForDuplicateRegistration(); } orAddValueRef2 = dispatcher; } } public void UnregisterAll(object recipient) { ArgumentNullException.ThrowIfNull(recipient, "recipient"); lock (recipientsMap) { Dictionary2<Type2, ConditionalWeakTable2<object, object>>.Enumerator enumerator = recipientsMap.GetEnumerator(); while (enumerator.MoveNext()) { enumerator.GetValue().Remove(recipient); } } } public void UnregisterAll<TToken>(object recipient, TToken token) where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); if (typeof(TToken) == typeof(Unit)) { throw new NotImplementedException(); } lock (recipientsMap) { Dictionary2<Type2, ConditionalWeakTable2<object, object>>.Enumerator enumerator = recipientsMap.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.GetKey().TToken == typeof(TToken) && enumerator.GetValue().TryGetValue(recipient, out var value)) { Unsafe.As<Dictionary2<TToken, object>>(value).TryRemove(token); } } } } public void Unregister<TMessage, TToken>(object recipient, TToken token) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(recipient, "recipient"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); lock (recipientsMap) { Type2 key = new Type2(typeof(TMessage), typeof(TToken)); if (recipientsMap.TryGetValue(key, out ConditionalWeakTable2<object, object> value)) { object value2; if (typeof(TToken) == typeof(Unit)) { value.Remove(recipient); } else if (value.TryGetValue(recipient, out value2)) { Unsafe.As<Dictionary2<TToken, object>>(value2).TryRemove(token); } } } } public TMessage Send<TMessage, TToken>(TMessage message, TToken token) where TMessage : class where TToken : IEquatable<TToken> { ArgumentNullException.ThrowIfNull(message, "message"); ArgumentNullException.For<TToken>.ThrowIfNull(token, "token"); int num = 0; ArrayPoolBufferWriter<object> arrayPoolBufferWriter; lock (recipientsMap) { Type2 key = new Type2(typeof(TMessage), typeof(TToken)); if (!recipientsMap.TryGetValue(key, out ConditionalWeakTable2<object, object> value)) { return message; } arrayPoolBufferWriter = ArrayPoolBufferWriter<object>.Create(); ConditionalWeakTable2<object, object>.Enumerator enumerator = value.GetEnumerator(); try { while (enumerator.MoveNext()) { object value2; if (typeof(TToken) == typeof(Unit)) { arrayPoolBufferWriter.Add(enumerator.GetValue()); arrayPoolBufferWriter.Add(enumerator.GetKey()); num++; } else if (Unsafe.As<Dictionary2<TToken, object>>(enumerator.GetValue()).TryGetValue(token, out value2)) { arrayPoolBufferWriter.Add(value2); arrayPoolBufferWriter.Add(enumerator.GetKey()); num++; } } } finally { enumerator.Dispose(); } } try { SendAll(arrayPoolBufferWriter.Span, num, message); return message; } finally { arrayPoolBufferWriter.Dispose(); } } [MethodImpl(MethodImplOptions.NoInlining)] internal static void SendAll<TMessage>(ReadOnlySpan<object?> pairs, int i, TMessage message) where TMessage : class { ReadOnlySpan<object> span = pairs.Slice(0, 2 * i); ref object reference = ref MemoryMarshal.GetReference(span); ref object right = ref Unsafe.Add(ref reference, span.Length); while (Unsafe.IsAddressLessThan(ref reference, ref right)) { object obj = reference; object obj2 = Unsafe.Add(ref reference, 1); if (obj == null) { Unsafe.As<IRecipient<TMessage>>(obj2).Receive(message); } else { Unsafe.As<MessageHandlerDispatcher>(obj).Invoke(obj2, message); } reference = ref Unsafe.Add(ref reference, 2); } } public void Cleanup() { lock (recipientsMap) { CleanupWithoutLock(); } } public void Reset() { lock (recipientsMap) { recipientsMap.Clear(); } } private void CleanupWithNonBlockingLock() { object obj = recipientsMap; bool lockTaken = false; try { Monitor.TryEnter(obj, ref lockTaken); if (lockTaken) { CleanupWithoutLock(); } } finally { if (lockTaken) { Monitor.Exit(obj); } } } private void CleanupWithoutLock() { ArrayPoolBufferWriter<Type2> arrayPoolBufferWriter = ArrayPoolBufferWriter<Type2>.Create(); try { ArrayPoolBufferWriter<object> arrayPoolBufferWriter2 = ArrayPoolBufferWriter<object>.Create(); try { Dictionary2<Type2, ConditionalWeakTable2<object, object>>.Enumerator enumerator = recipientsMap.GetEnumerator(); while (enumerator.MoveNext()) { arrayPoolBufferWriter2.Reset(); bool flag = false; if (enumerator.GetKey().TToken == typeof(Unit)) { ConditionalWeakTable2<object, object>.Enumerator enumerator2 = enumerator.GetValue().GetEnumerator(); try { if (enumerator2.MoveNext()) { flag = true; } } finally { enumerator2.Dispose(); } } else { ConditionalWeakTable2<object, object>.Enumerator enumerator3 = enumerator.GetValue().GetEnumerator(); try { while (enumerator3.MoveNext()) { if (Unsafe.As<IDictionary2>(enumerator3.GetValue()).Count == 0) { arrayPoolBufferWriter2.Add(enumerator3.GetKey()); } else { flag = true; } } } finally { enumerator3.Dispose(); } ReadOnlySpan<object> span = arrayPoolBufferWriter2.Span; for (int i = 0; i < span.Length; i++) { object key = span[i]; enumerator.GetValue().Remove(key); } } if (!flag) { arrayPoolBufferWriter.Add(enumerator.GetKey()); } } ReadOnlySpan<Type2> span2 = arrayPoolBufferWriter.Span; for (int i = 0; i < span2.Length; i++) { Type2 key2 = span2[i]; recipientsMap.TryRemove(key2); } } finally { arrayPoolBufferWriter2.Dispose(); } } finally { arrayPoolBufferWriter.Dispose(); } } private static void ThrowInvalidOperationExceptionForDuplicateRegistration() { throw new InvalidOperationException("The target recipient has already subscribed to the target message."); } } } namespace CommunityToolkit.Mvvm.Messaging.Messages { public class AsyncCollectionRequestMessage<T> : IAsyncEnumerable<T> { private readonly List<(Task<T>?, Func<CancellationToken, Task<T>>?)> responses = new List<(Task<T>, Func<CancellationToken, Task<T>>)>(); private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); public CancellationToken CancellationToken => cancellationTokenSource.Token; public void Reply(T response) { Reply(Task.FromResult(response)); } public void Reply(Task<T> response) { ArgumentNullException.ThrowIfNull(response, "response"); responses.Add((response, null)); } public void Reply(Func<CancellationToken, Task<T>> response) { ArgumentNullException.ThrowIfNull(response, "response"); responses.Add((null, response)); } public async Task<IReadOnlyCollection<T>> GetResponsesAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.CanBeCanceled) { cancellationToken.Register(cancellationTokenSource.Cancel); } List<T> results = new List<T>(responses.Count); await foreach (T item in this.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { results.Add(item); } return results; } [EditorBrowsable(EditorBrowsableState.Never)] public async IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.CanBeCanceled) { cancellationToken.Register(cancellationTokenSource.Cancel); } foreach (var (task, func) in responses) { if (cancellationToken.IsCancellationRequested) { yield break; } if (task != null) { yield return await task.ConfigureAwait(continueOnCapturedContext: false); } else { yield return await func(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } } } public class AsyncRequestMessage<T> { private Task<T>? response; public Task<T> Response { get { if (!HasReceivedResponse) { ThrowInvalidOperationExceptionForNoResponseReceived(); } return response; } } public bool HasReceivedResponse { get; private set; } public void Reply(T response) { Reply(Task.FromResult(response)); } public void Reply(Task<T> response) { ArgumentNullException.ThrowIfNull(response, "response"); if (HasReceivedResponse) { ThrowInvalidOperationExceptionForDuplicateReply(); } HasReceivedResponse = true; this.response = response; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] public TaskAwaiter<T> GetAwaiter() { return Response.GetAwaiter(); } [DoesNotReturn] private static void ThrowInvalidOperationExceptionForNoResponseReceived() { throw new InvalidOperationException("No response was received for the given request message."); } [DoesNotReturn] private static void ThrowInvalidOperationExceptionForDuplicateReply() { throw new InvalidOperationException("A response has already been issued for the current message."); } } public class CollectionRequestMessage<T> : IEnumerable<T>, IEnumerable { private readonly List<T> responses = new List<T>(); public IReadOnlyCollection<T> Responses => responses; public void Reply(T response) { responses.Add(response); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] public IEnumerator<T> GetEnumerator() { return responses.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class PropertyChangedMessage<T> { public object Sender { get; } public string? PropertyName { get; } public T OldValue { get; } public T NewValue { get; } public PropertyChangedMessage(object sender, string? propertyName, T oldValue, T newValue) { ArgumentNullException.ThrowIfNull(sender, "sender"); Sender = sender; PropertyName = propertyName; OldValue = oldValue; NewValue = newValue; } } public class RequestMessage<T> { private T response; public T Response { get { if (!HasReceivedResponse) { ThrowInvalidOperationExceptionForNoResponseReceived(); } return response; } } public bool HasReceivedResponse { get; private set; } public void Reply(T response) { if (HasReceivedResponse) { ThrowInvalidOperationExceptionForDuplicateReply(); } HasReceivedResponse = true; this.response = response; } public static implicit operator T(RequestMessage<T> message) { ArgumentNullException.ThrowIfNull(message, "message"); return message.Response; } [DoesNotReturn] private static void ThrowInvalidOperationExceptionForNoResponseReceived() { throw new InvalidOperationException("No response was received for the given request message."); } [DoesNotReturn] private static void ThrowInvalidOperationExceptionForDuplicateReply() { throw new InvalidOperationException("A response has already been issued for the current message."); } } public class ValueChangedMessage<T> { public T Value { get; } public ValueChangedMessage(T value) { Value = value; } } } namespace CommunityToolkit.Mvvm.Messaging.Internals { internal ref struct ArrayPoolBufferWriter<T> { private const int DefaultInitialBufferSize = 128; private T[] array; private Span<T> span; private int index; public ReadOnlySpan<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return span.Slice(0, index); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ArrayPoolBufferWriter<T> Create() { Unsafe.SkipInit(out ArrayPoolBufferWriter<T> result); result.span = (result.array = ArrayPool<T>.Shared.Rent(128)); result.index = 0; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { Span<T> span = this.span; int num = index; if ((uint)num < (uint)span.Length) { span[num] = item; index = num + 1; } else { ResizeBufferAndAdd(item); } } public void Reset() { Array.Clear(array, 0, index); index = 0; } [MethodImpl(MethodImplOptions.NoInlining)] private void ResizeBufferAndAdd(T item) { T[] destinationArray = ArrayPool<T>.Shared.Rent(index << 2); Array.Copy(array, 0, destinationArray, 0, index); Array.Clear(array, 0, index); ArrayPool<T>.Shared.Return(array); span = (array = destinationArray); span[index++] = item; } public void Dispose() { Array.Clear(array, 0, index); ArrayPool<T>.Shared.Return(array); } } internal abstract class MessageHandlerDispatcher { public sealed class For<TRecipient, TMessage> : MessageHandlerDispatcher where TRecipient : class where TMessage : class { private readonly MessageHandler<TRecipient, TMessage> handler; public For(MessageHandler<TRecipient, TMessage> handler) { this.handler = handler; } public override void Invoke(object recipient, object message) { handler(Unsafe.As<TRecipient>(recipient), Unsafe.As<TMessage>(message)); } } public abstract void Invoke(object recipient, object message); } internal readonly struct Type2 : IEquatable<Type2> { public readonly Type TMessage; public readonly Type TToken; [MethodImpl(MethodImplOptions.AggressiveInlining)] public Type2(Type tMessage, Type tToken) { TMessage = tMessage; TToken = tToken; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Type2 other) { if (TMessage == other.TMessage) { return TToken == other.TToken; } return false; } public override bool Equals(object? obj) { if (obj is Type2 other) { return Equals(other); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { int hashCode = TMessage.GetHashCode(); hashCode = (hashCode << 5) + hashCode; return hashCode + TToken.GetHashCode(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal readonly struct Unit : IEquatable<Unit> { [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Unit other) { return true; } public override bool Equals(object? obj) { return obj is Unit; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return 0; } } } namespace CommunityToolkit.Mvvm.Input { public sealed class AsyncRelayCommand : IAsyncRelayCommand, IRelayCommand, ICommand, INotifyPropertyChanged, ICancellationAwareCommand { internal static readonly PropertyChangedEventArgs ExecutionTaskChangedEventArgs = new PropertyChangedEventArgs("ExecutionTask"); internal static readonly PropertyChangedEventArgs CanBeCanceledChangedEventArgs = new PropertyChangedEventArgs("CanBeCanceled"); internal static readonly PropertyChangedEventArgs IsCancellationRequestedChangedEventArgs = new PropertyChangedEventArgs("IsCancellationRequested"); internal static readonly PropertyChangedEventArgs IsRunningChangedEventArgs = new PropertyChangedEventArgs("IsRunning"); private readonly Func<Task>? execute; private readonly Func<CancellationToken, Task>? cancelableExecute; private readonly Func<bool>? canExecute; private readonly AsyncRelayCommandOptions options; private CancellationTokenSource? cancellationTokenSource; private Task? executionTask; public Task? ExecutionTask { get { return executionTask; } private set { if (executionTask != value) { executionTask = value; this.PropertyChanged?.Invoke(this, ExecutionTaskChangedEventArgs); this.PropertyChanged?.Invoke(this, IsRunningChangedEventArgs); bool num = value?.IsCompleted ?? true; if (cancellationTokenSource != null) { this.PropertyChanged?.Invoke(this, CanBeCanceledChangedEventArgs); this.PropertyChanged?.Invoke(this, IsCancellationRequestedChangedEventArgs); } if (!num) { MonitorTask(this, value); } } static async void MonitorTask(AsyncRelayCommand @this, Task task) { await task.GetAwaitableWithoutEndValidation(); if (@this.executionTask == task) { @this.PropertyChanged?.Invoke(@this, ExecutionTaskChangedEventArgs); @this.PropertyChanged?.Invoke(@this, IsRunningChangedEventArgs); if (@this.cancellationTokenSource != null) { @this.PropertyChanged?.Invoke(@this, CanBeCanceledChangedEventArgs); } if ((@this.options & AsyncRelayCommandOptions.AllowConcurrentExecutions) == 0) { @this.CanExecuteChanged?.Invoke(@this, EventArgs.Empty); } } } } } public bool CanBeCanceled { get { if (IsRunning) { CancellationTokenSource cancellationTokenSource = this.cancellationTokenSource; if (cancellationTokenSource != null) { return !cancellationTokenSource.IsCancellationRequested; } return false; } return false; } } public bool IsCancellationRequested => cancellationTokenSource?.IsCancellationRequested ?? false; public bool IsRunning { get { Task task = ExecutionTask; if (task != null) { return !task.IsCompleted; } return false; } } bool ICancellationAwareCommand.IsCancellationSupported => execute == null; public event PropertyChangedEventHandler? PropertyChanged; public event EventHandler? CanExecuteChanged; public AsyncRelayCommand(Func<Task> execute) { ArgumentNullException.ThrowIfNull(execute, "execute"); this.execute = execute; } public AsyncRelayCommand(Func<Task> execute, AsyncRelayCommandOptions options) { ArgumentNullException.ThrowIfNull(execute, "execute"); this.execute = execute; this.options = options; } public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute) { ArgumentNullException.ThrowIfNull(cancelableExecute, "cancelableExecute"); this.cancelableExecute = cancelableExecute; } public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute, AsyncRelayCommandOptions options) { ArgumentNullException.ThrowIfNull(cancelableExecute, "cancelableExecute"); this.cancelableExecute = cancelableExecute; this.options = options; } public AsyncRelayCommand(Func<Task> execute, Func<bool> canExecute) { ArgumentNullException.ThrowIfNull(execute, "execute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.execute = execute; this.canExecute = canExecute; } public AsyncRelayCommand(Func<Task> execute, Func<bool> canExecute, AsyncRelayCommandOptions options) { ArgumentNullException.ThrowIfNull(execute, "execute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.execute = execute; this.canExecute = canExecute; this.options = options; } public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute, Func<bool> canExecute) { ArgumentNullException.ThrowIfNull(cancelableExecute, "cancelableExecute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.cancelableExecute = cancelableExecute; this.canExecute = canExecute; } public AsyncRelayCommand(Func<CancellationToken, Task> cancelableExecute, Func<bool> canExecute, AsyncRelayCommandOptions options) { ArgumentNullException.ThrowIfNull(cancelableExecute, "cancelableExecute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.cancelableExecute = cancelableExecute; this.canExecute = canExecute; this.options = options; } public void NotifyCanExecuteChanged() { this.CanExecuteChanged?.Invoke(this, EventArgs.Empty); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CanExecute(object? parameter) { Func<bool>? func = canExecute; if (func == null || func()) { if ((options & AsyncRelayCommandOptions.AllowConcurrentExecutions) == 0) { Task task = ExecutionTask; return task == null || task.IsCompleted; } return true; } return false; } public void Execute(object? parameter) { Task task = ExecuteAsync(parameter); if ((options & AsyncRelayCommandOptions.FlowExceptionsToTaskScheduler) == 0) { AwaitAndThrowIfFailed(task); } } public Task ExecuteAsync(object? parameter) { Task result; if (execute != null) { Task task2 = (ExecutionTask = execute()); result = task2; } else { this.cancellationTokenSource?.Cancel(); CancellationTokenSource cancellationTokenSource = (this.cancellationTokenSource = new CancellationTokenSource()); Task task2 = (ExecutionTask = cancelableExecute(cancellationTokenSource.Token)); result = task2; } if ((options & AsyncRelayCommandOptions.AllowConcurrentExecutions) == 0) { this.CanExecuteChanged?.Invoke(this, EventArgs.Empty); } return result; } public void Cancel() { CancellationTokenSource cancellationTokenSource = this.cancellationTokenSource; if (cancellationTokenSource != null && !cancellationTokenSource.IsCancellationRequested) { cancellationTokenSource.Cancel(); this.PropertyChanged?.Invoke(this, CanBeCanceledChangedEventArgs); this.PropertyChanged?.Invoke(this, IsCancellationRequestedChangedEventArgs); } } internal static async void AwaitAndThrowIfFailed(Task executionTask) { await executionTask; } } [Flags] public enum AsyncRelayCommandOptions { None = 0, AllowConcurrentExecutions = 1, FlowExceptionsToTaskScheduler = 2 } public sealed class AsyncRelayCommand<T> : IAsyncRelayCommand<T>, IAsyncRelayCommand, IRelayCommand, ICommand, INotifyPropertyChanged, IRelayCommand<T>, ICancellationAwareCommand { private readonly Func<T?, Task>? execute; private readonly Func<T?, CancellationToken, Task>? cancelableExecute; private readonly Predicate<T?>? canExecute; private readonly AsyncRelayCommandOptions options; private CancellationTokenSource? cancellationTokenSource; private Task? executionTask; public Task? ExecutionTask { get { return executionTask; } private set { if (executionTask != value) { executionTask = value; this.PropertyChanged?.Invoke(this, AsyncRelayCommand.ExecutionTaskChangedEventArgs); this.PropertyChanged?.Invoke(this, AsyncRelayCommand.IsRunningChangedEventArgs); bool num = value?.IsCompleted ?? true; if (cancellationTokenSource != null) { this.PropertyChanged?.Invoke(this, AsyncRelayCommand.CanBeCanceledChangedEventArgs); this.PropertyChanged?.Invoke(this, AsyncRelayCommand.IsCancellationRequestedChangedEventArgs); } if (!num) { MonitorTask(this, value); } } static async void MonitorTask(AsyncRelayCommand<T> @this, Task task) { await task.GetAwaitableWithoutEndValidation(); if (@this.executionTask == task) { @this.PropertyChanged?.Invoke(@this, AsyncRelayCommand.ExecutionTaskChangedEventArgs); @this.PropertyChanged?.Invoke(@this, AsyncRelayCommand.IsRunningChangedEventArgs); if (@this.cancellationTokenSource != null) { @this.PropertyChanged?.Invoke(@this, AsyncRelayCommand.CanBeCanceledChangedEventArgs); } if ((@this.options & AsyncRelayCommandOptions.AllowConcurrentExecutions) == 0) { @this.CanExecuteChanged?.Invoke(@this, EventArgs.Empty); } } } } } public bool CanBeCanceled { get { if (IsRunning) { CancellationTokenSource cancellationTokenSource = this.cancellationTokenSource; if (cancellationTokenSource != null) { return !cancellationTokenSource.IsCancellationRequested; } return false; } return false; } } public bool IsCancellationRequested => cancellationTokenSource?.IsCancellationRequested ?? false; public bool IsRunning { get { Task task = ExecutionTask; if (task != null) { return !task.IsCompleted; } return false; } } bool ICancellationAwareCommand.IsCancellationSupported => execute == null; public event PropertyChangedEventHandler? PropertyChanged; public event EventHandler? CanExecuteChanged; public AsyncRelayCommand(Func<T?, Task> execute) { ArgumentNullException.ThrowIfNull(execute, "execute"); this.execute = execute; } public AsyncRelayCommand(Func<T?, Task> execute, AsyncRelayCommandOptions options) { ArgumentNullException.ThrowIfNull(execute, "execute"); this.execute = execute; this.options = options; } public AsyncRelayCommand(Func<T?, CancellationToken, Task> cancelableExecute) { ArgumentNullException.ThrowIfNull(cancelableExecute, "cancelableExecute"); this.cancelableExecute = cancelableExecute; } public AsyncRelayCommand(Func<T?, CancellationToken, Task> cancelableExecute, AsyncRelayCommandOptions options) { ArgumentNullException.ThrowIfNull(cancelableExecute, "cancelableExecute"); this.cancelableExecute = cancelableExecute; this.options = options; } public AsyncRelayCommand(Func<T?, Task> execute, Predicate<T?> canExecute) { ArgumentNullException.ThrowIfNull(execute, "execute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.execute = execute; this.canExecute = canExecute; } public AsyncRelayCommand(Func<T?, Task> execute, Predicate<T?> canExecute, AsyncRelayCommandOptions options) { ArgumentNullException.ThrowIfNull(execute, "execute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.execute = execute; this.canExecute = canExecute; this.options = options; } public AsyncRelayCommand(Func<T?, CancellationToken, Task> cancelableExecute, Predicate<T?> canExecute) { ArgumentNullException.ThrowIfNull(cancelableExecute, "cancelableExecute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.cancelableExecute = cancelableExecute; this.canExecute = canExecute; } public AsyncRelayCommand(Func<T?, CancellationToken, Task> cancelableExecute, Predicate<T?> canExecute, AsyncRelayCommandOptions options) { ArgumentNullException.ThrowIfNull(cancelableExecute, "cancelableExecute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.cancelableExecute = cancelableExecute; this.canExecute = canExecute; this.options = options; } public void NotifyCanExecuteChanged() { this.CanExecuteChanged?.Invoke(this, EventArgs.Empty); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CanExecute(T? parameter) { Predicate<T?>? predicate = canExecute; if (predicate == null || predicate(parameter)) { if ((options & AsyncRelayCommandOptions.AllowConcurrentExecutions) == 0) { Task task = ExecutionTask; return task == null || task.IsCompleted; } return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CanExecute(object? parameter) { if (parameter == null && default(T) != null) { return false; } if (!RelayCommand<T>.TryGetCommandArgument(parameter, out T result)) { RelayCommand<T>.ThrowArgumentExceptionForInvalidCommandArgument(parameter); } return CanExecute(result); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Execute(T? parameter) { Task task = ExecuteAsync(parameter); if ((options & AsyncRelayCommandOptions.FlowExceptionsToTaskScheduler) == 0) { AsyncRelayCommand.AwaitAndThrowIfFailed(task); } } public void Execute(object? parameter) { if (!RelayCommand<T>.TryGetCommandArgument(parameter, out T result)) { RelayCommand<T>.ThrowArgumentExceptionForInvalidCommandArgument(parameter); } Execute(result); } public Task ExecuteAsync(T? parameter) { Task result; if (execute != null) { Task task2 = (ExecutionTask = execute(parameter)); result = task2; } else { this.cancellationTokenSource?.Cancel(); CancellationTokenSource cancellationTokenSource = (this.cancellationTokenSource = new CancellationTokenSource()); Task task2 = (ExecutionTask = cancelableExecute(parameter, cancellationTokenSource.Token)); result = task2; } if ((options & AsyncRelayCommandOptions.AllowConcurrentExecutions) == 0) { this.CanExecuteChanged?.Invoke(this, EventArgs.Empty); } return result; } public Task ExecuteAsync(object? parameter) { if (!RelayCommand<T>.TryGetCommandArgument(parameter, out T result)) { RelayCommand<T>.ThrowArgumentExceptionForInvalidCommandArgument(parameter); } return ExecuteAsync(result); } public void Cancel() { CancellationTokenSource cancellationTokenSource = this.cancellationTokenSource; if (cancellationTokenSource != null && !cancellationTokenSource.IsCancellationRequested) { cancellationTokenSource.Cancel(); this.PropertyChanged?.Invoke(this, AsyncRelayCommand.CanBeCanceledChangedEventArgs); this.PropertyChanged?.Invoke(this, AsyncRelayCommand.IsCancellationRequestedChangedEventArgs); } } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class RelayCommandAttribute : Attribute { public string? CanExecute { get; init; } public bool AllowConcurrentExecutions { get; init; } public bool FlowExceptionsToTaskScheduler { get; init; } public bool IncludeCancelCommand { get; init; } } public static class IAsyncRelayCommandExtensions { public static ICommand CreateCancelCommand(this IAsyncRelayCommand command) { ArgumentNullException.ThrowIfNull(command, "command"); if (command is ICancellationAwareCommand cancellationAwareCommand && !cancellationAwareCommand.IsCancellationSupported) { return DisabledCommand.Instance; } return new CancelCommand(command); } } public interface IAsyncRelayCommand : IRelayCommand, ICommand, INotifyPropertyChanged { Task? ExecutionTask { get; } bool CanBeCanceled { get; } bool IsCancellationRequested { get; } bool IsRunning { get; } Task ExecuteAsync(object? parameter); void Cancel(); } public interface IAsyncRelayCommand<in T> : IAsyncRelayCommand, IRelayCommand, ICommand, INotifyPropertyChanged, IRelayCommand<T> { Task ExecuteAsync(T? parameter); } public interface IRelayCommand : ICommand { void NotifyCanExecuteChanged(); } public interface IRelayCommand<in T> : IRelayCommand, ICommand { bool CanExecute(T? parameter); void Execute(T? parameter); } public sealed class RelayCommand : IRelayCommand, ICommand { private readonly Action execute; private readonly Func<bool>? canExecute; public event EventHandler? CanExecuteChanged; public RelayCommand(Action execute) { ArgumentNullException.ThrowIfNull(execute, "execute"); this.execute = execute; } public RelayCommand(Action execute, Func<bool> canExecute) { ArgumentNullException.ThrowIfNull(execute, "execute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.execute = execute; this.canExecute = canExecute; } public void NotifyCanExecuteChanged() { this.CanExecuteChanged?.Invoke(this, EventArgs.Empty); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CanExecute(object? parameter) { return canExecute?.Invoke() ?? true; } public void Execute(object? parameter) { execute(); } } public sealed class RelayCommand<T> : IRelayCommand<T>, IRelayCommand, ICommand { private readonly Action<T?> execute; private readonly Predicate<T?>? canExecute; public event EventHandler? CanExecuteChanged; public RelayCommand(Action<T?> execute) { ArgumentNullException.ThrowIfNull(execute, "execute"); this.execute = execute; } public RelayCommand(Action<T?> execute, Predicate<T?> canExecute) { ArgumentNullException.ThrowIfNull(execute, "execute"); ArgumentNullException.ThrowIfNull(canExecute, "canExecute"); this.execute = execute; this.canExecute = canExecute; } public void NotifyCanExecuteChanged() { this.CanExecuteChanged?.Invoke(this, EventArgs.Empty); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CanExecute(T? parameter) { return canExecute?.Invoke(parameter) ?? true; } public bool CanExecute(object? parameter) { if (parameter == null && default(T) != null) { return false; } if (!TryGetCommandArgument(parameter, out T result)) { ThrowArgumentExceptionForInvalidCommandArgument(parameter); } return CanExecute(result); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Execute(T? parameter) { execute(parameter); } public void Execute(object? parameter) { if (!TryGetCommandArgument(parameter, out T result)) { ThrowArgumentExceptionForInvalidCommandArgument(parameter); } Execute(result); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryGetCommandArgument(object? parameter, out T? result) { if (parameter == null && default(T) == null) { result = default(T); return true; } if (parameter is T val) { result = val; return true; } result = default(T); return false; } [DoesNotReturn] internal static void ThrowArgumentExceptionForInvalidCommandArgument(object? parameter) { throw GetException(parameter); [MethodImpl(MethodImplOptions.NoInlining)] static Exception GetException(object? parameter) { if (parameter == null) { return new ArgumentException($"Parameter \"{"parameter"}\" (object) must not be null, as the command type requires an argument of type {typeof(T)}.", "parameter"); } return new ArgumentException($"Parameter \"{"parameter"}\" (object) cannot be of type {parameter.GetType()}, as the command type requires an argument of type {typeof(T)}.", "parameter"); } } } } namespace CommunityToolkit.Mvvm.Input.Internals { internal sealed class CancelCommand : ICommand { private readonly IAsyncRelayCommand command; public event EventHandler? CanExecuteChanged; public CancelCommand(IAsyncRelayCommand command) { this.command = command; this.command.PropertyChanged += OnPropertyChanged; } public bool CanExecute(object? parameter) { return command.CanBeCanceled; } public void Execute(object? parameter) { command.Cancel(); } private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) { string propertyName = e.PropertyName; if ((propertyName == null || propertyName == "CanBeCanceled") ? true : false) { this.CanExecuteChanged?.Invoke(this, EventArgs.Empty); } } } internal sealed class DisabledCommand : ICommand { public static DisabledCommand Instance { get; } = new DisabledCommand(); public event EventHandler? CanExecuteChanged { add { } remove { } } public bool CanExecute(object? parameter) { return false; } public void Execute(object? parameter) { } } internal interface ICancellationAwareCommand { bool IsCancellationSupported { get; } } } namespace CommunityToolkit.Mvvm.DependencyInjection { public sealed class Ioc : IServiceProvider { private volatile IServiceProvider? serviceProvider; public static Ioc Default { get; } = new Ioc(); public object? GetService(Type serviceType) { ArgumentNullException.ThrowIfNull(serviceType, "serviceType"); IServiceProvider? obj = serviceProvider; if (obj == null) { ThrowInvalidOperationExceptionForMissingInitialization(); } return obj.GetService(serviceType); } public T? GetService<T>() where T : class { IServiceProvider? obj = serviceProvider; if (obj == null) { ThrowInvalidOperationExceptionForMissingInitialization(); } return (T)obj.GetService(typeof(T)); } public T GetRequiredService<T>() where T : class { IServiceProvider? obj = serviceProvider; if (obj == null) { ThrowInvalidOperationExceptionForMissingInitialization(); } T obj2 = (T)obj.GetService(typeof(T)); if (obj2 == null) { ThrowInvalidOperationExceptionForUnregisteredType(); } return obj2; } public void ConfigureServices(IServiceProvider serviceProvider) { ArgumentNullException.ThrowIfNull(serviceProvider, "serviceProvider"); if (Interlocked.CompareExchange(ref this.serviceProvider, serviceProvider, null) != null) { ThrowInvalidOperationExceptionForRepeatedConfiguration(); } } [DoesNotReturn] private static void ThrowInvalidOperationExceptionForMissingInitialization() { throw new InvalidOperationException("The service provider has not been configured yet."); } [DoesNotReturn] private static void ThrowInvalidOperationExceptionForUnregisteredType() { throw new InvalidOperationException("The requested service type was not registered."); } [DoesNotReturn] private static void ThrowInvalidOperationExceptionForRepeatedConfiguration() { throw new InvalidOperationException("The default service provider has already been configured."); } } } namespace CommunityToolkit.Mvvm.ComponentModel { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class INotifyPropertyChangedAttribute : Attribute { public bool IncludeAdditionalHelperMethods { get; init; } = true; } [AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = false)] public sealed class NotifyCanExecuteChangedForAttribute : Attribute { public string[] CommandNames { get; } public NotifyCanExecuteChangedForAttribute(string commandName) { CommandNames = new string[1] { commandName }; } public NotifyCanExecuteChangedForAttribute(string commandName, params string[] otherCommandNames) { CommandNames = new string[1] { commandName }.Concat(otherCommandNames).ToArray(); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class NotifyDataErrorInfoAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = false)] public sealed class NotifyPropertyChangedForAttribute : Attribute { public string[] PropertyNames { get; } public NotifyPropertyChangedForAttribute(string propertyName) { PropertyNames = new string[1] { propertyName }; } public NotifyPropertyChangedForAttribute(string propertyName, params string[] otherPropertyNames) { PropertyNames = new string[1] { propertyName }.Concat(otherPropertyNames).ToArray(); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class NotifyPropertyChangedRecipientsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class ObservableObjectAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class ObservablePropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class ObservableRecipientAttribute : Attribute { } public abstract class ObservableObject : INotifyPropertyChanged, INotifyPropertyChanging { private interface ITaskNotifier<TTask> where TTask : Task { TTask? Task { get; set; } } protected sealed class TaskNotifier : ITaskNotifier<Task> { private Task? task; Task? ITaskNotifier<Task>.Task { get { return task; } set { task = value; } } internal TaskNotifier() { } public static implicit operator Task?(TaskNotifier? notifier) { return notifier?.task; } } protected sealed class TaskNotifier<T> : ITaskNotifier<Task<T>> { private Task<T>? task; Task<T>? ITaskNotifier<Task<T>>.Task { get { return task; } set { task = value; } } internal TaskNotifier() { } public static implicit operator Task<T>?(TaskNotifier<T>? notifier) { return notifier?.task; } } public event PropertyChangedEventHandler? PropertyChanged; public event PropertyChangingEventHandler? PropertyChanging; protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { ArgumentNullException.ThrowIfNull(e, "e"); this.PropertyChanged?.Invoke(this, e); } protected virtual void OnPropertyChanging(PropertyChangingEventArgs e) { ArgumentNullException.ThrowIfNull(e, "e"); this.PropertyChanging?.Invoke(this, e); } protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } protected void OnPropertyChanging([CallerMemberName] string? propertyName = null) { if (!Configuration.IsINotifyPropertyChangingDisabled) { OnPropertyChanging(new PropertyChangingEventArgs(propertyName)); } } protected bool SetProperty<T>([NotNullIfNotNull("newValue")] ref T field, T newValue, [CallerMemberName] string? propertyName = null) { if (EqualityComparer<T>.Default.Equals(field, newValue)) { return false; } OnPropertyChanging(propertyName); field = newValue; OnPropertyChanged(propertyName); return true; } protected bool SetProperty<T>([NotNullIfNotNull("newValue")] ref T field, T newValue, IEqualityComparer<T> comparer, [CallerMemberName] string? propertyName = null) { ArgumentNullException.ThrowIfNull(comparer, "comparer"); if (comparer.Equals(field, newValue)) { return false; } OnPropertyChanging(propertyName); field = newValue; OnPropertyChanged(propertyName); return true; } protected bool SetProperty<T>(T oldValue, T newValue, Action<T> callback, [CallerMemberName] string? propertyName = null) { ArgumentNullException.ThrowIfNull(callback, "callback"); if (EqualityComparer<T>.Default.Equals(oldValue, newValue)) { return false; } OnPropertyChanging(propertyName); callback(newValue); OnPropertyChanged(propertyName); return true; } protected bool SetProperty<T>(T oldValue, T newValue, IEqualityComparer<T> comparer, Action<T> callback, [CallerMemberName] string? propertyName = null) { ArgumentNullException.ThrowIfNull(comparer, "comparer"); ArgumentNullException.ThrowIfNull(callback, "callback"); if (comparer.Equals(oldValue, newValue)) { return false; } OnPropertyChanging(propertyName); callback(newValue); OnPropertyChanged(propertyName); return true; } protected bool SetProperty<TModel, T>(T oldValue, T newValue, TModel model, Action<TModel, T> callback, [CallerMemberName] string? propertyName = null) where TModel : class { ArgumentNullException.ThrowIfNull(model, "model"); ArgumentNullException.ThrowIfNull(callback, "callback"); if (EqualityComparer<T>.Default.Equals(oldValue, newValue)) { return false; } OnPropertyChanging(propertyName); callback(model, newValue); OnPropertyChanged(propertyName); return true; } protected bool SetProperty<TModel, T>(T oldValue, T newValue, IEqualityComparer<T> comparer, TModel model, Action<TModel, T> callback, [CallerMemberName] string? propertyName = null) where TModel : class { ArgumentNullException.ThrowIfNull(comparer, "comparer"); ArgumentNullException.ThrowIfNull(model, "model"); ArgumentNullException.ThrowIfNull(callback, "callback"); if (comparer.Equals(oldValue, newValue)) { return false; } OnPropertyChanging(propertyName); callback(model, newValue); OnPropertyChanged(propertyName); return true; } protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ?? (taskNotifier = new TaskNotifier()), newValue, null, propertyName); } protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, Action<Task?> callback, [CallerMemberName] string? propertyName = null) { ArgumentNullException.ThrowIfNull(callback, "callback"); return SetPropertyAndNotifyOnCompletion(taskNotifier ?? (taskNotifier = new TaskNotifier()), newValue, callback, propertyName); } protected bool SetPropertyAndNotifyOnCompletion<T>([NotNull] ref TaskNotifier<T>? taskNotifier, Task<T>? newValue, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ?? (taskNotifier = new TaskNotifier<T>()), newValue, null, propertyName); } protected bool SetPropertyAndNotifyOnCompletion<T>([NotNull] ref TaskNotifier<T>? taskNotifier, Task<T>? newValue, Action<Task<T>?> callback, [CallerMemberName] string? propertyName = null) { ArgumentNullException.ThrowIfNull(callback, "callback"); return SetPropertyAndNotifyOnCompletion(taskNotifier ?? (taskNotifier = new TaskNotifier<T>()), newValue, callback, propertyName); } private bool SetPropertyAndNotifyOnCompletion<TTask>(ITaskNotifier<TTask> taskNotifier, TTask? newValue, Action<TTask?>? callback, [CallerMemberName] string? propertyName = null) where TTask : Task { TTask newValue2 = newValue; ITaskNotifier<TTask> taskNotifier2 = taskNotifier; string propertyName2 = propertyName; Action<TTask?> callback2 = callback; if (taskNotifier2.Task == newValue2) { return false; } bool num = newValue2?.IsCompleted ?? true; OnPropertyChanging(propertyName2); taskNotifier2.Task = newValue2; OnPropertyChanged(propertyName2); if (num) { if (callback2 != null) { callback2(newValue2); } return true; } MonitorTask(); return true; async void MonitorTask() { await newValue2.GetAwaitableWithoutEndValidation(); if (taskNotifier2.Task == newValue2) { OnPropertyChanged(propertyName2); } if (callback2 != null) { callback2(newValue2); } } } } public abstract class ObservableRecipient : ObservableObject { private bool isActive; protected IMessenger Messenger { get; } public bool IsActive { get { return isActive; } [RequiresUnreferencedCode("When this property is set to true, the OnActivated() method will be invoked, which will register all necessary message handlers for this recipient. This method requires the generated CommunityToolkit.Mvvm.Messaging.__Internals.__IMessengerExtensions type not to be removed to use the fast path. If this type is removed by the linker, or if the target recipient was created dynamically and was missed by the source generator, a slower fallback path using a compiled LINQ expression will be used. This will have more overhead in the first invocation of this method for any given recipient type. Alternatively, OnActivated() can be manually overwritten, and registration can be done individually for each required message for this recipient.")] set { if (SetProperty(ref isActive, value, broadcast: true, "IsActive")) { if (value) { OnActivated(); } else { OnDeactivated(); } } } } protected ObservableRecipient() : this(WeakReferenceMessenger.Default) { } protected ObservableRecipient(IMessenger messenger) { ArgumentNullException.ThrowIfNull(messenger, "messenger"); Messenger = messenger; } [RequiresUnreferencedCode("This method requires th
AuriePack/AurieInstaller/Microsoft.Extensions.Configuration.Abstractions.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using FxResources.Microsoft.Extensions.Configuration.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Abstractions of key-value pair based configuration.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Configuration.IConfiguration\r\nMicrosoft.Extensions.Configuration.IConfigurationBuilder\r\nMicrosoft.Extensions.Configuration.IConfigurationProvider\r\nMicrosoft.Extensions.Configuration.IConfigurationRoot\r\nMicrosoft.Extensions.Configuration.IConfigurationSection")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Configuration.Abstractions.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string InvalidSectionName => GetResourceString("InvalidSectionName"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Configuration { public readonly struct ConfigurationDebugViewContext { [field: CompilerGenerated] public string Path { [CompilerGenerated] get; } [field: CompilerGenerated] public string Key { [CompilerGenerated] get; } [field: CompilerGenerated] public string? Value { [CompilerGenerated] get; } [field: CompilerGenerated] public IConfigurationProvider ConfigurationProvider { [CompilerGenerated] get; } public ConfigurationDebugViewContext(string path, string key, string? value, IConfigurationProvider configurationProvider) { Path = path; Key = key; Value = value; ConfigurationProvider = configurationProvider; } } public static class ConfigurationExtensions { [CompilerGenerated] private sealed class <AsEnumerable>d__3 : System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<KeyValuePair<string, string>>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private KeyValuePair<string, string> <>2__current; private int <>l__initialThreadId; private IConfiguration configuration; public IConfiguration <>3__configuration; private bool makePathsRelative; public bool <>3__makePathsRelative; private Stack<IConfiguration> <stack>5__2; private int <prefixLength>5__3; private IConfiguration <config>5__4; KeyValuePair<string, string> System.Collections.Generic.IEnumerator<KeyValuePair<string, string>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <AsEnumerable>d__3(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; goto IL_00d0; } <>1__state = -1; <stack>5__2 = new Stack<IConfiguration>(); <stack>5__2.Push(configuration); <prefixLength>5__3 = ((makePathsRelative && configuration is IConfigurationSection configurationSection) ? (configurationSection.Path.Length + 1) : 0); goto IL_0113; IL_00d0: System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator = <config>5__4.GetChildren().GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSection current = enumerator.Current; <stack>5__2.Push((IConfiguration)current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } <config>5__4 = null; goto IL_0113; IL_0113: if (<stack>5__2.Count > 0) { <config>5__4 = <stack>5__2.Pop(); if (<config>5__4 is IConfigurationSection configurationSection2 && (!makePathsRelative || <config>5__4 != configuration)) { <>2__current = new KeyValuePair<string, string>(configurationSection2.Path.Substring(<prefixLength>5__3), configurationSection2.Value); <>1__state = 1; return true; } goto IL_00d0; } return false; } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>.GetEnumerator() { <AsEnumerable>d__3 <AsEnumerable>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <AsEnumerable>d__ = this; } else { <AsEnumerable>d__ = new <AsEnumerable>d__3(0); } <AsEnumerable>d__.configuration = <>3__configuration; <AsEnumerable>d__.makePathsRelative = <>3__makePathsRelative; return <AsEnumerable>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)this).GetEnumerator(); } } public static IConfigurationBuilder Add<TSource>(this IConfigurationBuilder builder, Action<TSource>? configureSource) where TSource : IConfigurationSource, new() { TSource val = new TSource(); configureSource?.Invoke(val); return builder.Add(val); } public static string? GetConnectionString(this IConfiguration configuration, string name) { return configuration?.GetSection("ConnectionStrings")[name]; } public static System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>> AsEnumerable(this IConfiguration configuration) { return configuration.AsEnumerable(makePathsRelative: false); } [IteratorStateMachine(typeof(<AsEnumerable>d__3))] public static System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>> AsEnumerable(this IConfiguration configuration, bool makePathsRelative) { Stack<IConfiguration> stack = new Stack<IConfiguration>(); stack.Push(configuration); int prefixLength = ((makePathsRelative && configuration is IConfigurationSection configurationSection) ? (configurationSection.Path.Length + 1) : 0); while (stack.Count > 0) { IConfiguration config = stack.Pop(); if (config is IConfigurationSection configurationSection2 && (!makePathsRelative || config != configuration)) { yield return new KeyValuePair<string, string>(configurationSection2.Path.Substring(prefixLength), configurationSection2.Value); } System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator = config.GetChildren().GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSection current = enumerator.Current; stack.Push((IConfiguration)current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } public static bool Exists([NotNullWhen(true)] this IConfigurationSection? section) { if (section == null) { return false; } if (section.Value == null) { return Enumerable.Any<IConfigurationSection>(section.GetChildren()); } return true; } public static IConfigurationSection GetRequiredSection(this IConfiguration configuration, string key) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(configuration, "configuration"); IConfigurationSection section = configuration.GetSection(key); if (section.Exists()) { return section; } throw new InvalidOperationException(System.SR.Format(System.SR.InvalidSectionName, (object)key)); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class ConfigurationKeyNameAttribute : System.Attribute { [field: CompilerGenerated] public string Name { [CompilerGenerated] get; } public ConfigurationKeyNameAttribute(string name) { Name = name; } } public static class ConfigurationPath { public static readonly string KeyDelimiter = ":"; public static string Combine(params string[] pathSegments) { ThrowHelper.ThrowIfNull(pathSegments, "pathSegments"); return string.Join(KeyDelimiter, pathSegments); } public static string Combine(System.Collections.Generic.IEnumerable<string> pathSegments) { ThrowHelper.ThrowIfNull(pathSegments, "pathSegments"); return string.Join(KeyDelimiter, pathSegments); } [return: NotNullIfNotNull("path")] public static string? GetSectionKey(string? path) { if (string.IsNullOrEmpty(path)) { return path; } int num = path.LastIndexOf(KeyDelimiter, (StringComparison)5); if (num != -1) { return path.Substring(num + 1); } return path; } public static string? GetParentPath(string? path) { if (string.IsNullOrEmpty(path)) { return null; } int num = path.LastIndexOf(KeyDelimiter, (StringComparison)5); if (num != -1) { return path.Substring(0, num); } return null; } } public static class ConfigurationRootExtensions { public static string GetDebugView(this IConfigurationRoot root) { return root.GetDebugView(null); } public static string GetDebugView(this IConfigurationRoot root, Func<ConfigurationDebugViewContext, string>? processValue) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown IConfigurationRoot root2 = root; Func<ConfigurationDebugViewContext, string> processValue2 = processValue; StringBuilder val = new StringBuilder(); RecurseChildren(val, root2.GetChildren(), ""); return ((object)val).ToString(); [CompilerGenerated] void RecurseChildren(StringBuilder stringBuilder, System.Collections.Generic.IEnumerable<IConfigurationSection> children, string indent) { //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_0025: 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_0055: 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_008f: Unknown result type (might be due to invalid IL or missing references) System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator = children.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSection current = enumerator.Current; ValueTuple<string, IConfigurationProvider> valueAndProvider = GetValueAndProvider(root2, current.Path); if (valueAndProvider.Item2 != null) { string text = ((processValue2 != null) ? processValue2.Invoke(new ConfigurationDebugViewContext(current.Key, current.Path, valueAndProvider.Item1, valueAndProvider.Item2)) : valueAndProvider.Item1); stringBuilder.Append(indent).Append(current.Key).Append('=') .Append(text) .Append(" (") .Append((object)valueAndProvider.Item2) .AppendLine(")"); } else { stringBuilder.Append(indent).Append(current.Key).AppendLine(":"); } RecurseChildren(stringBuilder, current.GetChildren(), indent + " "); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } private static ValueTuple<string, IConfigurationProvider> GetValueAndProvider(IConfigurationRoot root, string key) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) System.Collections.Generic.IEnumerator<IConfigurationProvider> enumerator = Enumerable.Reverse<IConfigurationProvider>(root.Providers).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationProvider current = enumerator.Current; if (current.TryGet(key, out string value)) { return new ValueTuple<string, IConfigurationProvider>(value, current); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } return new ValueTuple<string, IConfigurationProvider>((string)null, (IConfigurationProvider)null); } } [DefaultMember("Item")] public interface IConfiguration { string? this[string key] { get; set; } IConfigurationSection GetSection(string key); System.Collections.Generic.IEnumerable<IConfigurationSection> GetChildren(); IChangeToken GetReloadToken(); } public interface IConfigurationBuilder { IDictionary<string, object> Properties { get; } System.Collections.Generic.IList<IConfigurationSource> Sources { get; } IConfigurationBuilder Add(IConfigurationSource source); IConfigurationRoot Build(); } public interface IConfigurationProvider { bool TryGet(string key, out string? value); void Set(string key, string? value); IChangeToken GetReloadToken(); void Load(); System.Collections.Generic.IEnumerable<string> GetChildKeys(System.Collections.Generic.IEnumerable<string> earlierKeys, string? parentPath); } public interface IConfigurationRoot : IConfiguration { System.Collections.Generic.IEnumerable<IConfigurationProvider> Providers { get; } void Reload(); } public interface IConfigurationSection : IConfiguration { string Key { get; } string Path { get; } string? Value { get; set; } } public interface IConfigurationSource { IConfigurationProvider Build(IConfigurationBuilder builder); } }
AuriePack/AurieInstaller/Microsoft.Extensions.Configuration.Binder.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using FxResources.Microsoft.Extensions.Configuration.Binder; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Binder.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.Binder")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Functionality to bind an object to data in configuration providers for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("7.0.323.6910")] [assembly: AssemblyInformationalVersion("7.0.3+0a2bda10e81d901396c3cff95533529e3a93ad47")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.Binder")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.Binder { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Configuration.Binder.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string Error_CannotActivateAbstractOrInterface => GetResourceString("Error_CannotActivateAbstractOrInterface"); internal static string Error_CannotBindToConstructorParameter => GetResourceString("Error_CannotBindToConstructorParameter"); internal static string Error_ConstructorParametersDoNotMatchProperties => GetResourceString("Error_ConstructorParametersDoNotMatchProperties"); internal static string Error_FailedBinding => GetResourceString("Error_FailedBinding"); internal static string Error_FailedToActivate => GetResourceString("Error_FailedToActivate"); internal static string Error_MissingConfig => GetResourceString("Error_MissingConfig"); internal static string Error_MissingPublicInstanceConstructor => GetResourceString("Error_MissingPublicInstanceConstructor"); internal static string Error_MultipleParameterizedConstructors => GetResourceString("Error_MultipleParameterizedConstructors"); internal static string Error_ParameterBeingBoundToIsUnnamed => GetResourceString("Error_ParameterBeingBoundToIsUnnamed"); internal static string Error_ParameterHasNoMatchingConfig => GetResourceString("Error_ParameterHasNoMatchingConfig"); internal static string Error_UnsupportedMultidimensionalArray => GetResourceString("Error_UnsupportedMultidimensionalArray"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Internal { internal static class ParameterDefaultValue { public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue) { bool tryToGetDefaultValue; bool flag = CheckHasDefaultValue(parameter, out tryToGetDefaultValue); defaultValue = null; if (flag) { if (tryToGetDefaultValue) { defaultValue = parameter.DefaultValue; } bool flag2 = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(System.Nullable<>); if (defaultValue == null && parameter.ParameterType.IsValueType && !flag2) { defaultValue = CreateValueType(parameter.ParameterType); } if (defaultValue != null && flag2) { System.Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType != (System.Type)null && underlyingType.IsEnum) { defaultValue = System.Enum.ToObject(underlyingType, defaultValue); } } } return flag; [CompilerGenerated] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")] static object? CreateValueType(System.Type t) { return RuntimeHelpers.GetUninitializedObject(t); } } public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue) { tryToGetDefaultValue = true; return parameter.HasDefaultValue; } } } namespace Microsoft.Extensions.Configuration { public class BinderOptions { [field: CompilerGenerated] public bool BindNonPublicProperties { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public bool ErrorOnUnknownConfiguration { [CompilerGenerated] get; [CompilerGenerated] set; } } internal sealed class BindingPoint { private readonly Func<object> _initialValueProvider; private object _initialValue; private object _setValue; private bool _valueSet; [field: CompilerGenerated] public bool IsReadOnly { [CompilerGenerated] get; } public bool HasNewValue { get { if (IsReadOnly) { return false; } if (_valueSet) { return true; } System.Type type = _initialValue?.GetType(); if (type != null && type.IsValueType) { return !type.IsPrimitive; } return false; } } public object? Value { get { object obj; if (!_valueSet) { obj = _initialValue; if (obj == null) { return _initialValue = _initialValueProvider?.Invoke(); } } else { obj = _setValue; } return obj; } } public BindingPoint(object? initialValue = null, bool isReadOnly = false) { _initialValue = initialValue; IsReadOnly = isReadOnly; } public BindingPoint(Func<object?> initialValueProvider, bool isReadOnly) { _initialValueProvider = initialValueProvider; IsReadOnly = isReadOnly; } public void SetValue(object? newValue) { _setValue = newValue; _valueSet = true; } public void TrySetValue(object? newValue) { if (!IsReadOnly) { SetValue(newValue); } } } public static class ConfigurationBinder { private const BindingFlags DeclaredOnlyLookup = 62; private const string DynamicCodeWarningMessage = "Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types."; private const string TrimmingWarningMessage = "In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed."; private const string InstanceGetTypeTrimmingWarningMessage = "Cannot statically analyze the type of instance so its members may be trimmed"; private const string PropertyTrimmingWarningMessage = "Cannot statically analyze property.PropertyType so its members may be trimmed."; [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? Get<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] T>(this IConfiguration configuration) { return configuration.Get<T>(delegate { }); } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? Get<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] T>(this IConfiguration configuration, Action<BinderOptions>? configureOptions) { ThrowHelper.ThrowIfNull(configuration, "configuration"); object obj = configuration.Get(typeof(T), configureOptions); if (obj == null) { return default(T); } return (T)obj; } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? Get(this IConfiguration configuration, System.Type type) { return configuration.Get(type, delegate { }); } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? Get(this IConfiguration configuration, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, Action<BinderOptions>? configureOptions) { ThrowHelper.ThrowIfNull(configuration, "configuration"); BinderOptions binderOptions = new BinderOptions(); configureOptions?.Invoke(binderOptions); BindingPoint bindingPoint = new BindingPoint(); BindInstance(type, bindingPoint, configuration, binderOptions); return bindingPoint.Value; } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this IConfiguration configuration, string key, object? instance) { ((IConfiguration)(object)configuration.GetSection(key)).Bind(instance); } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this IConfiguration configuration, object? instance) { configuration.Bind(instance, delegate { }); } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this IConfiguration configuration, object? instance, Action<BinderOptions>? configureOptions) { ThrowHelper.ThrowIfNull(configuration, "configuration"); if (instance != null) { BinderOptions binderOptions = new BinderOptions(); configureOptions?.Invoke(binderOptions); BindingPoint bindingPoint = new BindingPoint(instance, isReadOnly: true); BindInstance(instance.GetType(), bindingPoint, configuration, binderOptions); } } [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? GetValue<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] T>(this IConfiguration configuration, string key) { return configuration.GetValue(key, default(T)); } [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? GetValue<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] T>(this IConfiguration configuration, string key, T defaultValue) { return (T)configuration.GetValue(typeof(T), key, defaultValue); } [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? GetValue(this IConfiguration configuration, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string key) { return configuration.GetValue(type, key, null); } [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? GetValue(this IConfiguration configuration, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string key, object? defaultValue) { IConfigurationSection section = configuration.GetSection(key); string value = section.Value; if (value != null) { return ConvertValue(type, value, section.Path); } return defaultValue; } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")] private static void BindProperties(object instance, IConfiguration configuration, BinderOptions options) { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) List<PropertyInfo> allProperties = GetAllProperties(instance.GetType()); if (options.ErrorOnUnknownConfiguration) { HashSet<string> propertyNames = new HashSet<string>(Enumerable.Select<PropertyInfo, string>((System.Collections.Generic.IEnumerable<PropertyInfo>)allProperties, (Func<PropertyInfo, string>)((PropertyInfo mp) => ((MemberInfo)mp).Name)), (IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); System.Collections.Generic.IEnumerable<IConfigurationSection> children = configuration.GetChildren(); List<string> val = Enumerable.ToList<string>(Enumerable.Select<IConfigurationSection, string>(Enumerable.Where<IConfigurationSection>(children, (Func<IConfigurationSection, bool>)((IConfigurationSection cs) => !propertyNames.Contains(cs.Key))), (Func<IConfigurationSection, string>)((IConfigurationSection mp) => "'" + mp.Key + "'"))); if (val.Count > 0) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_MissingConfig, new object[4] { "ErrorOnUnknownConfiguration", "BinderOptions", instance.GetType(), string.Join(", ", (System.Collections.Generic.IEnumerable<string>)val) })); } } Enumerator<PropertyInfo> enumerator = allProperties.GetEnumerator(); try { while (enumerator.MoveNext()) { PropertyInfo current = enumerator.Current; BindProperty(current, instance, configuration, options); } } finally { ((System.IDisposable)enumerator).Dispose(); } } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")] private static void BindProperty(PropertyInfo property, object instance, IConfiguration config, BinderOptions options) { if (!(property.GetMethod == (MethodInfo)null) && (options.BindNonPublicProperties || ((MethodBase)property.GetMethod).IsPublic) && ((MethodBase)property.GetMethod).GetParameters().Length == 0) { BindingPoint bindingPoint = new BindingPoint(() => property.GetValue(instance), property.SetMethod == null || (!((MethodBase)property.SetMethod).IsPublic && !options.BindNonPublicProperties)); BindInstance(property.PropertyType, bindingPoint, (IConfiguration)(object)config.GetSection(GetPropertyName((MemberInfo)(object)property)), options); if (!bindingPoint.IsReadOnly && bindingPoint.Value != null) { property.SetValue(instance, bindingPoint.Value); } } } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] private static void BindInstance([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, BindingPoint bindingPoint, IConfiguration config, BinderOptions options) { if (type == typeof(IConfigurationSection)) { bindingPoint.TrySetValue(config); return; } IConfigurationSection val = (IConfigurationSection)(object)((config is IConfigurationSection) ? config : null); string text = ((val != null) ? val.Value : null); if (text != null && TryConvertValue(type, text, (val != null) ? val.Path : null, out var result, out var error)) { if (error != null) { throw error; } bindingPoint.TrySetValue(result); } else { if (config == null || !Enumerable.Any<IConfigurationSection>(config.GetChildren())) { return; } if (type.IsArray || IsImmutableArrayCompatibleInterface(type)) { if (!bindingPoint.IsReadOnly) { bindingPoint.SetValue(BindArray(type, (System.Collections.IEnumerable)bindingPoint.Value, config, options)); } return; } if (TypeIsASetInterface(type) && !bindingPoint.IsReadOnly) { object obj = BindSet(type, (System.Collections.IEnumerable)bindingPoint.Value, config, options); if (obj != null) { bindingPoint.SetValue(obj); } return; } if (TypeIsADictionaryInterface(type) && !bindingPoint.IsReadOnly) { object obj2 = BindDictionaryInterface(bindingPoint.Value, type, config, options); if (obj2 != null) { bindingPoint.SetValue(obj2); } return; } if (bindingPoint.Value == null) { if (bindingPoint.IsReadOnly) { return; } System.Type type2 = ((type.IsInterface && type.IsConstructedGenericType) ? type.GetGenericTypeDefinition() : null); if (type2 != null && (type2 == typeof(System.Collections.Generic.ICollection<>) || type2 == typeof(System.Collections.Generic.IList<>))) { System.Type type3 = typeof(List<>).MakeGenericType(new System.Type[1] { type.GenericTypeArguments[0] }); bindingPoint.SetValue(Activator.CreateInstance(type3)); } else { bindingPoint.SetValue(CreateInstance(type, config, options)); } } System.Type type4 = FindOpenGenericInterface(typeof(IDictionary<, >), type); if (type4 != (System.Type)null) { BindDictionary(bindingPoint.Value, type4, config, options); return; } System.Type type5 = FindOpenGenericInterface(typeof(System.Collections.Generic.ICollection<>), type); if (type5 != (System.Type)null) { BindCollection(bindingPoint.Value, type5, config, options); } else { BindProperties(bindingPoint.Value, config, options); } } } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("In case type is a Nullable<T>, cannot statically analyze what the underlying type is so its members may be trimmed.")] private static object CreateInstance([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, IConfiguration config, BinderOptions options) { //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) if (type.IsInterface || type.IsAbstract) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_CannotActivateAbstractOrInterface, type)); } ConstructorInfo[] constructors = type.GetConstructors((BindingFlags)20); bool flag = type.IsValueType || Enumerable.Any<ConstructorInfo>((System.Collections.Generic.IEnumerable<ConstructorInfo>)constructors, (Func<ConstructorInfo, bool>)((ConstructorInfo ctor) => ((MethodBase)ctor).GetParameters().Length == 0)); if (!type.IsValueType && constructors.Length == 0) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_MissingPublicInstanceConstructor, type)); } if (constructors.Length > 1 && !flag) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_MultipleParameterizedConstructors, type)); } if (constructors.Length == 1 && !flag) { ConstructorInfo val = constructors[0]; ParameterInfo[] parameters = ((MethodBase)val).GetParameters(); if (!CanBindToTheseConstructorParameters(parameters, out var nameOfInvalidParameter)) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_CannotBindToConstructorParameter, type, nameOfInvalidParameter)); } List<PropertyInfo> allProperties = GetAllProperties(type); if (!DoAllParametersHaveEquivalentProperties(parameters, allProperties, out var missing)) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_ConstructorParametersDoNotMatchProperties, type, missing)); } object[] array = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = BindParameter(parameters[i], type, config, options); } return val.Invoke(array); } object obj; try { obj = Activator.CreateInstance(Nullable.GetUnderlyingType(type) ?? type); } catch (System.Exception ex) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_FailedToActivate, type), ex); } return obj ?? throw new InvalidOperationException(System.SR.Format(System.SR.Error_FailedToActivate, type)); } private static bool DoAllParametersHaveEquivalentProperties(ParameterInfo[] parameters, List<PropertyInfo> properties, out string missing) { //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) HashSet<string> val = new HashSet<string>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); Enumerator<PropertyInfo> enumerator = properties.GetEnumerator(); try { while (enumerator.MoveNext()) { PropertyInfo current = enumerator.Current; val.Add(((MemberInfo)current).Name); } } finally { ((System.IDisposable)enumerator).Dispose(); } List<string> val2 = new List<string>(); foreach (ParameterInfo val3 in parameters) { string name = val3.Name; if (!val.Contains(name)) { val2.Add(name); } } missing = string.Join(",", (System.Collections.Generic.IEnumerable<string>)val2); return missing.Length == 0; } private static bool CanBindToTheseConstructorParameters(ParameterInfo[] constructorParameters, out string nameOfInvalidParameter) { nameOfInvalidParameter = string.Empty; foreach (ParameterInfo val in constructorParameters) { if (val.IsOut || val.IsIn || val.ParameterType.IsByRef) { nameOfInvalidParameter = val.Name; return false; } } return true; } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze what the element type is of the value objects in the dictionary so its members may be trimmed.")] private static object BindDictionaryInterface(object source, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type dictionaryType, IConfiguration config, BinderOptions options) { System.Type type = dictionaryType.GenericTypeArguments[0]; System.Type type2 = dictionaryType.GenericTypeArguments[1]; bool isEnum = type.IsEnum; bool flag = type == typeof(sbyte) || type == typeof(byte) || type == typeof(short) || type == typeof(ushort) || type == typeof(int) || type == typeof(uint) || type == typeof(long) || type == typeof(ulong); if (type != typeof(string) && !isEnum && !flag) { return null; } System.Type type3 = typeof(Dictionary<, >).MakeGenericType(new System.Type[2] { type, type2 }); MethodInfo method = type3.GetMethod("Add", (BindingFlags)62); System.Type type4 = typeof(KeyValuePair<, >).MakeGenericType(new System.Type[2] { type, type2 }); PropertyInfo property = type4.GetProperty("Key", (BindingFlags)62); PropertyInfo property2 = type4.GetProperty("Value", (BindingFlags)62); object obj = Activator.CreateInstance(type3); System.Collections.IEnumerable enumerable = source as System.Collections.IEnumerable; object[] array = new object[2]; if (enumerable != null) { foreach (object item in enumerable) { object obj2 = ((MethodBase)property.GetMethod).Invoke(item, (object[])null); object obj3 = ((MethodBase)property2.GetMethod).Invoke(item, (object[])null); array[0] = obj2; array[1] = obj3; ((MethodBase)method).Invoke(obj, array); } } BindDictionary(obj, type3, config, options); return obj; } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze what the element type is of the value objects in the dictionary so its members may be trimmed.")] private static void BindDictionary(object dictionary, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type dictionaryType, IConfiguration config, BinderOptions options) { System.Type type = dictionaryType.GenericTypeArguments[0]; System.Type type2 = dictionaryType.GenericTypeArguments[1]; bool isEnum = type.IsEnum; bool flag = type == typeof(sbyte) || type == typeof(byte) || type == typeof(short) || type == typeof(ushort) || type == typeof(int) || type == typeof(uint) || type == typeof(long) || type == typeof(ulong); if (type != typeof(string) && !isEnum && !flag) { return; } MethodInfo tryGetValue = dictionaryType.GetMethod("TryGetValue", (BindingFlags)62); PropertyInfo property = dictionaryType.GetProperty("Item", (BindingFlags)62); if (property == null || !property.CanWrite) { return; } System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator = config.GetChildren().GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSection current = enumerator.Current; try { object key = (isEnum ? System.Enum.Parse(type, current.Key, true) : (flag ? Convert.ChangeType((object)current.Key, type) : current.Key)); BindingPoint bindingPoint = new BindingPoint(delegate { object[] array = new object[2] { key, null }; return (!(bool)((MethodBase)tryGetValue).Invoke(dictionary, array)) ? null : array[1]; }, isReadOnly: false); BindInstance(type2, bindingPoint, (IConfiguration)(object)current, options); if (bindingPoint.HasNewValue) { property.SetValue(dictionary, bindingPoint.Value, new object[1] { key }); } } catch { } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze what the element type is of the object collection so its members may be trimmed.")] private static void BindCollection(object collection, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type collectionType, IConfiguration config, BinderOptions options) { System.Type type = collectionType.GenericTypeArguments[0]; MethodInfo method = collectionType.GetMethod("Add", (BindingFlags)62); System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator = config.GetChildren().GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSection current = enumerator.Current; try { BindingPoint bindingPoint = new BindingPoint(); BindInstance(type, bindingPoint, (IConfiguration)(object)current, options); if (bindingPoint.HasNewValue && method != null) { ((MethodBase)method).Invoke(collection, new object[1] { bindingPoint.Value }); } } catch { } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze what the element type is of the Array so its members may be trimmed.")] private static System.Array BindArray(System.Type type, System.Collections.IEnumerable source, IConfiguration config, BinderOptions options) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) System.Type type2; if (type.IsArray) { if (type.GetArrayRank() > 1) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_UnsupportedMultidimensionalArray, type)); } type2 = type.GetElementType(); } else { type2 = type.GetGenericArguments()[0]; } System.Collections.IList list = (System.Collections.IList)new List<object>(); if (source != null) { foreach (object item in source) { list.Add(item); } } System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator2 = config.GetChildren().GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator2).MoveNext()) { IConfigurationSection current2 = enumerator2.Current; BindingPoint bindingPoint = new BindingPoint(); try { BindInstance(type2, bindingPoint, (IConfiguration)(object)current2, options); if (bindingPoint.HasNewValue) { list.Add(bindingPoint.Value); } } catch { } } } finally { ((System.IDisposable)enumerator2)?.Dispose(); } System.Array array = System.Array.CreateInstance(type2, ((System.Collections.ICollection)list).Count); ((System.Collections.ICollection)list).CopyTo(array, 0); return array; } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze what the element type is of the Array so its members may be trimmed.")] private static object BindSet(System.Type type, System.Collections.IEnumerable source, IConfiguration config, BinderOptions options) { System.Type type2 = type.GetGenericArguments()[0]; System.Type type3 = type.GenericTypeArguments[0]; bool isEnum = type3.IsEnum; if (type3 != typeof(string) && !isEnum) { return null; } System.Type type4 = typeof(HashSet<>).MakeGenericType(new System.Type[1] { type3 }); object obj = Activator.CreateInstance(type4); MethodInfo method = type4.GetMethod("Add", (BindingFlags)62); object[] array = new object[1]; if (source != null) { foreach (object item in source) { array[0] = item; ((MethodBase)method).Invoke(obj, array); } } System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator2 = config.GetChildren().GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator2).MoveNext()) { IConfigurationSection current2 = enumerator2.Current; BindingPoint bindingPoint = new BindingPoint(); try { BindInstance(type2, bindingPoint, (IConfiguration)(object)current2, options); if (bindingPoint.HasNewValue) { array[0] = bindingPoint.Value; ((MethodBase)method).Invoke(obj, array); } } catch { } } return obj; } finally { ((System.IDisposable)enumerator2)?.Dispose(); } } [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] private static bool TryConvertValue([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string value, string path, out object result, out System.Exception error) { //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_00b3: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown error = null; result = null; if (type == typeof(object)) { result = value; return true; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Nullable<>)) { if (string.IsNullOrEmpty(value)) { return true; } return TryConvertValue(Nullable.GetUnderlyingType(type), value, path, out result, out error); } TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(string))) { try { result = converter.ConvertFromInvariantString(value); } catch (System.Exception ex) { error = (System.Exception)new InvalidOperationException(System.SR.Format(System.SR.Error_FailedBinding, (object?)path, (object?)type), ex); } return true; } if (type == typeof(byte[])) { try { result = Convert.FromBase64String(value); } catch (FormatException val) { FormatException val2 = val; error = (System.Exception)new InvalidOperationException(System.SR.Format(System.SR.Error_FailedBinding, (object?)path, (object?)type), (System.Exception)(object)val2); } return true; } return false; } [RequiresUnreferencedCode("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] private static object ConvertValue([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type, string value, string path) { TryConvertValue(type, value, path, out var result, out var error); if (error != null) { throw error; } return result; } private static bool TypeIsADictionaryInterface(System.Type type) { if (!type.IsInterface || !type.IsConstructedGenericType) { return false; } System.Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (!(genericTypeDefinition == typeof(IDictionary<, >))) { return genericTypeDefinition == typeof(IReadOnlyDictionary<, >); } return true; } private static bool IsImmutableArrayCompatibleInterface(System.Type type) { if (!type.IsInterface || !type.IsConstructedGenericType) { return false; } System.Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (!(genericTypeDefinition == typeof(System.Collections.Generic.IEnumerable<>)) && !(genericTypeDefinition == typeof(System.Collections.Generic.IReadOnlyCollection<>))) { return genericTypeDefinition == typeof(System.Collections.Generic.IReadOnlyList<>); } return true; } private static bool TypeIsASetInterface(System.Type type) { if (!type.IsInterface || !type.IsConstructedGenericType) { return false; } System.Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (!(genericTypeDefinition == typeof(ISet<>))) { return genericTypeDefinition == typeof(IReadOnlySet<>); } return true; } private static System.Type FindOpenGenericInterface(System.Type expected, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type actual) { if (actual.IsGenericType && actual.GetGenericTypeDefinition() == expected) { return actual; } System.Type[] interfaces = actual.GetInterfaces(); System.Type[] array = interfaces; foreach (System.Type type in array) { if (type.IsGenericType && type.GetGenericTypeDefinition() == expected) { return type; } } return null; } private static List<PropertyInfo> GetAllProperties([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type) { List<PropertyInfo> val = new List<PropertyInfo>(); System.Type type2 = type; while (type2 != typeof(object)) { PropertyInfo[] properties = type2.GetProperties((BindingFlags)62); PropertyInfo[] array = properties; foreach (PropertyInfo val2 in array) { MethodInfo setMethod = val2.GetSetMethod(true); if (setMethod == null || !((MethodBase)setMethod).IsVirtual || setMethod == setMethod.GetBaseDefinition()) { val.Add(val2); } } type2 = type2.BaseType; } return val; } [RequiresDynamicCode("Binding strongly typed objects to configuration values requires generating dynamic code at runtime, for example instantiating generic types.")] [RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")] private static object BindParameter(ParameterInfo parameter, System.Type type, IConfiguration config, BinderOptions options) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) string name = parameter.Name; if (name == null) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_ParameterBeingBoundToIsUnnamed, type)); } BindingPoint bindingPoint = new BindingPoint(config.GetSection(name).Value); if (bindingPoint.Value == null) { if (!ParameterDefaultValue.TryGetDefaultValue(parameter, out object defaultValue)) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_ParameterHasNoMatchingConfig, type, name)); } bindingPoint.SetValue(defaultValue); } BindInstance(parameter.ParameterType, bindingPoint, (IConfiguration)(object)config.GetSection(name), options); return bindingPoint.Value; } private static string GetPropertyName(MemberInfo property) { //IL_004e: 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) ThrowHelper.ThrowIfNull(property, "property"); System.Collections.Generic.IEnumerator<CustomAttributeData> enumerator = ((System.Collections.Generic.IEnumerable<CustomAttributeData>)property.GetCustomAttributesData()).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { CustomAttributeData current = enumerator.Current; if (!(current.AttributeType != typeof(ConfigurationKeyNameAttribute))) { if (((System.Collections.Generic.ICollection<CustomAttributeTypedArgument>)current.ConstructorArguments).Count != 1) { break; } CustomAttributeTypedArgument val = current.ConstructorArguments[0]; string text = ((CustomAttributeTypedArgument)(ref val)).Value?.ToString(); return (!string.IsNullOrWhiteSpace(text)) ? text : property.Name; } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } return property.Name; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Configuration.CommandLine.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using FxResources.Microsoft.Extensions.Configuration.CommandLine; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration.CommandLine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.CommandLine.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.CommandLine")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Command line configuration provider implementation for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.CommandLine")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.CommandLine { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Configuration.CommandLine.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string Error_DuplicatedKeyInSwitchMappings => GetResourceString("Error_DuplicatedKeyInSwitchMappings"); internal static string Error_InvalidSwitchMapping => GetResourceString("Error_InvalidSwitchMapping"); internal static string Error_ShortSwitchNotDefined => GetResourceString("Error_ShortSwitchNotDefined"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Configuration { public static class CommandLineConfigurationExtensions { public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder configurationBuilder, string[] args) { return configurationBuilder.AddCommandLine(args, null); } public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder configurationBuilder, string[] args, IDictionary<string, string>? switchMappings) { configurationBuilder.Add((IConfigurationSource)(object)new CommandLineConfigurationSource { Args = args, SwitchMappings = switchMappings }); return configurationBuilder; } public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action<CommandLineConfigurationSource>? configureSource) { return ConfigurationExtensions.Add<CommandLineConfigurationSource>(builder, configureSource); } } } namespace Microsoft.Extensions.Configuration.CommandLine { public class CommandLineConfigurationProvider : ConfigurationProvider { private readonly Dictionary<string, string> _switchMappings; [field: CompilerGenerated] protected System.Collections.Generic.IEnumerable<string> Args { [CompilerGenerated] get; [CompilerGenerated] private set; } public CommandLineConfigurationProvider(System.Collections.Generic.IEnumerable<string> args, IDictionary<string, string>? switchMappings = null) { ThrowHelper.ThrowIfNull(args, "args"); Args = args; if (switchMappings != null) { _switchMappings = GetValidatedSwitchMappingsCopy(switchMappings); } } public override void Load() { //IL_0102: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, string> val = new Dictionary<string, string>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); System.Collections.Generic.IEnumerator<string> enumerator = Args.GetEnumerator(); try { string text2 = default(string); string text6 = default(string); while (((System.Collections.IEnumerator)enumerator).MoveNext()) { string text = enumerator.Current; int num = 0; if (text.StartsWith("--")) { num = 2; } else if (text.StartsWith("-")) { num = 1; } else if (text.StartsWith("/")) { text = "--" + text.Substring(1); num = 2; } int num2 = text.IndexOf('='); string text3; string text4; if (num2 < 0) { if (num == 0) { continue; } if (_switchMappings != null && _switchMappings.TryGetValue(text, ref text2)) { text3 = text2; } else { if (num == 1) { continue; } text3 = text.Substring(num); } if (!((System.Collections.IEnumerator)enumerator).MoveNext()) { continue; } text4 = enumerator.Current; } else { string text5 = text.Substring(0, num2); if (_switchMappings != null && _switchMappings.TryGetValue(text5, ref text6)) { text3 = text6; } else { if (num == 1) { throw new FormatException(System.SR.Format(System.SR.Error_ShortSwitchNotDefined, (object?)text)); } text3 = text.Substring(num, num2 - num); } text4 = text.Substring(num2 + 1); } val[text3] = text4; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } ((ConfigurationProvider)this).Data = (IDictionary<string, string>)(object)val; } private static Dictionary<string, string> GetValidatedSwitchMappingsCopy(IDictionary<string, string> switchMappings) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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) Dictionary<string, string> val = new Dictionary<string, string>(((System.Collections.Generic.ICollection<KeyValuePair<string, string>>)switchMappings).Count, (IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator = ((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)switchMappings).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, string> current = enumerator.Current; if (!current.Key.StartsWith("-") && !current.Key.StartsWith("--")) { throw new ArgumentException(System.SR.Format(System.SR.Error_InvalidSwitchMapping, (object?)current.Key), "switchMappings"); } if (val.ContainsKey(current.Key)) { throw new ArgumentException(System.SR.Format(System.SR.Error_DuplicatedKeyInSwitchMappings, (object?)current.Key), "switchMappings"); } val.Add(current.Key, current.Value); } return val; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } public class CommandLineConfigurationSource : IConfigurationSource { [field: CompilerGenerated] public IDictionary<string, string>? SwitchMappings { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public System.Collections.Generic.IEnumerable<string> Args { [CompilerGenerated] get; [CompilerGenerated] set; } = System.Array.Empty<string>(); public IConfigurationProvider Build(IConfigurationBuilder builder) { return (IConfigurationProvider)(object)new CommandLineConfigurationProvider(Args, SwitchMappings); } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Configuration.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using FxResources.Microsoft.Extensions.Configuration; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration.Memory; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Implementation of key-value pair based configuration for Microsoft.Extensions.Configuration. Includes the memory configuration provider.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Configuration.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string Error_NoSources => GetResourceString("Error_NoSources"); internal static string InvalidNullArgument => GetResourceString("InvalidNullArgument"); internal static string StreamConfigurationProvidersAlreadyLoaded => GetResourceString("StreamConfigurationProvidersAlreadyLoaded"); internal static string StreamConfigurationSourceStreamCannotBeNull => GetResourceString("StreamConfigurationSourceStreamCannotBeNull"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Configuration { public static class ChainedBuilderExtensions { public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder configurationBuilder, IConfiguration config) { return configurationBuilder.AddConfiguration(config, shouldDisposeConfiguration: false); } public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder configurationBuilder, IConfiguration config, bool shouldDisposeConfiguration) { ThrowHelper.ThrowIfNull(configurationBuilder, "configurationBuilder"); ThrowHelper.ThrowIfNull(config, "config"); configurationBuilder.Add((IConfigurationSource)(object)new ChainedConfigurationSource { Configuration = config, ShouldDisposeConfiguration = shouldDisposeConfiguration }); return configurationBuilder; } } public class ChainedConfigurationProvider : IConfigurationProvider, System.IDisposable { private readonly IConfiguration _config; private readonly bool _shouldDisposeConfig; public IConfiguration Configuration => _config; public ChainedConfigurationProvider(ChainedConfigurationSource source) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(source, "source"); _config = source.Configuration ?? throw new ArgumentException(System.SR.Format(System.SR.InvalidNullArgument, (object?)"source.Configuration"), "source"); _shouldDisposeConfig = source.ShouldDisposeConfiguration; } public bool TryGet(string key, out string? value) { value = _config[key]; return !string.IsNullOrEmpty(value); } public void Set(string key, string? value) { _config[key] = value; } public IChangeToken GetReloadToken() { return _config.GetReloadToken(); } public void Load() { } public System.Collections.Generic.IEnumerable<string> GetChildKeys(System.Collections.Generic.IEnumerable<string> earlierKeys, string? parentPath) { IConfiguration obj; if (parentPath != null) { IConfiguration section = (IConfiguration)(object)_config.GetSection(parentPath); obj = section; } else { obj = _config; } IConfiguration val = obj; List<string> val2 = new List<string>(); System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator = val.GetChildren().GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSection current = enumerator.Current; val2.Add(current.Key); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } val2.AddRange(earlierKeys); val2.Sort(ConfigurationKeyComparer.Comparison); return (System.Collections.Generic.IEnumerable<string>)val2; } public void Dispose() { if (_shouldDisposeConfig) { (_config as System.IDisposable)?.Dispose(); } } } public class ChainedConfigurationSource : IConfigurationSource { [field: CompilerGenerated] public IConfiguration? Configuration { [CompilerGenerated] get; [CompilerGenerated] [param: DisallowNull] set; } [field: CompilerGenerated] public bool ShouldDisposeConfiguration { [CompilerGenerated] get; [CompilerGenerated] set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return (IConfigurationProvider)(object)new ChainedConfigurationProvider(this); } } public class ConfigurationBuilder : IConfigurationBuilder { [field: CompilerGenerated] public System.Collections.Generic.IList<IConfigurationSource> Sources { [CompilerGenerated] get; } = (System.Collections.Generic.IList<IConfigurationSource>)new List<IConfigurationSource>(); [field: CompilerGenerated] public IDictionary<string, object> Properties { [CompilerGenerated] get; } = (IDictionary<string, object>)(object)new Dictionary<string, object>(); public IConfigurationBuilder Add(IConfigurationSource source) { ThrowHelper.ThrowIfNull(source, "source"); ((System.Collections.Generic.ICollection<IConfigurationSource>)Sources).Add(source); return (IConfigurationBuilder)(object)this; } public IConfigurationRoot Build() { List<IConfigurationProvider> val = new List<IConfigurationProvider>(); System.Collections.Generic.IEnumerator<IConfigurationSource> enumerator = ((System.Collections.Generic.IEnumerable<IConfigurationSource>)Sources).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSource current = enumerator.Current; IConfigurationProvider val2 = current.Build((IConfigurationBuilder)(object)this); val.Add(val2); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } return (IConfigurationRoot)(object)new ConfigurationRoot((System.Collections.Generic.IList<IConfigurationProvider>)val); } } public class ConfigurationKeyComparer : IComparer<string> { private const char KeyDelimiter = ':'; [field: CompilerGenerated] public static ConfigurationKeyComparer Instance { [CompilerGenerated] get; } = new ConfigurationKeyComparer(); [field: CompilerGenerated] internal static Comparison<string> Comparison { [CompilerGenerated] get; } public int Compare(string? x, string? y) { System.ReadOnlySpan<char> a2 = MemoryExtensions.AsSpan(x); System.ReadOnlySpan<char> a3 = MemoryExtensions.AsSpan(y); a2 = SkipAheadOnDelimiter(a2); a3 = SkipAheadOnDelimiter(a3); while (!a2.IsEmpty && !a3.IsEmpty) { int num = MemoryExtensions.IndexOf<char>(a2, ':'); int num2 = MemoryExtensions.IndexOf<char>(a3, ':'); int num3 = Compare((num == -1) ? a2 : a2.Slice(0, num), (num2 == -1) ? a3 : a3.Slice(0, num2)); if (num3 != 0) { return num3; } a2 = ((num == -1) ? default(System.ReadOnlySpan<char>) : SkipAheadOnDelimiter(a2.Slice(num + 1))); a3 = ((num2 == -1) ? default(System.ReadOnlySpan<char>) : SkipAheadOnDelimiter(a3.Slice(num2 + 1))); } if (!a2.IsEmpty) { return 1; } if (!a3.IsEmpty) { return -1; } return 0; [CompilerGenerated] static int Compare(System.ReadOnlySpan<char> a, System.ReadOnlySpan<char> b) { int num4 = default(int); bool flag = int.TryParse(a, ref num4); int num5 = default(int); bool flag2 = int.TryParse(b, ref num5); if (!flag && !flag2) { return MemoryExtensions.CompareTo(a, b, (StringComparison)5); } if (flag && flag2) { return num4 - num5; } return (!flag) ? 1 : (-1); } [CompilerGenerated] static unsafe System.ReadOnlySpan<char> SkipAheadOnDelimiter(System.ReadOnlySpan<char> a) { while (!a.IsEmpty && *(ushort*)a[0] == 58) { a = a.Slice(1); } return a; } } static ConfigurationKeyComparer() { ConfigurationKeyComparer instance = Instance; Comparison = instance.Compare; } } [DefaultMember("Item")] public sealed class ConfigurationManager : IConfigurationBuilder, IConfigurationRoot, IConfiguration, System.IDisposable { [DefaultMember("Item")] private sealed class ConfigurationSources : System.Collections.Generic.IList<IConfigurationSource>, System.Collections.Generic.ICollection<IConfigurationSource>, System.Collections.Generic.IEnumerable<IConfigurationSource>, System.Collections.IEnumerable { private readonly List<IConfigurationSource> _sources = new List<IConfigurationSource>(); private readonly ConfigurationManager _config; public IConfigurationSource this[int index] { get { return _sources[index]; } set { _sources[index] = value; _config.ReloadSources(); } } public int Count => _sources.Count; public bool IsReadOnly => false; public ConfigurationSources(ConfigurationManager config) { _config = config; } public void Add(IConfigurationSource source) { _sources.Add(source); _config.AddSource(source); } public void Clear() { _sources.Clear(); _config.ReloadSources(); } public bool Contains(IConfigurationSource source) { return _sources.Contains(source); } public void CopyTo(IConfigurationSource[] array, int arrayIndex) { _sources.CopyTo(array, arrayIndex); } public System.Collections.Generic.IEnumerator<IConfigurationSource> GetEnumerator() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return (System.Collections.Generic.IEnumerator<IConfigurationSource>)(object)_sources.GetEnumerator(); } public int IndexOf(IConfigurationSource source) { return _sources.IndexOf(source); } public void Insert(int index, IConfigurationSource source) { _sources.Insert(index, source); _config.ReloadSources(); } public bool Remove(IConfigurationSource source) { bool result = _sources.Remove(source); _config.ReloadSources(); return result; } public void RemoveAt(int index) { _sources.RemoveAt(index); _config.ReloadSources(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } [DefaultMember("Item")] private sealed class ConfigurationBuilderProperties : IDictionary<string, object>, System.Collections.Generic.ICollection<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable { private readonly Dictionary<string, object> _properties = new Dictionary<string, object>(); private readonly ConfigurationManager _config; public object this[string key] { get { return _properties[key]; } set { _properties[key] = value; _config.ReloadSources(); } } public System.Collections.Generic.ICollection<string> Keys => (System.Collections.Generic.ICollection<string>)_properties.Keys; public System.Collections.Generic.ICollection<object> Values => (System.Collections.Generic.ICollection<object>)_properties.Values; public int Count => _properties.Count; public bool IsReadOnly => false; public ConfigurationBuilderProperties(ConfigurationManager config) { _config = config; } public void Add(string key, object value) { _properties.Add(key, value); _config.ReloadSources(); } public void Add(KeyValuePair<string, object> item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) ((System.Collections.Generic.ICollection<KeyValuePair<string, object>>)_properties).Add(item); _config.ReloadSources(); } public void Clear() { _properties.Clear(); _config.ReloadSources(); } public bool Contains(KeyValuePair<string, object> item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return Enumerable.Contains<KeyValuePair<string, object>>((System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>)_properties, item); } public bool ContainsKey(string key) { return _properties.ContainsKey(key); } public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { ((System.Collections.Generic.ICollection<KeyValuePair<string, object>>)_properties).CopyTo(array, arrayIndex); } public System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return (System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>)(object)_properties.GetEnumerator(); } public bool Remove(string key) { bool result = _properties.Remove(key); _config.ReloadSources(); return result; } public bool Remove(KeyValuePair<string, object> item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) bool result = ((System.Collections.Generic.ICollection<KeyValuePair<string, object>>)_properties).Remove(item); _config.ReloadSources(); return result; } public bool TryGetValue(string key, [NotNullWhen(true)] out object value) { return _properties.TryGetValue(key, ref value); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return (System.Collections.IEnumerator)(object)_properties.GetEnumerator(); } } private readonly ConfigurationSources _sources; private readonly ConfigurationBuilderProperties _properties; private readonly ReferenceCountedProviderManager _providerManager = new ReferenceCountedProviderManager(); private readonly List<System.IDisposable> _changeTokenRegistrations = new List<System.IDisposable>(); private ConfigurationReloadToken _changeToken = new ConfigurationReloadToken(); public string? this[string key] { get { using ReferenceCountedProviders referenceCountedProviders = _providerManager.GetReference(); return ConfigurationRoot.GetConfiguration((System.Collections.Generic.IList<IConfigurationProvider>)referenceCountedProviders.Providers, key); } set { using ReferenceCountedProviders referenceCountedProviders = _providerManager.GetReference(); ConfigurationRoot.SetConfiguration((System.Collections.Generic.IList<IConfigurationProvider>)referenceCountedProviders.Providers, key, value); } } IDictionary<string, object> IConfigurationBuilder.Properties => _properties; public System.Collections.Generic.IList<IConfigurationSource> Sources => _sources; System.Collections.Generic.IEnumerable<IConfigurationProvider> IConfigurationRoot.Providers => _providerManager.NonReferenceCountedProviders; public ConfigurationManager() { _sources = new ConfigurationSources(this); _properties = new ConfigurationBuilderProperties(this); _sources.Add((IConfigurationSource)(object)new MemoryConfigurationSource()); } public IConfigurationSection GetSection(string key) { return (IConfigurationSection)(object)new ConfigurationSection((IConfigurationRoot)(object)this, key); } public System.Collections.Generic.IEnumerable<IConfigurationSection> GetChildren() { return ((IConfigurationRoot)(object)this).GetChildrenImplementation(null); } public void Dispose() { DisposeRegistrations(); _providerManager.Dispose(); } IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source) { ThrowHelper.ThrowIfNull(source, "source"); _sources.Add(source); return (IConfigurationBuilder)(object)this; } IConfigurationRoot IConfigurationBuilder.Build() { return (IConfigurationRoot)(object)this; } IChangeToken IConfiguration.GetReloadToken() { return (IChangeToken)(object)_changeToken; } void IConfigurationRoot.Reload() { //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) using (ReferenceCountedProviders referenceCountedProviders = _providerManager.GetReference()) { Enumerator<IConfigurationProvider> enumerator = referenceCountedProviders.Providers.GetEnumerator(); try { while (enumerator.MoveNext()) { IConfigurationProvider current = enumerator.Current; current.Load(); } } finally { ((System.IDisposable)enumerator).Dispose(); } } RaiseChanged(); } internal ReferenceCountedProviders GetProvidersReference() { return _providerManager.GetReference(); } private void RaiseChanged() { ConfigurationReloadToken configurationReloadToken = Interlocked.Exchange<ConfigurationReloadToken>(ref _changeToken, new ConfigurationReloadToken()); configurationReloadToken.OnReload(); } private void AddSource(IConfigurationSource source) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown IConfigurationProvider val = source.Build((IConfigurationBuilder)(object)this); val.Load(); _changeTokenRegistrations.Add(ChangeToken.OnChange((Func<IChangeToken>)val.GetReloadToken, new Action(RaiseChanged))); _providerManager.AddProvider(val); RaiseChanged(); } private void ReloadSources() { //IL_004e: 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_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown DisposeRegistrations(); _changeTokenRegistrations.Clear(); List<IConfigurationProvider> val = new List<IConfigurationProvider>(); System.Collections.Generic.IEnumerator<IConfigurationSource> enumerator = _sources.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSource current = enumerator.Current; val.Add(current.Build((IConfigurationBuilder)(object)this)); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } Enumerator<IConfigurationProvider> enumerator2 = val.GetEnumerator(); try { while (enumerator2.MoveNext()) { IConfigurationProvider current2 = enumerator2.Current; current2.Load(); _changeTokenRegistrations.Add(ChangeToken.OnChange((Func<IChangeToken>)current2.GetReloadToken, new Action(RaiseChanged))); } } finally { ((System.IDisposable)enumerator2).Dispose(); } _providerManager.ReplaceProviders(val); RaiseChanged(); } private void DisposeRegistrations() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<System.IDisposable> enumerator = _changeTokenRegistrations.GetEnumerator(); try { while (enumerator.MoveNext()) { System.IDisposable current = enumerator.Current; current.Dispose(); } } finally { ((System.IDisposable)enumerator).Dispose(); } } } public abstract class ConfigurationProvider : IConfigurationProvider { private ConfigurationReloadToken _reloadToken = new ConfigurationReloadToken(); [field: CompilerGenerated] protected IDictionary<string, string?> Data { [CompilerGenerated] get; [CompilerGenerated] set; } protected ConfigurationProvider() { Data = (IDictionary<string, string?>)(object)new Dictionary<string, string>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); } public virtual bool TryGet(string key, out string? value) { return Data.TryGetValue(key, ref value); } public virtual void Set(string key, string? value) { Data[key] = value; } public virtual void Load() { } public virtual System.Collections.Generic.IEnumerable<string> GetChildKeys(System.Collections.Generic.IEnumerable<string> earlierKeys, string? parentPath) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: 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) List<string> val = new List<string>(); if (parentPath == null) { System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator = ((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)Data).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { val.Add(Segment(enumerator.Current.Key, 0)); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } else { System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator2 = ((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)Data).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator2).MoveNext()) { KeyValuePair<string, string> current = enumerator2.Current; if (current.Key.Length > parentPath.Length && current.Key.StartsWith(parentPath, (StringComparison)5) && current.Key[parentPath.Length] == ':') { val.Add(Segment(current.Key, parentPath.Length + 1)); } } } finally { ((System.IDisposable)enumerator2)?.Dispose(); } } val.AddRange(earlierKeys); val.Sort(ConfigurationKeyComparer.Comparison); return (System.Collections.Generic.IEnumerable<string>)val; } private static string Segment(string key, int prefixLength) { int num = key.IndexOf(ConfigurationPath.KeyDelimiter, prefixLength, (StringComparison)5); if (num >= 0) { return key.Substring(prefixLength, num - prefixLength); } return key.Substring(prefixLength); } public IChangeToken GetReloadToken() { return (IChangeToken)(object)_reloadToken; } protected void OnReload() { ConfigurationReloadToken configurationReloadToken = Interlocked.Exchange<ConfigurationReloadToken>(ref _reloadToken, new ConfigurationReloadToken()); configurationReloadToken.OnReload(); } public override string ToString() { return ((MemberInfo)base.GetType()).Name ?? ""; } } public class ConfigurationReloadToken : IChangeToken { private CancellationTokenSource _cts = new CancellationTokenSource(); public bool ActiveChangeCallbacks => true; public bool HasChanged => _cts.IsCancellationRequested; public System.IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) CancellationToken token = _cts.Token; return (System.IDisposable)(object)((CancellationToken)(ref token)).Register(callback, state); } public void OnReload() { _cts.Cancel(); } } [DefaultMember("Item")] public class ConfigurationRoot : IConfigurationRoot, IConfiguration, System.IDisposable { private readonly System.Collections.Generic.IList<IConfigurationProvider> _providers; private readonly System.Collections.Generic.IList<System.IDisposable> _changeTokenRegistrations; private ConfigurationReloadToken _changeToken = new ConfigurationReloadToken(); public System.Collections.Generic.IEnumerable<IConfigurationProvider> Providers => (System.Collections.Generic.IEnumerable<IConfigurationProvider>)_providers; public string? this[string key] { get { return GetConfiguration(_providers, key); } set { SetConfiguration(_providers, key, value); } } public ConfigurationRoot(System.Collections.Generic.IList<IConfigurationProvider> providers) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown ThrowHelper.ThrowIfNull(providers, "providers"); _providers = providers; _changeTokenRegistrations = (System.Collections.Generic.IList<System.IDisposable>)new List<System.IDisposable>(((System.Collections.Generic.ICollection<IConfigurationProvider>)providers).Count); System.Collections.Generic.IEnumerator<IConfigurationProvider> enumerator = ((System.Collections.Generic.IEnumerable<IConfigurationProvider>)providers).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationProvider current = enumerator.Current; current.Load(); ((System.Collections.Generic.ICollection<System.IDisposable>)_changeTokenRegistrations).Add(ChangeToken.OnChange((Func<IChangeToken>)current.GetReloadToken, new Action(RaiseChanged))); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public System.Collections.Generic.IEnumerable<IConfigurationSection> GetChildren() { return ((IConfigurationRoot)(object)this).GetChildrenImplementation(null); } public IChangeToken GetReloadToken() { return (IChangeToken)(object)_changeToken; } public IConfigurationSection GetSection(string key) { return (IConfigurationSection)(object)new ConfigurationSection((IConfigurationRoot)(object)this, key); } public void Reload() { System.Collections.Generic.IEnumerator<IConfigurationProvider> enumerator = ((System.Collections.Generic.IEnumerable<IConfigurationProvider>)_providers).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationProvider current = enumerator.Current; current.Load(); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } RaiseChanged(); } private void RaiseChanged() { ConfigurationReloadToken configurationReloadToken = Interlocked.Exchange<ConfigurationReloadToken>(ref _changeToken, new ConfigurationReloadToken()); configurationReloadToken.OnReload(); } public void Dispose() { System.Collections.Generic.IEnumerator<System.IDisposable> enumerator = ((System.Collections.Generic.IEnumerable<System.IDisposable>)_changeTokenRegistrations).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { System.IDisposable current = enumerator.Current; current.Dispose(); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } System.Collections.Generic.IEnumerator<IConfigurationProvider> enumerator2 = ((System.Collections.Generic.IEnumerable<IConfigurationProvider>)_providers).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator2).MoveNext()) { IConfigurationProvider current2 = enumerator2.Current; (current2 as System.IDisposable)?.Dispose(); } } finally { ((System.IDisposable)enumerator2)?.Dispose(); } } internal static string? GetConfiguration(System.Collections.Generic.IList<IConfigurationProvider> providers, string key) { string result = default(string); for (int num = ((System.Collections.Generic.ICollection<IConfigurationProvider>)providers).Count - 1; num >= 0; num--) { IConfigurationProvider val = providers[num]; if (val.TryGet(key, ref result)) { return result; } } return null; } internal static void SetConfiguration(System.Collections.Generic.IList<IConfigurationProvider> providers, string key, string? value) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (((System.Collections.Generic.ICollection<IConfigurationProvider>)providers).Count == 0) { throw new InvalidOperationException(System.SR.Error_NoSources); } System.Collections.Generic.IEnumerator<IConfigurationProvider> enumerator = ((System.Collections.Generic.IEnumerable<IConfigurationProvider>)providers).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationProvider current = enumerator.Current; current.Set(key, value); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } [DefaultMember("Item")] public class ConfigurationSection : IConfigurationSection, IConfiguration { private readonly IConfigurationRoot _root; private readonly string _path; private string _key; public string Path => _path; public string Key => _key ?? (_key = ConfigurationPath.GetSectionKey(_path)); public string? Value { get { return ((IConfiguration)_root)[Path]; } set { ((IConfiguration)_root)[Path] = value; } } public string? this[string key] { get { return ((IConfiguration)_root)[ConfigurationPath.Combine(new string[2] { Path, key })]; } set { ((IConfiguration)_root)[ConfigurationPath.Combine(new string[2] { Path, key })] = value; } } public ConfigurationSection(IConfigurationRoot root, string path) { ThrowHelper.ThrowIfNull(root, "root"); ThrowHelper.ThrowIfNull(path, "path"); _root = root; _path = path; } public IConfigurationSection GetSection(string key) { return ((IConfiguration)_root).GetSection(ConfigurationPath.Combine(new string[2] { Path, key })); } public System.Collections.Generic.IEnumerable<IConfigurationSection> GetChildren() { return _root.GetChildrenImplementation(Path); } public IChangeToken GetReloadToken() { return ((IConfiguration)_root).GetReloadToken(); } } internal static class InternalConfigurationRootExtensions { internal static System.Collections.Generic.IEnumerable<IConfigurationSection> GetChildrenImplementation(this IConfigurationRoot root, string? path) { string path2 = path; IConfigurationRoot root2 = root; using ReferenceCountedProviders referenceCountedProviders = (root2 as ConfigurationManager)?.GetProvidersReference(); System.Collections.Generic.IEnumerable<IConfigurationProvider> enumerable = (System.Collections.Generic.IEnumerable<IConfigurationProvider>)(referenceCountedProviders?.Providers); System.Collections.Generic.IEnumerable<IConfigurationProvider> enumerable2 = enumerable ?? root2.Providers; System.Collections.Generic.IEnumerable<IConfigurationSection> enumerable3 = Enumerable.Select<string, IConfigurationSection>(Enumerable.Distinct<string>(Enumerable.Aggregate<IConfigurationProvider, System.Collections.Generic.IEnumerable<string>>(enumerable2, Enumerable.Empty<string>(), (Func<System.Collections.Generic.IEnumerable<string>, IConfigurationProvider, System.Collections.Generic.IEnumerable<string>>)((System.Collections.Generic.IEnumerable<string> seed, IConfigurationProvider source) => source.GetChildKeys(seed, path2))), (IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase), (Func<string, IConfigurationSection>)((string key) => ((IConfiguration)root2).GetSection((path2 == null) ? key : ConfigurationPath.Combine(new string[2] { path2, key })))); if (referenceCountedProviders == null) { return enumerable3; } return (System.Collections.Generic.IEnumerable<IConfigurationSection>)Enumerable.ToList<IConfigurationSection>(enumerable3); } } public static class MemoryConfigurationBuilderExtensions { public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder) { ThrowHelper.ThrowIfNull(configurationBuilder, "configurationBuilder"); configurationBuilder.Add((IConfigurationSource)(object)new MemoryConfigurationSource()); return configurationBuilder; } public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder, System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>>? initialData) { ThrowHelper.ThrowIfNull(configurationBuilder, "configurationBuilder"); configurationBuilder.Add((IConfigurationSource)(object)new MemoryConfigurationSource { InitialData = initialData }); return configurationBuilder; } } internal abstract class ReferenceCountedProviders : System.IDisposable { private sealed class ActiveReferenceCountedProviders : ReferenceCountedProviders { private long _refCount = 1L; private volatile List<IConfigurationProvider> _providers; public override List<IConfigurationProvider> Providers { get { return _providers; } set { _providers = value; } } public override List<IConfigurationProvider> NonReferenceCountedProviders => _providers; public ActiveReferenceCountedProviders(List<IConfigurationProvider> providers) { _providers = providers; } public override void AddReference() { Interlocked.Increment(ref _refCount); } public override void Dispose() { //IL_0015: 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) if (Interlocked.Decrement(ref _refCount) != 0L) { return; } Enumerator<IConfigurationProvider> enumerator = _providers.GetEnumerator(); try { while (enumerator.MoveNext()) { IConfigurationProvider current = enumerator.Current; (current as System.IDisposable)?.Dispose(); } } finally { ((System.IDisposable)enumerator).Dispose(); } } } private sealed class DisposedReferenceCountedProviders : ReferenceCountedProviders { [field: CompilerGenerated] public override List<IConfigurationProvider> Providers { [CompilerGenerated] get; [CompilerGenerated] set; } public override List<IConfigurationProvider> NonReferenceCountedProviders => Providers; public DisposedReferenceCountedProviders(List<IConfigurationProvider> providers) { Providers = providers; } public override void AddReference() { } public override void Dispose() { } } public abstract List<IConfigurationProvider> Providers { get; set; } public abstract List<IConfigurationProvider> NonReferenceCountedProviders { get; } public static ReferenceCountedProviders Create(List<IConfigurationProvider> providers) { return new ActiveReferenceCountedProviders(providers); } public static ReferenceCountedProviders CreateDisposed(List<IConfigurationProvider> providers) { return new DisposedReferenceCountedProviders(providers); } public abstract void AddReference(); public abstract void Dispose(); } internal sealed class ReferenceCountedProviderManager : System.IDisposable { private readonly object _replaceProvidersLock = new object(); private ReferenceCountedProviders _refCountedProviders = ReferenceCountedProviders.Create(new List<IConfigurationProvider>()); private bool _disposed; public System.Collections.Generic.IEnumerable<IConfigurationProvider> NonReferenceCountedProviders => (System.Collections.Generic.IEnumerable<IConfigurationProvider>)_refCountedProviders.NonReferenceCountedProviders; public ReferenceCountedProviders GetReference() { lock (_replaceProvidersLock) { if (_disposed) { return ReferenceCountedProviders.CreateDisposed(_refCountedProviders.NonReferenceCountedProviders); } _refCountedProviders.AddReference(); return _refCountedProviders; } } public void ReplaceProviders(List<IConfigurationProvider> providers) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) ReferenceCountedProviders refCountedProviders = _refCountedProviders; lock (_replaceProvidersLock) { if (_disposed) { throw new ObjectDisposedException("ConfigurationManager"); } _refCountedProviders = ReferenceCountedProviders.Create(providers); } refCountedProviders.Dispose(); } public void AddProvider(IConfigurationProvider provider) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) lock (_replaceProvidersLock) { if (_disposed) { throw new ObjectDisposedException("ConfigurationManager"); } ReferenceCountedProviders refCountedProviders = _refCountedProviders; List<IConfigurationProvider> obj = new List<IConfigurationProvider>((System.Collections.Generic.IEnumerable<IConfigurationProvider>)_refCountedProviders.Providers); obj.Add(provider); refCountedProviders.Providers = obj; } } public void Dispose() { ReferenceCountedProviders refCountedProviders = _refCountedProviders; lock (_replaceProvidersLock) { _disposed = true; } refCountedProviders.Dispose(); } } public abstract class StreamConfigurationProvider : ConfigurationProvider { private bool _loaded; [field: CompilerGenerated] public StreamConfigurationSource Source { [CompilerGenerated] get; } public StreamConfigurationProvider(StreamConfigurationSource source) { ThrowHelper.ThrowIfNull(source, "source"); Source = source; } public abstract void Load(Stream stream); public override void Load() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (_loaded) { throw new InvalidOperationException(System.SR.StreamConfigurationProvidersAlreadyLoaded); } if (Source.Stream == null) { throw new InvalidOperationException(System.SR.StreamConfigurationSourceStreamCannotBeNull); } Load(Source.Stream); _loaded = true; } } public abstract class StreamConfigurationSource : IConfigurationSource { [field: CompilerGenerated] public Stream? Stream { [CompilerGenerated] get; [CompilerGenerated] [param: DisallowNull] set; } public abstract IConfigurationProvider Build(IConfigurationBuilder builder); } } namespace Microsoft.Extensions.Configuration.Memory { public class MemoryConfigurationProvider : ConfigurationProvider, System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>>, System.Collections.IEnumerable { private readonly MemoryConfigurationSource _source; public MemoryConfigurationProvider(MemoryConfigurationSource source) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(source, "source"); _source = source; if (_source.InitialData == null) { return; } System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator = _source.InitialData.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, string> current = enumerator.Current; base.Data.Add(current.Key, current.Value); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public void Add(string key, string? value) { base.Data.Add(key, value); } public System.Collections.Generic.IEnumerator<KeyValuePair<string, string?>> GetEnumerator() { return ((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)base.Data).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } public class MemoryConfigurationSource : IConfigurationSource { [field: CompilerGenerated] public System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>>? InitialData { [CompilerGenerated] get; [CompilerGenerated] set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return (IConfigurationProvider)(object)new MemoryConfigurationProvider(this); } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Configuration.EnvironmentVariables.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration.EnvironmentVariables; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.EnvironmentVariables.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.EnvironmentVariables")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Environment variables configuration provider implementation for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.EnvironmentVariables")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Microsoft.Extensions.Configuration { public static class EnvironmentVariablesExtensions { public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder configurationBuilder) { configurationBuilder.Add((IConfigurationSource)(object)new EnvironmentVariablesConfigurationSource()); return configurationBuilder; } public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder configurationBuilder, string? prefix) { configurationBuilder.Add((IConfigurationSource)(object)new EnvironmentVariablesConfigurationSource { Prefix = prefix }); return configurationBuilder; } public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action<EnvironmentVariablesConfigurationSource>? configureSource) { return ConfigurationExtensions.Add<EnvironmentVariablesConfigurationSource>(builder, configureSource); } } } namespace Microsoft.Extensions.Configuration.EnvironmentVariables { public class EnvironmentVariablesConfigurationProvider : ConfigurationProvider { private const string MySqlServerPrefix = "MYSQLCONNSTR_"; private const string SqlAzureServerPrefix = "SQLAZURECONNSTR_"; private const string SqlServerPrefix = "SQLCONNSTR_"; private const string CustomConnectionStringPrefix = "CUSTOMCONNSTR_"; private readonly string _prefix; private readonly string _normalizedPrefix; public EnvironmentVariablesConfigurationProvider() { _prefix = string.Empty; _normalizedPrefix = string.Empty; } public EnvironmentVariablesConfigurationProvider(string? prefix) { _prefix = prefix ?? string.Empty; _normalizedPrefix = Normalize(_prefix); } public override void Load() { Load(Environment.GetEnvironmentVariables()); } public override string ToString() { return ((MemberInfo)((object)this).GetType()).Name + " Prefix: '" + _prefix + "'"; } internal void Load(IDictionary envVariables) { //IL_0018: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, string> data = new Dictionary<string, string>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); IDictionaryEnumerator enumerator = envVariables.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { DictionaryEntry entry = enumerator.Entry; string text = (string)((DictionaryEntry)(ref entry)).Key; entry = enumerator.Entry; string value = (string)((DictionaryEntry)(ref entry)).Value; if (text.StartsWith("MYSQLCONNSTR_", (StringComparison)5)) { HandleMatchedConnectionStringPrefix(data, "MYSQLCONNSTR_", "MySql.Data.MySqlClient", text, value); } else if (text.StartsWith("SQLAZURECONNSTR_", (StringComparison)5)) { HandleMatchedConnectionStringPrefix(data, "SQLAZURECONNSTR_", "System.Data.SqlClient", text, value); } else if (text.StartsWith("SQLCONNSTR_", (StringComparison)5)) { HandleMatchedConnectionStringPrefix(data, "SQLCONNSTR_", "System.Data.SqlClient", text, value); } else if (text.StartsWith("CUSTOMCONNSTR_", (StringComparison)5)) { HandleMatchedConnectionStringPrefix(data, "CUSTOMCONNSTR_", null, text, value); } else { AddIfNormalizedKeyMatchesPrefix(data, Normalize(text), value); } } } finally { (enumerator as System.IDisposable)?.Dispose(); } ((ConfigurationProvider)this).Data = (IDictionary<string, string>)(object)data; } private void HandleMatchedConnectionStringPrefix(Dictionary<string, string> data, string connectionStringPrefix, string provider, string fullKey, string value) { string text = Normalize(fullKey.Substring(connectionStringPrefix.Length)); AddIfNormalizedKeyMatchesPrefix(data, "ConnectionStrings:" + text, value); if (provider != null) { AddIfNormalizedKeyMatchesPrefix(data, "ConnectionStrings:" + text + "_ProviderName", provider); } } private void AddIfNormalizedKeyMatchesPrefix(Dictionary<string, string> data, string normalizedKey, string value) { if (normalizedKey.StartsWith(_normalizedPrefix, (StringComparison)5)) { data[normalizedKey.Substring(_normalizedPrefix.Length)] = value; } } private static string Normalize(string key) { return key.Replace("__", ConfigurationPath.KeyDelimiter); } } public class EnvironmentVariablesConfigurationSource : IConfigurationSource { [field: CompilerGenerated] public string? Prefix { [CompilerGenerated] get; [CompilerGenerated] set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return (IConfigurationProvider)(object)new EnvironmentVariablesConfigurationProvider(Prefix); } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Configuration.FileExtensions.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using FxResources.Microsoft.Extensions.Configuration.FileExtensions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.FileExtensions.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.FileExtensions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Extension methods for configuring file-based configuration providers for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.FileExtensions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.FileExtensions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Configuration.FileExtensions.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string Error_ExpectedPhysicalPath => GetResourceString("Error_ExpectedPhysicalPath"); internal static string Error_FileNotFound => GetResourceString("Error_FileNotFound"); internal static string Error_FailedToLoad => GetResourceString("Error_FailedToLoad"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Configuration { public static class FileConfigurationExtensions { private static string FileProviderKey = "FileProvider"; private static string FileLoadExceptionHandlerKey = "FileLoadExceptionHandler"; public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder builder, IFileProvider fileProvider) { ThrowHelper.ThrowIfNull(builder, "builder"); ThrowHelper.ThrowIfNull(fileProvider, "fileProvider"); builder.Properties[FileProviderKey] = fileProvider; return builder; } public static IFileProvider GetFileProvider(this IConfigurationBuilder builder) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown ThrowHelper.ThrowIfNull(builder, "builder"); object obj = default(object); if (!builder.Properties.TryGetValue(FileProviderKey, ref obj)) { return (IFileProvider)new PhysicalFileProvider(AppContext.BaseDirectory ?? string.Empty); } return (IFileProvider)obj; } public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder builder, string basePath) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown ThrowHelper.ThrowIfNull(builder, "builder"); ThrowHelper.ThrowIfNull(basePath, "basePath"); return builder.SetFileProvider((IFileProvider)new PhysicalFileProvider(basePath)); } public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurationBuilder builder, Action<FileLoadExceptionContext> handler) { ThrowHelper.ThrowIfNull(builder, "builder"); builder.Properties[FileLoadExceptionHandlerKey] = handler; return builder; } public static Action<FileLoadExceptionContext>? GetFileLoadExceptionHandler(this IConfigurationBuilder builder) { ThrowHelper.ThrowIfNull(builder, "builder"); object obj = default(object); if (builder.Properties.TryGetValue(FileLoadExceptionHandlerKey, ref obj)) { return obj as Action<FileLoadExceptionContext>; } return null; } } public abstract class FileConfigurationProvider : ConfigurationProvider, System.IDisposable { private readonly System.IDisposable _changeTokenRegistration; [field: CompilerGenerated] public FileConfigurationSource Source { [CompilerGenerated] get; } public FileConfigurationProvider(FileConfigurationSource source) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown ThrowHelper.ThrowIfNull(source, "source"); Source = source; if (Source.ReloadOnChange && Source.FileProvider != null) { _changeTokenRegistration = ChangeToken.OnChange((Func<IChangeToken>)([CompilerGenerated] () => Source.FileProvider.Watch(Source.Path)), (Action)([CompilerGenerated] () => { Thread.Sleep(Source.ReloadDelay); Load(reload: true); })); } } public override string ToString() { return $"{((MemberInfo)((object)this).GetType()).Name} for '{Source.Path}' ({(Source.Optional ? "Optional" : "Required")})"; } private void Load(bool reload) { //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected O, but got Unknown IFileProvider? fileProvider = Source.FileProvider; IFileInfo val = ((fileProvider != null) ? fileProvider.GetFileInfo(Source.Path ?? string.Empty) : null); if (val == null || !val.Exists) { if (Source.Optional || reload) { ((ConfigurationProvider)this).Data = (IDictionary<string, string>)(object)new Dictionary<string, string>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); } else { StringBuilder val2 = new StringBuilder(System.SR.Format(System.SR.Error_FileNotFound, (object?)Source.Path)); if (!string.IsNullOrEmpty((val != null) ? val.PhysicalPath : null)) { val2.Append(System.SR.Format(System.SR.Error_ExpectedPhysicalPath, (object?)val.PhysicalPath)); } HandleException(ExceptionDispatchInfo.Capture((System.Exception)new FileNotFoundException(((object)val2).ToString()))); } } else { Stream val3 = OpenRead(val); try { Load(val3); } catch (System.Exception ex) { if (reload) { ((ConfigurationProvider)this).Data = (IDictionary<string, string>)(object)new Dictionary<string, string>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); } InvalidDataException val4 = new InvalidDataException(System.SR.Format(System.SR.Error_FailedToLoad, (object?)val.PhysicalPath), ex); HandleException(ExceptionDispatchInfo.Capture((System.Exception)(object)val4)); } finally { ((System.IDisposable)val3)?.Dispose(); } } ((ConfigurationProvider)this).OnReload(); [CompilerGenerated] static Stream OpenRead(IFileInfo fileInfo) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown if (fileInfo.PhysicalPath != null) { return (Stream)new FileStream(fileInfo.PhysicalPath, (FileMode)3, (FileAccess)1, (FileShare)3, 1, (FileOptions)134217728); } return fileInfo.CreateReadStream(); } } public override void Load() { Load(reload: false); } public abstract void Load(Stream stream); private void HandleException(ExceptionDispatchInfo info) { bool flag = false; if (Source.OnLoadException != null) { FileLoadExceptionContext fileLoadExceptionContext = new FileLoadExceptionContext { Provider = this, Exception = info.SourceException }; Source.OnLoadException.Invoke(fileLoadExceptionContext); flag = fileLoadExceptionContext.Ignore; } if (!flag) { info.Throw(); } } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { _changeTokenRegistration?.Dispose(); } } public abstract class FileConfigurationSource : IConfigurationSource { [field: CompilerGenerated] public IFileProvider? FileProvider { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string? Path { [CompilerGenerated] get; [CompilerGenerated] [param: DisallowNull] set; } [field: CompilerGenerated] public bool Optional { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public bool ReloadOnChange { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public int ReloadDelay { [CompilerGenerated] get; [CompilerGenerated] set; } = 250; [field: CompilerGenerated] public Action<FileLoadExceptionContext>? OnLoadException { [CompilerGenerated] get; [CompilerGenerated] set; } public abstract IConfigurationProvider Build(IConfigurationBuilder builder); public void EnsureDefaults(IConfigurationBuilder builder) { if (FileProvider == null) { IFileProvider val = (FileProvider = builder.GetFileProvider()); } if (OnLoadException == null) { Action<FileLoadExceptionContext> val2 = (OnLoadException = builder.GetFileLoadExceptionHandler()); } } public void ResolveFileProvider() { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown if (FileProvider == null && !string.IsNullOrEmpty(Path) && Path.IsPathRooted(Path)) { string directoryName = Path.GetDirectoryName(Path); string text = Path.GetFileName(Path); while (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { text = Path.Combine(Path.GetFileName(directoryName), text); directoryName = Path.GetDirectoryName(directoryName); } if (Directory.Exists(directoryName)) { FileProvider = (IFileProvider?)new PhysicalFileProvider(directoryName); Path = text; } } } } public class FileLoadExceptionContext { [field: CompilerGenerated] public FileConfigurationProvider Provider { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public System.Exception Exception { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public bool Ignore { [CompilerGenerated] get; [CompilerGenerated] set; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Configuration.Json.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Json; using FxResources.Microsoft.Extensions.Configuration.Json; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.FileProviders; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("JSON configuration provider implementation for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.Json")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(8, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.Json { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Configuration.Json.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string Error_InvalidFilePath => GetResourceString("Error_InvalidFilePath"); internal static string Error_InvalidTopLevelJSONElement => GetResourceString("Error_InvalidTopLevelJSONElement"); internal static string Error_JSONParseError => GetResourceString("Error_JSONParseError"); internal static string Error_KeyIsDuplicated => GetResourceString("Error_KeyIsDuplicated"); internal static string Error_UnsupportedJSONToken => GetResourceString("Error_UnsupportedJSONToken"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Configuration { public static class JsonConfigurationExtensions { public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, string path) { return builder.AddJsonFile(null, path, optional: false, reloadOnChange: false); } public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, string path, bool optional) { return builder.AddJsonFile(null, path, optional, reloadOnChange: false); } public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) { return builder.AddJsonFile(null, path, optional, reloadOnChange); } public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) IFileProvider provider2 = provider; string path2 = path; ThrowHelper.ThrowIfNull(builder, "builder"); if (string.IsNullOrEmpty(path2)) { throw new ArgumentException(System.SR.Error_InvalidFilePath, "path"); } return builder.AddJsonFile(delegate(JsonConfigurationSource s) { ((FileConfigurationSource)s).FileProvider = provider2; ((FileConfigurationSource)s).Path = path2; ((FileConfigurationSource)s).Optional = optional; ((FileConfigurationSource)s).ReloadOnChange = reloadOnChange; ((FileConfigurationSource)s).ResolveFileProvider(); }); } public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, Action<JsonConfigurationSource>? configureSource) { return ConfigurationExtensions.Add<JsonConfigurationSource>(builder, configureSource); } public static IConfigurationBuilder AddJsonStream(this IConfigurationBuilder builder, Stream stream) { Stream stream2 = stream; ThrowHelper.ThrowIfNull(builder, "builder"); return ConfigurationExtensions.Add<JsonStreamConfigurationSource>(builder, (Action<JsonStreamConfigurationSource>)delegate(JsonStreamConfigurationSource s) { ((StreamConfigurationSource)s).Stream = stream2; }); } } } namespace Microsoft.Extensions.Configuration.Json { internal sealed class JsonConfigurationFileParser { private readonly Dictionary<string, string> _data = new Dictionary<string, string>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); private readonly Stack<string> _paths = new Stack<string>(); private JsonConfigurationFileParser() { } public static IDictionary<string, string?> Parse(Stream input) { return new JsonConfigurationFileParser().ParseStream(input); } private IDictionary<string, string> ParseStream(Stream input) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Invalid comparison between Unknown and I4 //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: 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_005e: Unknown result type (might be due to invalid IL or missing references) JsonDocumentOptions val = default(JsonDocumentOptions); ((JsonDocumentOptions)(ref val)).CommentHandling = (JsonCommentHandling)1; ((JsonDocumentOptions)(ref val)).AllowTrailingCommas = true; JsonDocumentOptions val2 = val; StreamReader val3 = new StreamReader(input); try { JsonDocument val4 = JsonDocument.Parse(((TextReader)val3).ReadToEnd(), val2); try { JsonElement rootElement = val4.RootElement; if ((int)((JsonElement)(ref rootElement)).ValueKind != 1) { string error_InvalidTopLevelJSONElement = System.SR.Error_InvalidTopLevelJSONElement; rootElement = val4.RootElement; throw new FormatException(System.SR.Format(error_InvalidTopLevelJSONElement, ((JsonElement)(ref rootElement)).ValueKind)); } VisitObjectElement(val4.RootElement); } finally { ((System.IDisposable)val4)?.Dispose(); } } finally { ((System.IDisposable)val3)?.Dispose(); } return (IDictionary<string, string>)(object)_data; } private void VisitObjectElement(JsonElement element) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) bool nullIfElementIsEmpty = true; ObjectEnumerator val = ((JsonElement)(ref element)).EnumerateObject(); ObjectEnumerator enumerator = ((ObjectEnumerator)(ref val)).GetEnumerator(); try { while (((ObjectEnumerator)(ref enumerator)).MoveNext()) { JsonProperty current = ((ObjectEnumerator)(ref enumerator)).Current; nullIfElementIsEmpty = false; EnterContext(((JsonProperty)(ref current)).Name); VisitValue(((JsonProperty)(ref current)).Value); ExitContext(); } } finally { ((System.IDisposable)(ObjectEnumerator)(ref enumerator)).Dispose(); } SetNullIfElementIsEmpty(nullIfElementIsEmpty); } private void VisitArrayElement(JsonElement element) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) int num = 0; ArrayEnumerator val = ((JsonElement)(ref element)).EnumerateArray(); ArrayEnumerator enumerator = ((ArrayEnumerator)(ref val)).GetEnumerator(); try { while (((ArrayEnumerator)(ref enumerator)).MoveNext()) { JsonElement current = ((ArrayEnumerator)(ref enumerator)).Current; EnterContext(num.ToString()); VisitValue(current); ExitContext(); num++; } } finally { ((System.IDisposable)(ArrayEnumerator)(ref enumerator)).Dispose(); } SetNullIfElementIsEmpty(num == 0); } private void SetNullIfElementIsEmpty(bool isEmpty) { if (isEmpty && _paths.Count > 0) { _data[_paths.Peek()] = null; } } private void VisitValue(JsonElement value) { //IL_0002: 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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected I4, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) JsonValueKind valueKind = ((JsonElement)(ref value)).ValueKind; switch (valueKind - 1) { case 0: VisitObjectElement(value); break; case 1: VisitArrayElement(value); break; case 2: case 3: case 4: case 5: case 6: { string text = _paths.Peek(); if (_data.ContainsKey(text)) { throw new FormatException(System.SR.Format(System.SR.Error_KeyIsDuplicated, (object?)text)); } _data[text] = ((object)(JsonElement)(ref value)).ToString(); break; } default: throw new FormatException(System.SR.Format(System.SR.Error_UnsupportedJSONToken, ((JsonElement)(ref value)).ValueKind)); } } private void EnterContext(string context) { _paths.Push((_paths.Count > 0) ? (_paths.Peek() + ConfigurationPath.KeyDelimiter + context) : context); } private void ExitContext() { _paths.Pop(); } } public class JsonConfigurationProvider : FileConfigurationProvider { public JsonConfigurationProvider(JsonConfigurationSource source) : base((FileConfigurationSource)(object)source) { } public override void Load(Stream stream) { //IL_000f: Expected O, but got Unknown //IL_0015: Unknown result type (might be due to invalid IL or missing references) try { ((ConfigurationProvider)this).Data = JsonConfigurationFileParser.Parse(stream); } catch (JsonException val) { JsonException val2 = val; throw new FormatException(System.SR.Error_JSONParseError, (System.Exception)(object)val2); } } } public class JsonConfigurationSource : FileConfigurationSource { public override IConfigurationProvider Build(IConfigurationBuilder builder) { ((FileConfigurationSource)this).EnsureDefaults(builder); return (IConfigurationProvider)(object)new JsonConfigurationProvider(this); } } public class JsonStreamConfigurationProvider : StreamConfigurationProvider { public JsonStreamConfigurationProvider(JsonStreamConfigurationSource source) : base((StreamConfigurationSource)(object)source) { } public override void Load(Stream stream) { ((ConfigurationProvider)this).Data = JsonConfigurationFileParser.Parse(stream); } } public class JsonStreamConfigurationSource : StreamConfigurationSource { public override IConfigurationProvider Build(IConfigurationBuilder builder) { return (IConfigurationProvider)(object)new JsonStreamConfigurationProvider(this); } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Configuration.UserSecrets.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using FxResources.Microsoft.Extensions.Configuration.UserSecrets; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration.UserSecrets; using Microsoft.Extensions.FileProviders; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.UserSecrets.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.UserSecrets")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("User secrets configuration provider implementation for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.UserSecrets")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.UserSecrets { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Configuration.UserSecrets.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string Common_StringNullOrEmpty => GetResourceString("Common_StringNullOrEmpty"); internal static string Error_Invalid_Character_In_UserSecrets_Id => GetResourceString("Error_Invalid_Character_In_UserSecrets_Id"); internal static string Error_Missing_UserSecretsIdAttribute => GetResourceString("Error_Missing_UserSecretsIdAttribute"); internal static string Error_Missing_UserSecretsLocation => GetResourceString("Error_Missing_UserSecretsLocation"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Configuration { public static class UserSecretsConfigurationExtensions { public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration) where T : class { return configuration.AddUserSecrets(typeof(T).Assembly, optional: true, reloadOnChange: false); } public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration, bool optional) where T : class { return configuration.AddUserSecrets(typeof(T).Assembly, optional, reloadOnChange: false); } public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration, bool optional, bool reloadOnChange) where T : class { return configuration.AddUserSecrets(typeof(T).Assembly, optional, reloadOnChange); } public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly) { return configuration.AddUserSecrets(assembly, optional: true, reloadOnChange: false); } public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly, bool optional) { return configuration.AddUserSecrets(assembly, optional, reloadOnChange: false); } public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly, bool optional, bool reloadOnChange) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(configuration, "configuration"); ThrowHelper.ThrowIfNull(assembly, "assembly"); UserSecretsIdAttribute customAttribute = CustomAttributeExtensions.GetCustomAttribute<UserSecretsIdAttribute>(assembly); if (customAttribute != null) { return AddUserSecretsInternal(configuration, customAttribute.UserSecretsId, optional, reloadOnChange); } if (!optional) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_Missing_UserSecretsIdAttribute, (object?)assembly.GetName().Name)); } return configuration; } public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, string userSecretsId) { return configuration.AddUserSecrets(userSecretsId, reloadOnChange: false); } public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, string userSecretsId, bool reloadOnChange) { return AddUserSecretsInternal(configuration, userSecretsId, optional: true, reloadOnChange); } private static IConfigurationBuilder AddUserSecretsInternal(IConfigurationBuilder configuration, string userSecretsId, bool optional, bool reloadOnChange) { ThrowHelper.ThrowIfNull(configuration, "configuration"); ThrowHelper.ThrowIfNull(userSecretsId, "userSecretsId"); return AddSecretsFile(configuration, PathHelper.InternalGetSecretsPathFromSecretsId(userSecretsId, !optional), optional, reloadOnChange); } private static IConfigurationBuilder AddSecretsFile(IConfigurationBuilder configuration, string secretPath, bool optional, bool reloadOnChange) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(secretPath)) { return configuration; } string directoryName = Path.GetDirectoryName(secretPath); PhysicalFileProvider val = ((!Directory.Exists(directoryName)) ? ((PhysicalFileProvider)null) : new PhysicalFileProvider(directoryName)); return JsonConfigurationExtensions.AddJsonFile(configuration, (IFileProvider)(object)val, "secrets.json", optional, reloadOnChange); } } } namespace Microsoft.Extensions.Configuration.UserSecrets { public class PathHelper { internal const string SecretsFileName = "secrets.json"; public static string GetSecretsPathFromSecretsId(string userSecretsId) { return InternalGetSecretsPathFromSecretsId(userSecretsId, throwIfNoRoot: true); } internal static string InternalGetSecretsPathFromSecretsId(string userSecretsId, bool throwIfNoRoot) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(userSecretsId)) { throw new ArgumentException(System.SR.Common_StringNullOrEmpty, "userSecretsId"); } int num = userSecretsId.IndexOfAny(Path.GetInvalidFileNameChars()); if (num != -1) { throw new InvalidOperationException(string.Format(System.SR.Error_Invalid_Character_In_UserSecrets_Id, (object)userSecretsId[num], (object)num)); } string environmentVariable = Environment.GetEnvironmentVariable("APPDATA"); string text = environmentVariable ?? Environment.GetEnvironmentVariable("HOME") ?? Environment.GetFolderPath((SpecialFolder)26) ?? Environment.GetFolderPath((SpecialFolder)40) ?? Environment.GetEnvironmentVariable("DOTNET_USER_SECRETS_FALLBACK_DIR"); if (string.IsNullOrEmpty(text)) { if (throwIfNoRoot) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_Missing_UserSecretsLocation, (object?)"DOTNET_USER_SECRETS_FALLBACK_DIR")); } return string.Empty; } if (string.IsNullOrEmpty(environmentVariable)) { return Path.Combine(new string[5] { text, ".microsoft", "usersecrets", userSecretsId, "secrets.json" }); } return Path.Combine(new string[5] { text, "Microsoft", "UserSecrets", userSecretsId, "secrets.json" }); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class UserSecretsIdAttribute : System.Attribute { [field: CompilerGenerated] public string UserSecretsId { [CompilerGenerated] get; } public UserSecretsIdAttribute(string userSecretId) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(userSecretId)) { throw new ArgumentException(System.SR.Common_StringNullOrEmpty, "userSecretId"); } UserSecretsId = userSecretId; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.DependencyInjection.Abstractions.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq.Expressions; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.DependencyInjection.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [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("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.DependencyInjection.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.DependencyInjection.Abstractions.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } 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"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Internal { internal static class ParameterDefaultValue { public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue) { bool tryToGetDefaultValue; bool flag = CheckHasDefaultValue(parameter, out tryToGetDefaultValue); defaultValue = null; if (flag) { if (tryToGetDefaultValue) { defaultValue = parameter.DefaultValue; } bool flag2 = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(System.Nullable<>); if (defaultValue == null && parameter.ParameterType.IsValueType && !flag2) { defaultValue = CreateValueType(parameter.ParameterType); } if (defaultValue != null && flag2) { System.Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType != (System.Type)null && underlyingType.IsEnum) { defaultValue = System.Enum.ToObject(underlyingType, defaultValue); } } } return flag; [CompilerGenerated] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")] static object? CreateValueType(System.Type t) { return RuntimeHelpers.GetUninitializedObject(t); } } public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue) { tryToGetDefaultValue = true; return parameter.HasDefaultValue; } } } namespace Microsoft.Extensions.DependencyInjection { public static class ActivatorUtilities { private struct ConstructorMatcher { private readonly ConstructorInfo _constructor; private readonly ParameterInfo[] _parameters; private readonly object[] _parameterValues; public ConstructorMatcher(ConstructorInfo constructor) { _constructor = constructor; _parameters = ((MethodBase)_constructor).GetParameters(); _parameterValues = new object[_parameters.Length]; } public int Match(object[] givenParameters) { int num = 0; int result = 0; for (int i = 0; i != givenParameters.Length; i++) { System.Type type = givenParameters[i]?.GetType(); bool flag = false; int num2 = num; while (!flag && num2 != _parameters.Length) { if (_parameterValues[num2] == null && _parameters[num2].ParameterType.IsAssignableFrom(type)) { flag = true; _parameterValues[num2] = givenParameters[i]; if (num == num2) { num++; if (num2 == i) { result = num2; } } } num2++; } if (!flag) { return -1; } } return result; } public object CreateInstance(IServiceProvider provider) { //IL_0097: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i != _parameters.Length; i++) { if (_parameterValues[i] != null) { continue; } object service = provider.GetService(_parameters[i].ParameterType); if (service == null) { if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object defaultValue)) { throw new InvalidOperationException($"Unable to resolve service for type '{_parameters[i].ParameterType}' while attempting to activate '{((MemberInfo)_constructor).DeclaringType}'."); } _parameterValues[i] = defaultValue; } else { _parameterValues[i] = service; } } return _constructor.Invoke((BindingFlags)33554432, (Binder)null, _parameterValues, (CultureInfo)null); } } private static readonly MethodInfo GetServiceInfo; public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type instanceType, params object[] parameters) { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) int num = -1; bool flag = false; ConstructorMatcher constructorMatcher = default(ConstructorMatcher); if (!instanceType.IsAbstract) { ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo val in constructors) { ConstructorMatcher constructorMatcher2 = new ConstructorMatcher(val); bool flag2 = ((MemberInfo)val).IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false); int num2 = constructorMatcher2.Match(parameters); if (flag2) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (num2 == -1) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } } if (flag2 || num < num2) { num = num2; constructorMatcher = constructorMatcher2; } flag = flag || flag2; } } if (num == -1) { string text = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided."; throw new InvalidOperationException(text); } return constructorMatcher.CreateInstance(provider); } public static ObjectFactory CreateFactory([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type instanceType, System.Type[] argumentTypes) { FindApplicableConstructor(instanceType, argumentTypes, out var matchingConstructor, out var matchingParameterMap); ParameterExpression val = Expression.Parameter(typeof(IServiceProvider), "provider"); ParameterExpression val2 = Expression.Parameter(typeof(object[]), "argumentArray"); Expression val3 = BuildFactoryExpression(matchingConstructor, matchingParameterMap, (Expression)(object)val, (Expression)(object)val2); Expression<Func<IServiceProvider, object[], object>> val4 = Expression.Lambda<Func<IServiceProvider, object[], object>>(val3, (ParameterExpression[])(object)new ParameterExpression[2] { val, val2 }); Func<IServiceProvider, object[], object> @object = val4.Compile(); return @object.Invoke; } public static T CreateInstance<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] T>(IServiceProvider provider, params object[] parameters) { return (T)CreateInstance(provider, typeof(T), parameters); } public static T GetServiceOrCreateInstance<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] T>(IServiceProvider provider) { return (T)GetServiceOrCreateInstance(provider, typeof(T)); } public static object GetServiceOrCreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type type) { return provider.GetService(type) ?? CreateInstance(provider, type); } private static MethodInfo GetMethodInfo<T>(Expression<T> expr) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown MethodCallExpression val = (MethodCallExpression)((LambdaExpression)expr).Body; return val.Method; } private static object GetService(IServiceProvider sp, System.Type type, System.Type requiredBy, bool isDefaultParameterRequired) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) object service = sp.GetService(type); if (service == null && !isDefaultParameterRequired) { string text = $"Unable to resolve service for type '{type}' while attempting to activate '{requiredBy}'."; throw new InvalidOperationException(text); } return service; } private static Expression BuildFactoryExpression(ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray) { ParameterInfo[] parameters = ((MethodBase)constructor).GetParameters(); Expression[] array = (Expression[])(object)new Expression[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ParameterInfo val = parameters[i]; System.Type parameterType = val.ParameterType; object defaultValue; bool flag = ParameterDefaultValue.TryGetDefaultValue(val, out defaultValue); if (parameterMap[i].HasValue) { array[i] = (Expression)(object)Expression.ArrayAccess(factoryArgumentArray, (Expression[])(object)new Expression[1] { (Expression)Expression.Constant((object)parameterMap[i]) }); } else { Expression[] array2 = (Expression[])(object)new Expression[4] { serviceProvider, (Expression)Expression.Constant((object)parameterType, typeof(System.Type)), (Expression)Expression.Constant((object)((MemberInfo)constructor).DeclaringType, typeof(System.Type)), (Expression)Expression.Constant((object)flag) }; array[i] = (Expression)(object)Expression.Call(GetServiceInfo, array2); } if (flag) { ConstantExpression val2 = Expression.Constant(defaultValue); array[i] = (Expression)(object)Expression.Coalesce(array[i], (Expression)(object)val2); } array[i] = (Expression)(object)Expression.Convert(array[i], parameterType); } return (Expression)(object)Expression.New(constructor, array); } private static void FindApplicableConstructor([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type instanceType, System.Type[] argumentTypes, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) ConstructorInfo matchingConstructor2 = null; int?[] parameterMap = null; if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref matchingConstructor2, ref parameterMap) && !TryFindMatchingConstructor(instanceType, argumentTypes, ref matchingConstructor2, ref parameterMap)) { string text = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided."; throw new InvalidOperationException(text); } matchingConstructor = matchingConstructor2; matchingParameterMap = parameterMap; } private static bool TryFindMatchingConstructor([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type instanceType, System.Type[] argumentTypes, [NotNullWhen(true)] ref ConstructorInfo matchingConstructor, [NotNullWhen(true)] ref int?[] parameterMap) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo val in constructors) { if (TryCreateParameterMap(((MethodBase)val).GetParameters(), argumentTypes, out var parameterMap2)) { if (matchingConstructor != (ConstructorInfo)null) { throw new InvalidOperationException($"Multiple constructors accepting all given argument types have been found in type '{instanceType}'. There should only be one applicable constructor."); } matchingConstructor = val; parameterMap = parameterMap2; } } if (matchingConstructor != (ConstructorInfo)null) { return true; } return false; } private static bool TryFindPreferredConstructor([DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type instanceType, System.Type[] argumentTypes, [NotNullWhen(true)] ref ConstructorInfo matchingConstructor, [NotNullWhen(true)] ref int?[] parameterMap) { bool flag = false; ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo val in constructors) { if (((MemberInfo)val).IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false)) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (!TryCreateParameterMap(((MethodBase)val).GetParameters(), argumentTypes, out var parameterMap2)) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } matchingConstructor = val; parameterMap = parameterMap2; flag = true; } } if (matchingConstructor != (ConstructorInfo)null) { return true; } return false; } private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, System.Type[] argumentTypes, out int?[] parameterMap) { parameterMap = new int?[constructorParameters.Length]; for (int i = 0; i < argumentTypes.Length; i++) { bool flag = false; System.Type type = argumentTypes[i]; for (int j = 0; j < constructorParameters.Length; j++) { if (!parameterMap[j].HasValue && constructorParameters[j].ParameterType.IsAssignableFrom(type)) { flag = true; parameterMap[j] = i; break; } } if (!flag) { return false; } } return true; } private static void ThrowMultipleCtorsMarkedWithAttributeException() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new InvalidOperationException("Multiple constructors were marked with ActivatorUtilitiesConstructorAttribute."); } private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new InvalidOperationException("Constructor marked with ActivatorUtilitiesConstructorAttribute does not accept all given argument types."); } static ActivatorUtilities() { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown ParameterExpression val = Expression.Parameter(typeof(IServiceProvider), "sp"); ParameterExpression val2 = Expression.Parameter(typeof(System.Type), "t"); ParameterExpression val3 = Expression.Parameter(typeof(System.Type), "r"); ParameterExpression val4 = Expression.Parameter(typeof(bool), "c"); GetServiceInfo = GetMethodInfo<Func<IServiceProvider, System.Type, System.Type, bool, object>>(Expression.Lambda<Func<IServiceProvider, System.Type, System.Type, bool, object>>((Expression)(object)Expression.Call((Expression)null, (MethodInfo)MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Expression[])(object)new Expression[4] { (Expression)val, (Expression)val2, (Expression)val3, (Expression)val4 }), (ParameterExpression[])(object)new ParameterExpression[4] { val, val2, val3, val4 })); } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class ActivatorUtilitiesConstructorAttribute : System.Attribute { } public readonly struct AsyncServiceScope : IServiceScope, System.IDisposable, System.IAsyncDisposable { private readonly IServiceScope _serviceScope; public IServiceProvider ServiceProvider => _serviceScope.ServiceProvider; public AsyncServiceScope(IServiceScope serviceScope) { ThrowHelper.ThrowIfNull(serviceScope, "serviceScope"); _serviceScope = serviceScope; } public void Dispose() { ((System.IDisposable)_serviceScope).Dispose(); } public System.Threading.Tasks.ValueTask DisposeAsync() { if (_serviceScope is System.IAsyncDisposable asyncDisposable) { return asyncDisposable.DisposeAsync(); } ((System.IDisposable)_serviceScope).Dispose(); return default(System.Threading.Tasks.ValueTask); } } public interface IServiceCollection : System.Collections.Generic.IList<ServiceDescriptor>, System.Collections.Generic.ICollection<ServiceDescriptor>, System.Collections.Generic.IEnumerable<ServiceDescriptor>, System.Collections.IEnumerable { } public interface IServiceProviderFactory<TContainerBuilder> where TContainerBuilder : notnull { TContainerBuilder CreateBuilder(IServiceCollection services); IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder); } public interface IServiceProviderIsService { bool IsService(System.Type serviceType); } public interface IServiceScope : System.IDisposable { IServiceProvider ServiceProvider { get; } } public interface IServiceScopeFactory { IServiceScope CreateScope(); } public interface ISupportRequiredService { object GetRequiredService(System.Type serviceType); } public delegate object ObjectFactory(IServiceProvider serviceProvider, object?[]? arguments); [DefaultMember("Item")] public class ServiceCollection : IServiceCollection, System.Collections.Generic.IList<ServiceDescriptor>, System.Collections.Generic.ICollection<ServiceDescriptor>, System.Collections.Generic.IEnumerable<ServiceDescriptor>, System.Collections.IEnumerable { 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 System.Collections.Generic.IEnumerator<ServiceDescriptor> GetEnumerator() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return (System.Collections.Generic.IEnumerator<ServiceDescriptor>)(object)_descriptors.GetEnumerator(); } void System.Collections.Generic.ICollection<ServiceDescriptor>.Add(ServiceDescriptor item) { CheckReadOnly(); _descriptors.Add(item); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)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() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new InvalidOperationException(System.SR.ServiceCollectionReadOnly); } } public static class ServiceCollectionServiceExtensions { public static IServiceCollection AddTransient(this IServiceCollection services, System.Type serviceType, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddTransient(this IServiceCollection services, System.Type serviceType, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); } public static IServiceCollection AddTransient<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type serviceType) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddTransient(serviceType, serviceType); } public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TService>(this IServiceCollection services) where TService : class { ThrowHelper.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService)); } public static IServiceCollection AddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory); } public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory); } public static IServiceCollection AddScoped(this IServiceCollection services, System.Type serviceType, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped(this IServiceCollection services, System.Type serviceType, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type serviceType) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddScoped(serviceType, serviceType); } public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TService>(this IServiceCollection services) where TService : class { ThrowHelper.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService)); } public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory); } public static IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, System.Type serviceType, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton(this IServiceCollection services, System.Type serviceType, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type serviceType) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddSingleton(serviceType, serviceType); } public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TService>(this IServiceCollection services) where TService : class { ThrowHelper.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService)); } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory); } public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, System.Type serviceType, object implementationInstance) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); ServiceDescriptor serviceDescriptor = new ServiceDescriptor(serviceType, implementationInstance); ((System.Collections.Generic.ICollection<ServiceDescriptor>)services).Add(serviceDescriptor); return services; } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, TService implementationInstance) where TService : class { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return services.AddSingleton(typeof(TService), (object)implementationInstance); } private static IServiceCollection Add(IServiceCollection collection, System.Type serviceType, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType, ServiceLifetime lifetime) { ServiceDescriptor serviceDescriptor = new ServiceDescriptor(serviceType, implementationType, lifetime); ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Add(serviceDescriptor); return collection; } private static IServiceCollection Add(IServiceCollection collection, System.Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime) { ServiceDescriptor serviceDescriptor = new ServiceDescriptor(serviceType, implementationFactory, lifetime); ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Add(serviceDescriptor); return collection; } } [DebuggerDisplay("Lifetime = {Lifetime}, ServiceType = {ServiceType}, ImplementationType = {ImplementationType}")] public class ServiceDescriptor { [field: CompilerGenerated] public ServiceLifetime Lifetime { [CompilerGenerated] get; } [field: CompilerGenerated] public System.Type ServiceType { [CompilerGenerated] get; } [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] [field: CompilerGenerated] public System.Type? ImplementationType { [CompilerGenerated] get; } [field: CompilerGenerated] public object? ImplementationInstance { [CompilerGenerated] get; } [field: CompilerGenerated] public Func<IServiceProvider, object>? ImplementationFactory { [CompilerGenerated] get; } public ServiceDescriptor(System.Type serviceType, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType, ServiceLifetime lifetime) : this(serviceType, lifetime) { ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ImplementationType = implementationType; } public ServiceDescriptor(System.Type serviceType, object instance) : this(serviceType, ServiceLifetime.Singleton) { ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(instance, "instance"); ImplementationInstance = instance; } public ServiceDescriptor(System.Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime) : this(serviceType, lifetime) { ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(factory, "factory"); ImplementationFactory = factory; } private ServiceDescriptor(System.Type serviceType, ServiceLifetime lifetime) { Lifetime = lifetime; ServiceType = serviceType; } public virtual string ToString() { string text = $"{"ServiceType"}: {ServiceType} {"Lifetime"}: {Lifetime} "; if (ImplementationType != (System.Type)null) { return text + $"{"ImplementationType"}: {ImplementationType}"; } if (ImplementationFactory != null) { return text + $"{"ImplementationFactory"}: {((System.Delegate)(object)ImplementationFactory).Method}"; } return text + $"{"ImplementationInstance"}: {ImplementationInstance}"; } internal System.Type GetImplementationType() { if (ImplementationType != (System.Type)null) { return ImplementationType; } if (ImplementationInstance != null) { return ImplementationInstance.GetType(); } if (ImplementationFactory != null) { System.Type[] genericTypeArguments = ((object)ImplementationFactory).GetType().GenericTypeArguments; return genericTypeArguments[1]; } return null; } public static ServiceDescriptor Transient<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>() where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Transient); } public static ServiceDescriptor Transient(System.Type service, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(System.Type service, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Scoped<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>() where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(System.Type service, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { return Describe(service, implementationType, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(System.Type service, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Singleton<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>() where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(System.Type service, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), (Func<IServiceProvider, object>)(object)implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(System.Type serviceType, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(TService implementationInstance) where TService : class { ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return Singleton(typeof(TService), (object)implementationInstance); } public static ServiceDescriptor Singleton(System.Type serviceType, object implementationInstance) { ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, implementationInstance); } private static ServiceDescriptor Describe<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>(ServiceLifetime lifetime) where TService : class where TImplementation : class, TService { return Describe(typeof(TService), typeof(TImplementation), lifetime); } public static ServiceDescriptor Describe(System.Type serviceType, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationType, lifetime); } public static ServiceDescriptor Describe(System.Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationFactory, lifetime); } } public enum ServiceLifetime { Singleton, Scoped, Transient } public static class ServiceProviderServiceExtensions { public static T? GetService<T>(this IServiceProvider provider) { ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetService(typeof(T)); } public static object GetRequiredService(this IServiceProvider provider, System.Type serviceType) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(provider, "provider"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); if (provider is ISupportRequiredService supportRequiredService) { return supportRequiredService.GetRequiredService(serviceType); } object service = provider.GetService(serviceType); if (service == null) { throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType)); } return service; } public static T GetRequiredService<T>(this IServiceProvider provider) where T : notnull { ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredService(typeof(T)); } public static System.Collections.Generic.IEnumerable<T> GetServices<T>(this IServiceProvider provider) { ThrowHelper.ThrowIfNull(provider, "provider"); return provider.GetRequiredService<System.Collections.Generic.IEnumerable<T>>(); } [RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")] public static System.Collections.Generic.IEnumerable<object?> GetServices(this IServiceProvider provider, System.Type serviceType) { ThrowHelper.ThrowIfNull(provider, "provider"); ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.Type serviceType2 = typeof(System.Collections.Generic.IEnumerable<>).MakeGenericType(new System.Type[1] { serviceType }); return (System.Collections.Generic.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) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(descriptor, "descriptor"); ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Add(descriptor); return collection; } public static IServiceCollection Add(this IServiceCollection collection, System.Collections.Generic.IEnumerable<ServiceDescriptor> descriptors) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(descriptors, "descriptors"); System.Collections.Generic.IEnumerator<ServiceDescriptor> enumerator = descriptors.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { ServiceDescriptor current = enumerator.Current; ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Add(current); } return collection; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(descriptor, "descriptor"); int count = ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Count; for (int i = 0; i < count; i++) { if (((System.Collections.Generic.IList<ServiceDescriptor>)collection)[i].ServiceType == descriptor.ServiceType) { return; } } ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Add(descriptor); } public static void TryAdd(this IServiceCollection collection, System.Collections.Generic.IEnumerable<ServiceDescriptor> descriptors) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(descriptors, "descriptors"); System.Collections.Generic.IEnumerator<ServiceDescriptor> enumerator = descriptors.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { ServiceDescriptor current = enumerator.Current; collection.TryAdd(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type service) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, service); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, System.Type service, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, System.Type service, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddTransient<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TService>(this IServiceCollection collection) where TService : class { ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TService)); } public static void TryAddTransient<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TImplementation)); } public static void TryAddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Transient<TService>(implementationFactory)); } public static void TryAddScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type service) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, service); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, System.Type service, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, System.Type service, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddScoped<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TService>(this IServiceCollection collection) where TService : class { ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TService)); } public static void TryAddScoped<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TImplementation)); } public static void TryAddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Scoped<TService>(implementationFactory)); } public static void TryAddSingleton(this IServiceCollection collection, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type service) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, service); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, System.Type service, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, System.Type service, Func<IServiceProvider, object> implementationFactory) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(service, "service"); ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddSingleton<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TService>(this IServiceCollection collection) where TService : class { ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TService)); } public static void TryAddSingleton<TService, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TImplementation)); } public static void TryAddSingleton<TService>(this IServiceCollection collection, TService instance) where TService : class { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(instance, "instance"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(typeof(TService), (object)instance); collection.TryAdd(descriptor); } public static void TryAddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Singleton<TService>(implementationFactory)); } public static void TryAddEnumerable(this IServiceCollection services, ServiceDescriptor descriptor) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(descriptor, "descriptor"); System.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 = ((System.Collections.Generic.ICollection<ServiceDescriptor>)services).Count; for (int i = 0; i < count; i++) { ServiceDescriptor serviceDescriptor = ((System.Collections.Generic.IList<ServiceDescriptor>)services)[i]; if (serviceDescriptor.ServiceType == descriptor.ServiceType && serviceDescriptor.GetImplementationType() == implementationType) { return; } } ((System.Collections.Generic.ICollection<ServiceDescriptor>)services).Add(descriptor); } public static void TryAddEnumerable(this IServiceCollection services, System.Collections.Generic.IEnumerable<ServiceDescriptor> descriptors) { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(descriptors, "descriptors"); System.Collections.Generic.IEnumerator<ServiceDescriptor> enumerator = descriptors.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { ServiceDescriptor current = enumerator.Current; services.TryAddEnumerable(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor) { ThrowHelper.ThrowIfNull(collection, "collection"); ThrowHelper.ThrowIfNull(descriptor, "descriptor"); int count = ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Count; for (int i = 0; i < count; i++) { if (((System.Collections.Generic.IList<ServiceDescriptor>)collection)[i].ServiceType == descriptor.ServiceType) { ((System.Collections.Generic.IList<ServiceDescriptor>)collection).RemoveAt(i); break; } } ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Add(descriptor); return collection; } public static IServiceCollection RemoveAll<T>(this IServiceCollection collection) { return collection.RemoveAll(typeof(T)); } public static IServiceCollection RemoveAll(this IServiceCollection collection, System.Type serviceType) { ThrowHelper.ThrowIfNull(serviceType, "serviceType"); for (int num = ((System.Collections.Generic.ICollection<ServiceDescriptor>)collection).Count - 1; num >= 0; num--) { ServiceDescriptor serviceDescriptor = ((System.Collections.Generic.IList<ServiceDescriptor>)collection)[num]; if (serviceDescriptor.ServiceType == serviceType) { ((System.Collections.Generic.IList<ServiceDescriptor>)collection).RemoveAt(num); } } return collection; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.DependencyInjection.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.DependencyInjection; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.ServiceLookup; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("MicroBenchmarks, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Default implementation of dependency injection for Microsoft.Extensions.DependencyInjection.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [assembly: TypeForwardedTo(typeof(ServiceCollection))] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.DependencyInjection { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.DependencyInjection.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string AmbiguousConstructorException => GetResourceString("AmbiguousConstructorException"); internal static string CannotResolveService => GetResourceString("CannotResolveService"); internal static string CircularDependencyException => GetResourceString("CircularDependencyException"); internal static string UnableToActivateTypeException => GetResourceString("UnableToActivateTypeException"); internal static string OpenGenericServiceRequiresOpenGenericImplementation => GetResourceString("OpenGenericServiceRequiresOpenGenericImplementation"); internal static string ArityOfOpenGenericServiceNotEqualArityOfOpenGenericImplementation => GetResourceString("ArityOfOpenGenericServiceNotEqualArityOfOpenGenericImplementation"); internal static string TypeCannotBeActivated => GetResourceString("TypeCannotBeActivated"); internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch"); internal static string ScopedInSingletonException => GetResourceString("ScopedInSingletonException"); internal static string ScopedResolvedFromRootException => GetResourceString("ScopedResolvedFromRootException"); internal static string DirectScopedResolvedFromRootException => GetResourceString("DirectScopedResolvedFromRootException"); internal static string ConstantCantBeConvertedToServiceType => GetResourceString("ConstantCantBeConvertedToServiceType"); internal static string ImplementationTypeCantBeConvertedToServiceType => GetResourceString("ImplementationTypeCantBeConvertedToServiceType"); internal static string AsyncDisposableServiceDispose => GetResourceString("AsyncDisposableServiceDispose"); internal static string GetCaptureDisposableNotSupported => GetResourceString("GetCaptureDisposableNotSupported"); internal static string InvalidServiceDescriptor => GetResourceString("InvalidServiceDescriptor"); internal static string ServiceDescriptorNotExist => GetResourceString("ServiceDescriptorNotExist"); internal static string CallSiteTypeNotSupported => GetResourceString("CallSiteTypeNotSupported"); internal static string TrimmingAnnotationsDoNotMatch => GetResourceString("TrimmingAnnotationsDoNotMatch"); internal static string TrimmingAnnotationsDoNotMatch_NewConstraint => GetResourceString("TrimmingAnnotationsDoNotMatch_NewConstraint"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.DependencyInjection { internal sealed class CallSiteJsonFormatter : CallSiteVisitor<CallSiteJsonFormatter.CallSiteFormatterContext, object?> { internal struct CallSiteFormatterContext { private readonly HashSet<ServiceCallSite> _processedCallSites; private bool _firstItem; [field: CompilerGenerated] public int Offset { [CompilerGenerated] get; } [field: CompilerGenerated] public StringBuilder Builder { [CompilerGenerated] get; } public CallSiteFormatterContext(StringBuilder builder, int offset, HashSet<ServiceCallSite> processedCallSites) { Builder = builder; Offset = offset; _processedCallSites = processedCallSites; _firstItem = true; } public bool ShouldFormat(ServiceCallSite serviceCallSite) { return _processedCallSites.Add(serviceCallSite); } public CallSiteFormatterContext IncrementOffset() { CallSiteFormatterContext result = new CallSiteFormatterContext(Builder, Offset + 4, _processedCallSites); result._firstItem = true; return result; } public CallSiteFormatterContext StartObject() { Builder.Append('{'); return IncrementOffset(); } public void EndObject() { Builder.Append('}'); } public void StartProperty(string name) { if (!_firstItem) { Builder.Append(','); } else { _firstItem = false; } Builder.AppendFormat("\"{0}\":", (object)name); } public void StartArrayItem() { if (!_firstItem) { Builder.Append(','); } else { _firstItem = false; } } public void WriteProperty(string name, object? value) { StartProperty(name); if (value != null) { Builder.AppendFormat(" \"{0}\"", value); } else { Builder.Append("null"); } } public CallSiteFormatterContext StartArray() { Builder.Append('['); return IncrementOffset(); } public void EndArray() { Builder.Append(']'); } } internal static CallSiteJsonFormatter Instance = new CallSiteJsonFormatter(); private CallSiteJsonFormatter() { } public string Format(ServiceCallSite callSite) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown StringBuilder val = new StringBuilder(); CallSiteFormatterContext argument = new CallSiteFormatterContext(val, 0, new HashSet<ServiceCallSite>()); VisitCallSite(callSite, argument); return ((object)val).ToString(); } protected override object? VisitConstructor(ConstructorCallSite constructorCallSite, CallSiteFormatterContext argument) { argument.WriteProperty("implementationType", constructorCallSite.ImplementationType); if (constructorCallSite.ParameterCallSites.Length != 0) { argument.StartProperty("arguments"); CallSiteFormatterContext argument2 = argument.StartArray(); ServiceCallSite[] parameterCallSites = constructorCallSite.ParameterCallSites; foreach (ServiceCallSite callSite in parameterCallSites) { argument2.StartArrayItem(); VisitCallSite(callSite, argument2); } argument.EndArray(); } return null; } protected override object? VisitCallSiteMain(ServiceCallSite callSite, CallSiteFormatterContext argument) { if (argument.ShouldFormat(callSite)) { CallSiteFormatterContext argument2 = argument.StartObject(); argument2.WriteProperty("serviceType", callSite.ServiceType); argument2.WriteProperty("kind", callSite.Kind); argument2.WriteProperty("cache", callSite.Cache.Location); base.VisitCallSiteMain(callSite, argument2); argument.EndObject(); } else { argument.StartObject().WriteProperty("ref", callSite.ServiceType); argument.EndObject(); } return null; } protected override object? VisitConstant(ConstantCallSite constantCallSite, CallSiteFormatterContext argument) { argument.WriteProperty("value", constantCallSite.DefaultValue ?? ""); return null; } protected override object? VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, CallSiteFormatterContext argument) { return null; } protected override object? VisitIEnumerable(IEnumerableCallSite enumerableCallSite, CallSiteFormatterContext argument) { argument.WriteProperty("itemType", enumerableCallSite.ItemType); argument.WriteProperty("size", enumerableCallSite.ServiceCallSites.Length); if (enumerableCallSite.ServiceCallSites.Length != 0) { argument.StartProperty("items"); CallSiteFormatterContext argument2 = argument.StartArray(); ServiceCallSite[] serviceCallSites = enumerableCallSite.ServiceCallSites; foreach (ServiceCallSite callSite in serviceCallSites) { argument2.StartArrayItem(); VisitCallSite(callSite, argument2); } argument.EndArray(); } return null; } protected override object? VisitFactory(FactoryCallSite factoryCallSite, CallSiteFormatterContext argument) { argument.WriteProperty("method", ((System.Delegate)(object)factoryCallSite.Factory).Method); return null; } } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] public class DefaultServiceProviderFactory : IServiceProviderFactory<IServiceCollection> { private readonly ServiceProviderOptions _options; public DefaultServiceProviderFactory() : this(ServiceProviderOptions.Default) { } public DefaultServiceProviderFactory(ServiceProviderOptions options) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) _options = options ?? throw new ArgumentNullException("options"); } public IServiceCollection CreateBuilder(IServiceCollection services) { return services; } public IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder) { return (IServiceProvider)(object)containerBuilder.BuildServiceProvider(_options); } } [EventSource(Name = "Microsoft-Extensions-DependencyInjection")] internal sealed class DependencyInjectionEventSource : EventSource { public static class Keywords { public const EventKeywords ServiceProviderInitialized = 1L; } public static readonly DependencyInjectionEventSource Log = new DependencyInjectionEventSource(); private const int MaxChunkSize = 10240; private readonly List<WeakReference<ServiceProvider>> _providers = new List<WeakReference<ServiceProvider>>(); private DependencyInjectionEventSource() : base((EventSourceSettings)8) { } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")] [Event(/*Could not decode attribute arguments.*/)] private void CallSiteBuilt(string serviceType, string callSite, int chunkIndex, int chunkCount, int serviceProviderHashCode) { ((EventSource)this).WriteEvent(1, new object[5] { serviceType, callSite, chunkIndex, chunkCount, serviceProviderHashCode }); } [Event(/*Could not decode attribute arguments.*/)] public void ServiceResolved(string serviceType, int serviceProviderHashCode) { ((EventSource)this).WriteEvent(2, serviceType, serviceProviderHashCode); } [Event(/*Could not decode attribute arguments.*/)] public void ExpressionTreeGenerated(string serviceType, int nodeCount, int serviceProviderHashCode) { ((EventSource)this).WriteEvent(3, serviceType, nodeCount, serviceProviderHashCode); } [Event(/*Could not decode attribute arguments.*/)] public void DynamicMethodBuilt(string serviceType, int methodSize, int serviceProviderHashCode) { ((EventSource)this).WriteEvent(4, serviceType, methodSize, serviceProviderHashCode); } [Event(/*Could not decode attribute arguments.*/)] public void ScopeDisposed(int serviceProviderHashCode, int scopedServicesResolved, int disposableServices) { ((EventSource)this).WriteEvent(5, serviceProviderHashCode, scopedServicesResolved, disposableServices); } [Event(/*Could not decode attribute arguments.*/)] public void ServiceRealizationFailed(string? exceptionMessage, int serviceProviderHashCode) { ((EventSource)this).WriteEvent(6, exceptionMessage, serviceProviderHashCode); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")] [Event(/*Could not decode attribute arguments.*/)] private void ServiceProviderBuilt(int serviceProviderHashCode, int singletonServices, int scopedServices, int transientServices, int closedGenericsServices, int openGenericsServices) { ((EventSource)this).WriteEvent(7, new object[6] { serviceProviderHashCode, singletonServices, scopedServices, transientServices, closedGenericsServices, openGenericsServices }); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")] [Event(/*Could not decode attribute arguments.*/)] private void ServiceProviderDescriptors(int serviceProviderHashCode, string descriptors, int chunkIndex, int chunkCount) { ((EventSource)this).WriteEvent(8, new object[4] { serviceProviderHashCode, descriptors, chunkIndex, chunkCount }); } [NonEvent] public void ServiceResolved(ServiceProvider provider, System.Type serviceType) { if (((EventSource)this).IsEnabled((EventLevel)5, (EventKeywords)(-1))) { ServiceResolved(((object)serviceType).ToString(), ((object)provider).GetHashCode()); } } [NonEvent] public void CallSiteBuilt(ServiceProvider provider, System.Type serviceType, ServiceCallSite callSite) { if (((EventSource)this).IsEnabled((EventLevel)5, (EventKeywords)(-1))) { string text = CallSiteJsonFormatter.Instance.Format(callSite); int num = text.Length / 10240 + ((text.Length % 10240 > 0) ? 1 : 0); int hashCode = ((object)provider).GetHashCode(); for (int i = 0; i < num; i++) { CallSiteBuilt(((object)serviceType).ToString(), text.Substring(i * 10240, Math.Min(10240, text.Length - i * 10240)), i, num, hashCode); } } } [NonEvent] public void DynamicMethodBuilt(ServiceProvider provider, System.Type serviceType, int methodSize) { if (((EventSource)this).IsEnabled((EventLevel)5, (EventKeywords)(-1))) { DynamicMethodBuilt(((object)serviceType).ToString(), methodSize, ((object)provider).GetHashCode()); } } [NonEvent] public void ServiceRealizationFailed(System.Exception exception, int serviceProviderHashCode) { if (((EventSource)this).IsEnabled((EventLevel)2, (EventKeywords)(-1))) { ServiceRealizationFailed(((object)exception).ToString(), serviceProviderHashCode); } } [NonEvent] public void ServiceProviderBuilt(ServiceProvider provider) { lock (_providers) { _providers.Add(new WeakReference<ServiceProvider>(provider)); } WriteServiceProviderBuilt(provider); } [NonEvent] public void ServiceProviderDisposed(ServiceProvider provider) { lock (_providers) { ServiceProvider serviceProvider = default(ServiceProvider); for (int num = _providers.Count - 1; num >= 0; num--) { WeakReference<ServiceProvider> val = _providers[num]; if (!val.TryGetTarget(ref serviceProvider) || serviceProvider == provider) { _providers.RemoveAt(num); } } } } [NonEvent] private void WriteServiceProviderBuilt(ServiceProvider provider) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected I4, but got Unknown if (!((EventSource)this).IsEnabled((EventLevel)4, (EventKeywords)1)) { return; } int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = 0; StringBuilder val = new StringBuilder("{ \"descriptors\":[ "); bool flag = true; ServiceDescriptor[] descriptors = provider.CallSiteFactory.Descriptors; foreach (ServiceDescriptor val2 in descriptors) { if (flag) { flag = false; } else { val.Append(", "); } AppendServiceDescriptor(val, val2); ServiceLifetime lifetime = val2.Lifetime; switch ((int)lifetime) { case 0: num++; break; case 1: num2++; break; case 2: num3++; break; } if (val2.ServiceType.IsGenericType) { if (val2.ServiceType.IsConstructedGenericType) { num4++; } else { num5++; } } } val.Append(" ] }"); int hashCode = ((object)provider).GetHashCode(); ServiceProviderBuilt(hashCode, num, num2, num3, num4, num5); string text = ((object)val).ToString(); int num6 = text.Length / 10240 + ((text.Length % 10240 > 0) ? 1 : 0); for (int j = 0; j < num6; j++) { ServiceProviderDescriptors(hashCode, text.Substring(j * 10240, Math.Min(10240, text.Length - j * 10240)), j, num6); } } [NonEvent] private static void AppendServiceDescriptor(StringBuilder builder, ServiceDescriptor descriptor) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) builder.Append("{ \"serviceType\": \""); builder.Append((object)descriptor.ServiceType); builder.Append("\", \"lifetime\": \""); builder.Append((object)descriptor.Lifetime); builder.Append("\", "); if (descriptor.ImplementationType != null) { builder.Append("\"implementationType\": \""); builder.Append((object)descriptor.ImplementationType); } else if (descriptor.ImplementationFactory != null) { builder.Append("\"implementationFactory\": \""); builder.Append((object)((System.Delegate)(object)descriptor.ImplementationFactory).Method); } else if (descriptor.ImplementationInstance != null) { builder.Append("\"implementationInstance\": \""); builder.Append((object)descriptor.ImplementationInstance.GetType()); builder.Append(" (instance)"); } else { builder.Append("\"unknown\": \""); } builder.Append("\" }"); } protected override void OnEventCommand(EventCommandEventArgs command) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) if ((int)command.Command != -2) { return; } lock (_providers) { Enumerator<WeakReference<ServiceProvider>> enumerator = _providers.GetEnumerator(); try { ServiceProvider provider = default(ServiceProvider); while (enumerator.MoveNext()) { WeakReference<ServiceProvider> current = enumerator.Current; if (current.TryGetTarget(ref provider)) { WriteServiceProviderBuilt(provider); } } } finally { ((System.IDisposable)enumerator).Dispose(); } } } } internal static class DependencyInjectionEventSourceExtensions { private sealed class NodeCountingVisitor : ExpressionVisitor { [field: CompilerGenerated] public int NodeCount { [CompilerGenerated] get; [CompilerGenerated] private set; } [return: NotNullIfNotNull("e")] public override Expression Visit(Expression e) { ((ExpressionVisitor)this).Visit(e); NodeCount++; return e; } } public static void ExpressionTreeGenerated(this DependencyInjectionEventSource source, ServiceProvider provider, System.Type serviceType, Expression expression) { if (((EventSource)source).IsEnabled((EventLevel)5, (EventKeywords)(-1))) { NodeCountingVisitor nodeCountingVisitor = new NodeCountingVisitor(); ((ExpressionVisitor)nodeCountingVisitor).Visit(expression); source.ExpressionTreeGenerated(((object)serviceType).ToString(), nodeCountingVisitor.NodeCount, ((object)provider).GetHashCode()); } } } public static class ServiceCollectionContainerBuilderExtensions { [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] public static ServiceProvider BuildServiceProvider(this IServiceCollection services) { return services.BuildServiceProvider(ServiceProviderOptions.Default); } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] public static ServiceProvider BuildServiceProvider(this IServiceCollection services, bool validateScopes) { return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = validateScopes }); } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (services == null) { throw new ArgumentNullException("services"); } if (options == null) { throw new ArgumentNullException("options"); } return new ServiceProvider((System.Collections.Generic.ICollection<ServiceDescriptor>)services, options); } } public sealed class ServiceProvider : IServiceProvider, System.IDisposable, System.IAsyncDisposable { internal const string RequiresDynamicCodeMessage = "Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services."; private readonly CallSiteValidator _callSiteValidator; private readonly Func<System.Type, Func<ServiceProviderEngineScope, object>> _createServiceAccessor; internal ServiceProviderEngine _engine; private bool _disposed; private ConcurrentDictionary<System.Type, Func<ServiceProviderEngineScope, object>> _realizedServices; [field: CompilerGenerated] internal CallSiteFactory CallSiteFactory { [CompilerGenerated] get; } [field: CompilerGenerated] internal ServiceProviderEngineScope Root { [CompilerGenerated] get; } [field: CompilerGenerated] internal static bool VerifyOpenGenericServiceTrimmability { [CompilerGenerated] get; } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] internal ServiceProvider(System.Collections.Generic.ICollection<ServiceDescriptor> serviceDescriptors, ServiceProviderOptions options) { //IL_0121: Unknown result type (might be due to invalid IL or missing references) Root = new ServiceProviderEngineScope(this, isRootScope: true); _engine = GetEngine(); _createServiceAccessor = CreateServiceAccessor; _realizedServices = new ConcurrentDictionary<System.Type, Func<ServiceProviderEngineScope, object>>(); CallSiteFactory = new CallSiteFactory(serviceDescriptors); CallSiteFactory.Add(typeof(IServiceProvider), new ServiceProviderCallSite()); CallSiteFactory.Add(typeof(IServiceScopeFactory), new ConstantCallSite(typeof(IServiceScopeFactory), Root)); CallSiteFactory.Add(typeof(IServiceProviderIsService), new ConstantCallSite(typeof(IServiceProviderIsService), CallSiteFactory)); if (options.ValidateScopes) { _callSiteValidator = new CallSiteValidator(); } if (options.ValidateOnBuild) { List<System.Exception> val = null; System.Collections.Generic.IEnumerator<ServiceDescriptor> enumerator = ((System.Collections.Generic.IEnumerable<ServiceDescriptor>)serviceDescriptors).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { ServiceDescriptor current = enumerator.Current; try { ValidateService(current); } catch (System.Exception ex) { if (val == null) { val = new List<System.Exception>(); } val.Add(ex); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } if (val != null) { throw new AggregateException("Some services are not able to be constructed", val.ToArray()); } } DependencyInjectionEventSource.Log.ServiceProviderBuilt(this); } public object? GetService(System.Type serviceType) { return GetService(serviceType, Root); } internal bool IsDisposed() { return _disposed; } public void Dispose() { DisposeCore(); Root.Dispose(); } public System.Threading.Tasks.ValueTask DisposeAsync() { DisposeCore(); return Root.DisposeAsync(); } private void DisposeCore() { _disposed = true; DependencyInjectionEventSource.Log.ServiceProviderDisposed(this); } private void OnCreate(ServiceCallSite callSite) { _callSiteValidator?.ValidateCallSite(callSite); } private void OnResolve(System.Type serviceType, IServiceScope scope) { _callSiteValidator?.ValidateResolution(serviceType, scope, (IServiceScope)(object)Root); } internal object? GetService(System.Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) { if (_disposed) { ThrowHelper.ThrowObjectDisposedException(); } Func<ServiceProviderEngineScope, object> orAdd = _realizedServices.GetOrAdd(serviceType, _createServiceAccessor); OnResolve(serviceType, (IServiceScope)(object)serviceProviderEngineScope); DependencyInjectionEventSource.Log.ServiceResolved(this, serviceType); return orAdd.Invoke(serviceProviderEngineScope); } private void ValidateService(ServiceDescriptor descriptor) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) if (descriptor.ServiceType.IsGenericType && !descriptor.ServiceType.IsConstructedGenericType) { return; } try { ServiceCallSite callSite = CallSiteFactory.GetCallSite(descriptor, new CallSiteChain()); if (callSite != null) { OnCreate(callSite); } } catch (System.Exception ex) { throw new InvalidOperationException($"Error while validating the service descriptor '{descriptor}': {ex.Message}", ex); } } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] private Func<ServiceProviderEngineScope, object> CreateServiceAccessor(System.Type serviceType) { ServiceCallSite callSite = CallSiteFactory.GetCallSite(serviceType, new CallSiteChain()); if (callSite != null) { DependencyInjectionEventSource.Log.CallSiteBuilt(this, serviceType, callSite); OnCreate(callSite); if (callSite.Cache.Location == CallSiteResultCacheLocation.Root) { object value = CallSiteRuntimeResolver.Instance.Resolve(callSite, Root); return (ServiceProviderEngineScope scope) => value; } return _engine.RealizeService(callSite); } return (ServiceProviderEngineScope _) => null; } internal void ReplaceServiceAccessor(ServiceCallSite callSite, Func<ServiceProviderEngineScope, object?> accessor) { _realizedServices[callSite.ServiceType] = accessor; } internal IServiceScope CreateScope() { if (_disposed) { ThrowHelper.ThrowObjectDisposedException(); } return (IServiceScope)(object)new ServiceProviderEngineScope(this, isRootScope: false); } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] private ServiceProviderEngine GetEngine() { if (RuntimeFeature.IsDynamicCodeCompiled) { return new DynamicServiceProviderEngine(this); } return RuntimeServiceProviderEngine.Instance; } static ServiceProvider() { bool flag = default(bool); VerifyOpenGenericServiceTrimmability = AppContext.TryGetSwitch("Microsoft.Extensions.DependencyInjection.VerifyOpenGenericServiceTrimmability", ref flag) && flag; } } public class ServiceProviderOptions { internal static readonly ServiceProviderOptions Default = new ServiceProviderOptions(); [field: CompilerGenerated] public bool ValidateScopes { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public bool ValidateOnBuild { [CompilerGenerated] get; [CompilerGenerated] set; } } } namespace Microsoft.Extensions.DependencyInjection.ServiceLookup { internal sealed class CallSiteChain { private readonly struct ChainItemInfo { [field: CompilerGenerated] public int Order { [CompilerGenerated] get; } [field: CompilerGenerated] public System.Type ImplementationType { [CompilerGenerated] get; } public ChainItemInfo(int order, System.Type implementationType) { Order = order; ImplementationType = implementationType; } } private readonly Dictionary<System.Type, ChainItemInfo> _callSiteChain; public CallSiteChain() { _callSiteChain = new Dictionary<System.Type, ChainItemInfo>(); } public void CheckCircularDependency(System.Type serviceType) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (_callSiteChain.ContainsKey(serviceType)) { throw new InvalidOperationException(CreateCircularDependencyExceptionMessage(serviceType)); } } public void Remove(System.Type serviceType) { _callSiteChain.Remove(serviceType); } public void Add(System.Type serviceType, System.Type? implementationType = null) { _callSiteChain[serviceType] = new ChainItemInfo(_callSiteChain.Count, implementationType); } private string CreateCircularDependencyExceptionMessage(System.Type type) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown StringBuilder val = new StringBuilder(); val.Append(System.SR.Format(System.SR.CircularDependencyException, (object?)TypeNameHelper.GetTypeDisplayName(type))); val.AppendLine(); AppendResolutionPath(val, type); return ((object)val).ToString(); } private void AppendResolutionPath(StringBuilder builder, System.Type currentlyResolving) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) List<KeyValuePair<System.Type, ChainItemInfo>> val = new List<KeyValuePair<System.Type, ChainItemInfo>>((System.Collections.Generic.IEnumerable<KeyValuePair<System.Type, ChainItemInfo>>)_callSiteChain); val.Sort((Comparison<KeyValuePair<System.Type, ChainItemInfo>>)((KeyValuePair<System.Type, ChainItemInfo> a, KeyValuePair<System.Type, ChainItemInfo> b) => a.Value.Order.CompareTo(b.Value.Order))); Enumerator<KeyValuePair<System.Type, ChainItemInfo>> enumerator = val.GetEnumerator(); try { while (enumerator.MoveNext()) { KeyValuePair<System.Type, ChainItemInfo> current = enumerator.Current; System.Type key = current.Key; System.Type implementationType = current.Value.ImplementationType; if (implementationType == (System.Type)null || key == implementationType) { builder.Append(TypeNameHelper.GetTypeDisplayName(key)); } else { builder.AppendFormat("{0}({1})", (object)TypeNameHelper.GetTypeDisplayName(key), (object)TypeNameHelper.GetTypeDisplayName(implementationType)); } builder.Append(" -> "); } } finally { ((System.IDisposable)enumerator).Dispose(); } builder.Append(TypeNameHelper.GetTypeDisplayName(currentlyResolving)); } } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] internal sealed class CallSiteFactory : IServiceProviderIsService { [DefaultMember("Item")] private struct ServiceDescriptorCacheItem { [DisallowNull] private ServiceDescriptor _item; [DisallowNull] private List<ServiceDescriptor> _items; public ServiceDescriptor Last { get { if (_items != null && _items.Count > 0) { return _items[_items.Count - 1]; } return _item; } } public int Count { get { if (_item == null) { return 0; } return 1 + (_items?.Count ?? 0); } } public ServiceDescriptor this[int index] { get { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (index >= Count) { throw new ArgumentOutOfRangeException("index"); } if (index == 0) { return _item; } return _items[index - 1]; } } public int GetSlot(ServiceDescriptor descriptor) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (descriptor == _item) { return Count - 1; } if (_items != null) { int num = _items.IndexOf(descriptor); if (num != -1) { return _items.Count - (num + 1); } } throw new InvalidOperationException(System.SR.ServiceDescriptorNotExist); } public ServiceDescriptorCacheItem Add(ServiceDescriptor descriptor) { ServiceDescriptorCacheItem result = default(ServiceDescriptorCacheItem); if (_item == null) { result._item = descriptor; } else { result._item = _item; result._items = _items ?? new List<ServiceDescriptor>(); result._items.Add(descriptor); } return result; } } private const int DefaultSlot = 0; private readonly ServiceDescriptor[] _descriptors; private readonly ConcurrentDictionary<ServiceCacheKey, ServiceCallSite> _callSiteCache = new ConcurrentDictionary<ServiceCacheKey, ServiceCallSite>(); private readonly Dictionary<System.Type, ServiceDescriptorCacheItem> _descriptorLookup = new Dictionary<System.Type, ServiceDescriptorCacheItem>(); private readonly ConcurrentDictionary<System.Type, object> _callSiteLocks = new ConcurrentDictionary<System.Type, object>(); private readonly StackGuard _stackGuard; internal ServiceDescriptor[] Descriptors => _descriptors; public CallSiteFactory(System.Collections.Generic.ICollection<ServiceDescriptor> descriptors) { _stackGuard = new StackGuard(); _descriptors = (ServiceDescriptor[])(object)new ServiceDescriptor[descriptors.Count]; descriptors.CopyTo(_descriptors, 0); Populate(); } private void Populate() { //IL_004f: 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) ServiceDescriptor[] descriptors = _descriptors; ServiceDescriptorCacheItem serviceDescriptorCacheItem = default(ServiceDescriptorCacheItem); foreach (ServiceDescriptor val in descriptors) { System.Type serviceType = val.ServiceType; if (serviceType.IsGenericTypeDefinition) { System.Type implementationType = val.ImplementationType; if (implementationType == (System.Type)null || !implementationType.IsGenericTypeDefinition) { throw new ArgumentException(System.SR.Format(System.SR.OpenGenericServiceRequiresOpenGenericImplementation, serviceType), "descriptors"); } if (implementationType.IsAbstract || implementationType.IsInterface) { throw new ArgumentException(System.SR.Format(System.SR.TypeCannotBeActivated, implementationType, serviceType)); } System.Type[] genericArguments = serviceType.GetGenericArguments(); System.Type[] genericArguments2 = implementationType.GetGenericArguments(); if (genericArguments.Length != genericArguments2.Length) { throw new ArgumentException(System.SR.Format(System.SR.ArityOfOpenGenericServiceNotEqualArityOfOpenGenericImplementation, serviceType, implementationType), "descriptors"); } if (ServiceProvider.VerifyOpenGenericServiceTrimmability) { ValidateTrimmingAnnotations(serviceType, genericArguments, implementationType, genericArguments2); } } else if (val.ImplementationInstance == null && val.ImplementationFactory == null) { System.Type implementationType2 = val.ImplementationType; if (implementationType2.IsGenericTypeDefinition || implementationType2.IsAbstract || implementationType2.IsInterface) { throw new ArgumentException(System.SR.Format(System.SR.TypeCannotBeActivated, implementationType2, serviceType)); } } System.Type type = serviceType; _descriptorLookup.TryGetValue(type, ref serviceDescriptorCacheItem); _descriptorLookup[type] = serviceDescriptorCacheItem.Add(val); } } private static void ValidateTrimmingAnnotations(System.Type serviceType, System.Type[] serviceTypeGenericArguments, System.Type implementationType, System.Type[] implementationTypeGenericArguments) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: 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_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < serviceTypeGenericArguments.Length; i++) { System.Type type = serviceTypeGenericArguments[i]; System.Type type2 = implementationTypeGenericArguments[i]; DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes = GetDynamicallyAccessedMemberTypes(type); DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes2 = GetDynamicallyAccessedMemberTypes(type2); if (!AreCompatible(dynamicallyAccessedMemberTypes, dynamicallyAccessedMemberTypes2)) { throw new ArgumentException(System.SR.Format(System.SR.TrimmingAnnotationsDoNotMatch, (object?)implementationType.FullName, (object?)serviceType.FullName)); } bool flag = ((System.Enum)type.GenericParameterAttributes).HasFlag((System.Enum)(object)(GenericParameterAttributes)16); if (((System.Enum)type2.GenericParameterAttributes).HasFlag((System.Enum)(object)(GenericParameterAttributes)16) && !flag) { throw new ArgumentException(System.SR.Format(System.SR.TrimmingAnnotationsDoNotMatch_NewConstraint, (object?)implementationType.FullName, (object?)serviceType.FullName)); } } } private static DynamicallyAccessedMemberTypes GetDynamicallyAccessedMemberTypes(System.Type serviceGenericType) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) System.Collections.Generic.IEnumerator<CustomAttributeData> enumerator = ((System.Collections.Generic.IEnumerable<CustomAttributeData>)((MemberInfo)serviceGenericType).GetCustomAttributesData()).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { CustomAttributeData current = enumerator.Current; if (current.AttributeType.FullName == "System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute" && ((System.Collections.Generic.ICollection<CustomAttributeTypedArgument>)current.ConstructorArguments).Count == 1) { CustomAttributeTypedArgument val = current.ConstructorArguments[0]; if (((CustomAttributeTypedArgument)(ref val)).ArgumentType.FullName == "System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes") { val = current.ConstructorArguments[0]; return (DynamicallyAccessedMemberTypes)(int)((CustomAttributeTypedArgument)(ref val)).Value; } } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } return (DynamicallyAccessedMemberTypes)0; } private static bool AreCompatible(DynamicallyAccessedMemberTypes serviceDynamicallyAccessedMembers, DynamicallyAccessedMemberTypes implementationDynamicallyAccessedMembers) { //IL_0000: 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) return ((System.Enum)serviceDynamicallyAccessedMembers).HasFlag((System.Enum)(object)implementationDynamicallyAccessedMembers); } internal int? GetSlot(ServiceDescriptor serviceDescriptor) { ServiceDescriptorCacheItem serviceDescriptorCacheItem = default(ServiceDescriptorCacheItem); if (_descriptorLookup.TryGetValue(serviceDescriptor.ServiceType, ref serviceDescriptorCacheItem)) { return serviceDescriptorCacheItem.GetSlot(serviceDescriptor); } return null; } internal ServiceCallSite? GetCallSite(System.Type serviceType, CallSiteChain callSiteChain) { ServiceCallSite result = default(ServiceCallSite); if (!_callSiteCache.TryGetValue(new ServiceCacheKey(serviceType, 0), ref result)) { return CreateCallSite(serviceType, callSiteChain); } return result; } internal ServiceCallSite? GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) { ServiceDescriptorCacheItem serviceDescriptorCacheItem = default(ServiceDescriptorCacheItem); if (_descriptorLookup.TryGetValue(serviceDescriptor.ServiceType, ref serviceDescriptorCacheItem)) { return TryCreateExact(serviceDescriptor, serviceDescriptor.ServiceType, callSiteChain, serviceDescriptorCacheItem.GetSlot(serviceDescriptor)); } return null; } private ServiceCallSite CreateCallSite(System.Type serviceType, CallSiteChain callSiteChain) { if (!_stackGuard.TryEnterOnCurrentStack()) { return _stackGuard.RunOnEmptyStack<System.Type, CallSiteChain, ServiceCallSite>(CreateCallSite, serviceType, callSiteChain); } object orAdd = _callSiteLocks.GetOrAdd(serviceType, (Func<System.Type, object>)((System.Type _) => new object())); lock (orAdd) { callSiteChain.CheckCircularDependency(serviceType); return TryCreateExact(serviceType, callSiteChain) ?? TryCreateOpenGeneric(serviceType, callSiteChain) ?? TryCreateEnumerable(serviceType, callSiteChain); } } private ServiceCallSite TryCreateExact(System.Type serviceType, CallSiteChain callSiteChain) { ServiceDescriptorCacheItem serviceDescriptorCacheItem = default(ServiceDescriptorCacheItem); if (_descriptorLookup.TryGetValue(serviceType, ref serviceDescriptorCacheItem)) { return TryCreateExact(serviceDescriptorCacheItem.Last, serviceType, callSiteChain, 0); } return null; } private ServiceCallSite TryCreateOpenGeneric(System.Type serviceType, CallSiteChain callSiteChain) { ServiceDescriptorCacheItem serviceDescriptorCacheItem = default(ServiceDescriptorCacheItem); if (serviceType.IsConstructedGenericType && _descriptorLookup.TryGetValue(serviceType.GetGenericTypeDefinition(), ref serviceDescriptorCacheItem)) { return TryCreateOpenGeneric(serviceDescriptorCacheItem.Last, serviceType, callSiteChain, 0, throwOnConstraintViolation: true); } return null; } private ServiceCallSite TryCreateEnumerable(System.Type serviceType, CallSiteChain callSiteChain) { ServiceCacheKey serviceCacheKey = new ServiceCacheKey(serviceType, 0); ServiceCallSite result = default(ServiceCallSite); if (_callSiteCache.TryGetValue(serviceCacheKey, ref result)) { return result; } ServiceCallSite serviceCallSite4; try { callSiteChain.Add(serviceType); if (serviceType.IsConstructedGenericType && serviceType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable<>)) { System.Type type = serviceType.GenericTypeArguments[0]; CallSiteResultCacheLocation callSiteResultCacheLocation = CallSiteResultCacheLocation.Root; List<ServiceCallSite> val = new List<ServiceCallSite>(); ServiceDescriptorCacheItem serviceDescriptorCacheItem = default(ServiceDescriptorCacheItem); if (!type.IsConstructedGenericType && _descriptorLookup.TryGetValue(type, ref serviceDescriptorCacheItem)) { for (int i = 0; i < serviceDescriptorCacheItem.Count; i++) { ServiceDescriptor descriptor = serviceDescriptorCacheItem[i]; int slot = serviceDescriptorCacheItem.Count - i - 1; ServiceCallSite serviceCallSite = TryCreateExact(descriptor, type, callSiteChain, slot); callSiteResultCacheLocation = GetCommonCacheLocation(callSiteResultCacheLocation, serviceCallSite.Cache.Location); val.Add(serviceCallSite); } } else { int num = 0; for (int num2 = _descriptors.Length - 1; num2 >= 0; num2--) { ServiceDescriptor descriptor2 = _descriptors[num2]; ServiceCallSite serviceCallSite2 = TryCreateExact(descriptor2, type, callSiteChain, num) ?? TryCreateOpenGeneric(descriptor2, type, callSiteChain, num, throwOnConstraintViolation: false); if (serviceCallSite2 != null) { num++; callSiteResultCacheLocation = GetCommonCacheLocation(callSiteResultCacheLocation, serviceCallSite2.Cache.Location); val.Add(serviceCallSite2); } } val.Reverse(); } ResultCache cache = ResultCache.None; if (callSiteResultCacheLocation == CallSiteResultCacheLocation.Scope || callSiteResultCacheLocation == CallSiteResultCacheLocation.Root) { cache = new ResultCache(callSiteResultCacheLocation, serviceCacheKey); } serviceCallSite4 = (_callSiteCache[serviceCacheKey] = new IEnumerableCallSite(cache, type, val.ToArray())); serviceCallSite4 = serviceCallSite4; } else { serviceCallSite4 = null; } } finally { callSiteChain.Remove(serviceType); } return serviceCallSite4; } private static CallSiteResultCacheLocation GetCommonCacheLocation(CallSiteResultCacheLocation locationA, CallSiteResultCacheLocation locationB) { return (CallSiteResultCacheLocation)Math.Max((int)locationA, (int)locationB); } private ServiceCallSite TryCreateExact(ServiceDescriptor descriptor, System.Type serviceType, CallSiteChain callSiteChain, int slot) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) if (serviceType == descriptor.ServiceType) { ServiceCacheKey serviceCacheKey = new ServiceCacheKey(serviceType, slot); ServiceCallSite result = default(ServiceCallSite); if (_callSiteCache.TryGetValue(serviceCacheKey, ref result)) { return result; } ResultCache resultCache = new ResultCache(descriptor.Lifetime, serviceType, slot); ServiceCallSite serviceCallSite; if (descriptor.ImplementationInstance != null) { serviceCallSite = new ConstantCallSite(descriptor.ServiceType, descriptor.ImplementationInstance); } else if (descriptor.ImplementationFactory != null) { serviceCallSite = new FactoryCallSite(resultCache, descriptor.ServiceType, descriptor.ImplementationFactory); } else { if (!(descriptor.ImplementationType != (System.Type)null)) { throw new InvalidOperationException(System.SR.InvalidServiceDescriptor); } serviceCallSite = CreateConstructorCallSite(resultCache, descriptor.ServiceType, descriptor.ImplementationType, callSiteChain); } return _callSiteCache[serviceCacheKey] = serviceCallSite; } return null; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:MakeGenericType", Justification = "MakeGenericType here is used to create a closed generic implementation type given the closed service type. Trimming annotations on the generic types are verified when 'Microsoft.Extensions.DependencyInjection.VerifyOpenGenericServiceTrimmability' is set, which is set by default when PublishTrimmed=true. That check informs developers when these generic types don't have compatible trimming annotations.")] private ServiceCallSite TryCreateOpenGeneric(ServiceDescriptor descriptor, System.Type serviceType, CallSiteChain callSiteChain, int slot, bool throwOnConstraintViolation) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (serviceType.IsConstructedGenericType && serviceType.GetGenericTypeDefinition() == descriptor.ServiceType) { ServiceCacheKey serviceCacheKey = new ServiceCacheKey(serviceType, slot); ServiceCallSite result = default(ServiceCallSite); if (_callSiteCache.TryGetValue(serviceCacheKey, ref result)) { return result; } ResultCache lifetime = new ResultCache(descriptor.Lifetime, serviceType, slot); System.Type implementationType; try { implementationType = descriptor.ImplementationType.MakeGenericType(serviceType.GenericTypeArguments); } catch (ArgumentException) { if (throwOnConstraintViolation) { throw; } return null; } return _callSiteCache[serviceCacheKey] = CreateConstructorCallSite(lifetime, serviceType, implementationType, callSiteChain); } return null; } private ServiceCallSite CreateConstructorCallSite(ResultCache lifetime, System.Type serviceType, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type implementationType, CallSiteChain callSiteChain) { //IL_0021: 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_0156: Unknown result type (might be due to invalid IL or missing references) try { callSiteChain.Add(serviceType, implementationType); ConstructorInfo[] constructors = implementationType.GetConstructors(); ServiceCallSite[] parameterCallSites = null; if (constructors.Length == 0) { throw new InvalidOperationException(System.SR.Format(System.SR.NoConstructorMatch, implementationType)); } if (constructors.Length == 1) { ConstructorInfo val = constructors[0]; ParameterInfo[] parameters = ((MethodBase)val).GetParameters(); if (parameters.Length == 0) { return new ConstructorCallSite(lifetime, serviceType, val); } parameterCallSites = CreateArgumentCallSites(implementationType, callSiteChain, parameters, throwIfCallSiteNotFound: true); return new ConstructorCallSite(lifetime, serviceType, val, parameterCallSites); } System.Array.Sort<ConstructorInfo>(constructors, (Comparison<ConstructorInfo>)((ConstructorInfo a, ConstructorInfo b) => ((MethodBase)b).GetParameters().Length.CompareTo(((MethodBase)a).GetParameters().Length))); ConstructorInfo val2 = null; HashSet<System.Type> val3 = null; for (int i = 0; i < constructors.Length; i++) { ParameterInfo[] parameters2 = ((MethodBase)constructors[i]).GetParameters(); ServiceCallSite[] array = CreateArgumentCallSites(implementationType, callSiteChain, parameters2, throwIfCallSiteNotFound: false); if (array == null) { continue; } if (val2 == (ConstructorInfo)null) { val2 = constructors[i]; parameterCallSites = array; continue; } if (val3 == null) { val3 = new HashSet<System.Type>(); ParameterInfo[] parameters3 = ((MethodBase)val2).GetParameters(); foreach (ParameterInfo val4 in parameters3) { val3.Add(val4.ParameterType); } } ParameterInfo[] array2 = parameters2; foreach (ParameterInfo val5 in array2) { if (!val3.Contains(val5.ParameterType)) { throw new InvalidOperationException(string.Join(Environment.NewLine, new object[3] { System.SR.Format(System.SR.AmbiguousConstructorException, implementationType), val2, constructors[i] })); } } } if (val2 == (ConstructorInfo)null) { throw new InvalidOperationException(System.SR.Format(System.SR.UnableToActivateTypeException, implementationType)); } return new ConstructorCallSite(lifetime, serviceType, val2, parameterCallSites); } finally { callSiteChain.Remove(serviceType); } } private ServiceCallSite[] CreateArgumentCallSites(System.Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) ServiceCallSite[] array = new ServiceCallSite[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { System.Type parameterType = parameters[i].ParameterType; ServiceCallSite serviceCallSite = GetCallSite(parameterType, callSiteChain); if (serviceCallSite == null && ParameterDefaultValue.TryGetDefaultValue(parameters[i], out object defaultValue)) { serviceCallSite = new ConstantCallSite(parameterType, defaultValue); } if (serviceCallSite == null) { if (throwIfCallSiteNotFound) { throw new InvalidOperationException(System.SR.Format(System.SR.CannotResolveService, parameterType, implementationType)); } return null; } array[i] = serviceCallSite; } return array; } public void Add(System.Type type, ServiceCallSite serviceCallSite) { _callSiteCache[new ServiceCacheKey(type, 0)] = serviceCallSite; } public bool IsService(System.Type serviceType) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (serviceType == null) { throw new ArgumentNullException("serviceType"); } if (serviceType.IsGenericTypeDefinition) { return false; } if (_descriptorLookup.ContainsKey(serviceType)) { return true; } if (serviceType.IsConstructedGenericType) { System.Type genericTypeDefinition = serviceType.GetGenericTypeDefinition(); if (genericTypeDefinition != null) { if (!(genericTypeDefinition == typeof(System.Collections.Generic.IEnumerable<>))) { return _descriptorLookup.ContainsKey(genericTypeDefinition); } return true; } } if (!(serviceType == typeof(IServiceProvider)) && !(serviceType == typeof(IServiceScopeFactory))) { return serviceType == typeof(IServiceProviderIsService); } return true; } } internal enum CallSiteKind { Factory, Constructor, Constant, IEnumerable, ServiceProvider } internal enum CallSiteResultCacheLocation { Root, Scope, Dispose, None } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] internal sealed class CallSiteRuntimeResolver : CallSiteVisitor<RuntimeResolverContext, object?> { [field: CompilerGenerated] public static CallSiteRuntimeResolver Instance { [CompilerGenerated] get; } = new CallSiteRuntimeResolver(); private CallSiteRuntimeResolver() { } public object? Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) { if (scope.IsRootScope) { object value = callSite.Value; if (value != null) { return value; } } return VisitCallSite(callSite, new RuntimeResolverContext { Scope = scope }); } protected override object? VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context) { return context.Scope.CaptureDisposable(VisitCallSiteMain(transientCallSite, context)); } protected override object VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) { object[] array; if (constructorCallSite.ParameterCallSites.Length == 0) { array = System.Array.Empty<object>(); } else { array = new object[constructorCallSite.ParameterCallSites.Length]; for (int i = 0; i < array.Length; i++) { array[i] = VisitCallSite(constructorCallSite.ParameterCallSites[i], context); } } return constructorCallSite.ConstructorInfo.Invoke((BindingFlags)33554432, (Binder)null, array, (CultureInfo)null); } protected override object? VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context) { object value = callSite.Value; if (value != null) { return value; } RuntimeResolverLock runtimeResolverLock = RuntimeResolverLock.Root; ServiceProviderEngineScope root = context.Scope.RootProvider.Root; lock (callSite) { object value2 = callSite.Value; if (value2 != null) { return value2; } object obj = VisitCallSiteMain(callSite, new RuntimeResolverContext { Scope = root, AcquiredLocks = (context.AcquiredLocks | runtimeResolverLock) }); root.CaptureDisposable(obj); callSite.Value = obj; return obj; } } protected override object? VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context) { if (!context.Scope.IsRootScope) { return VisitCache(callSite, context, context.Scope, RuntimeResolverLock.Scope); } return VisitRootCache(callSite, context); } private object VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) { bool flag = false; object sync = serviceProviderEngine.Sync; Dictionary<ServiceCacheKey, object> resolvedServices = serviceProviderEngine.ResolvedServices; if ((context.AcquiredLocks & lockType) == 0) { Monitor.Enter(sync, ref flag); } try { object result = default(object); if (resolvedServices.TryGetValue(callSite.Cache.Key, ref result)) { return result; } result = VisitCallSiteMain(callSite, new RuntimeResolverContext { Scope = serviceProviderEngine, AcquiredLocks = (context.AcquiredLocks | lockType) }); serviceProviderEngine.CaptureDisposable(result); resolvedServices.Add(callSite.Cache.Key, result); return result; } finally { if (flag) { Monitor.Exit(sync); } } } protected override object? VisitConstant(ConstantCallSite constantCallSite, RuntimeResolverContext context) { return constantCallSite.DefaultValue; } protected override object VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, RuntimeResolverContext context) { return context.Scope; } protected override object VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context) { System.Array array = System.Array.CreateInstance(enumerableCallSite.ItemType, enumerableCallSite.ServiceCallSites.Length); for (int i = 0; i < enumerableCallSite.ServiceCallSites.Length; i++) { object obj = VisitCallSite(enumerableCallSite.ServiceCallSites[i], context); array.SetValue(obj, i); } return array; } protected override object VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context) { return factoryCallSite.Factory.Invoke((IServiceProvider)(object)context.Scope); } } internal struct RuntimeResolverContext { [field: CompilerGenerated] public ServiceProviderEngineScope Scope { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public RuntimeResolverLock AcquiredLocks { [CompilerGenerated] get; [CompilerGenerated] set; } } [Flags] internal enum RuntimeResolverLock { Scope = 1, Root = 2 } internal sealed class CallSiteValidator : CallSiteVisitor<CallSiteValidator.CallSiteValidatorState, System.Type?> { internal struct CallSiteValidatorState { [field: CompilerGenerated] public ServiceCallSite? Singleton { [CompilerGenerated] get; [CompilerGenerated] [param: DisallowNull] set; } } private readonly ConcurrentDictionary<System.Type, System.Type> _scopedServices = new ConcurrentDictionary<System.Type, System.Type>(); public void ValidateCallSite(ServiceCallSite callSite) { System.Type type = VisitCallSite(callSite, default(CallSiteValidatorState)); if (type != (System.Type)null) { _scopedServices[callSite.ServiceType] = type; } } public void ValidateResolution(System.Type serviceType, IServiceScope scope, IServiceScope rootScope) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) System.Type type = default(System.Type); if (scope == rootScope && _scopedServices.TryGetValue(serviceType, ref type)) { if (serviceType == type) { throw new InvalidOperationException(System.SR.Format(System.SR.DirectScopedResolvedFromRootException, serviceType, "Scoped".ToLowerInvariant())); } throw new InvalidOperationException(System.SR.Format(System.SR.ScopedResolvedFromRootException, serviceType, type, "Scoped".ToLowerInvariant())); } } protected override System.Type? VisitConstructor(ConstructorCallSite constructorCallSite, CallSiteValidatorState state) { System.Type type = null; ServiceCallSite[] parameterCallSites = constructorCallSite.ParameterCallSites; foreach (ServiceCallSite callSite in parameterCallSites) { System.Type type2 = VisitCallSite(callSite, state); if (type == null) { type = type2; } } return type; } protected override System.Type? VisitIEnumerable(IEnumerableCallSite enumerableCallSite, CallSiteValidatorState state) { System.Type type = null; ServiceCallSite[] serviceCallSites = enumerableCallSite.ServiceCallSites; foreach (ServiceCallSite callSite in serviceCallSites) { System.Type type2 = VisitCallSite(callSite, state); if (type == null) { type = type2; } } return type; } protected override System.Type? VisitRootCache(ServiceCallSite singletonCallSite, CallSiteValidatorState state) { state.Singleton = singletonCallSite; return VisitCallSiteMain(singletonCallSite, state); } protected override System.Type? VisitScopeCache(ServiceCallSite scopedCallSite, CallSiteValidatorState state) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) if (scopedCallSite.ServiceType == typeof(IServiceScopeFactory)) { return null; } if (state.Singleton != null) { throw new InvalidOperationException(System.SR.Format(System.SR.ScopedInSingletonException, scopedCallSite.ServiceType, state.Singleton.ServiceType, "Scoped".ToLowerInvariant(), "Singleton".ToLowerInvariant())); } VisitCallSiteMain(scopedCallSite, state); return scopedCallSite.ServiceType; } protected override System.Type? VisitConstant(ConstantCallSite constantCallSite, CallSiteValidatorState state) { return null; } protected override System.Type? VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, CallSiteValidatorState state) { return null; } protected override System.Type? VisitFactory(FactoryCallSite factoryCallSite, CallSiteValidatorState state) { return null; } } internal abstract class CallSiteVisitor<TArgument, TResult> { private readonly StackGuard _stackGuard; protected CallSiteVisitor() { _stackGuard = new StackGuard(); } protected virtual TResult VisitCallSite(ServiceCallSite callSite, TArgument argument) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) if (!_stackGuard.TryEnterOnCurrentStack()) { return _stackGuard.RunOnEmptyStack<ServiceCallSite, TArgument, TResult>((Func<ServiceCallSite, TArgument, TResult>)(object)new Func<ServiceCallSite, ServiceCallSite, TArgument>(VisitCallSite), callSite, argument); } return callSite.Cache.Location switch { CallSiteResultCacheLocation.Root => VisitRootCache(callSite, argument), CallSiteResultCacheLocation.Scope => VisitScopeCache(callSite, argument), CallSiteResultCacheLocation.Dispose => VisitDisposeCache(callSite, argument), CallSiteResultCacheLocation.None => VisitNoCache(callSite, argument), _ => throw new ArgumentOutOfRangeException(), }; } protected virtual TResult VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) return callSite.Kind switch { CallSiteKind.Factory => VisitFactory((FactoryCallSite)callSite, argument), CallSiteKind.IEnumerable => VisitIEnumerable((IEnumerableCallSite)callSite, argument), CallSiteKind.Constructor => VisitConstructor((ConstructorCallSite)callSite, argument), CallSiteKind.Constant => VisitConstant((ConstantCallSite)callSite, argument), CallSiteKind.ServiceProvider => VisitServiceProvider((ServiceProviderCallSite)callSite, argument), _ => throw new NotSupportedException(System.SR.Format(System.SR.CallSiteTypeNotSupported, ((object)callSite).GetType())), }; } protected virtual TResult VisitNoCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitDisposeCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitRootCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected virtual TResult VisitScopeCache(ServiceCallSite callSite, TArgument argument) { return VisitCallSiteMain(callSite, argument); } protected abstract TResult VisitConstructor(ConstructorCallSite constructorCallSite, TArgument argument); protected abstract TResult VisitConstant(ConstantCallSite constantCallSite, TArgument argument); protected abstract TResult VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, TArgument argument); protected abstract TResult VisitIEnumerable(IEnumerableCallSite enumerableCallSite, TArgument argument); protected abstract TResult VisitFactory(FactoryCallSite factoryCallSite, TArgument argument); } internal abstract class CompiledServiceProviderEngine : ServiceProviderEngine { [field: CompilerGenerated] public ILEmitResolverBuilder ResolverBuilder { [CompilerGenerated] get; } [RequiresDynamicCode("Creates DynamicMethods")] public CompiledServiceProviderEngine(ServiceProvider provider) { ResolverBuilder = new ILEmitResolverBuilder(provider); } public override Func<ServiceProviderEngineScope, object?> RealizeService(ServiceCallSite callSite) { return ResolverBuilder.Build(callSite); } } internal sealed class ConstantCallSite : ServiceCallSite { private readonly System.Type _serviceType; internal object? DefaultValue => base.Value; public override System.Type ServiceType => _serviceType; public override System.Type ImplementationType => DefaultValue?.GetType() ?? _serviceType; [field: CompilerGenerated] public override CallSiteKind Kind { [CompilerGenerated] get; } = CallSiteKind.Constant; public ConstantCallSite(System.Type serviceType, object? defaultValue) : base(ResultCache.None) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) _serviceType = serviceType ?? throw new ArgumentNullException("serviceType"); if (defaultValue != null && !serviceType.IsInstanceOfType(defaultValue)) { throw new ArgumentException(System.SR.Format(System.SR.ConstantCantBeConvertedToServiceType, defaultValue.GetType(), serviceType)); } base.Value = defaultValue; } } internal sealed class ConstructorCallSite : ServiceCallSite { [field: CompilerGenerated] internal ConstructorInfo ConstructorInfo { [CompilerGenerated] get; } [field: CompilerGenerated] internal ServiceCallSite[] ParameterCallSites { [CompilerGenerated] get; } [field: CompilerGenerated] public override System.Type ServiceType { [CompilerGenerated] get; } public override System.Type? ImplementationType => ((MemberInfo)ConstructorInfo).DeclaringType; [field: CompilerGenerated] public override CallSiteKind Kind { [CompilerGenerated] get; } = CallSiteKind.Constructor; public ConstructorCallSite(ResultCache cache, System.Type serviceType, ConstructorInfo constructorInfo) : this(cache, serviceType, constructorInfo, System.Array.Empty<ServiceCallSite>()) { } public ConstructorCallSite(ResultCache cache, System.Type serviceType, ConstructorInfo constructorInfo, ServiceCallSite[] parameterCallSites) : base(cache) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (!serviceType.IsAssignableFrom(((MemberInfo)constructorInfo).DeclaringType)) { throw new ArgumentException(System.SR.Format(System.SR.ImplementationTypeCantBeConvertedToServiceType, ((MemberInfo)constructorInfo).DeclaringType, serviceType)); } ServiceType = serviceType; ConstructorInfo = constructorInfo; ParameterCallSites = parameterCallSites; } } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] internal sealed class DynamicServiceProviderEngine : CompiledServiceProviderEngine { private readonly ServiceProvider _serviceProvider; public DynamicServiceProviderEngine(ServiceProvider serviceProvider) : base(serviceProvider) { _serviceProvider = serviceProvider; } public override Func<ServiceProviderEngineScope, object?> RealizeService(ServiceCallSite callSite) { ServiceCallSite callSite2 = callSite; int callCount = 0; WaitCallback val = default(WaitCallback); return delegate(ServiceProviderEngineScope scope) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown //IL_003e: Expected O, but got Unknown object result = CallSiteRuntimeResolver.Instance.Resolve(callSite2, scope); if (Interlocked.Increment(ref callCount) == 2) { WaitCallback obj = val; if (obj == null) { WaitCallback val2 = delegate { try { _serviceProvider.ReplaceServiceAccessor(callSite2, base.RealizeService(callSite2)); } catch (System.Exception exception) { DependencyInjectionEventSource.Log.ServiceRealizationFailed(exception, ((object)_serviceProvider).GetHashCode()); } }; WaitCallback val3 = val2; val = val2; obj = val3; } ThreadPool.UnsafeQueueUserWorkItem(obj, (object)null); } return result; }; } } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] internal sealed class ExpressionResolverBuilder : CallSiteVisitor<object?, Expression> { private static readonly ParameterExpression ScopeParameter = Expression.Parameter(typeof(ServiceProviderEngineScope)); private static readonly ParameterExpression ResolvedServices = Expression.Variable(typeof(IDictionary<ServiceCacheKey, object>), ScopeParameter.Name + "resolvedServices"); private static readonly ParameterExpression Sync = Expression.Variable(typeof(object), ScopeParameter.Name + "sync"); private static readonly BinaryExpression ResolvedServicesVariableAssignment = Expression.Assign((Expression)(object)ResolvedServices, (Expression)(object)Expression.Property((Expression)(object)ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("ResolvedServices", (BindingFlags)36))); private static readonly BinaryExpression SyncVariableAssignment = Expression.Assign((Expression)(object)Sync, (Expression)(object)Expression.Property((Expression)(object)ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("Sync", (BindingFlags)36))); private static readonly ParameterExpression CaptureDisposableParameter = Expression.Parameter(typeof(object)); private static readonly LambdaExpression CaptureDisposable = Expression.Lambda((Expression)(object)Expression.Call((Expression)(object)ScopeParameter, ServiceLookupHelpers.CaptureDisposableMethodInfo, (Expression[])(object)new Expression[1] { (Expression)CaptureDisposableParameter }), (ParameterExpression[])(object)new ParameterExpression[1] { CaptureDisposableParameter }); private static readonly ConstantExpression CallSiteRuntimeResolverInstanceExpression = Expression.Constant((object)CallSiteRuntimeResolver.Instance, typeof(CallSiteRuntimeResolver)); private readonly ServiceProviderEngineScope _rootScope; private readonly ConcurrentDictionary<ServiceCacheKey, Func<ServiceProviderEngineScope, object>> _scopeResolverCache; private readonly Func<ServiceCacheKey, ServiceCallSite, Func<ServiceProviderEngineScope, object>> _buildTypeDelegate; public ExpressionResolverBuilder(ServiceProvider serviceProvider) { _rootScope = serviceProvider.Root; _scopeResolverCache = new ConcurrentDictionary<ServiceCacheKey, Func<ServiceProviderEngineScope, object>>(); _buildTypeDelegate = [CompilerGenerated] (ServiceCacheKey key, ServiceCallSite cs) => BuildNoCache(cs); } public Func<ServiceProviderEngineScope, object> Build(ServiceCallSite callSite) { if (callSite.Cache.Location == CallSiteResultCacheLocation.Scope) { return _scopeResolverCache.GetOrAdd<ServiceCallSite>(callSite.Cache.Key, _buildTypeDelegate, callSite); } return BuildNoCache(callSite); } public Func<ServiceProviderEngineScope, object> BuildNoCache(ServiceCallSite callSite) { Expression<Func<ServiceProviderEngineScope, object>> val = BuildExpression(callSite); DependencyInjectionEventSource.Log.ExpressionTreeGenerated(_rootScope.RootProvider, callSite.ServiceType, (Expression)(object)val); return val.Compile(); } private Expression<Func<ServiceProviderEngineScope, object>> BuildExpression(ServiceCallSite callSite) { if (callSite.Cache.Location == CallSiteResultCacheLocation.Scope) { return Expression.Lambda<Func<ServiceProviderEngineScope, object>>((Expression)(object)Expression.Block((System.Collections.Generic.IEnumerable<ParameterExpression>)(object)new ParameterExpression[2] { ResolvedServices, Sync }, (Expression[])(object)new Expression[3] { (Expression)ResolvedServicesVariableAssignment, (Expression)SyncVariableAssignment, BuildScopedExpression(callSite) }), (ParameterExpression[])(object)new ParameterExpression[1] { ScopeParameter }); } return Expression.Lambda<Func<ServiceProviderEngineScope, object>>(Convert(VisitCallSite(callSite, null), typeof(object), forceValueTypeConversion: true), (ParameterExpression[])(object)new ParameterExpression[1] { ScopeParameter }); } protected override Expression VisitRootCache(ServiceCallSite singletonCallSite, object? context) { return (Expression)(object)Expression.Constant(CallSiteRuntimeResolver.Instance.Resolve(singletonCallSite, _rootScope)); } protected override Expression VisitConstant(ConstantCallSite constantCallSite, object? context) { return (Expression)(object)Expression.Constant(constantCallSite.DefaultValue); } protected override Expression VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, object? context) { return (Expression)(object)ScopeParameter; } protected override Expression VisitFactory(FactoryCallSite factoryCallSite, object? context) { return (Expression)(object)Expression.Invoke((Expression)(object)Expression.Constant((object)factoryCallSite.Factory), (Expression[])(object)new Expression[1] { (Expression)ScopeParameter }); } protected override Expression VisitIEnumerable(IEnumerableCallSite callSite, object? context) { object context2 = context; IEnumerableCallSite callSite2 = callSite; if (callSite2.ServiceCallSites.Length == 0) { return (Expression)(object)Expression.Constant(((MethodBase)ServiceLookupHelpers.GetArrayEmptyMethodInfo(callSite2.ItemType)).Invoke((object)null, System.Array.Empty<object>())); } return (Expression)(object)Expression.NewArrayInit(callSite2.ItemType, Enumerable.Select<ServiceCallSite, Expression>((System.Collections.Generic.IEnumerable<ServiceCallSite>)callSite2.ServiceCallSites, (Func<ServiceCallSite, Expression>)((ServiceCallSite cs) => Convert(VisitCallSite(cs, context2), callSite2.ItemType)))); } protected override Expression VisitDisposeCache(ServiceCallSite callSite, object? context) { return TryCaptureDisposable(callSite, ScopeParameter, VisitCallSiteMain(callSite, context)); } private static Expression TryCaptureDisposable(ServiceCallSite callSite, ParameterExpression scope, Expression service) { if (!callSite.CaptureDisposable) { return service; } return (Expression)(object)Expression.Invoke(GetCaptureDisposable(scope), (Expression[])(object)new Expression[1] { service }); } protected override Expression VisitConstructor(ConstructorCallSite callSite, object? context) { ParameterInfo[] parameters = ((MethodBase)callSite.ConstructorInfo).GetParameters(); Expression[] array; if (callSite.ParameterCallSites.Length == 0) { array = System.Array.Empty<Expression>(); } else { array = (Expression[])(object)new Expression[callSite.ParameterCallSites.Length]; for (int i = 0; i < array.Length; i++) { array[i] = Convert(VisitCallSite(callSite.ParameterCallSites[i], context), parameters[i].ParameterType); } } Expression val = (Expression)(object)Expression.New(callSite.ConstructorInfo, array); if (callSite.ImplementationType.IsValueType) { val = (Expression)(object)Expression.Convert(val, typeof(object)); } return val; } private static Expression Convert(Expression expression, System.Type type, bool forceValueTypeConversion = false) { if (type.IsAssignableFrom(expression.Type) && (!expression.Type.IsValueType || !forceValueTypeConversion)) { return expression; } return (Expression)(object)Expression.Convert(expression, type); } protected override Expression VisitScopeCache(ServiceCallSite callSite, object? context) { Func<ServiceProviderEngineScope, object> val = Build(callSite); return (Expression)(object)Expression.Invoke((Expression)(object)Expression.Constant((object)val), (Expression[])(object)new Expression[1] { (Expression)ScopeParameter }); } private Expression BuildScopedExpression(ServiceCallSite callSite) { ConstantExpression val = Expression.Constant((object)callSite, typeof(ServiceCallSite)); MethodCallExpression val2 = Expression.Call((Expression)(object)CallSiteRuntimeResolverInstanceExpression, ServiceLookupHelpers.ResolveCallSiteAndScopeMethodInfo, (Expression)(object)val, (Expression)(object)ScopeParameter); ConstantExpression val3 = Expression.Constant((object)callSite.Cache.Key, typeof(ServiceCacheKey)); ParameterExpression val4 = Expression.Variable(typeof(object), "resolved"); ParameterExpression resolvedServices = ResolvedServices; MethodCallExpression val5 = Expression.Call((Expression)(object)resolvedServices, ServiceLookupHelpers.TryGetValueMethodInfo, (Expression)(object)val3, (Expression)(object)val4); Expression val6 = TryCaptureDisposable(callSite, ScopeParameter, VisitCallSiteMain(callSite, null)); BinaryExpression val7 = Expression.Assign((Expression)(object)val4, val6); MethodCallExpression val8 = Expression.Call((Expression)(object)resolvedServices, ServiceLookupHelpers.AddMethodInfo, (Expression)(object)val3, (Expression)(object)val4); BlockExpression val9 = Expression.Block(typeof(object), (System.Collections.Generic.IEnumerable<ParameterExpression>)(object)new ParameterExpression[1] { val4 }, (Expression[])(object)new Expression[2] { (Expression)Expression.IfThen((Expression)(object)Expression.Not((Expression)(object)val5), (Expression)(object)Expression.Block((Expression)(object)val7, (Expression)(object)val8)), (Expression)val4 }); ParameterExpression val10 = Expression.Variable(typeof(bool), "lockWasTaken"); ParameterExpression sync = Sync; MethodCallExpression val11 = Expression.Call(ServiceLookupHelpers.MonitorEnterMethodInfo, (Expression)(object)sync, (Expression)(object)val10); MethodCallExpression val12 = Expression.Call(ServiceLookupHelpers.MonitorExitMethodInfo, (Expression)(object)sync); BlockExpression val13 = Expression.Block((Expression)(object)val11, (Expression)(object)val9); ConditionalExpression val14 = Expression.IfThen((Expression)(object)val10, (Expression)(object)val12); return (Expression)(object)Expression.Condition((Expression)(object)Expression.Property((Expression)(object)ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("IsRootScope", (BindingFlags)20)), (Expression)(object)val2, (Expression)(object)Expression.Block(typeof(object), (System.Collections.Generic.IEnumerable<ParameterExpression>)(object)new ParameterExpression[1] { val10 }, (Expression[])(object)new Expression[1] { (Expression)Expression.TryFinally((Expression)(object)val13, (Expression)(object)val14) })); } public static Expression GetCaptureDisposable(ParameterExpression scope) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (scope != ScopeParameter) { throw new NotSupportedException(System.SR.GetCaptureDisposableNotSupported); } return (Expression)(object)CaptureDisposable; } } internal sealed class ExpressionsServiceProviderEngine : ServiceProviderEngine { private readonly ExpressionResolverBuilder _expressionResolverBuilder; [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] public ExpressionsServiceProviderEngine(ServiceProvider serviceProvider) { _expressionResolverBuilder = new ExpressionResolverBuilder(serviceProvider); } public override Func<ServiceProviderEngineScope, object> RealizeService(ServiceCallSite callSite) { return _expressionResolverBuilder.Build(callSite); } } internal sealed class FactoryCallSite : ServiceCallSite { [field: CompilerGenerated] public Func<IServiceProvider, object> Factory { [CompilerGenerated] get; } [field: CompilerGenerated] public override System.Type ServiceType { [CompilerGenerated] get; } public override System.Type? ImplementationType => null; [field: CompilerGenerated] public override CallSiteKind Kind { [CompilerGenerated] get; } public FactoryCallSite(ResultCache cache, System.Type serviceType, Func<IServiceProvider, object> factory) : base(cache) { Factory = factory; ServiceType = serviceType; } } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] internal sealed class IEnumerableCallSite : ServiceCallSite { [field: CompilerGenerated] internal System.Type ItemType { [CompilerGenerated] get; } [field: CompilerGenerated] internal ServiceCallSite[] ServiceCallSites { [CompilerGenerated] get; } public override System.Type ServiceType => typeof(System.Collections.Generic.IEnumerable<>).MakeGenericType(new System.Type[1] { ItemType }); public override System.Type ImplementationType => ItemType.MakeArrayType(); [field: CompilerGenerated] public override CallSiteKind Kind { [CompilerGenerated] get; } = CallSiteKind.IEnumerable; public IEnumerableCallSite(ResultCache cache, System.Type itemType, ServiceCallSite[] serviceCallSites) : base(cache) { ItemType = itemType; ServiceCallSites = serviceCallSites; } } internal struct ResultCache { [field: CompilerGenerated] public static ResultCache None { [CompilerGenerated] get; } = new ResultCache(CallSiteResultCacheLocation.None, ServiceCacheKey.Empty); [field: CompilerGenerated] public CallSiteResultCacheLocation Location { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public ServiceCacheKey Key { [CompilerGenerated] get; [CompilerGenerated] set; } internal ResultCache(CallSiteResultCacheLocation lifetime, ServiceCacheKey cacheKey) { Location = lifetime; Key = cacheKey; } public ResultCache(ServiceLifetime lifetime, System.Type? type, int slot) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected I4, but got Unknown switch ((int)lifetime) { case 0: Location = CallSiteResultCacheLocation.Root; break; case 1: Location = CallSiteResultCacheLocation.Scope; break; case 2: Location = CallSiteResultCacheLocation.Dispose; break; default: Location = CallSiteResultCacheLocation.None; break; } Key = new ServiceCacheKey(type, slot); } } [RequiresDynamicCode("Using Microsoft.Extensions.DependencyInjection requires generating code dynamically at runtime. For example, when using enumerable and generic ValueType services.")] internal sealed class RuntimeServiceProviderEngine : ServiceProviderEngine { [field: CompilerGenerated] public static RuntimeServiceProviderEngine Instance { [CompilerGenerated] get; } = new RuntimeServiceProviderEngine(); private RuntimeServiceProviderEngine() { } public override Func<ServiceProviderEngineScope, object?> RealizeService(ServiceCallSite callSite) { ServiceCallSite callSite2 = callSite; return (ServiceProviderEngineScope scope) => CallSiteRuntimeResolver.Instance.Resolve(callSite2, scope); } } internal readonly struct ServiceCacheKey : IEquatable<ServiceCacheKey> { [field: CompilerGenerated] public static ServiceCacheKey Empty { [CompilerGenerated] get; } = new ServiceCacheKey(null, 0); [field: CompilerGenerated] public System.Type? Type { [CompilerGenerated] get; } [field: CompilerGenerated] public int Slot { [CompilerGenerated] get; } public ServiceCacheKey(System.Type? type, int slot) { Type = type; Slot = slot; } public bool Equals(ServiceCacheKey other) { if (Type == other.Type) { return Slot == other.Slot; } return false; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ServiceCacheKey other) { return Equals(other); } return false; } public override int GetHashCode() { return ((((object)Type)?.GetHashCode() ?? 23) * 397) ^ Slot; } } internal abstract class ServiceCallSite { public abstract System.Type ServiceType { get; } public abstract System.Type? ImplementationType { get; } public abstract CallSiteKind Kind { get; } [field: CompilerGenerated] public ResultCache Cache { [CompilerGenerated] get; } [field: CompilerGenerated] public object? Value { [CompilerGenerated] get; [CompilerGenerated] set; } public bool CaptureDisposable { get { if (!(ImplementationType == (System.Type)null) && !typeof(System.IDisposable).IsAssignableFrom(ImplementationType)) { return typeof(System.IAsyncDisposable).IsAssignableFrom(ImplementationType); } return true; } } protected ServiceCallSite(ResultCache cache) { Cache = cache; } } internal static class ServiceLookupHelpers { private const BindingFlags LookupFlags = 52; private static readonly MethodInfo ArrayEmptyMethodInfo = typeof(System.Array).GetMethod("Empty"); internal static readonly MethodInfo InvokeFactoryMethodInfo = typeof(Func<IServiceProvider, object>).GetMethod("Invoke", (BindingFlags)52); internal static readonly MethodInfo CaptureDisposableMethodInfo = typeof(ServiceProviderEngineScope).GetMethod("CaptureDisposable", (BindingFlags)52); internal static readonly MethodInfo TryGetValueMethodInfo = typeof(IDictionary<ServiceCacheKey, object>).GetMethod("TryGetValue", (BindingFlags)52); internal static readonly MethodInfo ResolveCallSiteAndScopeMethodInfo = typeof(CallSiteRuntimeResolver).GetMethod("Resolve", (BindingFlags)52); internal static readonly MethodInfo AddMethodInfo = typeof(IDictionary<ServiceCacheKey, object>).GetMethod("Add", (BindingFlags)52); internal static readonly MethodInfo MonitorEnterMethodInfo = typeof(Monitor).GetMethod("Enter", (BindingFlags)24, (Binder)null, new System.Type[2] { typeof(object), typeof(bool).MakeByRefType() }, (ParameterModifier[])null); internal static readonly MethodInfo MonitorExitMethodInfo = typeof(Monitor).GetMethod("Exit", (BindingFlags)24, (Binder)null, new System.Type[1] { typeof(object) }, (ParameterModifier[])null); [RequiresDynamicCode("The code for an array of the specified type might not be available.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "Calling Array.Empty<T>() is safe since the T doesn't have trimming annotations.")] internal static MethodInfo GetArrayEmptyMethodInfo(System.Type itemType) { return ArrayEmptyMethodInfo.MakeGenericMethod(new System.Type[1] { itemType }); } } internal sealed class ServiceProviderCallSite : ServiceCallSite { [field: CompilerGenerated] public override System.Type ServiceType { [CompilerGenerated] get; } = typeof(IServiceProvider); [field: CompilerGenerated] public override System.Type ImplementationType { [CompilerGenerated] get; } = typeof(ServiceProvider); [field: CompilerGenerated] public override CallSiteKind Kind { [CompilerGenerated] get; } = CallSiteKind.ServiceProvider; public ServiceProviderCallSite() : base(ResultCache.None) { } } internal abstract class ServiceProviderEngine { public abstract Func<ServiceProviderEngineScope, object?> RealizeService(ServiceCallSite callSite); } internal sealed class ServiceProviderEngineScope : IServiceScope, System.IDisposable, IServiceProvider, System.IAsyncDisposable, IServiceScopeFactory { [StructLayout(3)] [CompilerGenerated] private struct <<DisposeAsync>g__Await|22_0>d : IAsyncStateMachine { public int <>1__state; public AsyncValueTaskMethodBuilder <>t__builder; public System.Threading.Tasks.ValueTask vt; public int i; public List<object> toDispose; private ConfiguredValueTaskAwaiter <>u__1; private void MoveNext() { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: 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_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { ConfiguredValueTaskAwaiter awaiter; ConfiguredValueTaskAwaitable val; ConfiguredValueTaskAwaiter awaiter2; if (num != 0) { if (num == 1) { awaiter = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_010c; } val = vt.ConfigureAwait(false); awaiter2 = ((ConfiguredValueTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredValueTaskAwaiter)(ref awaiter2)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredValueTaskAwaiter, <<DisposeAsync>g__Await|22_0>d>(ref awaiter2, ref this); return; } } else { awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaiter); num = (<>1__state = -1); } ((ConfiguredValueTaskAwaiter)(ref awaiter2)).GetResult(); i--; goto IL_0131; IL_0121: i--; goto IL_0131; IL_0131: if (i >= 0) { object obj = toDispose[i]; if (obj is System.IAsyncDisposable asyncDisposable) { val = asyncDisposable.DisposeAsync().ConfigureAwait(false); awaiter = ((ConfiguredValueTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredValueTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__sta
AuriePack/AurieInstaller/Microsoft.Extensions.FileProviders.Abstractions.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using FxResources.Microsoft.Extensions.FileProviders.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.FileProviders.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Abstractions of files and directories.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.FileProviders.IDirectoryContents\r\nMicrosoft.Extensions.FileProviders.IFileInfo\r\nMicrosoft.Extensions.FileProviders.IFileProvider")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.FileProviders.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.FileProviders.Abstractions { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.FileProviders.Abstractions.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string FileNotExists => GetResourceString("FileNotExists"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.FileProviders { public interface IDirectoryContents : System.Collections.Generic.IEnumerable<IFileInfo>, System.Collections.IEnumerable { bool Exists { get; } } public interface IFileInfo { bool Exists { get; } long Length { get; } string? PhysicalPath { get; } string Name { get; } DateTimeOffset LastModified { get; } bool IsDirectory { get; } Stream CreateReadStream(); } public interface IFileProvider { IFileInfo GetFileInfo(string subpath); IDirectoryContents GetDirectoryContents(string subpath); IChangeToken Watch(string filter); } public class NotFoundDirectoryContents : IDirectoryContents, System.Collections.Generic.IEnumerable<IFileInfo>, System.Collections.IEnumerable { [field: CompilerGenerated] public static NotFoundDirectoryContents Singleton { [CompilerGenerated] get; } = new NotFoundDirectoryContents(); public bool Exists => false; public System.Collections.Generic.IEnumerator<IFileInfo> GetEnumerator() { return Enumerable.Empty<IFileInfo>().GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } public class NotFoundFileInfo : IFileInfo { public bool Exists => false; public bool IsDirectory => false; public DateTimeOffset LastModified => DateTimeOffset.MinValue; public long Length => -1L; [field: CompilerGenerated] public string Name { [CompilerGenerated] get; } public string? PhysicalPath => null; public NotFoundFileInfo(string name) { Name = name; } [DoesNotReturn] public Stream CreateReadStream() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) throw new FileNotFoundException(System.SR.Format(System.SR.FileNotExists, (object)Name)); } } public class NullChangeToken : IChangeToken { [field: CompilerGenerated] public static NullChangeToken Singleton { [CompilerGenerated] get; } = new NullChangeToken(); public bool HasChanged => false; public bool ActiveChangeCallbacks => false; private NullChangeToken() { } public System.IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { return EmptyDisposable.Instance; } } public class NullFileProvider : IFileProvider { public IDirectoryContents GetDirectoryContents(string subpath) { return NotFoundDirectoryContents.Singleton; } public IFileInfo GetFileInfo(string subpath) { return new NotFoundFileInfo(subpath); } public IChangeToken Watch(string filter) { return (IChangeToken)(object)NullChangeToken.Singleton; } } internal sealed class EmptyDisposable : System.IDisposable { [field: CompilerGenerated] public static EmptyDisposable Instance { [CompilerGenerated] get; } = new EmptyDisposable(); private EmptyDisposable() { } public void Dispose() { } } }
AuriePack/AurieInstaller/Microsoft.Extensions.FileProviders.Physical.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.FileProviders.Physical; using Microsoft.CodeAnalysis; using Microsoft.Extensions.FileProviders.Internal; using Microsoft.Extensions.FileProviders.Physical; using Microsoft.Extensions.FileProviders.Physical.Internal; using Microsoft.Extensions.FileSystemGlobbing; using Microsoft.Extensions.FileSystemGlobbing.Abstractions; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.FileProviders.Physical.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.FileProviders.Physical")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("File provider for physical files for Microsoft.Extensions.FileProviders.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.FileProviders.Physical")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(8, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.FileProviders.Physical { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.FileProviders.Physical.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string Error_FileSystemWatcherRequiredWithoutPolling => GetResourceString("Error_FileSystemWatcherRequiredWithoutPolling"); internal static string CannotCreateStream => GetResourceString("CannotCreateStream"); internal static string CannotModifyWhenFileWatcherInitialized => GetResourceString("CannotModifyWhenFileWatcherInitialized"); internal static string UnexpectedFileSystemInfo => GetResourceString("UnexpectedFileSystemInfo"); internal static string FileSystemWatcher_PlatformNotSupported => GetResourceString("FileSystemWatcher_PlatformNotSupported"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Internal { internal static class NonCapturingTimer { public static Timer Create(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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_0029: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (callback == null) { throw new ArgumentNullException("callback"); } bool flag = false; try { if (!ExecutionContext.IsFlowSuppressed()) { ExecutionContext.SuppressFlow(); flag = true; } return new Timer(callback, state, dueTime, period); } finally { if (flag) { ExecutionContext.RestoreFlow(); } } } } } namespace Microsoft.Extensions.FileProviders { internal interface IPollingChangeToken : IChangeToken { CancellationTokenSource? CancellationTokenSource { get; } } public class PhysicalFileProvider : IFileProvider, System.IDisposable { private const string PollingEnvironmentKey = "DOTNET_USE_POLLING_FILE_WATCHER"; private static readonly char[] _pathSeparators = new char[2] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; private readonly ExclusionFilters _filters; private readonly Func<PhysicalFilesWatcher> _fileWatcherFactory; private PhysicalFilesWatcher _fileWatcher; private bool _fileWatcherInitialized; private object _fileWatcherLock = new object(); private bool? _usePollingFileWatcher; private bool? _useActivePolling; private bool _disposed; public bool UsePollingFileWatcher { get { if (_fileWatcher != null) { return false; } if (!_usePollingFileWatcher.HasValue) { ReadPollingEnvironmentVariables(); } return _usePollingFileWatcher.GetValueOrDefault(); } set { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (_fileWatcher != null) { throw new InvalidOperationException(System.SR.Format(System.SR.CannotModifyWhenFileWatcherInitialized, (object?)"UsePollingFileWatcher")); } _usePollingFileWatcher = value; } } public bool UseActivePolling { get { if (!_useActivePolling.HasValue) { ReadPollingEnvironmentVariables(); } return _useActivePolling.Value; } set { _useActivePolling = value; } } internal PhysicalFilesWatcher FileWatcher { get { return LazyInitializer.EnsureInitialized<PhysicalFilesWatcher>(ref _fileWatcher, ref _fileWatcherInitialized, ref _fileWatcherLock, _fileWatcherFactory); } set { _fileWatcherInitialized = true; _fileWatcher = value; } } [field: CompilerGenerated] public string Root { [CompilerGenerated] get; } public PhysicalFileProvider(string root) : this(root, ExclusionFilters.Sensitive) { } public PhysicalFileProvider(string root, ExclusionFilters filters) { //IL_0023: 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) if (!Path.IsPathRooted(root)) { throw new ArgumentException("The path must be absolute.", "root"); } string fullPath = Path.GetFullPath(root); Root = PathUtils.EnsureTrailingSlash(fullPath); if (!Directory.Exists(Root)) { throw new DirectoryNotFoundException(Root); } _filters = filters; _fileWatcherFactory = CreateFileWatcher; } internal PhysicalFilesWatcher CreateFileWatcher() { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown string text = PathUtils.EnsureTrailingSlash(Path.GetFullPath(Root)); FileSystemWatcher fileSystemWatcher; if (OperatingSystem.IsBrowser() || (OperatingSystem.IsIOS() && !OperatingSystem.IsMacCatalyst()) || OperatingSystem.IsTvOS()) { UsePollingFileWatcher = true; UseActivePolling = true; fileSystemWatcher = null; } else { fileSystemWatcher = ((UsePollingFileWatcher && UseActivePolling) ? ((FileSystemWatcher)null) : new FileSystemWatcher(text)); } return new PhysicalFilesWatcher(text, fileSystemWatcher, UsePollingFileWatcher, _filters) { UseActivePolling = UseActivePolling }; } [MemberNotNull("_usePollingFileWatcher")] [MemberNotNull("_useActivePolling")] private void ReadPollingEnvironmentVariables() { string environmentVariable = Environment.GetEnvironmentVariable("DOTNET_USE_POLLING_FILE_WATCHER"); bool flag = string.Equals(environmentVariable, "1", (StringComparison)4) || string.Equals(environmentVariable, "true", (StringComparison)5); _usePollingFileWatcher = flag; _useActivePolling = flag; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize((object)this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _fileWatcher?.Dispose(); } _disposed = true; } } private string GetFullPath(string path) { if (PathUtils.PathNavigatesAboveRoot(path)) { return null; } string fullPath; try { fullPath = Path.GetFullPath(Path.Combine(Root, path)); } catch { return null; } if (!IsUnderneathRoot(fullPath)) { return null; } return fullPath; } private bool IsUnderneathRoot(string fullPath) { return fullPath.StartsWith(Root, (StringComparison)5); } public IFileInfo GetFileInfo(string subpath) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown if (string.IsNullOrEmpty(subpath) || PathUtils.HasInvalidPathChars(subpath)) { return (IFileInfo)new NotFoundFileInfo(subpath); } subpath = subpath.TrimStart(_pathSeparators); if (Path.IsPathRooted(subpath)) { return (IFileInfo)new NotFoundFileInfo(subpath); } string fullPath = GetFullPath(subpath); if (fullPath == null) { return (IFileInfo)new NotFoundFileInfo(subpath); } FileInfo val = new FileInfo(fullPath); if (FileSystemInfoHelper.IsExcluded((FileSystemInfo)(object)val, _filters)) { return (IFileInfo)new NotFoundFileInfo(subpath); } return (IFileInfo)(object)new PhysicalFileInfo(val); } public IDirectoryContents GetDirectoryContents(string subpath) { try { if (subpath == null || PathUtils.HasInvalidPathChars(subpath)) { return (IDirectoryContents)(object)NotFoundDirectoryContents.Singleton; } subpath = subpath.TrimStart(_pathSeparators); if (Path.IsPathRooted(subpath)) { return (IDirectoryContents)(object)NotFoundDirectoryContents.Singleton; } string fullPath = GetFullPath(subpath); if (fullPath == null || !Directory.Exists(fullPath)) { return (IDirectoryContents)(object)NotFoundDirectoryContents.Singleton; } return (IDirectoryContents)(object)new PhysicalDirectoryContents(fullPath, _filters); } catch (DirectoryNotFoundException) { } catch (IOException) { } return (IDirectoryContents)(object)NotFoundDirectoryContents.Singleton; } public IChangeToken Watch(string filter) { if (filter == null || PathUtils.HasInvalidFilterChars(filter)) { return (IChangeToken)(object)NullChangeToken.Singleton; } filter = filter.TrimStart(_pathSeparators); return FileWatcher.CreateFileChangeToken(filter); } } internal sealed class EmptyDisposable : System.IDisposable { [field: CompilerGenerated] public static EmptyDisposable Instance { [CompilerGenerated] get; } = new EmptyDisposable(); private EmptyDisposable() { } public void Dispose() { } } } namespace Microsoft.Extensions.FileProviders.Internal { public class PhysicalDirectoryContents : IDirectoryContents, System.Collections.Generic.IEnumerable<IFileInfo>, System.Collections.IEnumerable { private System.Collections.Generic.IEnumerable<IFileInfo> _entries; private readonly string _directory; private readonly ExclusionFilters _filters; public bool Exists => Directory.Exists(_directory); public PhysicalDirectoryContents(string directory) : this(directory, ExclusionFilters.Sensitive) { } public PhysicalDirectoryContents(string directory, ExclusionFilters filters) { ThrowHelper.ThrowIfNull(directory, "directory"); _directory = directory; _filters = filters; } public System.Collections.Generic.IEnumerator<IFileInfo> GetEnumerator() { EnsureInitialized(); return _entries.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { EnsureInitialized(); return (System.Collections.IEnumerator)_entries.GetEnumerator(); } [MemberNotNull("_entries")] private void EnsureInitialized() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) try { _entries = Enumerable.Select<FileSystemInfo, IFileInfo>(Enumerable.Where<FileSystemInfo>(new DirectoryInfo(_directory).EnumerateFileSystemInfos(), (Func<FileSystemInfo, bool>)([CompilerGenerated] (FileSystemInfo info) => !FileSystemInfoHelper.IsExcluded(info, _filters))), (Func<FileSystemInfo, IFileInfo>)delegate(FileSystemInfo info) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) FileInfo val = (FileInfo)(object)((info is FileInfo) ? info : null); if (val != null) { return (IFileInfo)(object)new PhysicalFileInfo(val); } DirectoryInfo val2 = (DirectoryInfo)(object)((info is DirectoryInfo) ? info : null); if (val2 != null) { return (IFileInfo)(object)new PhysicalDirectoryInfo(val2); } throw new InvalidOperationException(System.SR.UnexpectedFileSystemInfo); }); } catch (System.Exception ex) when (ex is DirectoryNotFoundException || ex is IOException) { _entries = Enumerable.Empty<IFileInfo>(); } } } } namespace Microsoft.Extensions.FileProviders.Physical { [Flags] public enum ExclusionFilters { Sensitive = 7, DotPrefixed = 1, Hidden = 2, System = 4, None = 0 } internal sealed class Clock : IClock { public static readonly Clock Instance = new Clock(); public System.DateTime UtcNow => System.DateTime.UtcNow; private Clock() { } } internal static class FileSystemInfoHelper { public static bool IsExcluded(FileSystemInfo fileSystemInfo, ExclusionFilters filters) { //IL_0028: 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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) if (filters == ExclusionFilters.None) { return false; } if (fileSystemInfo.Name.StartsWith(".", (StringComparison)4) && (filters & ExclusionFilters.DotPrefixed) != 0) { return true; } if (fileSystemInfo.Exists && (((fileSystemInfo.Attributes & 2) != 0 && (filters & ExclusionFilters.Hidden) != 0) || ((fileSystemInfo.Attributes & 4) != 0 && (filters & ExclusionFilters.System) != 0))) { return true; } return false; } public static System.DateTime? GetFileLinkTargetLastWriteTimeUtc(string filePath) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown FileInfo val = new FileInfo(filePath); if (((FileSystemInfo)val).Exists) { return GetFileLinkTargetLastWriteTimeUtc(val); } return null; } public static System.DateTime? GetFileLinkTargetLastWriteTimeUtc(FileInfo fileInfo) { if (((FileSystemInfo)fileInfo).LinkTarget != null) { try { FileSystemInfo val = ((FileSystemInfo)fileInfo).ResolveLinkTarget(true); if (val != null && val.Exists) { return val.LastWriteTimeUtc; } } catch (System.Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { } return System.DateTime.MinValue; } return null; } } internal interface IClock { System.DateTime UtcNow { get; } } public class PhysicalDirectoryInfo : IFileInfo { private readonly DirectoryInfo _info; public bool Exists => ((FileSystemInfo)_info).Exists; public long Length => -1L; public string PhysicalPath => ((FileSystemInfo)_info).FullName; public string Name => ((FileSystemInfo)_info).Name; public DateTimeOffset LastModified => DateTimeOffset.op_Implicit(((FileSystemInfo)_info).LastWriteTimeUtc); public bool IsDirectory => true; public PhysicalDirectoryInfo(DirectoryInfo info) { _info = info; } public Stream CreateReadStream() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) throw new InvalidOperationException(System.SR.CannotCreateStream); } } public class PhysicalFileInfo : IFileInfo { private readonly FileInfo _info; public bool Exists => ((FileSystemInfo)_info).Exists; public long Length => _info.Length; public string PhysicalPath => ((FileSystemInfo)_info).FullName; public string Name => ((FileSystemInfo)_info).Name; public DateTimeOffset LastModified => DateTimeOffset.op_Implicit(((FileSystemInfo)_info).LastWriteTimeUtc); public bool IsDirectory => false; public PhysicalFileInfo(FileInfo info) { _info = info; } public Stream CreateReadStream() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown int num = 1; return (Stream)new FileStream(PhysicalPath, (FileMode)3, (FileAccess)1, (FileShare)3, num, (FileOptions)1207959552); } } public class PhysicalFilesWatcher : System.IDisposable { private readonly struct ChangeTokenInfo { [field: CompilerGenerated] public CancellationTokenSource TokenSource { [CompilerGenerated] get; } [field: CompilerGenerated] public CancellationChangeToken ChangeToken { [CompilerGenerated] get; } [field: CompilerGenerated] public Matcher Matcher { [CompilerGenerated] get; } public ChangeTokenInfo(CancellationTokenSource tokenSource, CancellationChangeToken changeToken) : this(tokenSource, changeToken, null) { } public ChangeTokenInfo(CancellationTokenSource tokenSource, CancellationChangeToken changeToken, Matcher matcher) { TokenSource = tokenSource; ChangeToken = changeToken; Matcher = matcher; } } [CompilerGenerated] private static class <>O { public static TimerCallback <0>__RaiseChangeEvents; } private static readonly Action<object> _cancelTokenSource = delegate(object state) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ((CancellationTokenSource)state).Cancel(); }; internal static TimeSpan DefaultPollingInterval = TimeSpan.FromSeconds(4.0); private readonly ConcurrentDictionary<string, ChangeTokenInfo> _filePathTokenLookup = new ConcurrentDictionary<string, ChangeTokenInfo>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary<string, ChangeTokenInfo> _wildcardTokenLookup = new ConcurrentDictionary<string, ChangeTokenInfo>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); private readonly FileSystemWatcher _fileWatcher; private readonly object _fileWatcherLock = new object(); private readonly string _root; private readonly ExclusionFilters _filters; private Timer _timer; private bool _timerInitialized; private object _timerLock = new object(); private Func<Timer> _timerFactory; private bool _disposed; [field: CompilerGenerated] internal bool PollForChanges { [CompilerGenerated] get; } [field: CompilerGenerated] internal bool UseActivePolling { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] internal ConcurrentDictionary<IPollingChangeToken, IPollingChangeToken> PollingChangeTokens { [CompilerGenerated] get; } public PhysicalFilesWatcher(string root, FileSystemWatcher? fileSystemWatcher, bool pollForChanges) : this(root, fileSystemWatcher, pollForChanges, ExclusionFilters.Sensitive) { } public PhysicalFilesWatcher(string root, FileSystemWatcher? fileSystemWatcher, bool pollForChanges, ExclusionFilters filters) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Expected O, but got Unknown //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Expected O, but got Unknown //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Expected O, but got Unknown //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown if (fileSystemWatcher == null && !pollForChanges) { throw new ArgumentNullException("fileSystemWatcher", System.SR.Error_FileSystemWatcherRequiredWithoutPolling); } _root = root; if (fileSystemWatcher != null) { if (OperatingSystem.IsBrowser() || (OperatingSystem.IsIOS() && !OperatingSystem.IsMacCatalyst()) || OperatingSystem.IsTvOS()) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.FileSystemWatcher_PlatformNotSupported, typeof(FileSystemWatcher))); } _fileWatcher = fileSystemWatcher; _fileWatcher.IncludeSubdirectories = true; _fileWatcher.Created += new FileSystemEventHandler(OnChanged); _fileWatcher.Changed += new FileSystemEventHandler(OnChanged); _fileWatcher.Renamed += new RenamedEventHandler(OnRenamed); _fileWatcher.Deleted += new FileSystemEventHandler(OnChanged); _fileWatcher.Error += new ErrorEventHandler(OnError); } PollForChanges = pollForChanges; _filters = filters; PollingChangeTokens = new ConcurrentDictionary<IPollingChangeToken, IPollingChangeToken>(); _timerFactory = [CompilerGenerated] () => { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown object obj = <>O.<0>__RaiseChangeEvents; if (obj == null) { TimerCallback val = RaiseChangeEvents; <>O.<0>__RaiseChangeEvents = val; obj = (object)val; } return NonCapturingTimer.Create((TimerCallback)obj, PollingChangeTokens, TimeSpan.Zero, DefaultPollingInterval); }; } public IChangeToken CreateFileChangeToken(string filter) { ThrowHelper.ThrowIfNull(filter, "filter"); filter = NormalizePath(filter); if (Path.IsPathRooted(filter) || PathUtils.PathNavigatesAboveRoot(filter)) { return (IChangeToken)(object)NullChangeToken.Singleton; } IChangeToken orAddChangeToken = GetOrAddChangeToken(filter); TryEnableFileSystemWatcher(); return orAddChangeToken; } private IChangeToken GetOrAddChangeToken(string pattern) { if (UseActivePolling) { LazyInitializer.EnsureInitialized<Timer>(ref _timer, ref _timerInitialized, ref _timerLock, _timerFactory); } if (pattern.IndexOf('*') != -1 || IsDirectoryPath(pattern)) { return GetOrAddWildcardChangeToken(pattern); } return GetOrAddFilePathChangeToken(pattern); } internal IChangeToken GetOrAddFilePathChangeToken(string filePath) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown ChangeTokenInfo orAdd = default(ChangeTokenInfo); if (!_filePathTokenLookup.TryGetValue(filePath, ref orAdd)) { CancellationTokenSource val = new CancellationTokenSource(); CancellationChangeToken changeToken = new CancellationChangeToken(val.Token); orAdd = new ChangeTokenInfo(val, changeToken); orAdd = _filePathTokenLookup.GetOrAdd(filePath, orAdd); } IChangeToken val2 = (IChangeToken)(object)orAdd.ChangeToken; if (PollForChanges) { PollingFileChangeToken pollingFileChangeToken = new PollingFileChangeToken(new FileInfo(Path.Combine(_root, filePath))); if (UseActivePolling) { pollingFileChangeToken.ActiveChangeCallbacks = true; pollingFileChangeToken.CancellationTokenSource = new CancellationTokenSource(); PollingChangeTokens.TryAdd((IPollingChangeToken)pollingFileChangeToken, (IPollingChangeToken)pollingFileChangeToken); } val2 = (IChangeToken)new CompositeChangeToken((System.Collections.Generic.IReadOnlyList<IChangeToken>)(object)new IChangeToken[2] { val2, pollingFileChangeToken }); } return val2; } internal IChangeToken GetOrAddWildcardChangeToken(string pattern) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown ChangeTokenInfo orAdd = default(ChangeTokenInfo); if (!_wildcardTokenLookup.TryGetValue(pattern, ref orAdd)) { CancellationTokenSource val = new CancellationTokenSource(); CancellationChangeToken changeToken = new CancellationChangeToken(val.Token); Matcher val2 = new Matcher((StringComparison)5); val2.AddInclude(pattern); orAdd = new ChangeTokenInfo(val, changeToken, val2); orAdd = _wildcardTokenLookup.GetOrAdd(pattern, orAdd); } IChangeToken val3 = (IChangeToken)(object)orAdd.ChangeToken; if (PollForChanges) { PollingWildCardChangeToken pollingWildCardChangeToken = new PollingWildCardChangeToken(_root, pattern); if (UseActivePolling) { pollingWildCardChangeToken.ActiveChangeCallbacks = true; pollingWildCardChangeToken.CancellationTokenSource = new CancellationTokenSource(); PollingChangeTokens.TryAdd((IPollingChangeToken)pollingWildCardChangeToken, (IPollingChangeToken)pollingWildCardChangeToken); } val3 = (IChangeToken)new CompositeChangeToken((System.Collections.Generic.IReadOnlyList<IChangeToken>)(object)new IChangeToken[2] { val3, pollingWildCardChangeToken }); } return val3; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize((object)this); } protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { FileSystemWatcher fileWatcher = _fileWatcher; if (fileWatcher != null) { ((Component)fileWatcher).Dispose(); } Timer timer = _timer; if (timer != null) { timer.Dispose(); } } _disposed = true; } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void OnRenamed(object sender, RenamedEventArgs e) { OnFileSystemEntryChange(e.OldFullPath); OnFileSystemEntryChange(((FileSystemEventArgs)e).FullPath); if (!Directory.Exists(((FileSystemEventArgs)e).FullPath)) { return; } try { System.Collections.Generic.IEnumerator<string> enumerator = Directory.EnumerateFileSystemEntries(((FileSystemEventArgs)e).FullPath, "*", (SearchOption)1).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { string current = enumerator.Current; string fullPath = Path.Combine(e.OldFullPath, current.Substring(((FileSystemEventArgs)e).FullPath.Length + 1)); OnFileSystemEntryChange(fullPath); OnFileSystemEntryChange(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } catch (System.Exception ex) when (ex is IOException || ex is SecurityException || ex is DirectoryNotFoundException || ex is UnauthorizedAccessException) { } } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void OnChanged(object sender, FileSystemEventArgs e) { OnFileSystemEntryChange(e.FullPath); } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void OnError(object sender, ErrorEventArgs e) { System.Collections.Generic.IEnumerator<string> enumerator = ((System.Collections.Generic.IEnumerable<string>)_filePathTokenLookup.Keys).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { string current = enumerator.Current; ReportChangeForMatchedEntries(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void OnFileSystemEntryChange(string fullPath) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown try { FileInfo fileSystemInfo = new FileInfo(fullPath); if (!FileSystemInfoHelper.IsExcluded((FileSystemInfo)(object)fileSystemInfo, _filters)) { string path = fullPath.Substring(_root.Length); ReportChangeForMatchedEntries(path); } } catch (System.Exception ex) when (ex is IOException || ex is SecurityException || ex is UnauthorizedAccessException) { } } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void ReportChangeForMatchedEntries(string path) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(path)) { return; } path = NormalizePath(path); bool flag = false; ChangeTokenInfo matchInfo = default(ChangeTokenInfo); if (_filePathTokenLookup.TryRemove(path, ref matchInfo)) { CancelToken(matchInfo); flag = true; } System.Collections.Generic.IEnumerator<KeyValuePair<string, ChangeTokenInfo>> enumerator = _wildcardTokenLookup.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, ChangeTokenInfo> current = enumerator.Current; PatternMatchingResult val = MatcherExtensions.Match(current.Value.Matcher, path); if (val.HasMatches && _wildcardTokenLookup.TryRemove(current.Key, ref matchInfo)) { CancelToken(matchInfo); flag = true; } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } if (flag) { TryDisableFileSystemWatcher(); } } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void TryDisableFileSystemWatcher() { if (_fileWatcher == null) { return; } lock (_fileWatcherLock) { if (_filePathTokenLookup.IsEmpty && _wildcardTokenLookup.IsEmpty && _fileWatcher.EnableRaisingEvents) { _fileWatcher.EnableRaisingEvents = false; } } } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void TryEnableFileSystemWatcher() { if (_fileWatcher == null) { return; } lock (_fileWatcherLock) { if ((!_filePathTokenLookup.IsEmpty || !_wildcardTokenLookup.IsEmpty) && !_fileWatcher.EnableRaisingEvents) { _fileWatcher.EnableRaisingEvents = true; } } } private static string NormalizePath(string filter) { return filter.Replace('\\', '/'); } private static bool IsDirectoryPath(string path) { if (path.Length > 0) { if (path[path.Length - 1] != Path.DirectorySeparatorChar) { return path[path.Length - 1] == Path.AltDirectorySeparatorChar; } return true; } return false; } private static void CancelToken(ChangeTokenInfo matchInfo) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (!matchInfo.TokenSource.IsCancellationRequested) { System.Threading.Tasks.Task.Factory.StartNew(_cancelTokenSource, (object)matchInfo.TokenSource, CancellationToken.None, (TaskCreationOptions)8, TaskScheduler.Default); } } internal static void RaiseChangeEvents(object? state) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) ConcurrentDictionary<IPollingChangeToken, IPollingChangeToken> val = (ConcurrentDictionary<IPollingChangeToken, IPollingChangeToken>)state; System.Collections.Generic.IEnumerator<KeyValuePair<IPollingChangeToken, IPollingChangeToken>> enumerator = val.GetEnumerator(); try { IPollingChangeToken pollingChangeToken = default(IPollingChangeToken); while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IPollingChangeToken key = enumerator.Current.Key; if (((IChangeToken)key).HasChanged && val.TryRemove(key, ref pollingChangeToken)) { try { key.CancellationTokenSource.Cancel(); } catch { } } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } public class PollingFileChangeToken : IPollingChangeToken, IChangeToken { private readonly FileInfo _fileInfo; private System.DateTime _previousWriteTimeUtc; private System.DateTime _lastCheckedTimeUtc; private bool _hasChanged; private CancellationTokenSource _tokenSource; private CancellationChangeToken _changeToken; [field: CompilerGenerated] internal static TimeSpan PollingInterval { [CompilerGenerated] get; [CompilerGenerated] set; } = PhysicalFilesWatcher.DefaultPollingInterval; [field: CompilerGenerated] public bool ActiveChangeCallbacks { [CompilerGenerated] get; [CompilerGenerated] internal set; } internal CancellationTokenSource? CancellationTokenSource { get { return _tokenSource; } [param: DisallowNull] set { //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_001d: Expected O, but got Unknown _tokenSource = value; _changeToken = new CancellationChangeToken(_tokenSource.Token); } } CancellationTokenSource? IPollingChangeToken.CancellationTokenSource => CancellationTokenSource; public bool HasChanged { get { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (_hasChanged) { return _hasChanged; } System.DateTime utcNow = System.DateTime.UtcNow; if (utcNow - _lastCheckedTimeUtc < PollingInterval) { return _hasChanged; } System.DateTime lastWriteTimeUtc = GetLastWriteTimeUtc(); if (_previousWriteTimeUtc != lastWriteTimeUtc) { _previousWriteTimeUtc = lastWriteTimeUtc; _hasChanged = true; } _lastCheckedTimeUtc = utcNow; return _hasChanged; } } public PollingFileChangeToken(FileInfo fileInfo) { _fileInfo = fileInfo; _previousWriteTimeUtc = GetLastWriteTimeUtc(); } private System.DateTime GetLastWriteTimeUtc() { ((FileSystemInfo)_fileInfo).Refresh(); if (!((FileSystemInfo)_fileInfo).Exists) { return System.DateTime.MinValue; } return FileSystemInfoHelper.GetFileLinkTargetLastWriteTimeUtc(_fileInfo) ?? ((FileSystemInfo)_fileInfo).LastWriteTimeUtc; } public System.IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { if (!ActiveChangeCallbacks) { return EmptyDisposable.Instance; } return _changeToken.RegisterChangeCallback(callback, state); } } public class PollingWildCardChangeToken : IPollingChangeToken, IChangeToken { private static readonly byte[] Separator = Encoding.Unicode.GetBytes("|"); private readonly object _enumerationLock = new object(); private readonly DirectoryInfoBase _directoryInfo; private readonly Matcher _matcher; private bool _changed; private System.DateTime? _lastScanTimeUtc; private byte[] _byteBuffer; private byte[] _previousHash; private CancellationTokenSource _tokenSource; private CancellationChangeToken _changeToken; [field: CompilerGenerated] public bool ActiveChangeCallbacks { [CompilerGenerated] get; [CompilerGenerated] internal set; } [field: CompilerGenerated] internal TimeSpan PollingInterval { [CompilerGenerated] get; [CompilerGenerated] set; } = PhysicalFilesWatcher.DefaultPollingInterval; internal CancellationTokenSource? CancellationTokenSource { get { return _tokenSource; } [param: DisallowNull] set { //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_001d: Expected O, but got Unknown _tokenSource = value; _changeToken = new CancellationChangeToken(_tokenSource.Token); } } CancellationTokenSource? IPollingChangeToken.CancellationTokenSource => CancellationTokenSource; [field: CompilerGenerated] private IClock Clock { [CompilerGenerated] get; } public bool HasChanged { get { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) if (_changed) { return _changed; } System.DateTime utcNow = Clock.UtcNow; System.DateTime? lastScanTimeUtc = _lastScanTimeUtc; TimeSpan? val = (lastScanTimeUtc.HasValue ? new TimeSpan?(utcNow - lastScanTimeUtc.GetValueOrDefault()) : null); TimeSpan pollingInterval = PollingInterval; if (val.HasValue && val.GetValueOrDefault() >= pollingInterval) { lock (_enumerationLock) { _changed = CalculateChanges(); } } return _changed; } } public PollingWildCardChangeToken(string root, string pattern) : this((DirectoryInfoBase)new DirectoryInfoWrapper(new DirectoryInfo(root)), pattern, Microsoft.Extensions.FileProviders.Physical.Clock.Instance) { }//IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown internal PollingWildCardChangeToken(DirectoryInfoBase directoryInfo, string pattern, IClock clock) { //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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown _directoryInfo = directoryInfo; Clock = clock; _matcher = new Matcher((StringComparison)5); _matcher.AddInclude(pattern); CalculateChanges(); } private bool CalculateChanges() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) PatternMatchingResult val = _matcher.Execute(_directoryInfo); IOrderedEnumerable<FilePatternMatch> val2 = Enumerable.OrderBy<FilePatternMatch, string>(val.Files, (Func<FilePatternMatch, string>)((FilePatternMatch f) => ((FilePatternMatch)(ref f)).Path), (IComparer<string>)(object)StringComparer.Ordinal); IncrementalHash val3 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); try { System.Collections.Generic.IEnumerator<FilePatternMatch> enumerator = ((System.Collections.Generic.IEnumerable<FilePatternMatch>)val2).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { FilePatternMatch current = enumerator.Current; System.DateTime lastWriteUtc = GetLastWriteUtc(((FilePatternMatch)(ref current)).Path); if (_lastScanTimeUtc.HasValue) { System.DateTime? lastScanTimeUtc = _lastScanTimeUtc; System.DateTime dateTime = lastWriteUtc; if (lastScanTimeUtc.HasValue && lastScanTimeUtc.GetValueOrDefault() < dateTime) { return true; } } ComputeHash(val3, ((FilePatternMatch)(ref current)).Path, lastWriteUtc); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } byte[] hashAndReset = val3.GetHashAndReset(); if (!ArrayEquals(_previousHash, hashAndReset)) { return true; } _previousHash = hashAndReset; _lastScanTimeUtc = Clock.UtcNow; } finally { ((System.IDisposable)val3)?.Dispose(); } return false; } protected virtual System.DateTime GetLastWriteUtc(string path) { string text = Path.Combine(((FileSystemInfoBase)_directoryInfo).FullName, path); return FileSystemInfoHelper.GetFileLinkTargetLastWriteTimeUtc(text) ?? File.GetLastWriteTimeUtc(text); } private static bool ArrayEquals(byte[] previousHash, byte[] currentHash) { if (previousHash == null) { return true; } return MemoryExtensions.SequenceEqual<byte>(MemoryExtensions.AsSpan<byte>(previousHash), System.Span<byte>.op_Implicit(MemoryExtensions.AsSpan<byte>(currentHash))); } private unsafe void ComputeHash(IncrementalHash sha256, string path, System.DateTime lastChangedUtc) { int byteCount = Encoding.Unicode.GetByteCount(path); if (_byteBuffer == null || byteCount > _byteBuffer.Length) { _byteBuffer = new byte[Math.Max(byteCount, 256)]; } int bytes = Encoding.Unicode.GetBytes(path, 0, path.Length, _byteBuffer, 0); sha256.AppendData(_byteBuffer, 0, bytes); sha256.AppendData(Separator, 0, Separator.Length); fixed (byte* ptr = _byteBuffer) { *(long*)ptr = lastChangedUtc.Ticks; } sha256.AppendData(_byteBuffer, 0, 8); sha256.AppendData(Separator, 0, Separator.Length); } System.IDisposable IChangeToken.RegisterChangeCallback(Action<object> callback, object state) { if (!ActiveChangeCallbacks) { return EmptyDisposable.Instance; } return _changeToken.RegisterChangeCallback(callback, state); } } } namespace Microsoft.Extensions.FileProviders.Physical.Internal { internal static class PathUtils { private static readonly char[] _invalidFileNameChars = Enumerable.ToArray<char>(Enumerable.Where<char>((System.Collections.Generic.IEnumerable<char>)Path.GetInvalidFileNameChars(), (Func<char, bool>)((char c) => c != Path.DirectorySeparatorChar && c != Path.AltDirectorySeparatorChar))); private static readonly char[] _invalidFilterChars = Enumerable.ToArray<char>(Enumerable.Where<char>((System.Collections.Generic.IEnumerable<char>)_invalidFileNameChars, (Func<char, bool>)((char c) => c != '*' && c != '|' && c != '?'))); private static readonly char[] _pathSeparators = new char[2] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; internal static bool HasInvalidPathChars(string path) { return path.IndexOfAny(_invalidFileNameChars) != -1; } internal static bool HasInvalidFilterChars(string path) { return path.IndexOfAny(_invalidFilterChars) != -1; } internal static string EnsureTrailingSlash(string path) { if (!string.IsNullOrEmpty(path) && path[path.Length - 1] != Path.DirectorySeparatorChar) { return path + Path.DirectorySeparatorChar; } return path; } internal static bool PathNavigatesAboveRoot(string path) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) StringTokenizer val = default(StringTokenizer); ((StringTokenizer)(ref val))..ctor(path, _pathSeparators); int num = 0; Enumerator enumerator = ((StringTokenizer)(ref val)).GetEnumerator(); try { while (((Enumerator)(ref enumerator)).MoveNext()) { StringSegment current = ((Enumerator)(ref enumerator)).Current; if (((StringSegment)(ref current)).Equals(".") || ((StringSegment)(ref current)).Equals("")) { continue; } if (((StringSegment)(ref current)).Equals("..")) { num--; if (num == -1) { return true; } } else { num++; } } } finally { ((System.IDisposable)(Enumerator)(ref enumerator)).Dispose(); } return false; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.FileSystemGlobbing.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using FxResources.Microsoft.Extensions.FileSystemGlobbing; using Microsoft.CodeAnalysis; using Microsoft.Extensions.FileSystemGlobbing.Abstractions; using Microsoft.Extensions.FileSystemGlobbing.Internal; using Microsoft.Extensions.FileSystemGlobbing.Internal.PathSegments; using Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts; using Microsoft.Extensions.FileSystemGlobbing.Internal.Patterns; using Microsoft.Extensions.FileSystemGlobbing.Util; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.FileSystemGlobbing.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.FileSystemGlobbing")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("File system globbing to find files matching a specified pattern.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.FileSystemGlobbing")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.FileSystemGlobbing { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.FileSystemGlobbing.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string CannotDeclarePathSegment => GetResourceString("CannotDeclarePathSegment"); internal static string CannotTestDirectory => GetResourceString("CannotTestDirectory"); internal static string CannotTestFile => GetResourceString("CannotTestFile"); internal static string StringComparisonTypeShouldBeOrdinal => GetResourceString("StringComparisonTypeShouldBeOrdinal"); internal static string UnexpectedStringComparisonType => GetResourceString("UnexpectedStringComparisonType"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace System.Numerics.Hashing { internal static class HashHelpers { public static int Combine(int h1, int h2) { uint num = (uint)(h1 << 5) | ((uint)h1 >> 27); return ((int)num + h1) ^ h2; } } } namespace Microsoft.Extensions.FileSystemGlobbing { public struct FilePatternMatch : IEquatable<FilePatternMatch> { [field: CompilerGenerated] public string Path { [CompilerGenerated] get; } [field: CompilerGenerated] public string? Stem { [CompilerGenerated] get; } public FilePatternMatch(string path, string? stem) { ThrowHelper.ThrowIfNull(path, "path"); Path = path; Stem = stem; } public bool Equals(FilePatternMatch other) { if (string.Equals(other.Path, Path, (StringComparison)5)) { return string.Equals(other.Stem, Stem, (StringComparison)5); } return false; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is FilePatternMatch other) { return Equals(other); } return false; } public override int GetHashCode() { return HashHelpers.Combine(GetHashCode(Path), GetHashCode(Stem)); } private static int GetHashCode(string value) { if (value == null) { return 0; } return StringComparer.OrdinalIgnoreCase.GetHashCode(value); } } public class InMemoryDirectoryInfo : DirectoryInfoBase { [CompilerGenerated] private sealed class <EnumerateFileSystemInfos>d__12 : System.Collections.Generic.IEnumerable<FileSystemInfoBase>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<FileSystemInfoBase>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private FileSystemInfoBase <>2__current; private int <>l__initialThreadId; public InMemoryDirectoryInfo <>4__this; private Dictionary<string, List<string>> <dict>5__2; private System.Collections.Generic.IEnumerator<string> <>7__wrap2; private Enumerator<string, List<string>> <>7__wrap3; FileSystemInfoBase System.Collections.Generic.IEnumerator<FileSystemInfoBase>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <EnumerateFileSystemInfos>d__12(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { switch (<>1__state) { case -3: case 1: try { break; } finally { <>m__Finally1(); } case -4: case 2: try { break; } finally { <>m__Finally2(); } case -2: case -1: case 0: break; } } private bool MoveNext() { //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0146: 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_0193: Unknown result type (might be due to invalid IL or missing references) try { int num = <>1__state; InMemoryDirectoryInfo inMemoryDirectoryInfo = <>4__this; List<string> val = default(List<string>); switch (num) { default: return false; case 0: <>1__state = -1; <dict>5__2 = new Dictionary<string, List<string>>(); <>7__wrap2 = inMemoryDirectoryInfo._files.GetEnumerator(); <>1__state = -3; goto IL_0108; case 1: <>1__state = -3; goto IL_0108; case 2: { <>1__state = -4; break; } IL_0108: while (((System.Collections.IEnumerator)<>7__wrap2).MoveNext()) { string current = <>7__wrap2.Current; if (IsRootDirectory(inMemoryDirectoryInfo.FullName, current)) { int length = current.Length; int num2 = inMemoryDirectoryInfo.FullName.Length + 1; int num3 = current.IndexOfAny(DirectorySeparators, num2, length - num2); if (num3 == -1) { <>2__current = new InMemoryFileInfo(current, inMemoryDirectoryInfo); <>1__state = 1; return true; } string text = current.Substring(0, num3); if (!<dict>5__2.TryGetValue(text, ref val)) { Dictionary<string, List<string>> obj = <dict>5__2; List<string> obj2 = new List<string>(); obj2.Add(current); obj[text] = obj2; } else { val.Add(current); } } } <>m__Finally1(); <>7__wrap2 = null; <>7__wrap3 = <dict>5__2.GetEnumerator(); <>1__state = -4; break; } if (<>7__wrap3.MoveNext()) { KeyValuePair<string, List<string>> current2 = <>7__wrap3.Current; <>2__current = new InMemoryDirectoryInfo(current2.Key, (System.Collections.Generic.IEnumerable<string>)current2.Value, normalized: true); <>1__state = 2; return true; } <>m__Finally2(); <>7__wrap3 = default(Enumerator<string, List<string>>); return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.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) { ((System.IDisposable)<>7__wrap2).Dispose(); } } private void <>m__Finally2() { <>1__state = -1; ((System.IDisposable)<>7__wrap3).Dispose(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<FileSystemInfoBase> System.Collections.Generic.IEnumerable<FileSystemInfoBase>.GetEnumerator() { <EnumerateFileSystemInfos>d__12 result; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; result = this; } else { result = new <EnumerateFileSystemInfos>d__12(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<FileSystemInfoBase>)this).GetEnumerator(); } } private static readonly char[] DirectorySeparators = new char[2] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; private readonly System.Collections.Generic.IEnumerable<string> _files; [field: CompilerGenerated] public override string FullName { [CompilerGenerated] get; } [field: CompilerGenerated] public override string Name { [CompilerGenerated] get; } public override DirectoryInfoBase? ParentDirectory => new InMemoryDirectoryInfo(Path.GetDirectoryName(FullName), _files, normalized: true); public InMemoryDirectoryInfo(string rootDir, System.Collections.Generic.IEnumerable<string>? files) : this(rootDir, files, normalized: false) { } private InMemoryDirectoryInfo(string rootDir, System.Collections.Generic.IEnumerable<string> files, bool normalized) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(rootDir)) { throw new ArgumentNullException("rootDir"); } if (files == null) { files = (System.Collections.Generic.IEnumerable<string>)new List<string>(); } Name = Path.GetFileName(rootDir); if (normalized) { _files = files; FullName = rootDir; return; } List<string> val = new List<string>(Enumerable.Count<string>(files)); System.Collections.Generic.IEnumerator<string> enumerator = files.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { string current = enumerator.Current; val.Add(Path.GetFullPath(current.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar))); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } _files = (System.Collections.Generic.IEnumerable<string>)val; FullName = Path.GetFullPath(rootDir.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); } [IteratorStateMachine(typeof(<EnumerateFileSystemInfos>d__12))] public override System.Collections.Generic.IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos() { Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); System.Collections.Generic.IEnumerator<string> enumerator = _files.GetEnumerator(); try { List<string> val = default(List<string>); while (((System.Collections.IEnumerator)enumerator).MoveNext()) { string current = enumerator.Current; if (!IsRootDirectory(FullName, current)) { continue; } int length = current.Length; int num = FullName.Length + 1; int num2 = current.IndexOfAny(DirectorySeparators, num, length - num); if (num2 == -1) { yield return new InMemoryFileInfo(current, this); continue; } string text = current.Substring(0, num2); if (!dict.TryGetValue(text, ref val)) { List<string> obj = new List<string>(); obj.Add(current); dict[text] = obj; } else { val.Add(current); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } Enumerator<string, List<string>> enumerator2 = dict.GetEnumerator(); try { while (enumerator2.MoveNext()) { KeyValuePair<string, List<string>> current2 = enumerator2.Current; yield return new InMemoryDirectoryInfo(current2.Key, (System.Collections.Generic.IEnumerable<string>)current2.Value, normalized: true); } } finally { ((System.IDisposable)enumerator2).Dispose(); } } private static bool IsRootDirectory(string rootDir, string filePath) { int length = rootDir.Length; if (filePath.StartsWith(rootDir, (StringComparison)4)) { if (rootDir[length - 1] != Path.DirectorySeparatorChar) { return filePath.IndexOf(Path.DirectorySeparatorChar, length) == length; } return true; } return false; } public override DirectoryInfoBase GetDirectory(string path) { if (string.Equals(path, "..", (StringComparison)4)) { return new InMemoryDirectoryInfo(Path.Combine(FullName, path), _files, normalized: true); } string fullPath = Path.GetFullPath(path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); return new InMemoryDirectoryInfo(fullPath, _files, normalized: true); } public override FileInfoBase? GetFile(string path) { string fullPath = Path.GetFullPath(path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); System.Collections.Generic.IEnumerator<string> enumerator = _files.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { string current = enumerator.Current; if (string.Equals(current, fullPath)) { return new InMemoryFileInfo(current, this); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } return null; } } public class Matcher { private readonly System.Collections.Generic.IList<IPattern> _includePatterns = (System.Collections.Generic.IList<IPattern>)new List<IPattern>(); private readonly System.Collections.Generic.IList<IPattern> _excludePatterns = (System.Collections.Generic.IList<IPattern>)new List<IPattern>(); private readonly PatternBuilder _builder; private readonly StringComparison _comparison; public Matcher() : this((StringComparison)5) { } public Matcher(StringComparison comparisonType) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) _comparison = comparisonType; _builder = new PatternBuilder(comparisonType); } public virtual Matcher AddInclude(string pattern) { ((System.Collections.Generic.ICollection<IPattern>)_includePatterns).Add(_builder.Build(pattern)); return this; } public virtual Matcher AddExclude(string pattern) { ((System.Collections.Generic.ICollection<IPattern>)_excludePatterns).Add(_builder.Build(pattern)); return this; } public virtual PatternMatchingResult Execute(DirectoryInfoBase directoryInfo) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(directoryInfo, "directoryInfo"); MatcherContext matcherContext = new MatcherContext((System.Collections.Generic.IEnumerable<IPattern>)_includePatterns, (System.Collections.Generic.IEnumerable<IPattern>)_excludePatterns, directoryInfo, _comparison); return matcherContext.Execute(); } } public static class MatcherExtensions { public static void AddExcludePatterns(this Matcher matcher, params System.Collections.Generic.IEnumerable<string>[] excludePatternsGroups) { foreach (System.Collections.Generic.IEnumerable<string> enumerable in excludePatternsGroups) { System.Collections.Generic.IEnumerator<string> enumerator = enumerable.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { string current = enumerator.Current; matcher.AddExclude(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } public static void AddIncludePatterns(this Matcher matcher, params System.Collections.Generic.IEnumerable<string>[] includePatternsGroups) { foreach (System.Collections.Generic.IEnumerable<string> enumerable in includePatternsGroups) { System.Collections.Generic.IEnumerator<string> enumerator = enumerable.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { string current = enumerator.Current; matcher.AddInclude(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } public static System.Collections.Generic.IEnumerable<string> GetResultsInFullPath(this Matcher matcher, string directoryPath) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown string directoryPath2 = directoryPath; System.Collections.Generic.IEnumerable<FilePatternMatch> files = matcher.Execute(new DirectoryInfoWrapper(new DirectoryInfo(directoryPath2))).Files; return Enumerable.ToArray<string>(Enumerable.Select<FilePatternMatch, string>(files, (Func<FilePatternMatch, string>)((FilePatternMatch match) => Path.GetFullPath(Path.Combine(directoryPath2, match.Path))))); } public static PatternMatchingResult Match(this Matcher matcher, string file) { string currentDirectory = Directory.GetCurrentDirectory(); List<string> obj = new List<string>(); obj.Add(file); return matcher.Match(currentDirectory, (System.Collections.Generic.IEnumerable<string>?)obj); } public static PatternMatchingResult Match(this Matcher matcher, string rootDir, string file) { List<string> obj = new List<string>(); obj.Add(file); return matcher.Match(rootDir, (System.Collections.Generic.IEnumerable<string>?)obj); } public static PatternMatchingResult Match(this Matcher matcher, System.Collections.Generic.IEnumerable<string>? files) { return matcher.Match(Directory.GetCurrentDirectory(), files); } public static PatternMatchingResult Match(this Matcher matcher, string rootDir, System.Collections.Generic.IEnumerable<string>? files) { ThrowHelper.ThrowIfNull(matcher, "matcher"); return matcher.Execute(new InMemoryDirectoryInfo(rootDir, files)); } } public class PatternMatchingResult { [field: CompilerGenerated] public System.Collections.Generic.IEnumerable<FilePatternMatch> Files { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public bool HasMatches { [CompilerGenerated] get; } public PatternMatchingResult(System.Collections.Generic.IEnumerable<FilePatternMatch> files) : this(files, Enumerable.Any<FilePatternMatch>(files)) { Files = files; } public PatternMatchingResult(System.Collections.Generic.IEnumerable<FilePatternMatch> files, bool hasMatches) { ThrowHelper.ThrowIfNull(files, "files"); Files = files; HasMatches = hasMatches; } } } namespace Microsoft.Extensions.FileSystemGlobbing.Util { internal static class StringComparisonHelper { public static StringComparer GetStringComparer(StringComparison comparisonType) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown //IL_0055: 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) return (StringComparer)((int)comparisonType switch { 0 => StringComparer.CurrentCulture, 1 => StringComparer.CurrentCultureIgnoreCase, 4 => StringComparer.Ordinal, 5 => StringComparer.OrdinalIgnoreCase, 2 => StringComparer.InvariantCulture, 3 => StringComparer.InvariantCultureIgnoreCase, _ => throw new InvalidOperationException(System.SR.Format(System.SR.UnexpectedStringComparisonType, comparisonType)), }); } } } namespace Microsoft.Extensions.FileSystemGlobbing.Internal { public interface ILinearPattern : IPattern { System.Collections.Generic.IList<IPathSegment> Segments { get; } } internal sealed class InMemoryFileInfo : FileInfoBase { private InMemoryDirectoryInfo _parent; [field: CompilerGenerated] public override string FullName { [CompilerGenerated] get; } [field: CompilerGenerated] public override string Name { [CompilerGenerated] get; } public override DirectoryInfoBase ParentDirectory => _parent; public InMemoryFileInfo(string file, InMemoryDirectoryInfo parent) { FullName = file; Name = Path.GetFileName(file); _parent = parent; } } public interface IPathSegment { bool CanProduceStem { get; } bool Match(string value); } public interface IPattern { IPatternContext CreatePatternContextForInclude(); IPatternContext CreatePatternContextForExclude(); } public interface IPatternContext { void Declare(Action<IPathSegment, bool> onDeclare); bool Test(DirectoryInfoBase directory); PatternTestResult Test(FileInfoBase file); void PushDirectory(DirectoryInfoBase directory); void PopDirectory(); } public interface IRaggedPattern : IPattern { System.Collections.Generic.IList<IPathSegment> Segments { get; } System.Collections.Generic.IList<IPathSegment> StartsWith { get; } System.Collections.Generic.IList<System.Collections.Generic.IList<IPathSegment>> Contains { get; } System.Collections.Generic.IList<IPathSegment> EndsWith { get; } } public class MatcherContext { private readonly DirectoryInfoBase _root; private readonly List<IPatternContext> _includePatternContexts; private readonly List<IPatternContext> _excludePatternContexts; private readonly List<FilePatternMatch> _files; private readonly HashSet<string> _declaredLiteralFolderSegmentInString; private readonly HashSet<LiteralPathSegment> _declaredLiteralFileSegments = new HashSet<LiteralPathSegment>(); private bool _declaredParentPathSegment; private bool _declaredWildcardPathSegment; private readonly StringComparison _comparisonType; public MatcherContext(System.Collections.Generic.IEnumerable<IPattern> includePatterns, System.Collections.Generic.IEnumerable<IPattern> excludePatterns, DirectoryInfoBase directoryInfo, StringComparison comparison) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) _root = directoryInfo; _files = new List<FilePatternMatch>(); _comparisonType = comparison; _includePatternContexts = Enumerable.ToList<IPatternContext>(Enumerable.Select<IPattern, IPatternContext>(includePatterns, (Func<IPattern, IPatternContext>)((IPattern pattern) => pattern.CreatePatternContextForInclude()))); _excludePatternContexts = Enumerable.ToList<IPatternContext>(Enumerable.Select<IPattern, IPatternContext>(excludePatterns, (Func<IPattern, IPatternContext>)((IPattern pattern) => pattern.CreatePatternContextForExclude()))); _declaredLiteralFolderSegmentInString = new HashSet<string>((IEqualityComparer<string>)(object)StringComparisonHelper.GetStringComparer(comparison)); } public PatternMatchingResult Execute() { _files.Clear(); Match(_root, null); return new PatternMatchingResult((System.Collections.Generic.IEnumerable<FilePatternMatch>)_files, _files.Count > 0); } private void Match(DirectoryInfoBase directory, string parentRelativePath) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) PushDirectory(directory); Declare(); List<FileSystemInfoBase> val = new List<FileSystemInfoBase>(); if (_declaredWildcardPathSegment || Enumerable.Any<LiteralPathSegment>((System.Collections.Generic.IEnumerable<LiteralPathSegment>)_declaredLiteralFileSegments)) { val.AddRange(directory.EnumerateFileSystemInfos()); } else { System.Collections.Generic.IEnumerable<DirectoryInfoBase> enumerable = Enumerable.OfType<DirectoryInfoBase>((System.Collections.IEnumerable)directory.EnumerateFileSystemInfos()); System.Collections.Generic.IEnumerator<DirectoryInfoBase> enumerator = enumerable.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { DirectoryInfoBase current = enumerator.Current; if (_declaredLiteralFolderSegmentInString.Contains(current.Name)) { val.Add((FileSystemInfoBase)current); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } if (_declaredParentPathSegment) { val.Add((FileSystemInfoBase)directory.GetDirectory("..")); } List<DirectoryInfoBase> val2 = new List<DirectoryInfoBase>(); Enumerator<FileSystemInfoBase> enumerator2 = val.GetEnumerator(); try { while (enumerator2.MoveNext()) { FileSystemInfoBase current2 = enumerator2.Current; if (current2 is FileInfoBase fileInfoBase) { PatternTestResult patternTestResult = MatchPatternContexts(fileInfoBase, (Func<IPatternContext, FileInfoBase, PatternTestResult>)((IPatternContext pattern, FileInfoBase file) => pattern.Test(file))); if (patternTestResult.IsSuccessful) { _files.Add(new FilePatternMatch(CombinePath(parentRelativePath, fileInfoBase.Name), patternTestResult.Stem)); } } else if (current2 is DirectoryInfoBase directoryInfoBase && MatchPatternContexts(directoryInfoBase, (Func<IPatternContext, DirectoryInfoBase, bool>)((IPatternContext pattern, DirectoryInfoBase dir) => pattern.Test(dir)))) { val2.Add(directoryInfoBase); } } } finally { ((System.IDisposable)enumerator2).Dispose(); } Enumerator<DirectoryInfoBase> enumerator3 = val2.GetEnumerator(); try { while (enumerator3.MoveNext()) { DirectoryInfoBase current3 = enumerator3.Current; string parentRelativePath2 = CombinePath(parentRelativePath, current3.Name); Match(current3, parentRelativePath2); } } finally { ((System.IDisposable)enumerator3).Dispose(); } PopDirectory(); } private void Declare() { //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) _declaredLiteralFileSegments.Clear(); _declaredParentPathSegment = false; _declaredWildcardPathSegment = false; Enumerator<IPatternContext> enumerator = _includePatternContexts.GetEnumerator(); try { while (enumerator.MoveNext()) { IPatternContext current = enumerator.Current; current.Declare(DeclareInclude); } } finally { ((System.IDisposable)enumerator).Dispose(); } } private void DeclareInclude(IPathSegment patternSegment, bool isLastSegment) { if (patternSegment is LiteralPathSegment literalPathSegment) { if (isLastSegment) { _declaredLiteralFileSegments.Add(literalPathSegment); } else { _declaredLiteralFolderSegmentInString.Add(literalPathSegment.Value); } } else if (patternSegment is ParentPathSegment) { _declaredParentPathSegment = true; } else if (patternSegment is WildcardPathSegment) { _declaredWildcardPathSegment = true; } } internal static string CombinePath(string? left, string right) { if (string.IsNullOrEmpty(left)) { return right; } return left + "/" + right; } private bool MatchPatternContexts<TFileInfoBase>(TFileInfoBase fileinfo, Func<IPatternContext, TFileInfoBase, bool> test) { return MatchPatternContexts(fileinfo, (Func<IPatternContext, TFileInfoBase, PatternTestResult>)((IPatternContext ctx, TFileInfoBase file) => test.Invoke(ctx, file) ? PatternTestResult.Success(string.Empty) : PatternTestResult.Failed)).IsSuccessful; } private PatternTestResult MatchPatternContexts<TFileInfoBase>(TFileInfoBase fileinfo, Func<IPatternContext, TFileInfoBase, PatternTestResult> test) { //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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) PatternTestResult result = PatternTestResult.Failed; Enumerator<IPatternContext> enumerator = _includePatternContexts.GetEnumerator(); try { while (enumerator.MoveNext()) { IPatternContext current = enumerator.Current; PatternTestResult patternTestResult = test.Invoke(current, fileinfo); if (patternTestResult.IsSuccessful) { result = patternTestResult; break; } } } finally { ((System.IDisposable)enumerator).Dispose(); } if (!result.IsSuccessful) { return PatternTestResult.Failed; } Enumerator<IPatternContext> enumerator2 = _excludePatternContexts.GetEnumerator(); try { while (enumerator2.MoveNext()) { IPatternContext current2 = enumerator2.Current; if (test.Invoke(current2, fileinfo).IsSuccessful) { return PatternTestResult.Failed; } } return result; } finally { ((System.IDisposable)enumerator2).Dispose(); } } private void PopDirectory() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) Enumerator<IPatternContext> enumerator = _excludePatternContexts.GetEnumerator(); try { while (enumerator.MoveNext()) { IPatternContext current = enumerator.Current; current.PopDirectory(); } } finally { ((System.IDisposable)enumerator).Dispose(); } Enumerator<IPatternContext> enumerator2 = _includePatternContexts.GetEnumerator(); try { while (enumerator2.MoveNext()) { IPatternContext current2 = enumerator2.Current; current2.PopDirectory(); } } finally { ((System.IDisposable)enumerator2).Dispose(); } } private void PushDirectory(DirectoryInfoBase directory) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) Enumerator<IPatternContext> enumerator = _includePatternContexts.GetEnumerator(); try { while (enumerator.MoveNext()) { IPatternContext current = enumerator.Current; current.PushDirectory(directory); } } finally { ((System.IDisposable)enumerator).Dispose(); } Enumerator<IPatternContext> enumerator2 = _excludePatternContexts.GetEnumerator(); try { while (enumerator2.MoveNext()) { IPatternContext current2 = enumerator2.Current; current2.PushDirectory(directory); } } finally { ((System.IDisposable)enumerator2).Dispose(); } } } public struct PatternTestResult { public static readonly PatternTestResult Failed = new PatternTestResult(isSuccessful: false, null); [field: CompilerGenerated] public bool IsSuccessful { [CompilerGenerated] get; } [field: CompilerGenerated] public string? Stem { [CompilerGenerated] get; } private PatternTestResult(bool isSuccessful, string stem) { IsSuccessful = isSuccessful; Stem = stem; } public static PatternTestResult Success(string? stem) { return new PatternTestResult(isSuccessful: true, stem); } } } namespace Microsoft.Extensions.FileSystemGlobbing.Internal.Patterns { public class PatternBuilder { private sealed class LinearPattern : ILinearPattern, IPattern { [field: CompilerGenerated] public System.Collections.Generic.IList<IPathSegment> Segments { [CompilerGenerated] get; } public LinearPattern(List<IPathSegment> allSegments) { Segments = (System.Collections.Generic.IList<IPathSegment>)allSegments; } public IPatternContext CreatePatternContextForInclude() { return new PatternContextLinearInclude(this); } public IPatternContext CreatePatternContextForExclude() { return new PatternContextLinearExclude(this); } } private sealed class RaggedPattern : IRaggedPattern, IPattern { [field: CompilerGenerated] public System.Collections.Generic.IList<System.Collections.Generic.IList<IPathSegment>> Contains { [CompilerGenerated] get; } [field: CompilerGenerated] public System.Collections.Generic.IList<IPathSegment> EndsWith { [CompilerGenerated] get; } [field: CompilerGenerated] public System.Collections.Generic.IList<IPathSegment> Segments { [CompilerGenerated] get; } [field: CompilerGenerated] public System.Collections.Generic.IList<IPathSegment> StartsWith { [CompilerGenerated] get; } public RaggedPattern(List<IPathSegment> allSegments, System.Collections.Generic.IList<IPathSegment> segmentsPatternStartsWith, System.Collections.Generic.IList<IPathSegment> segmentsPatternEndsWith, System.Collections.Generic.IList<System.Collections.Generic.IList<IPathSegment>> segmentsPatternContains) { Segments = (System.Collections.Generic.IList<IPathSegment>)allSegments; StartsWith = segmentsPatternStartsWith; Contains = segmentsPatternContains; EndsWith = segmentsPatternEndsWith; } public IPatternContext CreatePatternContextForInclude() { return new PatternContextRaggedInclude(this); } public IPatternContext CreatePatternContextForExclude() { return new PatternContextRaggedExclude(this); } } private static readonly char[] _slashes = new char[2] { '/', '\\' }; private static readonly char[] _star = new char[1] { '*' }; [field: CompilerGenerated] public StringComparison ComparisonType { [CompilerGenerated] get; } public PatternBuilder() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) ComparisonType = (StringComparison)5; } public PatternBuilder(StringComparison comparisonType) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) ComparisonType = comparisonType; } public IPattern Build(string pattern) { //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(pattern, "pattern"); pattern = pattern.TrimStart(_slashes); if (pattern.TrimEnd(_slashes).Length < pattern.Length) { pattern = pattern.TrimEnd(_slashes) + "/**"; } List<IPathSegment> val = new List<IPathSegment>(); bool flag = true; System.Collections.Generic.IList<IPathSegment> list = null; System.Collections.Generic.IList<System.Collections.Generic.IList<IPathSegment>> list2 = null; System.Collections.Generic.IList<IPathSegment> list3 = null; int length = pattern.Length; int num = 0; while (num < length) { int num2 = num; int num3 = NextIndex(pattern, _slashes, num, length); IPathSegment pathSegment = null; if (pathSegment == null && num3 - num2 == 3 && pattern[num2] == '*' && pattern[num2 + 1] == '.' && pattern[num2 + 2] == '*') { num2 += 2; } if (pathSegment == null && num3 - num2 == 2) { if (pattern[num2] == '*' && pattern[num2 + 1] == '*') { pathSegment = new RecursiveWildcardSegment(); } else if (pattern[num2] == '.' && pattern[num2 + 1] == '.') { if (!flag) { throw new ArgumentException("\"..\" can be only added at the beginning of the pattern."); } pathSegment = new ParentPathSegment(); } } if (pathSegment == null && num3 - num2 == 1 && pattern[num2] == '.') { pathSegment = new CurrentPathSegment(); } if (pathSegment == null && num3 - num2 > 2 && pattern[num2] == '*' && pattern[num2 + 1] == '*' && pattern[num2 + 2] == '.') { pathSegment = new RecursiveWildcardSegment(); num3 = num2; } if (pathSegment == null) { string beginsWith = string.Empty; List<string> val2 = new List<string>(); string endsWith = string.Empty; int num4 = num2; while (num4 < num3) { int num5 = num4; int num6 = NextIndex(pattern, _star, num4, num3); if (num5 == num2) { if (num6 == num3) { pathSegment = new LiteralPathSegment(Portion(pattern, num5, num6), ComparisonType); } else { beginsWith = Portion(pattern, num5, num6); } } else if (num6 == num3) { endsWith = Portion(pattern, num5, num6); } else if (num5 != num6) { val2.Add(Portion(pattern, num5, num6)); } num4 = num6 + 1; } if (pathSegment == null) { pathSegment = new WildcardPathSegment(beginsWith, val2, endsWith, ComparisonType); } } if (!(pathSegment is ParentPathSegment)) { flag = false; } if (!(pathSegment is CurrentPathSegment)) { if (pathSegment is RecursiveWildcardSegment) { if (list == null) { list = (System.Collections.Generic.IList<IPathSegment>)new List<IPathSegment>((System.Collections.Generic.IEnumerable<IPathSegment>)val); list3 = (System.Collections.Generic.IList<IPathSegment>)new List<IPathSegment>(); list2 = (System.Collections.Generic.IList<System.Collections.Generic.IList<IPathSegment>>)new List<System.Collections.Generic.IList<IPathSegment>>(); } else if (((System.Collections.Generic.ICollection<IPathSegment>)list3).Count != 0) { ((System.Collections.Generic.ICollection<System.Collections.Generic.IList<IPathSegment>>)list2).Add(list3); list3 = (System.Collections.Generic.IList<IPathSegment>)new List<IPathSegment>(); } } else { ((System.Collections.Generic.ICollection<IPathSegment>)list3)?.Add(pathSegment); } val.Add(pathSegment); } num = num3 + 1; } if (list == null) { return new LinearPattern(val); } return new RaggedPattern(val, list, list3, list2); } private static int NextIndex(string pattern, char[] anyOf, int beginIndex, int endIndex) { int num = pattern.IndexOfAny(anyOf, beginIndex, endIndex - beginIndex); if (num != -1) { return num; } return endIndex; } private static string Portion(string pattern, int beginIndex, int endIndex) { return pattern.Substring(beginIndex, endIndex - beginIndex); } } } namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts { public abstract class PatternContext<TFrame> : IPatternContext where TFrame : struct { private Stack<TFrame> _stack = new Stack<TFrame>(); protected TFrame Frame; public virtual void Declare(Action<IPathSegment, bool> declare) { } public abstract PatternTestResult Test(FileInfoBase file); public abstract bool Test(DirectoryInfoBase directory); public abstract void PushDirectory(DirectoryInfoBase directory); public virtual void PopDirectory() { Frame = _stack.Pop(); } protected void PushDataFrame(TFrame frame) { _stack.Push(Frame); Frame = frame; } protected bool IsStackEmpty() { return _stack.Count == 0; } } public abstract class PatternContextLinear : PatternContext<PatternContextLinear.FrameData> { public struct FrameData { public bool IsNotApplicable; public int SegmentIndex; public bool InStem; private System.Collections.Generic.IList<string> _stemItems; public System.Collections.Generic.IList<string> StemItems => _stemItems ?? (_stemItems = (System.Collections.Generic.IList<string>)new List<string>()); public string? Stem { get { if (_stemItems != null) { return string.Join("/", (System.Collections.Generic.IEnumerable<string>)_stemItems); } return null; } } } [field: CompilerGenerated] protected ILinearPattern Pattern { [CompilerGenerated] get; } public PatternContextLinear(ILinearPattern pattern) { ThrowHelper.ThrowIfNull(pattern, "pattern"); Pattern = pattern; } public override PatternTestResult Test(FileInfoBase file) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotTestFile); } if (!Frame.IsNotApplicable && IsLastSegment() && TestMatchingSegment(file.Name)) { return PatternTestResult.Success(CalculateStem(file)); } return PatternTestResult.Failed; } public override void PushDirectory(DirectoryInfoBase directory) { FrameData frame = Frame; if (!IsStackEmpty() && !Frame.IsNotApplicable) { if (!TestMatchingSegment(directory.Name)) { frame.IsNotApplicable = true; } else { IPathSegment pathSegment = Pattern.Segments[Frame.SegmentIndex]; if (frame.InStem || pathSegment.CanProduceStem) { frame.InStem = true; ((System.Collections.Generic.ICollection<string>)frame.StemItems).Add(directory.Name); } frame.SegmentIndex++; } } PushDataFrame(frame); } protected bool IsLastSegment() { return Frame.SegmentIndex == ((System.Collections.Generic.ICollection<IPathSegment>)Pattern.Segments).Count - 1; } protected bool TestMatchingSegment(string value) { if (Frame.SegmentIndex >= ((System.Collections.Generic.ICollection<IPathSegment>)Pattern.Segments).Count) { return false; } return Pattern.Segments[Frame.SegmentIndex].Match(value); } protected string CalculateStem(FileInfoBase matchedFile) { return MatcherContext.CombinePath(Frame.Stem, matchedFile.Name); } } public class PatternContextLinearExclude : PatternContextLinear { public PatternContextLinearExclude(ILinearPattern pattern) : base(pattern) { } public override bool Test(DirectoryInfoBase directory) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotTestDirectory); } if (Frame.IsNotApplicable) { return false; } if (IsLastSegment()) { return TestMatchingSegment(directory.Name); } return false; } } public class PatternContextLinearInclude : PatternContextLinear { public PatternContextLinearInclude(ILinearPattern pattern) : base(pattern) { } public override void Declare(Action<IPathSegment, bool> onDeclare) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotDeclarePathSegment); } if (!Frame.IsNotApplicable && Frame.SegmentIndex < ((System.Collections.Generic.ICollection<IPathSegment>)base.Pattern.Segments).Count) { onDeclare.Invoke(base.Pattern.Segments[Frame.SegmentIndex], IsLastSegment()); } } public override bool Test(DirectoryInfoBase directory) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotTestDirectory); } if (Frame.IsNotApplicable) { return false; } if (!IsLastSegment()) { return TestMatchingSegment(directory.Name); } return false; } } public abstract class PatternContextRagged : PatternContext<PatternContextRagged.FrameData> { public struct FrameData { public bool IsNotApplicable; public int SegmentGroupIndex; public System.Collections.Generic.IList<IPathSegment> SegmentGroup; public int BacktrackAvailable; public int SegmentIndex; public bool InStem; private System.Collections.Generic.IList<string> _stemItems; public System.Collections.Generic.IList<string> StemItems => _stemItems ?? (_stemItems = (System.Collections.Generic.IList<string>)new List<string>()); public string? Stem { get { if (_stemItems != null) { return string.Join("/", (System.Collections.Generic.IEnumerable<string>)_stemItems); } return null; } } } [field: CompilerGenerated] protected IRaggedPattern Pattern { [CompilerGenerated] get; } public PatternContextRagged(IRaggedPattern pattern) { ThrowHelper.ThrowIfNull(pattern, "pattern"); Pattern = pattern; } public override PatternTestResult Test(FileInfoBase file) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotTestFile); } if (!Frame.IsNotApplicable && IsEndingGroup() && TestMatchingGroup(file)) { return PatternTestResult.Success(CalculateStem(file)); } return PatternTestResult.Failed; } public sealed override void PushDirectory(DirectoryInfoBase directory) { FrameData frame = Frame; if (IsStackEmpty()) { frame.SegmentGroupIndex = -1; frame.SegmentGroup = Pattern.StartsWith; } else if (!Frame.IsNotApplicable) { if (IsStartingGroup()) { if (!TestMatchingSegment(directory.Name)) { frame.IsNotApplicable = true; } else { frame.SegmentIndex++; } } else if (!IsStartingGroup() && directory.Name == "..") { frame.IsNotApplicable = true; } else if (!IsStartingGroup() && !IsEndingGroup() && TestMatchingGroup(directory)) { frame.SegmentIndex = ((System.Collections.Generic.ICollection<IPathSegment>)Frame.SegmentGroup).Count; frame.BacktrackAvailable = 0; } else { frame.BacktrackAvailable++; } } if (frame.InStem) { ((System.Collections.Generic.ICollection<string>)frame.StemItems).Add(directory.Name); } while (frame.SegmentIndex == ((System.Collections.Generic.ICollection<IPathSegment>)frame.SegmentGroup).Count && frame.SegmentGroupIndex != ((System.Collections.Generic.ICollection<System.Collections.Generic.IList<IPathSegment>>)Pattern.Contains).Count) { frame.SegmentGroupIndex++; frame.SegmentIndex = 0; if (frame.SegmentGroupIndex < ((System.Collections.Generic.ICollection<System.Collections.Generic.IList<IPathSegment>>)Pattern.Contains).Count) { frame.SegmentGroup = Pattern.Contains[frame.SegmentGroupIndex]; } else { frame.SegmentGroup = Pattern.EndsWith; } frame.InStem = true; } PushDataFrame(frame); } public override void PopDirectory() { base.PopDirectory(); if (((System.Collections.Generic.ICollection<string>)Frame.StemItems).Count > 0) { Frame.StemItems.RemoveAt(((System.Collections.Generic.ICollection<string>)Frame.StemItems).Count - 1); } } protected bool IsStartingGroup() { return Frame.SegmentGroupIndex == -1; } protected bool IsEndingGroup() { return Frame.SegmentGroupIndex == ((System.Collections.Generic.ICollection<System.Collections.Generic.IList<IPathSegment>>)Pattern.Contains).Count; } protected bool TestMatchingSegment(string value) { if (Frame.SegmentIndex >= ((System.Collections.Generic.ICollection<IPathSegment>)Frame.SegmentGroup).Count) { return false; } return Frame.SegmentGroup[Frame.SegmentIndex].Match(value); } protected bool TestMatchingGroup(FileSystemInfoBase value) { int count = ((System.Collections.Generic.ICollection<IPathSegment>)Frame.SegmentGroup).Count; int num = Frame.BacktrackAvailable + 1; if (num < count) { return false; } FileSystemInfoBase fileSystemInfoBase = value; for (int i = 0; i != count; i++) { IPathSegment pathSegment = Frame.SegmentGroup[count - i - 1]; if (fileSystemInfoBase == null || !pathSegment.Match(fileSystemInfoBase.Name)) { return false; } fileSystemInfoBase = fileSystemInfoBase.ParentDirectory; } return true; } protected string CalculateStem(FileInfoBase matchedFile) { return MatcherContext.CombinePath(Frame.Stem, matchedFile.Name); } } public class PatternContextRaggedExclude : PatternContextRagged { public PatternContextRaggedExclude(IRaggedPattern pattern) : base(pattern) { } public override bool Test(DirectoryInfoBase directory) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotTestDirectory); } if (Frame.IsNotApplicable) { return false; } if (IsEndingGroup() && TestMatchingGroup(directory)) { return true; } if (((System.Collections.Generic.ICollection<IPathSegment>)base.Pattern.EndsWith).Count == 0 && Frame.SegmentGroupIndex == ((System.Collections.Generic.ICollection<System.Collections.Generic.IList<IPathSegment>>)base.Pattern.Contains).Count - 1 && TestMatchingGroup(directory)) { return true; } return false; } } public class PatternContextRaggedInclude : PatternContextRagged { public PatternContextRaggedInclude(IRaggedPattern pattern) : base(pattern) { } public override void Declare(Action<IPathSegment, bool> onDeclare) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotDeclarePathSegment); } if (!Frame.IsNotApplicable) { if (IsStartingGroup() && Frame.SegmentIndex < ((System.Collections.Generic.ICollection<IPathSegment>)Frame.SegmentGroup).Count) { onDeclare.Invoke(Frame.SegmentGroup[Frame.SegmentIndex], false); } else { onDeclare.Invoke((IPathSegment)WildcardPathSegment.MatchAll, false); } } } public override bool Test(DirectoryInfoBase directory) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotTestDirectory); } if (Frame.IsNotApplicable) { return false; } if (IsStartingGroup() && !TestMatchingSegment(directory.Name)) { return false; } return true; } } } namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PathSegments { public class CurrentPathSegment : IPathSegment { public bool CanProduceStem => false; public bool Match(string value) { return false; } } public class LiteralPathSegment : IPathSegment { private readonly StringComparison _comparisonType; public bool CanProduceStem => false; [field: CompilerGenerated] public string Value { [CompilerGenerated] get; } public LiteralPathSegment(string value, StringComparison comparisonType) { //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) ThrowHelper.ThrowIfNull(value, "value"); Value = value; _comparisonType = comparisonType; } public bool Match(string value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) return string.Equals(Value, value, _comparisonType); } public virtual bool Equals([NotNullWhen(true)] object? obj) { //IL_000b: 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_0025: Unknown result type (might be due to invalid IL or missing references) if (obj is LiteralPathSegment literalPathSegment && _comparisonType == literalPathSegment._comparisonType) { return string.Equals(literalPathSegment.Value, Value, _comparisonType); } return false; } public virtual int GetHashCode() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return StringComparisonHelper.GetStringComparer(_comparisonType).GetHashCode(Value); } } public class ParentPathSegment : IPathSegment { private const string LiteralParent = ".."; public bool CanProduceStem => false; public bool Match(string value) { return string.Equals("..", value, (StringComparison)4); } } public class RecursiveWildcardSegment : IPathSegment { public bool CanProduceStem => true; public bool Match(string value) { return false; } } public class WildcardPathSegment : IPathSegment { public static readonly WildcardPathSegment MatchAll = new WildcardPathSegment(string.Empty, new List<string>(), string.Empty, (StringComparison)5); private readonly StringComparison _comparisonType; public bool CanProduceStem => true; [field: CompilerGenerated] public string BeginsWith { [CompilerGenerated] get; } [field: CompilerGenerated] public List<string> Contains { [CompilerGenerated] get; } [field: CompilerGenerated] public string EndsWith { [CompilerGenerated] get; } public WildcardPathSegment(string beginsWith, List<string> contains, string endsWith, StringComparison comparisonType) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0044: 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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(beginsWith, "beginsWith"); ThrowHelper.ThrowIfNull(contains, "contains"); ThrowHelper.ThrowIfNull(endsWith, "endsWith"); if (comparisonType - 4 > 1) { throw new InvalidOperationException(System.SR.Format(System.SR.StringComparisonTypeShouldBeOrdinal, comparisonType)); } _comparisonType = comparisonType; BeginsWith = beginsWith; Contains = contains; EndsWith = endsWith; } public bool Match(string value) { //IL_002b: 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_0088: Unknown result type (might be due to invalid IL or missing references) if (value.Length < BeginsWith.Length + EndsWith.Length) { return false; } if (!value.StartsWith(BeginsWith, _comparisonType)) { return false; } if (!value.EndsWith(EndsWith, _comparisonType)) { return false; } int num = BeginsWith.Length; int num2 = value.Length - EndsWith.Length; for (int i = 0; i != Contains.Count; i++) { string text = Contains[i]; int num3 = value.IndexOf(text, num, num2 - num, _comparisonType); if (num3 == -1) { return false; } num = num3 + text.Length; } return true; } } } namespace Microsoft.Extensions.FileSystemGlobbing.Abstractions { public abstract class DirectoryInfoBase : FileSystemInfoBase { public abstract System.Collections.Generic.IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos(); public abstract DirectoryInfoBase? GetDirectory(string path); public abstract FileInfoBase? GetFile(string path); } public class DirectoryInfoWrapper : DirectoryInfoBase { [CompilerGenerated] private sealed class <EnumerateFileSystemInfos>d__4 : System.Collections.Generic.IEnumerable<FileSystemInfoBase>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<FileSystemInfoBase>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private FileSystemInfoBase <>2__current; private int <>l__initialThreadId; public DirectoryInfoWrapper <>4__this; private System.Collections.Generic.IEnumerator<FileSystemInfo> <>7__wrap1; FileSystemInfoBase System.Collections.Generic.IEnumerator<FileSystemInfoBase>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <EnumerateFileSystemInfos>d__4(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { int num = <>1__state; if (num == -3 || (uint)(num - 1) <= 1u) { try { } finally { <>m__Finally1(); } } } private bool MoveNext() { //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Expected O, but got Unknown try { int num = <>1__state; DirectoryInfoWrapper directoryInfoWrapper = <>4__this; switch (num) { default: return false; case 0: { <>1__state = -1; if (!((FileSystemInfo)directoryInfoWrapper._directoryInfo).Exists) { break; } System.Collections.Generic.IEnumerable<FileSystemInfo> enumerable; try { enumerable = directoryInfoWrapper._directoryInfo.EnumerateFileSystemInfos("*", (SearchOption)0); } catch (DirectoryNotFoundException) { return false; } <>7__wrap1 = enumerable.GetEnumerator(); <>1__state = -3; goto IL_00d1; } case 1: <>1__state = -3; goto IL_00d1; case 2: { <>1__state = -3; goto IL_00d1; } IL_00d1: if (((System.Collections.IEnumerator)<>7__wrap1).MoveNext()) { FileSystemInfo current = <>7__wrap1.Current; DirectoryInfo val2 = (DirectoryInfo)(object)((current is DirectoryInfo) ? current : null); if (val2 != null) { <>2__current = new DirectoryInfoWrapper(val2); <>1__state = 1; return true; } <>2__current = new FileInfoWrapper((FileInfo)current); <>1__state = 2; return true; } <>m__Finally1(); <>7__wrap1 = null; break; } return false; } catch { //try-fault ((System.IDisposable)this).Dispose(); throw; } } bool System.Collections.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) { ((System.IDisposable)<>7__wrap1).Dispose(); } } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<FileSystemInfoBase> System.Collections.Generic.IEnumerable<FileSystemInfoBase>.GetEnumerator() { <EnumerateFileSystemInfos>d__4 result; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; result = this; } else { result = new <EnumerateFileSystemInfos>d__4(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<FileSystemInfoBase>)this).GetEnumerator(); } } private readonly DirectoryInfo _directoryInfo; private readonly bool _isParentPath; public override string Name { get { if (!_isParentPath) { return ((FileSystemInfo)_directoryInfo).Name; } return ".."; } } public override string FullName => ((FileSystemInfo)_directoryInfo).FullName; public override DirectoryInfoBase? ParentDirectory => new DirectoryInfoWrapper(_directoryInfo.Parent); public DirectoryInfoWrapper(DirectoryInfo directoryInfo) : this(directoryInfo, isParentPath: false) { } private DirectoryInfoWrapper(DirectoryInfo directoryInfo, bool isParentPath) { _directoryInfo = directoryInfo; _isParentPath = isParentPath; } [IteratorStateMachine(typeof(<EnumerateFileSystemInfos>d__4))] public override System.Collections.Generic.IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos() { if (!((FileSystemInfo)_directoryInfo).Exists) { yield break; } System.Collections.Generic.IEnumerable<FileSystemInfo> enumerable; try { enumerable = _directoryInfo.EnumerateFileSystemInfos("*", (SearchOption)0); } catch (DirectoryNotFoundException) { yield break; } System.Collections.Generic.IEnumerator<FileSystemInfo> enumerator = enumerable.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { FileSystemInfo current = enumerator.Current; DirectoryInfo val2 = (DirectoryInfo)(object)((current is DirectoryInfo) ? current : null); if (val2 != null) { yield return new DirectoryInfoWrapper(val2); } else { yield return new FileInfoWrapper((FileInfo)current); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public override DirectoryInfoBase? GetDirectory(string name) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_009f: Unknown result type (might be due to invalid IL or missing references) bool flag = string.Equals(name, "..", (StringComparison)4); if (flag) { return new DirectoryInfoWrapper(new DirectoryInfo(Path.Combine(((FileSystemInfo)_directoryInfo).FullName, name)), flag); } DirectoryInfo[] directories = _directoryInfo.GetDirectories(name); if (directories.Length == 1) { return new DirectoryInfoWrapper(directories[0], flag); } if (directories.Length == 0) { return null; } throw new InvalidOperationException($"More than one sub directories are found under {((FileSystemInfo)_directoryInfo).FullName} with name {name}."); } public override FileInfoBase GetFile(string name) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown return new FileInfoWrapper(new FileInfo(Path.Combine(((FileSystemInfo)_directoryInfo).FullName, name))); } } public abstract class FileInfoBase : FileSystemInfoBase { } public class FileInfoWrapper : FileInfoBase { private readonly FileInfo _fileInfo; public override string Name => ((FileSystemInfo)_fileInfo).Name; public override string FullName => ((FileSystemInfo)_fileInfo).FullName; public override DirectoryInfoBase? ParentDirectory => new DirectoryInfoWrapper(_fileInfo.Directory); public FileInfoWrapper(FileInfo fileInfo) { ThrowHelper.ThrowIfNull(fileInfo, "fileInfo"); _fileInfo = fileInfo; } } public abstract class FileSystemInfoBase { public abstract string Name { get; } public abstract string FullName { get; } public abstract DirectoryInfoBase? ParentDirectory { get; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Hosting.Abstractions.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.Hosting.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Hosting.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Hosting and startup abstractions for applications.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Hosting.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Hosting.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Hosting.Abstractions.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string HostAbortedExceptionMessage => GetResourceString("HostAbortedExceptionMessage"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionHostedServiceExtensions { public static IServiceCollection AddHostedService<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] THostedService>(this IServiceCollection services) where THostedService : class, IHostedService { ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, ServiceDescriptor.Singleton<IHostedService, THostedService>()); return services; } public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services, Func<IServiceProvider, THostedService> implementationFactory) where THostedService : class, IHostedService { ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, ServiceDescriptor.Singleton<IHostedService>((Func<IServiceProvider, IHostedService>)(object)implementationFactory)); return services; } } } namespace Microsoft.Extensions.Hosting { public abstract class BackgroundService : IHostedService, System.IDisposable { [StructLayout(3)] [CompilerGenerated] private struct <StopAsync>d__6 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public BackgroundService <>4__this; public CancellationToken cancellationToken; private object <>7__wrap1; private int <>7__wrap2; private ConfiguredTaskAwaiter<System.Threading.Tasks.Task> <>u__1; private void MoveNext() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0067: 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_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_0080: 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) int num = <>1__state; BackgroundService backgroundService = <>4__this; try { ConfiguredTaskAwaiter<System.Threading.Tasks.Task> awaiter; if (num == 0) { awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter<System.Threading.Tasks.Task>); num = (<>1__state = -1); goto IL_00b2; } if (backgroundService._executeTask != null) { <>7__wrap1 = null; <>7__wrap2 = 0; try { backgroundService._stoppingCts.Cancel(); } catch (object obj) { <>7__wrap1 = obj; } awaiter = System.Threading.Tasks.Task.WhenAny(backgroundService._executeTask, System.Threading.Tasks.Task.Delay(-1, cancellationToken)).ConfigureAwait(false).GetAwaiter(); if (!awaiter.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter<System.Threading.Tasks.Task>, <StopAsync>d__6>(ref awaiter, ref this); return; } goto IL_00b2; } goto end_IL_000e; IL_00b2: awaiter.GetResult(); object obj2 = <>7__wrap1; if (obj2 != null) { if (!(obj2 is System.Exception ex)) { throw obj2; } ExceptionDispatchInfo.Capture(ex).Throw(); } <>7__wrap1 = null; end_IL_000e:; } catch (System.Exception exception) { <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } private System.Threading.Tasks.Task _executeTask; private CancellationTokenSource _stoppingCts; public virtual System.Threading.Tasks.Task? ExecuteTask => _executeTask; protected abstract System.Threading.Tasks.Task ExecuteAsync(CancellationToken stoppingToken); public virtual System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); _executeTask = ExecuteAsync(_stoppingCts.Token); if (_executeTask.IsCompleted) { return _executeTask; } return System.Threading.Tasks.Task.CompletedTask; } [AsyncStateMachine(typeof(<StopAsync>d__6))] public virtual System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken) { //IL_0002: 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_0016: 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) <StopAsync>d__6 <StopAsync>d__ = default(<StopAsync>d__6); <StopAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <StopAsync>d__.<>4__this = this; <StopAsync>d__.cancellationToken = cancellationToken; <StopAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <StopAsync>d__.<>t__builder)).Start<<StopAsync>d__6>(ref <StopAsync>d__); return ((AsyncTaskMethodBuilder)(ref <StopAsync>d__.<>t__builder)).Task; } public virtual void Dispose() { CancellationTokenSource stoppingCts = _stoppingCts; if (stoppingCts != null) { stoppingCts.Cancel(); } } } [Obsolete("EnvironmentName has been deprecated. Use Microsoft.Extensions.Hosting.Environments instead.")] public static class EnvironmentName { public static readonly string Development = "Development"; public static readonly string Staging = "Staging"; public static readonly string Production = "Production"; } public static class Environments { public static readonly string Development = "Development"; public static readonly string Staging = "Staging"; public static readonly string Production = "Production"; } [Serializable] public sealed class HostAbortedException : System.Exception { private HostAbortedException(SerializationInfo info, StreamingContext context) : base(info, context) { }//IL_0002: Unknown result type (might be due to invalid IL or missing references) public HostAbortedException() : base(System.SR.HostAbortedExceptionMessage) { } public HostAbortedException(string? message) : base(message) { } public HostAbortedException(string? message, System.Exception? innerException) : base(message, innerException) { } } public class HostBuilderContext { [field: CompilerGenerated] public IHostEnvironment HostingEnvironment { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public IConfiguration Configuration { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public IDictionary<object, object> Properties { [CompilerGenerated] get; } public HostBuilderContext(IDictionary<object, object> properties) { ThrowHelper.ThrowIfNull(properties, "properties"); Properties = properties; } } public static class HostDefaults { public static readonly string ApplicationKey = "applicationName"; public static readonly string EnvironmentKey = "environment"; public static readonly string ContentRootKey = "contentRoot"; } public static class HostEnvironmentEnvExtensions { public static bool IsDevelopment(this IHostEnvironment hostEnvironment) { ThrowHelper.ThrowIfNull(hostEnvironment, "hostEnvironment"); return hostEnvironment.IsEnvironment(Environments.Development); } public static bool IsStaging(this IHostEnvironment hostEnvironment) { ThrowHelper.ThrowIfNull(hostEnvironment, "hostEnvironment"); return hostEnvironment.IsEnvironment(Environments.Staging); } public static bool IsProduction(this IHostEnvironment hostEnvironment) { ThrowHelper.ThrowIfNull(hostEnvironment, "hostEnvironment"); return hostEnvironment.IsEnvironment(Environments.Production); } public static bool IsEnvironment(this IHostEnvironment hostEnvironment, string environmentName) { ThrowHelper.ThrowIfNull(hostEnvironment, "hostEnvironment"); return string.Equals(hostEnvironment.EnvironmentName, environmentName, (StringComparison)5); } } public static class HostingAbstractionsHostBuilderExtensions { [StructLayout(3)] [CompilerGenerated] private struct <StartAsync>d__1 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder<IHost> <>t__builder; public IHostBuilder hostBuilder; public CancellationToken cancellationToken; private IHost <host>5__2; private ConfiguredTaskAwaiter <>u__1; private void MoveNext() { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_004e: 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) int num = <>1__state; IHost result; try { ConfiguredTaskAwaiter awaiter; if (num != 0) { <host>5__2 = hostBuilder.Build(); ConfiguredTaskAwaitable val = <host>5__2.StartAsync(cancellationToken).ConfigureAwait(false); awaiter = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; <>t__builder.AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <StartAsync>d__1>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); } ((ConfiguredTaskAwaiter)(ref awaiter)).GetResult(); result = <host>5__2; } catch (System.Exception exception) { <>1__state = -2; <host>5__2 = null; <>t__builder.SetException(exception); return; } <>1__state = -2; <host>5__2 = null; <>t__builder.SetResult(result); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { <>t__builder.SetStateMachine(stateMachine); } } public static IHost Start(this IHostBuilder hostBuilder) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) return hostBuilder.StartAsync().GetAwaiter().GetResult(); } [AsyncStateMachine(typeof(<StartAsync>d__1))] public static async System.Threading.Tasks.Task<IHost> StartAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default(CancellationToken)) { //IL_0002: 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_0016: 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) IHost host = hostBuilder.Build(); await host.StartAsync(cancellationToken).ConfigureAwait(false); return host; } } public static class HostingAbstractionsHostExtensions { [StructLayout(3)] [CompilerGenerated] private struct <RunAsync>d__4 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public IHost host; public CancellationToken token; private object <>7__wrap1; private int <>7__wrap2; private ConfiguredTaskAwaiter <>u__1; private ConfiguredValueTaskAwaiter <>u__2; private void MoveNext() { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0172: 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_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { ConfiguredValueTaskAwaiter awaiter; if ((uint)num > 1u) { if (num == 2) { awaiter = <>u__2; <>u__2 = default(ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_018e; } <>7__wrap1 = null; <>7__wrap2 = 0; } try { ConfiguredTaskAwaiter awaiter2; ConfiguredTaskAwaitable val; ConfiguredTaskAwaiter awaiter3; if (num != 0) { if (num == 1) { awaiter2 = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_0102; } val = host.StartAsync(token).ConfigureAwait(false); awaiter3 = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter3)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter3; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <RunAsync>d__4>(ref awaiter3, ref this); return; } } else { awaiter3 = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); } ((ConfiguredTaskAwaiter)(ref awaiter3)).GetResult(); val = host.WaitForShutdownAsync(token).ConfigureAwait(false); awaiter2 = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter2)).IsCompleted) { num = (<>1__state = 1); <>u__1 = awaiter2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <RunAsync>d__4>(ref awaiter2, ref this); return; } goto IL_0102; IL_0102: ((ConfiguredTaskAwaiter)(ref awaiter2)).GetResult(); } catch (object obj) { <>7__wrap1 = obj; } if (host is System.IAsyncDisposable asyncDisposable) { ConfiguredValueTaskAwaitable val2 = asyncDisposable.DisposeAsync().ConfigureAwait(false); awaiter = ((ConfiguredValueTaskAwaitable)(ref val2)).GetAwaiter(); if (!((ConfiguredValueTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 2); <>u__2 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredValueTaskAwaiter, <RunAsync>d__4>(ref awaiter, ref this); return; } goto IL_018e; } ((System.IDisposable)host).Dispose(); goto IL_01a2; IL_018e: ((ConfiguredValueTaskAwaiter)(ref awaiter)).GetResult(); goto IL_01a2; IL_01a2: object obj2 = <>7__wrap1; if (obj2 != null) { if (!(obj2 is System.Exception ex)) { throw obj2; } ExceptionDispatchInfo.Capture(ex).Throw(); } <>7__wrap1 = null; } catch (System.Exception exception) { <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } [StructLayout(3)] [CompilerGenerated] private struct <StopAsync>d__1 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public TimeSpan timeout; public IHost host; private CancellationTokenSource <cts>5__2; private ConfiguredTaskAwaiter <>u__1; private void MoveNext() { //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_001b: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { if (num != 0) { <cts>5__2 = new CancellationTokenSource(timeout); } try { ConfiguredTaskAwaiter awaiter; if (num != 0) { ConfiguredTaskAwaitable val = host.StopAsync(<cts>5__2.Token).ConfigureAwait(false); awaiter = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <StopAsync>d__1>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); } ((ConfiguredTaskAwaiter)(ref awaiter)).GetResult(); } finally { if (num < 0 && <cts>5__2 != null) { ((System.IDisposable)<cts>5__2).Dispose(); } } } catch (System.Exception exception) { <>1__state = -2; <cts>5__2 = null; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; <cts>5__2 = null; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } [StructLayout(3)] [CompilerGenerated] private struct <WaitForShutdownAsync>d__5 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public IHost host; public CancellationToken token; private ConfiguredTaskAwaiter<object> <>u__1; private ConfiguredTaskAwaiter <>u__2; private void MoveNext() { //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: 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_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { ConfiguredTaskAwaiter awaiter; ConfiguredTaskAwaiter<object> awaiter2; if (num != 0) { if (num == 1) { awaiter = <>u__2; <>u__2 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_0159; } IHostApplicationLifetime requiredService = ServiceProviderServiceExtensions.GetRequiredService<IHostApplicationLifetime>(host.Services); ((CancellationToken)(ref token)).Register((Action<object>)delegate(object state) { ((IHostApplicationLifetime)state).StopApplication(); }, (object)requiredService); TaskCompletionSource<object> val = new TaskCompletionSource<object>((TaskCreationOptions)64); CancellationToken applicationStopping = requiredService.ApplicationStopping; ((CancellationToken)(ref applicationStopping)).Register((Action<object>)delegate(object obj) { TaskCompletionSource<object> val3 = (TaskCompletionSource<object>)obj; val3.TrySetResult((object)null); }, (object)val); awaiter2 = val.Task.ConfigureAwait(false).GetAwaiter(); if (!awaiter2.IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter<object>, <WaitForShutdownAsync>d__5>(ref awaiter2, ref this); return; } } else { awaiter2 = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter<object>); num = (<>1__state = -1); } awaiter2.GetResult(); ConfiguredTaskAwaitable val2 = host.StopAsync(CancellationToken.None).ConfigureAwait(false); awaiter = ((ConfiguredTaskAwaitable)(ref val2)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 1); <>u__2 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <WaitForShutdownAsync>d__5>(ref awaiter, ref this); return; } goto IL_0159; IL_0159: ((ConfiguredTaskAwaiter)(ref awaiter)).GetResult(); } catch (System.Exception exception) { <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } public static void Start(this IHost host) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) TaskAwaiter awaiter = host.StartAsync().GetAwaiter(); ((TaskAwaiter)(ref awaiter)).GetResult(); } [AsyncStateMachine(typeof(<StopAsync>d__1))] public static System.Threading.Tasks.Task StopAsync(this IHost host, TimeSpan timeout) { //IL_0002: 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_0016: 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) <StopAsync>d__1 <StopAsync>d__ = default(<StopAsync>d__1); <StopAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <StopAsync>d__.host = host; <StopAsync>d__.timeout = timeout; <StopAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <StopAsync>d__.<>t__builder)).Start<<StopAsync>d__1>(ref <StopAsync>d__); return ((AsyncTaskMethodBuilder)(ref <StopAsync>d__.<>t__builder)).Task; } public static void WaitForShutdown(this IHost host) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) TaskAwaiter awaiter = host.WaitForShutdownAsync().GetAwaiter(); ((TaskAwaiter)(ref awaiter)).GetResult(); } public static void Run(this IHost host) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) TaskAwaiter awaiter = host.RunAsync().GetAwaiter(); ((TaskAwaiter)(ref awaiter)).GetResult(); } [AsyncStateMachine(typeof(<RunAsync>d__4))] public static System.Threading.Tasks.Task RunAsync(this IHost host, CancellationToken token = default(CancellationToken)) { //IL_0002: 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_0016: 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) <RunAsync>d__4 <RunAsync>d__ = default(<RunAsync>d__4); <RunAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <RunAsync>d__.host = host; <RunAsync>d__.token = token; <RunAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <RunAsync>d__.<>t__builder)).Start<<RunAsync>d__4>(ref <RunAsync>d__); return ((AsyncTaskMethodBuilder)(ref <RunAsync>d__.<>t__builder)).Task; } [AsyncStateMachine(typeof(<WaitForShutdownAsync>d__5))] public static System.Threading.Tasks.Task WaitForShutdownAsync(this IHost host, CancellationToken token = default(CancellationToken)) { //IL_0002: 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_0016: 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) <WaitForShutdownAsync>d__5 <WaitForShutdownAsync>d__ = default(<WaitForShutdownAsync>d__5); <WaitForShutdownAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <WaitForShutdownAsync>d__.host = host; <WaitForShutdownAsync>d__.token = token; <WaitForShutdownAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <WaitForShutdownAsync>d__.<>t__builder)).Start<<WaitForShutdownAsync>d__5>(ref <WaitForShutdownAsync>d__); return ((AsyncTaskMethodBuilder)(ref <WaitForShutdownAsync>d__.<>t__builder)).Task; } } public static class HostingEnvironmentExtensions { public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) { ThrowHelper.ThrowIfNull(hostingEnvironment, "hostingEnvironment"); return hostingEnvironment.IsEnvironment(EnvironmentName.Development); } public static bool IsStaging(this IHostingEnvironment hostingEnvironment) { ThrowHelper.ThrowIfNull(hostingEnvironment, "hostingEnvironment"); return hostingEnvironment.IsEnvironment(EnvironmentName.Staging); } public static bool IsProduction(this IHostingEnvironment hostingEnvironment) { ThrowHelper.ThrowIfNull(hostingEnvironment, "hostingEnvironment"); return hostingEnvironment.IsEnvironment(EnvironmentName.Production); } public static bool IsEnvironment(this IHostingEnvironment hostingEnvironment, string environmentName) { ThrowHelper.ThrowIfNull(hostingEnvironment, "hostingEnvironment"); return string.Equals(hostingEnvironment.EnvironmentName, environmentName, (StringComparison)5); } } [Obsolete("IApplicationLifetime has been deprecated. Use Microsoft.Extensions.Hosting.IHostApplicationLifetime instead.")] public interface IApplicationLifetime { CancellationToken ApplicationStarted { get; } CancellationToken ApplicationStopping { get; } CancellationToken ApplicationStopped { get; } void StopApplication(); } public interface IHost : System.IDisposable { IServiceProvider Services { get; } System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)); System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken = default(CancellationToken)); } public interface IHostApplicationLifetime { CancellationToken ApplicationStarted { get; } CancellationToken ApplicationStopping { get; } CancellationToken ApplicationStopped { get; } void StopApplication(); } public interface IHostBuilder { IDictionary<object, object> Properties { get; } IHostBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate); IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate); IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate); IHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory) where TContainerBuilder : notnull; IHostBuilder UseServiceProviderFactory<TContainerBuilder>(Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory) where TContainerBuilder : notnull; IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate); IHost Build(); } public interface IHostedService { System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken); System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken); } public interface IHostEnvironment { string EnvironmentName { get; set; } string ApplicationName { get; set; } string ContentRootPath { get; set; } IFileProvider ContentRootFileProvider { get; set; } } [Obsolete("IHostingEnvironment has been deprecated. Use Microsoft.Extensions.Hosting.IHostEnvironment instead.")] public interface IHostingEnvironment { string EnvironmentName { get; set; } string ApplicationName { get; set; } string ContentRootPath { get; set; } IFileProvider ContentRootFileProvider { get; set; } } public interface IHostLifetime { System.Threading.Tasks.Task WaitForStartAsync(CancellationToken cancellationToken); System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken); } }
AuriePack/AurieInstaller/Microsoft.Extensions.Hosting.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.Hosting; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting.Internal; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.EventLog; using Microsoft.Extensions.Options; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Hosting")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Hosting and startup infrastructures for applications.")] [assembly: AssemblyFileVersion("7.0.323.6910")] [assembly: AssemblyInformationalVersion("7.0.3+0a2bda10e81d901396c3cff95533529e3a93ad47")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Hosting")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Hosting { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Hosting.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string ApplicationNameChangeNotSupported => GetResourceString("ApplicationNameChangeNotSupported"); internal static string BackgroundServiceExceptionStoppedHost => GetResourceString("BackgroundServiceExceptionStoppedHost"); internal static string BuildCalled => GetResourceString("BuildCalled"); internal static string ContentRootChangeNotSupported => GetResourceString("ContentRootChangeNotSupported"); internal static string CreateBuilderCallBeforeCreateServiceProvider => GetResourceString("CreateBuilderCallBeforeCreateServiceProvider"); internal static string EnvironmentNameChangeNotSupoprted => GetResourceString("EnvironmentNameChangeNotSupoprted"); internal static string IHostApplicationLifetimeReplacementNotSupported => GetResourceString("IHostApplicationLifetimeReplacementNotSupported"); internal static string NullIServiceProvider => GetResourceString("NullIServiceProvider"); internal static string ResolverReturnedNull => GetResourceString("ResolverReturnedNull"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.DependencyInjection { [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2091:UnrecognizedReflectionPattern", Justification = "Workaround for https://github.com/mono/linker/issues/1416. Outer method has been annotated with DynamicallyAccessedMembers.")] public static class OptionsBuilderExtensions { public static OptionsBuilder<TOptions> ValidateOnStart<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class { OptionsBuilder<TOptions> optionsBuilder2 = optionsBuilder; ThrowHelper.ThrowIfNull(optionsBuilder2, "optionsBuilder"); ServiceCollectionHostedServiceExtensions.AddHostedService<ValidationHostedService>(optionsBuilder2.Services); OptionsServiceCollectionExtensions.AddOptions<ValidatorOptions>(optionsBuilder2.Services).Configure<IOptionsMonitor<TOptions>>((Action<ValidatorOptions, IOptionsMonitor<TOptions>>)delegate(ValidatorOptions vo, IOptionsMonitor<TOptions> options) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown vo.Validators[new ValueTuple<System.Type, string>(typeof(TOptions), optionsBuilder2.Name)] = (Action)delegate { options.Get(optionsBuilder2.Name); }; }); return optionsBuilder2; } } internal sealed class ValidationHostedService : IHostedService { private readonly IDictionary<ValueTuple<System.Type, string>, Action> _validators; public ValidationHostedService(IOptions<ValidatorOptions> validatorOptions) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) _validators = validatorOptions?.Value?.Validators ?? throw new ArgumentNullException("validatorOptions"); } public System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken) { //IL_0029: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) List<System.Exception> val = new List<System.Exception>(); System.Collections.Generic.IEnumerator<Action> enumerator = ((System.Collections.Generic.IEnumerable<Action>)_validators.Values).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { Action current = enumerator.Current; try { current.Invoke(); } catch (OptionsValidationException val2) { OptionsValidationException val3 = val2; val.Add((System.Exception)(object)val3); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } if (val.Count == 1) { ExceptionDispatchInfo.Capture(val[0]).Throw(); } if (val.Count > 1) { throw new AggregateException((System.Collections.Generic.IEnumerable<System.Exception>)val); } return System.Threading.Tasks.Task.CompletedTask; } public System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken) { return System.Threading.Tasks.Task.CompletedTask; } } internal sealed class ValidatorOptions { [field: CompilerGenerated] public IDictionary<ValueTuple<System.Type, string>, Action> Validators { [CompilerGenerated] get; } = (IDictionary<ValueTuple<System.Type, string>, Action>)(object)new Dictionary<ValueTuple<System.Type, string>, Action>(); } } namespace Microsoft.Extensions.Hosting { public enum BackgroundServiceExceptionBehavior { StopHost, Ignore } public class ConsoleLifetimeOptions { [field: CompilerGenerated] public bool SuppressStatusMessages { [CompilerGenerated] get; [CompilerGenerated] set; } } public static class Host { internal const string RequiresDynamicCodeMessage = "Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime."; [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public static IHostBuilder CreateDefaultBuilder() { return CreateDefaultBuilder(null); } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public static IHostBuilder CreateDefaultBuilder(string[]? args) { HostBuilder builder = new HostBuilder(); return ((IHostBuilder)(object)builder).ConfigureDefaults(args); } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public static HostApplicationBuilder CreateApplicationBuilder() { return new HostApplicationBuilder(); } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public static HostApplicationBuilder CreateApplicationBuilder(string[]? args) { return new HostApplicationBuilder(args); } } public sealed class HostApplicationBuilder { private sealed class HostBuilderAdapter : IHostBuilder { private readonly HostApplicationBuilder _hostApplicationBuilder; private readonly List<Action<IConfigurationBuilder>> _configureHostConfigActions = new List<Action<IConfigurationBuilder>>(); private readonly List<Action<HostBuilderContext, IConfigurationBuilder>> _configureAppConfigActions = new List<Action<HostBuilderContext, IConfigurationBuilder>>(); private readonly List<IConfigureContainerAdapter> _configureContainerActions = new List<IConfigureContainerAdapter>(); private readonly List<Action<HostBuilderContext, IServiceCollection>> _configureServicesActions = new List<Action<HostBuilderContext, IServiceCollection>>(); private IServiceFactoryAdapter _serviceProviderFactory; public IDictionary<object, object> Properties => _hostApplicationBuilder._hostBuilderContext.Properties; public HostBuilderAdapter(HostApplicationBuilder hostApplicationBuilder) { _hostApplicationBuilder = hostApplicationBuilder; } public void ApplyChanges() { //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) ConfigurationManager configuration = _hostApplicationBuilder.Configuration; if (_configureHostConfigActions.Count > 0) { string text = configuration[HostDefaults.ApplicationKey]; string text2 = configuration[HostDefaults.EnvironmentKey]; string text3 = configuration[HostDefaults.ContentRootKey]; string contentRootPath = _hostApplicationBuilder._hostBuilderContext.HostingEnvironment.ContentRootPath; Enumerator<Action<IConfigurationBuilder>> enumerator = _configureHostConfigActions.GetEnumerator(); try { while (enumerator.MoveNext()) { Action<IConfigurationBuilder> current = enumerator.Current; current.Invoke((IConfigurationBuilder)(object)configuration); } } finally { ((System.IDisposable)enumerator).Dispose(); } if (!string.Equals(text, configuration[HostDefaults.ApplicationKey], (StringComparison)5)) { throw new NotSupportedException(System.SR.Format(System.SR.ApplicationNameChangeNotSupported, (object)text, (object)configuration[HostDefaults.ApplicationKey])); } if (!string.Equals(text2, configuration[HostDefaults.EnvironmentKey], (StringComparison)5)) { throw new NotSupportedException(System.SR.Format(System.SR.EnvironmentNameChangeNotSupoprted, (object)text2, (object)configuration[HostDefaults.EnvironmentKey])); } string text4 = configuration[HostDefaults.ContentRootKey]; if (!string.Equals(text3, text4, (StringComparison)5) && !string.Equals(contentRootPath, HostBuilder.ResolveContentRootPath(text4, AppContext.BaseDirectory), (StringComparison)5)) { throw new NotSupportedException(System.SR.Format(System.SR.ContentRootChangeNotSupported, (object)text3, (object)text4)); } } Enumerator<Action<HostBuilderContext, IConfigurationBuilder>> enumerator2 = _configureAppConfigActions.GetEnumerator(); try { while (enumerator2.MoveNext()) { Action<HostBuilderContext, IConfigurationBuilder> current2 = enumerator2.Current; current2.Invoke(_hostApplicationBuilder._hostBuilderContext, (IConfigurationBuilder)(object)configuration); } } finally { ((System.IDisposable)enumerator2).Dispose(); } Enumerator<Action<HostBuilderContext, IServiceCollection>> enumerator3 = _configureServicesActions.GetEnumerator(); try { while (enumerator3.MoveNext()) { Action<HostBuilderContext, IServiceCollection> current3 = enumerator3.Current; current3.Invoke(_hostApplicationBuilder._hostBuilderContext, _hostApplicationBuilder.Services); } } finally { ((System.IDisposable)enumerator3).Dispose(); } if (_configureContainerActions.Count > 0) { Action<object> previousConfigureContainer = _hostApplicationBuilder._configureContainer; _hostApplicationBuilder._configureContainer = delegate(object containerBuilder) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) previousConfigureContainer.Invoke(containerBuilder); Enumerator<IConfigureContainerAdapter> enumerator4 = _configureContainerActions.GetEnumerator(); try { while (enumerator4.MoveNext()) { IConfigureContainerAdapter current4 = enumerator4.Current; current4.ConfigureContainer(_hostApplicationBuilder._hostBuilderContext, containerBuilder); } } finally { ((System.IDisposable)enumerator4).Dispose(); } }; } if (_serviceProviderFactory != null) { _hostApplicationBuilder._createServiceProvider = [CompilerGenerated] () => { object obj = _serviceProviderFactory.CreateBuilder(_hostApplicationBuilder.Services); _hostApplicationBuilder._configureContainer.Invoke(obj); return _serviceProviderFactory.CreateServiceProvider(obj); }; } } public IHost Build() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } public IHostBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate) { ThrowHelper.ThrowIfNull(configureDelegate, "configureDelegate"); _configureHostConfigActions.Add(configureDelegate); return (IHostBuilder)(object)this; } public IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate) { ThrowHelper.ThrowIfNull(configureDelegate, "configureDelegate"); _configureAppConfigActions.Add(configureDelegate); return (IHostBuilder)(object)this; } public IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate) { ThrowHelper.ThrowIfNull(configureDelegate, "configureDelegate"); _configureServicesActions.Add(configureDelegate); return (IHostBuilder)(object)this; } public IHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory) { ThrowHelper.ThrowIfNull(factory, "factory"); _serviceProviderFactory = new ServiceFactoryAdapter<TContainerBuilder>(factory); return (IHostBuilder)(object)this; } public IHostBuilder UseServiceProviderFactory<TContainerBuilder>(Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory) { ThrowHelper.ThrowIfNull(factory, "factory"); _serviceProviderFactory = new ServiceFactoryAdapter<TContainerBuilder>([CompilerGenerated] () => _hostApplicationBuilder._hostBuilderContext, factory); return (IHostBuilder)(object)this; } public IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate) { ThrowHelper.ThrowIfNull(configureDelegate, "configureDelegate"); _configureContainerActions.Add((IConfigureContainerAdapter)new ConfigureContainerAdapter<TContainerBuilder>(configureDelegate)); return (IHostBuilder)(object)this; } } private sealed class LoggingBuilder : ILoggingBuilder { [field: CompilerGenerated] public IServiceCollection Services { [CompilerGenerated] get; } public LoggingBuilder(IServiceCollection services) { Services = services; } } private readonly HostBuilderContext _hostBuilderContext; private readonly ServiceCollection _serviceCollection = new ServiceCollection(); private Func<IServiceProvider> _createServiceProvider; private Action<object> _configureContainer = delegate { }; private HostBuilderAdapter _hostBuilderAdapter; private IServiceProvider _appServices; private bool _hostBuilt; [field: CompilerGenerated] public IHostEnvironment Environment { [CompilerGenerated] get; } [field: CompilerGenerated] public ConfigurationManager Configuration { [CompilerGenerated] get; } public IServiceCollection Services => (IServiceCollection)(object)_serviceCollection; [field: CompilerGenerated] public ILoggingBuilder Logging { [CompilerGenerated] get; } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public HostApplicationBuilder() : this((string[]?)null) { } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public HostApplicationBuilder(string[]? args) : this(new HostApplicationBuilderSettings { Args = args }) { } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public HostApplicationBuilder(HostApplicationBuilderSettings? settings) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: 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_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Expected O, but got Unknown //IL_010d: Unknown result type (might be due to invalid IL or missing references) if (settings == null) { settings = new HostApplicationBuilderSettings(); } Configuration = (ConfigurationManager)(((object)settings.Configuration) ?? ((object)new ConfigurationManager())); if (!settings.DisableDefaults) { if (settings.ContentRootPath == null && Configuration[HostDefaults.ContentRootKey] == null) { HostingHostBuilderExtensions.SetDefaultContentRoot((IConfigurationBuilder)(object)Configuration); } HostingHostBuilderExtensions.AddDefaultHostConfigurationSources((IConfigurationBuilder)(object)Configuration, settings.Args); } List<KeyValuePair<string, string>> val = null; if (settings.ApplicationName != null) { if (val == null) { val = new List<KeyValuePair<string, string>>(); } val.Add(new KeyValuePair<string, string>(HostDefaults.ApplicationKey, settings.ApplicationName)); } if (settings.EnvironmentName != null) { if (val == null) { val = new List<KeyValuePair<string, string>>(); } val.Add(new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, settings.EnvironmentName)); } if (settings.ContentRootPath != null) { if (val == null) { val = new List<KeyValuePair<string, string>>(); } val.Add(new KeyValuePair<string, string>(HostDefaults.ContentRootKey, settings.ContentRootPath)); } if (val != null) { MemoryConfigurationBuilderExtensions.AddInMemoryCollection((IConfigurationBuilder)(object)Configuration, (System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)val); } ValueTuple<HostingEnvironment, PhysicalFileProvider> val2 = HostBuilder.CreateHostingEnvironment((IConfiguration)(object)Configuration); HostingEnvironment item = val2.Item1; PhysicalFileProvider item2 = val2.Item2; FileConfigurationExtensions.SetFileProvider((IConfigurationBuilder)(object)Configuration, (IFileProvider)(object)item2); _hostBuilderContext = new HostBuilderContext((IDictionary<object, object>)(object)new Dictionary<object, object>()) { HostingEnvironment = (IHostEnvironment)(object)item, Configuration = (IConfiguration)(object)Configuration }; Environment = (IHostEnvironment)(object)item; HostBuilder.PopulateServiceCollection(Services, _hostBuilderContext, item, item2, (IConfiguration)(object)Configuration, [CompilerGenerated] () => _appServices); Logging = (ILoggingBuilder)(object)new LoggingBuilder(Services); ServiceProviderOptions serviceProviderOptions = null; if (!settings.DisableDefaults) { HostingHostBuilderExtensions.ApplyDefaultAppConfiguration(_hostBuilderContext, (IConfigurationBuilder)(object)Configuration, settings.Args); HostingHostBuilderExtensions.AddDefaultServices(_hostBuilderContext, Services); serviceProviderOptions = HostingHostBuilderExtensions.CreateDefaultServiceProviderOptions(_hostBuilderContext); } _createServiceProvider = delegate { _configureContainer.Invoke((object)Services); return (IServiceProvider)(object)((serviceProviderOptions != null) ? ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Services, serviceProviderOptions) : ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Services)); }; } public void ConfigureContainer<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory, Action<TContainerBuilder>? configure = null) where TContainerBuilder : notnull { IServiceProviderFactory<TContainerBuilder> factory2 = factory; Action<TContainerBuilder> configure2 = configure; _createServiceProvider = delegate { TContainerBuilder val = factory2.CreateBuilder(Services); _configureContainer.Invoke((object)val); return factory2.CreateServiceProvider(val); }; _configureContainer = delegate(object containerBuilder) { configure2?.Invoke((TContainerBuilder)containerBuilder); }; } public IHost Build() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_hostBuilt) { throw new InvalidOperationException(System.SR.BuildCalled); } _hostBuilt = true; DiagnosticListener val = HostBuilder.LogHostBuilding(this); try { _hostBuilderAdapter?.ApplyChanges(); _appServices = _createServiceProvider.Invoke(); _serviceCollection.MakeReadOnly(); return HostBuilder.ResolveHost(_appServices, val); } finally { ((System.IDisposable)val)?.Dispose(); } } internal IHostBuilder AsHostBuilder() { return (IHostBuilder)(object)(_hostBuilderAdapter ?? (_hostBuilderAdapter = new HostBuilderAdapter(this))); } } public sealed class HostApplicationBuilderSettings { [field: CompilerGenerated] public bool DisableDefaults { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string[]? Args { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public ConfigurationManager? Configuration { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string? EnvironmentName { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string? ApplicationName { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string? ContentRootPath { [CompilerGenerated] get; [CompilerGenerated] set; } } public class HostBuilder : IHostBuilder { private const string HostBuildingDiagnosticListenerName = "Microsoft.Extensions.Hosting"; private const string HostBuildingEventName = "HostBuilding"; private const string HostBuiltEventName = "HostBuilt"; private List<Action<IConfigurationBuilder>> _configureHostConfigActions = new List<Action<IConfigurationBuilder>>(); private List<Action<HostBuilderContext, IConfigurationBuilder>> _configureAppConfigActions = new List<Action<HostBuilderContext, IConfigurationBuilder>>(); private List<Action<HostBuilderContext, IServiceCollection>> _configureServicesActions = new List<Action<HostBuilderContext, IServiceCollection>>(); private List<IConfigureContainerAdapter> _configureContainerActions = new List<IConfigureContainerAdapter>(); private IServiceFactoryAdapter _serviceProviderFactory; private bool _hostBuilt; private IConfiguration _hostConfiguration; private IConfiguration _appConfiguration; private HostBuilderContext _hostBuilderContext; private HostingEnvironment _hostingEnvironment; private IServiceProvider _appServices; private PhysicalFileProvider _defaultProvider; [field: CompilerGenerated] public IDictionary<object, object> Properties { [CompilerGenerated] get; } = (IDictionary<object, object>)(object)new Dictionary<object, object>(); [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public HostBuilder() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown _serviceProviderFactory = new ServiceFactoryAdapter<IServiceCollection>((IServiceProviderFactory<IServiceCollection>)new DefaultServiceProviderFactory()); } public IHostBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate) { ThrowHelper.ThrowIfNull(configureDelegate, "configureDelegate"); _configureHostConfigActions.Add(configureDelegate); return (IHostBuilder)(object)this; } public IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate) { ThrowHelper.ThrowIfNull(configureDelegate, "configureDelegate"); _configureAppConfigActions.Add(configureDelegate); return (IHostBuilder)(object)this; } public IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate) { ThrowHelper.ThrowIfNull(configureDelegate, "configureDelegate"); _configureServicesActions.Add(configureDelegate); return (IHostBuilder)(object)this; } public IHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory) where TContainerBuilder : notnull { ThrowHelper.ThrowIfNull(factory, "factory"); _serviceProviderFactory = new ServiceFactoryAdapter<TContainerBuilder>(factory); return (IHostBuilder)(object)this; } public IHostBuilder UseServiceProviderFactory<TContainerBuilder>(Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory) where TContainerBuilder : notnull { ThrowHelper.ThrowIfNull(factory, "factory"); _serviceProviderFactory = new ServiceFactoryAdapter<TContainerBuilder>([CompilerGenerated] () => _hostBuilderContext, factory); return (IHostBuilder)(object)this; } public IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate) { ThrowHelper.ThrowIfNull(configureDelegate, "configureDelegate"); _configureContainerActions.Add((IConfigureContainerAdapter)new ConfigureContainerAdapter<TContainerBuilder>(configureDelegate)); return (IHostBuilder)(object)this; } public IHost Build() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_hostBuilt) { throw new InvalidOperationException(System.SR.BuildCalled); } _hostBuilt = true; DiagnosticListener val = LogHostBuilding((IHostBuilder)(object)this); try { InitializeHostConfiguration(); InitializeHostingEnvironment(); InitializeHostBuilderContext(); InitializeAppConfiguration(); InitializeServiceProvider(); return ResolveHost(_appServices, val); } finally { ((System.IDisposable)val)?.Dispose(); } } private static DiagnosticListener LogHostBuilding(IHostBuilder hostBuilder) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown DiagnosticListener val = new DiagnosticListener("Microsoft.Extensions.Hosting"); if (val.IsEnabled() && ((DiagnosticSource)val).IsEnabled("HostBuilding")) { Write<IHostBuilder>((DiagnosticSource)(object)val, "HostBuilding", hostBuilder); } return val; } internal static DiagnosticListener LogHostBuilding(HostApplicationBuilder hostApplicationBuilder) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown DiagnosticListener val = new DiagnosticListener("Microsoft.Extensions.Hosting"); if (val.IsEnabled() && ((DiagnosticSource)val).IsEnabled("HostBuilding")) { Write<IHostBuilder>((DiagnosticSource)(object)val, "HostBuilding", hostApplicationBuilder.AsHostBuilder()); } return val; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "The values being passed into Write are being consumed by the application already.")] private static void Write<T>(DiagnosticSource diagnosticSource, string name, T value) { diagnosticSource.Write(name, (object)value); } [MemberNotNull("_hostConfiguration")] private void InitializeHostConfiguration() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected O, but got Unknown //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) IConfigurationBuilder val = MemoryConfigurationBuilderExtensions.AddInMemoryCollection((IConfigurationBuilder)new ConfigurationBuilder()); Enumerator<Action<IConfigurationBuilder>> enumerator = _configureHostConfigActions.GetEnumerator(); try { while (enumerator.MoveNext()) { Action<IConfigurationBuilder> current = enumerator.Current; current.Invoke(val); } } finally { ((System.IDisposable)enumerator).Dispose(); } _hostConfiguration = (IConfiguration)(object)val.Build(); } [MemberNotNull("_defaultProvider")] [MemberNotNull("_hostingEnvironment")] private void InitializeHostingEnvironment() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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) ValueTuple<HostingEnvironment, PhysicalFileProvider> val = CreateHostingEnvironment(_hostConfiguration); _hostingEnvironment = val.Item1; _defaultProvider = val.Item2; } internal static ValueTuple<HostingEnvironment, PhysicalFileProvider> CreateHostingEnvironment(IConfiguration hostConfiguration) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) HostingEnvironment hostingEnvironment = new HostingEnvironment { EnvironmentName = (hostConfiguration[HostDefaults.EnvironmentKey] ?? Environments.Production), ContentRootPath = ResolveContentRootPath(hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory) }; string text = hostConfiguration[HostDefaults.ApplicationKey]; if (string.IsNullOrEmpty(text)) { Assembly entryAssembly = Assembly.GetEntryAssembly(); text = ((entryAssembly != null) ? entryAssembly.GetName().Name : null); } if (text != null) { hostingEnvironment.ApplicationName = text; } PhysicalFileProvider val2 = (PhysicalFileProvider)(object)(hostingEnvironment.ContentRootFileProvider = (IFileProvider)new PhysicalFileProvider(hostingEnvironment.ContentRootPath)); return new ValueTuple<HostingEnvironment, PhysicalFileProvider>(hostingEnvironment, val2); } internal static string ResolveContentRootPath(string contentRootPath, string basePath) { if (string.IsNullOrEmpty(contentRootPath)) { return basePath; } if (Path.IsPathRooted(contentRootPath)) { return contentRootPath; } return Path.Combine(Path.GetFullPath(basePath), contentRootPath); } [MemberNotNull("_hostBuilderContext")] private void InitializeHostBuilderContext() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown _hostBuilderContext = new HostBuilderContext(Properties) { HostingEnvironment = (IHostEnvironment)(object)_hostingEnvironment, Configuration = _hostConfiguration }; } [MemberNotNull("_appConfiguration")] private void InitializeAppConfiguration() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) IConfigurationBuilder val = ChainedBuilderExtensions.AddConfiguration(FileConfigurationExtensions.SetBasePath((IConfigurationBuilder)new ConfigurationBuilder(), _hostingEnvironment.ContentRootPath), _hostConfiguration, true); Enumerator<Action<HostBuilderContext, IConfigurationBuilder>> enumerator = _configureAppConfigActions.GetEnumerator(); try { while (enumerator.MoveNext()) { Action<HostBuilderContext, IConfigurationBuilder> current = enumerator.Current; current.Invoke(_hostBuilderContext, val); } } finally { ((System.IDisposable)enumerator).Dispose(); } _appConfiguration = (IConfiguration)(object)val.Build(); _hostBuilderContext.Configuration = _appConfiguration; } [MemberNotNull("_appServices")] internal static void PopulateServiceCollection(IServiceCollection services, HostBuilderContext hostBuilderContext, HostingEnvironment hostingEnvironment, PhysicalFileProvider defaultFileProvider, IConfiguration appConfiguration, Func<IServiceProvider> serviceProviderGetter) { ServiceCollectionServiceExtensions.AddSingleton<IHostingEnvironment>(services, (IHostingEnvironment)(object)hostingEnvironment); ServiceCollectionServiceExtensions.AddSingleton<IHostEnvironment>(services, (IHostEnvironment)(object)hostingEnvironment); ServiceCollectionServiceExtensions.AddSingleton<HostBuilderContext>(services, hostBuilderContext); ServiceCollectionServiceExtensions.AddSingleton<IConfiguration>(services, (Func<IServiceProvider, IConfiguration>)((IServiceProvider _) => appConfiguration)); ServiceCollectionServiceExtensions.AddSingleton<IApplicationLifetime>(services, (Func<IServiceProvider, IApplicationLifetime>)((IServiceProvider s) => (IApplicationLifetime)ServiceProviderServiceExtensions.GetRequiredService<IHostApplicationLifetime>(s))); ServiceCollectionServiceExtensions.AddSingleton<IHostApplicationLifetime, ApplicationLifetime>(services); AddLifetime(services); ServiceCollectionServiceExtensions.AddSingleton<IHost>(services, (Func<IServiceProvider, IHost>)delegate { IServiceProvider val = serviceProviderGetter.Invoke(); return (IHost)(object)new Microsoft.Extensions.Hosting.Internal.Host(val, (IHostEnvironment)(object)hostingEnvironment, defaultFileProvider, ServiceProviderServiceExtensions.GetRequiredService<IHostApplicationLifetime>(val), ServiceProviderServiceExtensions.GetRequiredService<ILogger<Microsoft.Extensions.Hosting.Internal.Host>>(val), ServiceProviderServiceExtensions.GetRequiredService<IHostLifetime>(val), ServiceProviderServiceExtensions.GetRequiredService<IOptions<HostOptions>>(val)); }); OptionsServiceCollectionExtensions.Configure<HostOptions>(OptionsServiceCollectionExtensions.AddOptions(services), (Action<HostOptions>)delegate(HostOptions options) { options.Initialize(hostBuilderContext.Configuration); }); LoggingServiceCollectionExtensions.AddLogging(services); } [MemberNotNull("_appServices")] private void InitializeServiceProvider() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) ServiceCollection val = new ServiceCollection(); PopulateServiceCollection((IServiceCollection)(object)val, _hostBuilderContext, _hostingEnvironment, _defaultProvider, _appConfiguration, [CompilerGenerated] () => _appServices); Enumerator<Action<HostBuilderContext, IServiceCollection>> enumerator = _configureServicesActions.GetEnumerator(); try { while (enumerator.MoveNext()) { Action<HostBuilderContext, IServiceCollection> current = enumerator.Current; current.Invoke(_hostBuilderContext, (IServiceCollection)(object)val); } } finally { ((System.IDisposable)enumerator).Dispose(); } object containerBuilder = _serviceProviderFactory.CreateBuilder((IServiceCollection)(object)val); Enumerator<IConfigureContainerAdapter> enumerator2 = _configureContainerActions.GetEnumerator(); try { while (enumerator2.MoveNext()) { IConfigureContainerAdapter current2 = enumerator2.Current; current2.ConfigureContainer(_hostBuilderContext, containerBuilder); } } finally { ((System.IDisposable)enumerator2).Dispose(); } _appServices = _serviceProviderFactory.CreateServiceProvider(containerBuilder); } internal static IHost ResolveHost(IServiceProvider serviceProvider, DiagnosticListener diagnosticListener) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (serviceProvider == null) { throw new InvalidOperationException(System.SR.NullIServiceProvider); } ServiceProviderServiceExtensions.GetService<IConfiguration>(serviceProvider); IHost requiredService = ServiceProviderServiceExtensions.GetRequiredService<IHost>(serviceProvider); if (diagnosticListener.IsEnabled() && ((DiagnosticSource)diagnosticListener).IsEnabled("HostBuilt")) { Write<IHost>((DiagnosticSource)(object)diagnosticListener, "HostBuilt", requiredService); } return requiredService; } private static void AddLifetime(IServiceCollection services) { if (!OperatingSystem.IsAndroid() && !OperatingSystem.IsBrowser() && !OperatingSystem.IsIOS() && !OperatingSystem.IsTvOS()) { ServiceCollectionServiceExtensions.AddSingleton<IHostLifetime, ConsoleLifetime>(services); } else { ServiceCollectionServiceExtensions.AddSingleton<IHostLifetime, NullLifetime>(services); } } } public static class HostingHostBuilderExtensions { public static IHostBuilder UseEnvironment(this IHostBuilder hostBuilder, string environment) { string environment2 = environment; return hostBuilder.ConfigureHostConfiguration((Action<IConfigurationBuilder>)delegate(IConfigurationBuilder configBuilder) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(environment2, "environment"); MemoryConfigurationBuilderExtensions.AddInMemoryCollection(configBuilder, (System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)new KeyValuePair<string, string>[1] { new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, environment2) }); }); } public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, string contentRoot) { string contentRoot2 = contentRoot; return hostBuilder.ConfigureHostConfiguration((Action<IConfigurationBuilder>)delegate(IConfigurationBuilder configBuilder) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(contentRoot2, "contentRoot"); MemoryConfigurationBuilderExtensions.AddInMemoryCollection(configBuilder, (System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)new KeyValuePair<string, string>[1] { new KeyValuePair<string, string>(HostDefaults.ContentRootKey, contentRoot2) }); }); } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public static IHostBuilder UseDefaultServiceProvider(this IHostBuilder hostBuilder, Action<ServiceProviderOptions> configure) { Action<ServiceProviderOptions> configure2 = configure; return hostBuilder.UseDefaultServiceProvider((Action<HostBuilderContext, ServiceProviderOptions>)delegate(HostBuilderContext context, ServiceProviderOptions options) { configure2.Invoke(options); }); } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public static IHostBuilder UseDefaultServiceProvider(this IHostBuilder hostBuilder, Action<HostBuilderContext, ServiceProviderOptions> configure) { Action<HostBuilderContext, ServiceProviderOptions> configure2 = configure; return hostBuilder.UseServiceProviderFactory<IServiceCollection>((Func<HostBuilderContext, IServiceProviderFactory<IServiceCollection>>)delegate(HostBuilderContext context) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown ServiceProviderOptions val = new ServiceProviderOptions(); configure2.Invoke(context, val); return (IServiceProviderFactory<IServiceCollection>)new DefaultServiceProviderFactory(val); }); } public static IHostBuilder ConfigureLogging(this IHostBuilder hostBuilder, Action<HostBuilderContext, ILoggingBuilder> configureLogging) { Action<HostBuilderContext, ILoggingBuilder> configureLogging2 = configureLogging; return hostBuilder.ConfigureServices((Action<HostBuilderContext, IServiceCollection>)delegate(HostBuilderContext context, IServiceCollection collection) { LoggingServiceCollectionExtensions.AddLogging(collection, (Action<ILoggingBuilder>)delegate(ILoggingBuilder builder) { configureLogging2.Invoke(context, builder); }); }); } public static IHostBuilder ConfigureLogging(this IHostBuilder hostBuilder, Action<ILoggingBuilder> configureLogging) { Action<ILoggingBuilder> configureLogging2 = configureLogging; return hostBuilder.ConfigureServices((Action<HostBuilderContext, IServiceCollection>)delegate(HostBuilderContext context, IServiceCollection collection) { LoggingServiceCollectionExtensions.AddLogging(collection, (Action<ILoggingBuilder>)delegate(ILoggingBuilder builder) { configureLogging2.Invoke(builder); }); }); } public static IHostBuilder ConfigureHostOptions(this IHostBuilder hostBuilder, Action<HostBuilderContext, HostOptions> configureOptions) { Action<HostBuilderContext, HostOptions> configureOptions2 = configureOptions; return hostBuilder.ConfigureServices((Action<HostBuilderContext, IServiceCollection>)delegate(HostBuilderContext context, IServiceCollection collection) { OptionsServiceCollectionExtensions.Configure<HostOptions>(collection, (Action<HostOptions>)delegate(HostOptions options) { configureOptions2.Invoke(context, options); }); }); } public static IHostBuilder ConfigureHostOptions(this IHostBuilder hostBuilder, Action<HostOptions> configureOptions) { Action<HostOptions> configureOptions2 = configureOptions; return hostBuilder.ConfigureServices(delegate(IServiceCollection collection) { OptionsServiceCollectionExtensions.Configure<HostOptions>(collection, configureOptions2); }); } public static IHostBuilder ConfigureAppConfiguration(this IHostBuilder hostBuilder, Action<IConfigurationBuilder> configureDelegate) { Action<IConfigurationBuilder> configureDelegate2 = configureDelegate; return hostBuilder.ConfigureAppConfiguration((Action<HostBuilderContext, IConfigurationBuilder>)delegate(HostBuilderContext context, IConfigurationBuilder builder) { configureDelegate2.Invoke(builder); }); } public static IHostBuilder ConfigureServices(this IHostBuilder hostBuilder, Action<IServiceCollection> configureDelegate) { Action<IServiceCollection> configureDelegate2 = configureDelegate; return hostBuilder.ConfigureServices((Action<HostBuilderContext, IServiceCollection>)delegate(HostBuilderContext context, IServiceCollection collection) { configureDelegate2.Invoke(collection); }); } public static IHostBuilder ConfigureContainer<TContainerBuilder>(this IHostBuilder hostBuilder, Action<TContainerBuilder> configureDelegate) { Action<TContainerBuilder> configureDelegate2 = configureDelegate; return hostBuilder.ConfigureContainer<TContainerBuilder>((Action<HostBuilderContext, TContainerBuilder>)delegate(HostBuilderContext context, TContainerBuilder builder) { configureDelegate2.Invoke(builder); }); } [RequiresDynamicCode("Hosting uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public static IHostBuilder ConfigureDefaults(this IHostBuilder builder, string[]? args) { string[] args2 = args; return builder.ConfigureHostConfiguration((Action<IConfigurationBuilder>)delegate(IConfigurationBuilder config) { ApplyDefaultHostConfiguration(config, args2); }).ConfigureAppConfiguration((Action<HostBuilderContext, IConfigurationBuilder>)delegate(HostBuilderContext hostingContext, IConfigurationBuilder config) { ApplyDefaultAppConfiguration(hostingContext, config, args2); }).ConfigureServices((Action<HostBuilderContext, IServiceCollection>)AddDefaultServices) .UseServiceProviderFactory<IServiceCollection>((Func<HostBuilderContext, IServiceProviderFactory<IServiceCollection>>)((HostBuilderContext context) => (IServiceProviderFactory<IServiceCollection>)new DefaultServiceProviderFactory(CreateDefaultServiceProviderOptions(context)))); } private static void ApplyDefaultHostConfiguration(IConfigurationBuilder hostConfigBuilder, string[] args) { SetDefaultContentRoot(hostConfigBuilder); AddDefaultHostConfigurationSources(hostConfigBuilder, args); } internal static void SetDefaultContentRoot(IConfigurationBuilder hostConfigBuilder) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) string currentDirectory = Environment.CurrentDirectory; if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || !string.Equals(currentDirectory, Environment.GetFolderPath((SpecialFolder)37), (StringComparison)5)) { MemoryConfigurationBuilderExtensions.AddInMemoryCollection(hostConfigBuilder, (System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)new KeyValuePair<string, string>[1] { new KeyValuePair<string, string>(HostDefaults.ContentRootKey, currentDirectory) }); } } internal static void AddDefaultHostConfigurationSources(IConfigurationBuilder hostConfigBuilder, string[] args) { EnvironmentVariablesExtensions.AddEnvironmentVariables(hostConfigBuilder, "DOTNET_"); if (args != null && args.Length > 0) { CommandLineConfigurationExtensions.AddCommandLine(hostConfigBuilder, args); } } internal static void ApplyDefaultAppConfiguration(HostBuilderContext hostingContext, IConfigurationBuilder appConfigBuilder, string[] args) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown IHostEnvironment hostingEnvironment = hostingContext.HostingEnvironment; bool flag = GetReloadConfigOnChangeValue(hostingContext); JsonConfigurationExtensions.AddJsonFile(JsonConfigurationExtensions.AddJsonFile(appConfigBuilder, "appsettings.json", true, flag), "appsettings." + hostingEnvironment.EnvironmentName + ".json", true, flag); if (HostEnvironmentEnvExtensions.IsDevelopment(hostingEnvironment)) { string applicationName = hostingEnvironment.ApplicationName; if (applicationName != null && applicationName.Length > 0) { Assembly val = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName)); if (val != null) { UserSecretsConfigurationExtensions.AddUserSecrets(appConfigBuilder, val, true, flag); } } } EnvironmentVariablesExtensions.AddEnvironmentVariables(appConfigBuilder); if (args != null && args.Length > 0) { CommandLineConfigurationExtensions.AddCommandLine(appConfigBuilder, args); } [CompilerGenerated] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Calling IConfiguration.GetValue is safe when the T is bool.")] static bool GetReloadConfigOnChangeValue(HostBuilderContext hostingContext) { return ConfigurationBinder.GetValue<bool>(hostingContext.Configuration, "hostBuilder:reloadConfigOnChange", true); } } internal static void AddDefaultServices(HostBuilderContext hostingContext, IServiceCollection services) { LoggingServiceCollectionExtensions.AddLogging(services, (Action<ILoggingBuilder>)delegate(ILoggingBuilder logging) { bool flag = OperatingSystem.IsWindows(); if (flag) { FilterLoggingBuilderExtensions.AddFilter<EventLogLoggerProvider>(logging, (Func<LogLevel, bool>)((LogLevel level) => (int)level >= 3)); } LoggingBuilderExtensions.AddConfiguration(logging, (IConfiguration)(object)hostingContext.Configuration.GetSection("Logging")); if (!OperatingSystem.IsBrowser()) { ConsoleLoggerExtensions.AddConsole(logging); } DebugLoggerFactoryExtensions.AddDebug(logging); EventSourceLoggerFactoryExtensions.AddEventSourceLogger(logging); if (flag) { EventLoggerFactoryExtensions.AddEventLog(logging); } LoggingBuilderExtensions.Configure(logging, (Action<LoggerFactoryOptions>)delegate(LoggerFactoryOptions options) { options.ActivityTrackingOptions = (ActivityTrackingOptions)7; }); }); } internal static ServiceProviderOptions CreateDefaultServiceProviderOptions(HostBuilderContext context) { //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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown bool flag = HostEnvironmentEnvExtensions.IsDevelopment(context.HostingEnvironment); return new ServiceProviderOptions { ValidateScopes = flag, ValidateOnBuild = flag }; } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static IHostBuilder UseConsoleLifetime(this IHostBuilder hostBuilder) { return hostBuilder.ConfigureServices(delegate(IServiceCollection collection) { ServiceCollectionServiceExtensions.AddSingleton<IHostLifetime, ConsoleLifetime>(collection); }); } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static IHostBuilder UseConsoleLifetime(this IHostBuilder hostBuilder, Action<ConsoleLifetimeOptions> configureOptions) { Action<ConsoleLifetimeOptions> configureOptions2 = configureOptions; return hostBuilder.ConfigureServices(delegate(IServiceCollection collection) { ServiceCollectionServiceExtensions.AddSingleton<IHostLifetime, ConsoleLifetime>(collection); OptionsServiceCollectionExtensions.Configure<ConsoleLifetimeOptions>(collection, configureOptions2); }); } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static System.Threading.Tasks.Task RunConsoleAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default(CancellationToken)) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return HostingAbstractionsHostExtensions.RunAsync(hostBuilder.UseConsoleLifetime().Build(), cancellationToken); } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static System.Threading.Tasks.Task RunConsoleAsync(this IHostBuilder hostBuilder, Action<ConsoleLifetimeOptions> configureOptions, CancellationToken cancellationToken = default(CancellationToken)) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return HostingAbstractionsHostExtensions.RunAsync(hostBuilder.UseConsoleLifetime(configureOptions).Build(), cancellationToken); } } public class HostOptions { [field: CompilerGenerated] public TimeSpan ShutdownTimeout { [CompilerGenerated] get; [CompilerGenerated] set; } = TimeSpan.FromSeconds(30.0); [field: CompilerGenerated] public BackgroundServiceExceptionBehavior BackgroundServiceExceptionBehavior { [CompilerGenerated] get; [CompilerGenerated] set; } internal void Initialize(IConfiguration configuration) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) string text = configuration["shutdownTimeoutSeconds"]; int num = default(int); if (!string.IsNullOrEmpty(text) && int.TryParse(text, (NumberStyles)0, (IFormatProvider)(object)CultureInfo.InvariantCulture, ref num)) { ShutdownTimeout = TimeSpan.FromSeconds((double)num); } } } } namespace Microsoft.Extensions.Hosting.Internal { public class ApplicationLifetime : IApplicationLifetime, IHostApplicationLifetime { private readonly CancellationTokenSource _startedSource = new CancellationTokenSource(); private readonly CancellationTokenSource _stoppingSource = new CancellationTokenSource(); private readonly CancellationTokenSource _stoppedSource = new CancellationTokenSource(); private readonly ILogger<ApplicationLifetime> _logger; public CancellationToken ApplicationStarted => _startedSource.Token; public CancellationToken ApplicationStopping => _stoppingSource.Token; public CancellationToken ApplicationStopped => _stoppedSource.Token; public ApplicationLifetime(ILogger<ApplicationLifetime> logger) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown _logger = logger; } public void StopApplication() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) lock (_stoppingSource) { try { ExecuteHandlers(_stoppingSource); } catch (System.Exception exception) { ((ILogger)(object)_logger).ApplicationError(LoggerEventIds.ApplicationStoppingException, "An error occurred stopping the application", exception); } } } public void NotifyStarted() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) try { ExecuteHandlers(_startedSource); } catch (System.Exception exception) { ((ILogger)(object)_logger).ApplicationError(LoggerEventIds.ApplicationStartupException, "An error occurred starting the application", exception); } } public void NotifyStopped() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) try { ExecuteHandlers(_stoppedSource); } catch (System.Exception exception) { ((ILogger)(object)_logger).ApplicationError(LoggerEventIds.ApplicationStoppedException, "An error occurred stopping the application", exception); } } private static void ExecuteHandlers(CancellationTokenSource cancel) { if (!cancel.IsCancellationRequested) { cancel.Cancel(false); } } } internal sealed class ConfigureContainerAdapter<TContainerBuilder> : IConfigureContainerAdapter { private Action<HostBuilderContext, TContainerBuilder> _action; public ConfigureContainerAdapter(Action<HostBuilderContext, TContainerBuilder> action) { ThrowHelper.ThrowIfNull(action, "action"); _action = action; } public void ConfigureContainer(HostBuilderContext hostContext, object containerBuilder) { ((Action<HostBuilderContext, HostBuilderContext>)(object)_action).Invoke(hostContext, (HostBuilderContext)(TContainerBuilder)containerBuilder); } } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public class ConsoleLifetime : IHostLifetime, System.IDisposable { private CancellationTokenRegistration _applicationStartedRegistration; private CancellationTokenRegistration _applicationStoppingRegistration; private PosixSignalRegistration _sigIntRegistration; private PosixSignalRegistration _sigQuitRegistration; private PosixSignalRegistration _sigTermRegistration; [field: CompilerGenerated] private ConsoleLifetimeOptions Options { [CompilerGenerated] get; } [field: CompilerGenerated] private IHostEnvironment Environment { [CompilerGenerated] get; } [field: CompilerGenerated] private IHostApplicationLifetime ApplicationLifetime { [CompilerGenerated] get; } [field: CompilerGenerated] private HostOptions HostOptions { [CompilerGenerated] get; } [field: CompilerGenerated] private ILogger Logger { [CompilerGenerated] get; } public ConsoleLifetime(IOptions<ConsoleLifetimeOptions> options, IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, IOptions<HostOptions> hostOptions) : this(options, environment, applicationLifetime, hostOptions, (ILoggerFactory)(object)NullLoggerFactory.Instance) { } public ConsoleLifetime(IOptions<ConsoleLifetimeOptions> options, IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, IOptions<HostOptions> hostOptions, ILoggerFactory loggerFactory) { ThrowHelper.ThrowIfNull(options?.Value, "options"); ThrowHelper.ThrowIfNull(applicationLifetime, "applicationLifetime"); ThrowHelper.ThrowIfNull(environment, "environment"); ThrowHelper.ThrowIfNull(hostOptions?.Value, "hostOptions"); Options = options.Value; Environment = environment; ApplicationLifetime = applicationLifetime; HostOptions = hostOptions.Value; Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime"); } public System.Threading.Tasks.Task WaitForStartAsync(CancellationToken cancellationToken) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) if (!Options.SuppressStatusMessages) { CancellationToken val = ApplicationLifetime.ApplicationStarted; _applicationStartedRegistration = ((CancellationToken)(ref val)).Register((Action<object>)delegate(object state) { ((ConsoleLifetime)state).OnApplicationStarted(); }, (object)this); val = ApplicationLifetime.ApplicationStopping; _applicationStoppingRegistration = ((CancellationToken)(ref val)).Register((Action<object>)delegate(object state) { ((ConsoleLifetime)state).OnApplicationStopping(); }, (object)this); } RegisterShutdownHandlers(); return System.Threading.Tasks.Task.CompletedTask; } private void RegisterShutdownHandlers() { Action<PosixSignalContext> val = HandlePosixSignal; _sigIntRegistration = PosixSignalRegistration.Create((PosixSignal)(-2), val); _sigQuitRegistration = PosixSignalRegistration.Create((PosixSignal)(-3), val); _sigTermRegistration = PosixSignalRegistration.Create((PosixSignal)(-4), val); } private void OnApplicationStarted() { LoggerExtensions.LogInformation(Logger, "Application started. Press Ctrl+C to shut down.", System.Array.Empty<object>()); LoggerExtensions.LogInformation(Logger, "Hosting environment: {EnvName}", new object[1] { Environment.EnvironmentName }); LoggerExtensions.LogInformation(Logger, "Content root path: {ContentRoot}", new object[1] { Environment.ContentRootPath }); } private void OnApplicationStopping() { LoggerExtensions.LogInformation(Logger, "Application is shutting down...", System.Array.Empty<object>()); } public System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken) { return System.Threading.Tasks.Task.CompletedTask; } public void Dispose() { UnregisterShutdownHandlers(); ((CancellationTokenRegistration)(ref _applicationStartedRegistration)).Dispose(); ((CancellationTokenRegistration)(ref _applicationStoppingRegistration)).Dispose(); } private void UnregisterShutdownHandlers() { PosixSignalRegistration sigIntRegistration = _sigIntRegistration; if (sigIntRegistration != null) { sigIntRegistration.Dispose(); } PosixSignalRegistration sigQuitRegistration = _sigQuitRegistration; if (sigQuitRegistration != null) { sigQuitRegistration.Dispose(); } PosixSignalRegistration sigTermRegistration = _sigTermRegistration; if (sigTermRegistration != null) { sigTermRegistration.Dispose(); } } private void HandlePosixSignal(PosixSignalContext context) { context.Cancel = true; ApplicationLifetime.StopApplication(); } } internal sealed class Host : IHost, System.IDisposable, System.IAsyncDisposable { [StructLayout(3)] [CompilerGenerated] private struct <<DisposeAsync>g__DisposeAsync|16_0>d : IAsyncStateMachine { public int <>1__state; public AsyncValueTaskMethodBuilder <>t__builder; public object o; private ConfiguredValueTaskAwaiter <>u__1; private void MoveNext() { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007a: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; try { ConfiguredValueTaskAwaiter awaiter; if (num == 0) { awaiter = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_0089; } if (o is System.IAsyncDisposable asyncDisposable) { ConfiguredValueTaskAwaitable val = asyncDisposable.DisposeAsync().ConfigureAwait(false); awaiter = ((ConfiguredValueTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredValueTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredValueTaskAwaiter, <<DisposeAsync>g__DisposeAsync|16_0>d>(ref awaiter, ref this); return; } goto IL_0089; } if (o is System.IDisposable disposable) { disposable.Dispose(); } goto end_IL_0007; IL_0089: ((ConfiguredValueTaskAwaiter)(ref awaiter)).GetResult(); end_IL_0007:; } catch (System.Exception exception) { <>1__state = -2; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } [StructLayout(3)] [CompilerGenerated] private struct <DisposeAsync>d__16 : IAsyncStateMachine { public int <>1__state; public AsyncValueTaskMethodBuilder <>t__builder; public Host <>4__this; private ConfiguredValueTaskAwaiter <>u__1; private void MoveNext() { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017d: 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_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; Host host = <>4__this; try { ConfiguredValueTaskAwaitable val; ConfiguredValueTaskAwaiter awaiter4; ConfiguredValueTaskAwaiter awaiter3; ConfiguredValueTaskAwaiter awaiter2; ConfiguredValueTaskAwaiter awaiter; switch (num) { default: if (host._hostEnvironment.ContentRootFileProvider == host._defaultProvider) { val = <DisposeAsync>g__DisposeAsync|16_0(host._hostEnvironment.ContentRootFileProvider).ConfigureAwait(false); awaiter4 = ((ConfiguredValueTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredValueTaskAwaiter)(ref awaiter4)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter4; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredValueTaskAwaiter, <DisposeAsync>d__16>(ref awaiter4, ref this); return; } goto IL_00a2; } val = <DisposeAsync>g__DisposeAsync|16_0(host._hostEnvironment.ContentRootFileProvider).ConfigureAwait(false); awaiter3 = ((ConfiguredValueTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredValueTaskAwaiter)(ref awaiter3)).IsCompleted) { num = (<>1__state = 1); <>u__1 = awaiter3; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredValueTaskAwaiter, <DisposeAsync>d__16>(ref awaiter3, ref this); return; } goto IL_011c; case 0: awaiter4 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_00a2; case 1: awaiter3 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_011c; case 2: awaiter2 = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaiter); num = (<>1__state = -1); goto IL_018c; case 3: { awaiter = <>u__1; <>u__1 = default(ConfiguredValueTaskAwaiter); num = (<>1__state = -1); break; } IL_018c: ((ConfiguredValueTaskAwaiter)(ref awaiter2)).GetResult(); goto IL_0193; IL_0193: val = <DisposeAsync>g__DisposeAsync|16_0(host.Services).ConfigureAwait(false); awaiter = ((ConfiguredValueTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredValueTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 3); <>u__1 = awaiter; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredValueTaskAwaiter, <DisposeAsync>d__16>(ref awaiter, ref this); return; } break; IL_00a2: ((ConfiguredValueTaskAwaiter)(ref awaiter4)).GetResult(); goto IL_0193; IL_011c: ((ConfiguredValueTaskAwaiter)(ref awaiter3)).GetResult(); val = <DisposeAsync>g__DisposeAsync|16_0(host._defaultProvider).ConfigureAwait(false); awaiter2 = ((ConfiguredValueTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredValueTaskAwaiter)(ref awaiter2)).IsCompleted) { num = (<>1__state = 2); <>u__1 = awaiter2; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredValueTaskAwaiter, <DisposeAsync>d__16>(ref awaiter2, ref this); return; } goto IL_018c; } ((ConfiguredValueTaskAwaiter)(ref awaiter)).GetResult(); } catch (System.Exception exception) { <>1__state = -2; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncValueTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } [StructLayout(3)] [CompilerGenerated] private struct <StartAsync>d__12 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public Host <>4__this; public CancellationToken cancellationToken; private CancellationTokenSource <combinedCancellationTokenSource>5__2; private CancellationToken <combinedCancellationToken>5__3; private ConfiguredTaskAwaiter <>u__1; private System.Collections.Generic.IEnumerator<IHostedService> <>7__wrap3; private IHostedService <hostedService>5__5; private void MoveNext() { //IL_0217: 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) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005c: 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) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0089: 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_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0168: 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_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0126: 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_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; Host host = <>4__this; try { if ((uint)num > 1u) { ((ILogger)(object)host._logger).Starting(); <combinedCancellationTokenSource>5__2 = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, host._applicationLifetime.ApplicationStopping); } try { ConfiguredTaskAwaitable val; ConfiguredTaskAwaiter awaiter; if (num != 0) { if (num == 1) { goto IL_00f2; } <combinedCancellationToken>5__3 = <combinedCancellationTokenSource>5__2.Token; val = host._hostLifetime.WaitForStartAsync(<combinedCancellationToken>5__3).ConfigureAwait(false); awaiter = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <StartAsync>d__12>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); } ((ConfiguredTaskAwaiter)(ref awaiter)).GetResult(); ((CancellationToken)(ref <combinedCancellationToken>5__3)).ThrowIfCancellationRequested(); host._hostedServices = ServiceProviderServiceExtensions.GetRequiredService<System.Collections.Generic.IEnumerable<IHostedService>>(host.Services); <>7__wrap3 = host._hostedServices.GetEnumerator(); goto IL_00f2; IL_00f2: try { if (num != 1) { goto IL_019f; } ConfiguredTaskAwaiter awaiter2 = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); goto IL_0177; IL_019f: if (((System.Collections.IEnumerator)<>7__wrap3).MoveNext()) { <hostedService>5__5 = <>7__wrap3.Current; val = <hostedService>5__5.StartAsync(<combinedCancellationToken>5__3).ConfigureAwait(false); awaiter2 = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter2)).IsCompleted) { num = (<>1__state = 1); <>u__1 = awaiter2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <StartAsync>d__12>(ref awaiter2, ref this); return; } goto IL_0177; } goto end_IL_00f2; IL_0177: ((ConfiguredTaskAwaiter)(ref awaiter2)).GetResult(); IHostedService obj = <hostedService>5__5; BackgroundService val2 = (BackgroundService)(object)((obj is BackgroundService) ? obj : null); if (val2 != null) { host.TryExecuteBackgroundServiceAsync(val2); } <hostedService>5__5 = null; goto IL_019f; end_IL_00f2:; } finally { if (num < 0 && <>7__wrap3 != null) { ((System.IDisposable)<>7__wrap3).Dispose(); } } <>7__wrap3 = null; host._applicationLifetime.NotifyStarted(); ((ILogger)(object)host._logger).Started(); } finally { if (num < 0 && <combinedCancellationTokenSource>5__2 != null) { ((System.IDisposable)<combinedCancellationTokenSource>5__2).Dispose(); } } } catch (System.Exception exception) { <>1__state = -2; <combinedCancellationTokenSource>5__2 = null; <combinedCancellationToken>5__3 = default(CancellationToken); ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; <combinedCancellationTokenSource>5__2 = null; <combinedCancellationToken>5__3 = default(CancellationToken); ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } [StructLayout(3)] [CompilerGenerated] private struct <StopAsync>d__14 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public Host <>4__this; public CancellationToken cancellationToken; private CancellationTokenSource <cts>5__2; private CancellationTokenSource <linkedCts>5__3; private CancellationToken <token>5__4; private System.Collections.Generic.IList<System.Exception> <exceptions>5__5; private System.Collections.Generic.IEnumerator<IHostedService> <>7__wrap5; private ConfiguredTaskAwaiter <>u__1; private void MoveNext() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Expected O, but got Unknown //IL_0048: 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_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_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_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_019a: 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_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; Host host = <>4__this; try { if ((uint)num > 1u) { host._stopCalled = true; ((ILogger)(object)host._logger).Stopping(); <cts>5__2 = new CancellationTokenSource(host._options.ShutdownTimeout); } try { if ((uint)num > 1u) { <linkedCts>5__3 = CancellationTokenSource.CreateLinkedTokenSource(<cts>5__2.Token, cancellationToken); } try { if (num != 0) { if (num == 1) { goto IL_0184; } <token>5__4 = <linkedCts>5__3.Token; host._applicationLifetime.StopApplication(); <exceptions>5__5 = (System.Collections.Generic.IList<System.Exception>)new List<System.Exception>(); if (host._hostedServices == null) { goto IL_0178; } <>7__wrap5 = Enumerable.Reverse<IHostedService>(host._hostedServices).GetEnumerator(); } ConfiguredTaskAwaitable val; try { if (num == 0) { goto IL_00c6; } goto IL_0147; IL_00c6: IHostedService current = default(IHostedService); try { ConfiguredTaskAwaiter awaiter; if (num != 0) { val = current.StopAsync(<token>5__4).ConfigureAwait(false); awaiter = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <StopAsync>d__14>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); } ((ConfiguredTaskAwaiter)(ref awaiter)).GetResult(); } catch (System.Exception ex) { ((System.Collections.Generic.ICollection<System.Exception>)<exceptions>5__5).Add(ex); } goto IL_0147; IL_0147: if (((System.Collections.IEnumerator)<>7__wrap5).MoveNext()) { current = <>7__wrap5.Current; goto IL_00c6; } } finally { if (num < 0 && <>7__wrap5 != null) { ((System.IDisposable)<>7__wrap5).Dispose(); } } <>7__wrap5 = null; goto IL_0178; IL_0178: host._applicationLifetime.NotifyStopped(); goto IL_0184; IL_0184: try { ConfiguredTaskAwaiter awaiter2; if (num != 1) { val = host._hostLifetime.StopAsync(<token>5__4).ConfigureAwait(false); awaiter2 = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter2)).IsCompleted) { num = (<>1__state = 1); <>u__1 = awaiter2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <StopAsync>d__14>(ref awaiter2, ref this); return; } } else { awaiter2 = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); } ((ConfiguredTaskAwaiter)(ref awaiter2)).GetResult(); } catch (System.Exception ex2) { ((System.Collections.Generic.ICollection<System.Exception>)<exceptions>5__5).Add(ex2); } if (((System.Collections.Generic.ICollection<System.Exception>)<exceptions>5__5).Count > 0) { AggregateException val2 = new AggregateException("One or more hosted services failed to stop.", (System.Collections.Generic.IEnumerable<System.Exception>)<exceptions>5__5); ((ILogger)(object)host._logger).StoppedWithException((System.Exception)(object)val2); throw val2; } <token>5__4 = default(CancellationToken); <exceptions>5__5 = null; } finally { if (num < 0 && <linkedCts>5__3 != null) { ((System.IDisposable)<linkedCts>5__3).Dispose(); } } <linkedCts>5__3 = null; } finally { if (num < 0 && <cts>5__2 != null) { ((System.IDisposable)<cts>5__2).Dispose(); } } <cts>5__2 = null; ((ILogger)(object)host._logger).Stopped(); } catch (System.Exception exception) { <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } [StructLayout(3)] [CompilerGenerated] private struct <TryExecuteBackgroundServiceAsync>d__13 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder <>t__builder; public BackgroundService backgroundService; public Host <>4__this; private System.Threading.Tasks.Task <backgroundTask>5__2; private ConfiguredTaskAwaiter <>u__1; private void MoveNext() { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) int num = <>1__state; Host host = <>4__this; try { if (num == 0) { goto IL_0030; } <backgroundTask>5__2 = backgroundService.ExecuteTask; if (<backgroundTask>5__2 != null) { goto IL_0030; } goto end_IL_000e; IL_0030: try { ConfiguredTaskAwaiter awaiter; if (num != 0) { ConfiguredTaskAwaitable val = <backgroundTask>5__2.ConfigureAwait(false); awaiter = ((ConfiguredTaskAwaitable)(ref val)).GetAwaiter(); if (!((ConfiguredTaskAwaiter)(ref awaiter)).IsCompleted) { num = (<>1__state = 0); <>u__1 = awaiter; ((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<ConfiguredTaskAwaiter, <TryExecuteBackgroundServiceAsync>d__13>(ref awaiter, ref this); return; } } else { awaiter = <>u__1; <>u__1 = default(ConfiguredTaskAwaiter); num = (<>1__state = -1); } ((ConfiguredTaskAwaiter)(ref awaiter)).GetResult(); } catch (System.Exception ex) { if (!host._stopCalled || !<backgroundTask>5__2.IsCanceled || !(ex is OperationCanceledException)) { ((ILogger)(object)host._logger).BackgroundServiceFaulted(ex); if (host._options.BackgroundServiceExceptionBehavior == BackgroundServiceExceptionBehavior.StopHost) { ((ILogger)(object)host._logger).BackgroundServiceStoppingHost(ex); host._applicationLifetime.StopApplication(); } } } end_IL_000e:; } catch (System.Exception exception) { <>1__state = -2; <backgroundTask>5__2 = null; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception); return; } <>1__state = -2; <backgroundTask>5__2 = null; ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { ((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine); } } private readonly ILogger<Host> _logger; private readonly IHostLifetime _hostLifetime; private readonly ApplicationLifetime _applicationLifetime; private readonly HostOptions _options; private readonly IHostEnvironment _hostEnvironment; private readonly PhysicalFileProvider _defaultProvider; private System.Collections.Generic.IEnumerable<IHostedService> _hostedServices; private volatile bool _stopCalled; [field: CompilerGenerated] public IServiceProvider Services { [CompilerGenerated] get; } public Host(IServiceProvider services, IHostEnvironment hostEnvironment, PhysicalFileProvider defaultProvider, IHostApplicationLifetime applicationLifetime, ILogger<Host> logger, IHostLifetime hostLifetime, IOptions<HostOptions> options) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(applicationLifetime, "applicationLifetime"); ThrowHelper.ThrowIfNull(logger, "logger"); ThrowHelper.ThrowIfNull(hostLifetime, "hostLifetime"); Services = services; _applicationLifetime = applicationLifetime as ApplicationLifetime; _hostEnvironment = hostEnvironment; _defaultProvider = defaultProvider; if (_applicationLifetime == null) { throw new ArgumentException(System.SR.IHostApplicationLifetimeReplacementNotSupported, "applicationLifetime"); } _logger = logger; _hostLifetime = hostLifetime; _options = options?.Value ?? throw new ArgumentNullException("options"); } [AsyncStateMachine(typeof(<StartAsync>d__12))] public System.Threading.Tasks.Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) { //IL_0002: 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_0016: 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) <StartAsync>d__12 <StartAsync>d__ = default(<StartAsync>d__12); <StartAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <StartAsync>d__.<>4__this = this; <StartAsync>d__.cancellationToken = cancellationToken; <StartAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <StartAsync>d__.<>t__builder)).Start<<StartAsync>d__12>(ref <StartAsync>d__); return ((AsyncTaskMethodBuilder)(ref <StartAsync>d__.<>t__builder)).Task; } [AsyncStateMachine(typeof(<TryExecuteBackgroundServiceAsync>d__13))] private System.Threading.Tasks.Task TryExecuteBackgroundServiceAsync(BackgroundService backgroundService) { //IL_0002: 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) <TryExecuteBackgroundServiceAsync>d__13 <TryExecuteBackgroundServiceAsync>d__ = default(<TryExecuteBackgroundServiceAsync>d__13); <TryExecuteBackgroundServiceAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <TryExecuteBackgroundServiceAsync>d__.<>4__this = this; <TryExecuteBackgroundServiceAsync>d__.backgroundService = backgroundService; <TryExecuteBackgroundServiceAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <TryExecuteBackgroundServiceAsync>d__.<>t__builder)).Start<<TryExecuteBackgroundServiceAsync>d__13>(ref <TryExecuteBackgroundServiceAsync>d__); return ((AsyncTaskMethodBuilder)(ref <TryExecuteBackgroundServiceAsync>d__.<>t__builder)).Task; } [AsyncStateMachine(typeof(<StopAsync>d__14))] public System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken = default(CancellationToken)) { //IL_0002: 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_0016: 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) <StopAsync>d__14 <StopAsync>d__ = default(<StopAsync>d__14); <StopAsync>d__.<>t__builder = AsyncTaskMethodBuilder.Create(); <StopAsync>d__.<>4__this = this; <StopAsync>d__.cancellationToken = cancellationToken; <StopAsync>d__.<>1__state = -1; ((AsyncTaskMethodBuilder)(ref <StopAsync>d__.<>t__builder)).Start<<StopAsync>d__14>(ref <StopAsync>d__); return ((AsyncTaskMethodBuilder)(ref <StopAsync>d__.<>t__builder)).Task; } public void Dispose() { //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
AuriePack/AurieInstaller/Microsoft.Extensions.Logging.Abstractions.dll
Decompiled a year 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.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [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("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(8, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Logging.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Logging.Abstractions.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string UnexpectedNumberOfNamedParameters => GetResourceString("UnexpectedNumberOfNamedParameters"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace System.Text { [Obsolete("Types with embedded references are not supported in this version of your compiler.", true)] [CompilerFeatureRequired("RefStructs")] [DefaultMember("Item")] internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private System.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 System.Span<char> RawChars => _chars; public ValueStringBuilder(System.Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = System.Span<char>.op_Implicit(_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<char>(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference<char>(_chars); } public string ToString() { string result = ((object)_chars.Slice(0, _pos)).ToString(); Dispose(); return result; } public System.ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return System.Span<char>.op_Implicit(_chars.Slice(0, _pos)); } public System.ReadOnlySpan<char> AsSpan() { return System.Span<char>.op_Implicit(_chars.Slice(0, _pos)); } public System.ReadOnlySpan<char> AsSpan(int start) { return System.Span<char>.op_Implicit(_chars.Slice(start, _pos - start)); } public System.ReadOnlySpan<char> AsSpan(int start, int length) { return System.Span<char>.op_Implicit(_chars.Slice(start, length)); } public bool TryCopyTo(System.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 num = _pos - index; _chars.Slice(index, num).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 num = _pos - index; _chars.Slice(index, num).CopyTo(_chars.Slice(index + length)); s.CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(256)] public void Append(char c) { int pos = _pos; if ((uint)pos < (uint)_chars.Length) { _chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(256)] 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.CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } System.Span<char> span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } System.Span<char> span = _chars.Slice(_pos, length); for (int i = 0; i < span.Length; i++) { span[i] = *(value++); } _pos += length; } public void Append(System.ReadOnlySpan<char> value) { int pos = _pos; if (pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(256)] public System.Span<char> AppendSpan(int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } _pos = pos + length; return _chars.Slice(pos, length); } [MethodImpl(8)] private void GrowAndAppend(char c) { Grow(1); Append(c); } [MethodImpl(8)] private void Grow(int additionalCapacityBeyondPos) { int num = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u)); char[] array = ArrayPool<char>.Shared.Rent(num); _chars.Slice(0, _pos).CopyTo(System.Span<char>.op_Implicit(array)); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = System.Span<char>.op_Implicit(_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool, false); } } [MethodImpl(256)] public void Dispose() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(ValueStringBuilder); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool, false); } } } } namespace Microsoft.Extensions.Internal { internal static class TypeNameHelper { private readonly struct DisplayNameOptions { [field: CompilerGenerated] public bool FullName { [CompilerGenerated] get; } [field: CompilerGenerated] public bool IncludeGenericParameters { [CompilerGenerated] get; } [field: CompilerGenerated] public bool IncludeGenericParameterNames { [CompilerGenerated] get; } [field: CompilerGenerated] public char NestedTypeDelimiter { [CompilerGenerated] 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<System.Type, string> _builtInTypeNames; [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(System.Type type, bool fullName = true, bool includeGenericParameterNames = false, bool includeGenericParameters = true, char nestedTypeDelimiter = '+') { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown StringBuilder val = new StringBuilder(); DisplayNameOptions options = new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter); ProcessType(val, type, in options); return ((object)val).ToString(); } private static void ProcessType(StringBuilder builder, System.Type type, in DisplayNameOptions options) { if (type.IsGenericType) { System.Type[] genericArguments = type.GetGenericArguments(); ProcessGenericType(builder, type, genericArguments, genericArguments.Length, in options); return; } if (type.IsArray) { ProcessArrayType(builder, type, in options); return; } string text = default(string); if (_builtInTypeNames.TryGetValue(type, ref text)) { builder.Append(text); return; } if (type.IsGenericParameter) { if (options.IncludeGenericParameterNames) { builder.Append(((MemberInfo)type).Name); } return; } string text2 = (options.FullName ? type.FullName : ((MemberInfo)type).Name); builder.Append(text2); if (options.NestedTypeDelimiter != '+') { builder.Replace('+', options.NestedTypeDelimiter, builder.Length - text2.Length, text2.Length); } } private static void ProcessArrayType(StringBuilder builder, System.Type type, in DisplayNameOptions options) { System.Type type2 = type; while (type2.IsArray) { type2 = type2.GetElementType(); } ProcessType(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, System.Type type, System.Type[] genericArguments, int length, in DisplayNameOptions options) { int num = 0; if (type.IsNested) { num = ((MemberInfo)type).DeclaringType.GetGenericArguments().Length; } if (options.FullName) { if (type.IsNested) { ProcessGenericType(builder, ((MemberInfo)type).DeclaringType, genericArguments, num, in options); builder.Append(options.NestedTypeDelimiter); } else if (!string.IsNullOrEmpty(type.Namespace)) { builder.Append(type.Namespace); builder.Append('.'); } } int num2 = ((MemberInfo)type).Name.IndexOf('`'); if (num2 <= 0) { builder.Append(((MemberInfo)type).Name); return; } builder.Append(((MemberInfo)type).Name, 0, num2); if (!options.IncludeGenericParameters) { return; } builder.Append('<'); for (int i = num; i < length; i++) { ProcessType(builder, genericArguments[i], in options); if (i + 1 != length) { builder.Append(','); if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter) { builder.Append(' '); } } } builder.Append('>'); } static TypeNameHelper() { Dictionary<System.Type, string> val = new Dictionary<System.Type, string>(); val.Add(typeof(void), "void"); val.Add(typeof(bool), "bool"); val.Add(typeof(byte), "byte"); val.Add(typeof(char), "char"); val.Add(typeof(decimal), "decimal"); val.Add(typeof(double), "double"); val.Add(typeof(float), "float"); val.Add(typeof(int), "int"); val.Add(typeof(long), "long"); val.Add(typeof(object), "object"); val.Add(typeof(sbyte), "sbyte"); val.Add(typeof(short), "short"); val.Add(typeof(string), "string"); val.Add(typeof(uint), "uint"); val.Add(typeof(ulong), "ulong"); val.Add(typeof(ushort), "ushort"); _builtInTypeNames = val; } } } namespace Microsoft.Extensions.Logging { public readonly struct EventId : IEquatable<EventId> { [field: CompilerGenerated] public int Id { [CompilerGenerated] get; } [field: CompilerGenerated] public string? Name { [CompilerGenerated] 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; } } [DefaultMember("Item")] internal readonly struct FormattedLogValues : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object?>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object?>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object?>> { [CompilerGenerated] private sealed class <GetEnumerator>d__14 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public FormattedLogValues <>4__this; private int <i>5__2; KeyValuePair<string, object> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__14(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) 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 System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } internal const int MaxCachedFormatters = 1024; private const string NullFormat = "[null]"; private static int _count; private static ConcurrentDictionary<string, LogValuesFormatter> _formatters = new ConcurrentDictionary<string, LogValuesFormatter>(); private readonly LogValuesFormatter _formatter; private readonly object[] _values; private readonly string _originalMessage; internal LogValuesFormatter? Formatter => _formatter; public KeyValuePair<string, object?> this[int index] { get { //IL_0012: 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_002e: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= Count) { throw new IndexOutOfRangeException("index"); } if (index == Count - 1) { return new KeyValuePair<string, object>("{OriginalFormat}", (object)_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 (_count >= 1024) { if (!_formatters.TryGetValue(format, ref _formatter)) { _formatter = new LogValuesFormatter(format); } } else { _formatter = _formatters.GetOrAdd(format, (Func<string, LogValuesFormatter>)delegate(string f) { Interlocked.Increment(ref _count); return new LogValuesFormatter(f); }); } } else { _formatter = null; } _originalMessage = format ?? "[null]"; _values = values; } [IteratorStateMachine(typeof(<GetEnumerator>d__14))] public System.Collections.Generic.IEnumerator<KeyValuePair<string, object?>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public string ToString() { if (_formatter == null) { return _originalMessage; } return _formatter.Format(_values); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } public interface IExternalScopeProvider { void ForEachScope<TState>(Action<object?, TState> callback, TState state); System.IDisposable Push(object? state); } public interface ILogger { void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception? exception, Func<TState, System.Exception?, string> formatter); bool IsEnabled(LogLevel logLevel); System.IDisposable? BeginScope<TState>(TState state) where TState : notnull; } public interface ILoggerFactory : System.IDisposable { ILogger CreateLogger(string categoryName); void AddProvider(ILoggerProvider provider); } public interface ILoggerProvider : System.IDisposable { ILogger CreateLogger(string categoryName); } public interface ILogger<out TCategoryName> : ILogger { } public interface ISupportExternalScope { void SetScopeProvider(IExternalScopeProvider scopeProvider); } public class LogDefineOptions { [field: CompilerGenerated] public bool SkipEnabledCheck { [CompilerGenerated] get; [CompilerGenerated] set; } } public static class LoggerExtensions { private static readonly Func<FormattedLogValues, System.Exception, string> _messageFormatter = MessageFormatter; public static void LogDebug(this ILogger logger, EventId eventId, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.Exception? exception, string? message, params object?[] args) { ThrowHelper.ThrowIfNull(logger, "logger"); logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); } public static System.IDisposable? BeginScope(this ILogger logger, string messageFormat, params object?[] args) { ThrowHelper.ThrowIfNull(logger, "logger"); return logger.BeginScope(new FormattedLogValues(messageFormat, args)); } private static string MessageFormatter(FormattedLogValues state, System.Exception error) { return ((object)state).ToString(); } } public class LoggerExternalScopeProvider : IExternalScopeProvider { private sealed class Scope : System.IDisposable { private readonly LoggerExternalScopeProvider _provider; private bool _isDisposed; [field: CompilerGenerated] public Scope Parent { [CompilerGenerated] get; } [field: CompilerGenerated] public object State { [CompilerGenerated] get; } internal Scope(LoggerExternalScopeProvider provider, object state, Scope parent) { _provider = provider; State = state; Parent = parent; } public 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); [CompilerGenerated] void Report(Scope? current) { if (current != null) { Report(current.Parent); callback2.Invoke(current.State, state2); } } } public System.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) { ThrowHelper.ThrowIfNull(factory, "factory"); return new Logger<T>(factory); } public static ILogger CreateLogger(this ILoggerFactory factory, System.Type type) { ThrowHelper.ThrowIfNull(factory, "factory"); ThrowHelper.ThrowIfNull(type, "type"); return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.')); } } public static class LoggerMessage { [DefaultMember("Item")] private readonly struct LogValues : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> { [CompilerGenerated] private sealed class <GetEnumerator>d__7 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues <>4__this; KeyValuePair<string, object> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__7(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //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) 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 System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } public static readonly Func<LogValues, System.Exception, string> Callback = (LogValues state, System.Exception exception) => ((object)state).ToString(); private readonly LogValuesFormatter _formatter; public KeyValuePair<string, object> this[int index] { get { //IL_001e: 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) if (index == 0) { return new KeyValuePair<string, object>("{OriginalFormat}", (object)_formatter.OriginalFormat); } throw new IndexOutOfRangeException("index"); } } public int Count => 1; public LogValues(LogValuesFormatter formatter) { _formatter = formatter; } [IteratorStateMachine(typeof(<GetEnumerator>d__7))] public System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { yield return this[0]; } public string ToString() { return _formatter.Format(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } [DefaultMember("Item")] private readonly struct LogValues<T0> : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> { [CompilerGenerated] private sealed class <GetEnumerator>d__8 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public LogValues<T0> <>4__this; private int <i>5__2; KeyValuePair<string, object> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__8(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) 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 System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } public static readonly Func<LogValues<T0>, System.Exception, string> Callback = (Func<LogValues<T0>, System.Exception, string>)(object)(Func<LogValues<LogValues<T0>>, System.Exception, string>)((LogValues<T0> state, System.Exception exception) => ((object)state).ToString()); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; public KeyValuePair<string, object> this[int index] => (KeyValuePair<string, object>)(index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], (object)_value0), 1 => new KeyValuePair<string, object>("{OriginalFormat}", (object)_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 System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public string ToString() { return _formatter.Format(_value0); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } [DefaultMember("Item")] private readonly struct LogValues<T0, T1> : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> { [CompilerGenerated] private sealed class <GetEnumerator>d__9 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.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> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__9(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) 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 System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } public static readonly Func<LogValues<T0, T1>, System.Exception, string> Callback = (Func<LogValues<T0, T1>, System.Exception, string>)(object)(Func<LogValues<LogValues<T0, T1>, System.Exception>, System.Exception, string>)((LogValues<T0, T1> state, System.Exception exception) => ((object)state).ToString()); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; public KeyValuePair<string, object> this[int index] => (KeyValuePair<string, object>)(index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], (object)_value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], (object)_value1), 2 => new KeyValuePair<string, object>("{OriginalFormat}", (object)_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 System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public string ToString() { return _formatter.Format(_value0, _value1); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } [DefaultMember("Item")] private readonly struct LogValues<T0, T1, T2> : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> { [CompilerGenerated] private sealed class <GetEnumerator>d__11 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.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> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__11(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) 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 System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } public static readonly Func<LogValues<T0, T1, T2>, System.Exception, string> Callback = (Func<LogValues<T0, T1, T2>, System.Exception, string>)(object)(Func<LogValues<LogValues<T0, T1, T2>, System.Exception, string>, System.Exception, string>)((LogValues<T0, T1, T2> state, System.Exception exception) => ((object)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] => (KeyValuePair<string, object>)(index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], (object)_value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], (object)_value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], (object)_value2), 3 => new KeyValuePair<string, object>("{OriginalFormat}", (object)_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 string ToString() { return _formatter.Format(_value0, _value1, _value2); } [IteratorStateMachine(typeof(LogValues<, , >.<GetEnumerator>d__11))] public System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } [DefaultMember("Item")] private readonly struct LogValues<T0, T1, T2, T3> : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> { [CompilerGenerated] private sealed class <GetEnumerator>d__13 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.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> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__13(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) 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 System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } public static readonly Func<LogValues<T0, T1, T2, T3>, System.Exception, string> Callback = (Func<LogValues<T0, T1, T2, T3>, System.Exception, string>)(object)(Func<LogValues<LogValues<T0, T1, T2, T3>, System.Exception, string, ?>, System.Exception, string>)((LogValues<T0, T1, T2, T3> state, System.Exception exception) => ((object)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] => (KeyValuePair<string, object>)(index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], (object)_value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], (object)_value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], (object)_value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], (object)_value3), 4 => new KeyValuePair<string, object>("{OriginalFormat}", (object)_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 string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } [IteratorStateMachine(typeof(LogValues<, , , >.<GetEnumerator>d__13))] public System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } [DefaultMember("Item")] private readonly struct LogValues<T0, T1, T2, T3, T4> : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> { [CompilerGenerated] private sealed class <GetEnumerator>d__14 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.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> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__14(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) 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 System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } public static readonly Func<LogValues<T0, T1, T2, T3, T4>, System.Exception, string> Callback = (Func<LogValues<T0, T1, T2, T3, T4>, System.Exception, string>)(object)(Func<LogValues<LogValues<T0, T1, T2, T3, T4>, System.Exception, string, ?, ?>, System.Exception, string>)((LogValues<T0, T1, T2, T3, T4> state, System.Exception exception) => ((object)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] => (KeyValuePair<string, object>)(index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], (object)_value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], (object)_value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], (object)_value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], (object)_value3), 4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], (object)_value4), 5 => new KeyValuePair<string, object>("{OriginalFormat}", (object)_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 string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } [IteratorStateMachine(typeof(LogValues<, , , , >.<GetEnumerator>d__14))] public System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } [DefaultMember("Item")] private readonly struct LogValues<T0, T1, T2, T3, T4, T5> : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> { [CompilerGenerated] private sealed class <GetEnumerator>d__15 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.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> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__15(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) 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 System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } public static readonly Func<LogValues<T0, T1, T2, T3, T4, T5>, System.Exception, string> Callback = (Func<LogValues<T0, T1, T2, T3, T4, T5>, System.Exception, string>)(object)(Func<LogValues<LogValues<T0, T1, T2, T3, T4, T5>, System.Exception, string, ?, ?, ?>, System.Exception, string>)((LogValues<T0, T1, T2, T3, T4, T5> state, System.Exception exception) => ((object)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] => (KeyValuePair<string, object>)(index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], (object)_value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], (object)_value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], (object)_value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], (object)_value3), 4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], (object)_value4), 5 => new KeyValuePair<string, object>(_formatter.ValueNames[5], (object)_value5), 6 => new KeyValuePair<string, object>("{OriginalFormat}", (object)_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 string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } [IteratorStateMachine(typeof(LogValues<, , , , , >.<GetEnumerator>d__15))] public System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } public static Func<ILogger, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.Exception?> Define(LogLevel logLevel, EventId eventId, string formatString) { return Define(logLevel, eventId, formatString, null); } public static Action<ILogger, System.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, System.Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, exception); } }; void Log(ILogger logger, System.Exception exception) { logger.Log(logLevel, eventId, new LogValues(formatter), exception, LogValues.Callback); } } public static Action<ILogger, T1, System.Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, System.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, System.Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, exception); } }; void Log(ILogger logger, T1 arg1, System.Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1>(formatter, arg1), exception, LogValues<T1>.Callback); } } public static Action<ILogger, T1, T2, System.Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, System.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, System.Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, System.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, System.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, System.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, System.Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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, System.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) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) LogValuesFormatter logValuesFormatter = new LogValuesFormatter(formatString); int count = logValuesFormatter.ValueNames.Count; if (count != expectedNamedParameterCount) { throw new ArgumentException(System.SR.Format(System.SR.UnexpectedNumberOfNamedParameters, (object?)formatString, (object?)expectedNamedParameterCount, (object?)count)); } return logValuesFormatter; } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public sealed class LoggerMessageAttribute : System.Attribute { [field: CompilerGenerated] public int EventId { [CompilerGenerated] get; [CompilerGenerated] set; } = -1; [field: CompilerGenerated] public string? EventName { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public LogLevel Level { [CompilerGenerated] get; [CompilerGenerated] set; } = LogLevel.None; [field: CompilerGenerated] public string Message { [CompilerGenerated] get; [CompilerGenerated] set; } = ""; [field: CompilerGenerated] public bool SkipEnabledCheck { [CompilerGenerated] get; [CompilerGenerated] set; } public LoggerMessageAttribute() { } public LoggerMessageAttribute(int eventId, LogLevel level, string message) { EventId = eventId; Level = level; Message = message; } } public class Logger<T> : ILogger<T>, ILogger { private readonly ILogger _logger; public Logger(ILoggerFactory factory) { ThrowHelper.ThrowIfNull(factory, "factory"); _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T), fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.')); } System.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, System.Exception exception, Func<TState, System.Exception, string> formatter) { _logger.Log(logLevel, eventId, state, exception, formatter); } } public enum LogLevel { Trace, Debug, Information, Warning, Error, Critical, None } internal sealed class LogValuesFormatter { private const string NullValue = "(null)"; private static readonly char[] FormatDelimiters = new char[2] { ',', ':' }; private readonly string _format; private readonly List<string> _valueNames = new List<string>(); [field: CompilerGenerated] public string OriginalFormat { [CompilerGenerated] get; [CompilerGenerated] private set; } public List<string> ValueNames => _valueNames; public LogValuesFormatter(string format) { ThrowHelper.ThrowIfNull(format, "format"); OriginalFormat = format; System.Span<char> initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new 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(MemoryExtensions.AsSpan(format, num, length - num)); num = length; continue; } int num4 = FindIndexOfAny(format, FormatDelimiters, num2, num3); valueStringBuilder.Append(MemoryExtensions.AsSpan(format, num, num2 - num + 1)); valueStringBuilder.Append(_valueNames.Count.ToString()); _valueNames.Add(format.Substring(num2 + 1, num4 - num2 - 1)); valueStringBuilder.Append(MemoryExtensions.AsSpan(format, num4, num3 - num4 + 1)); num = num3 + 1; } _format = ((object)valueStringBuilder).ToString(); } private static int FindBraceIndex(string format, char brace, int startIndex, int endIndex) { int result = endIndex; int i = startIndex; int num = 0; for (; i < endIndex; i++) { if (num > 0 && format[i] != brace) { if (num % 2 != 0) { break; } num = 0; result = endIndex; } else { if (format[i] != brace) { continue; } if (brace == '}') { if (num == 0) { result = i; } } else { result = i; } num++; } } return result; } private static int FindIndexOfAny(string format, char[] chars, int startIndex, int endIndex) { int num = format.IndexOfAny(chars, startIndex, endIndex - startIndex); if (num != -1) { return num; } return endIndex; } public string Format(object?[]? values) { object[] array = values; if (values != null) { for (int i = 0; i < values.Length; i++) { object obj = FormatArgument(values[i]); if (obj != values[i]) { array = new object[values.Length]; System.Array.Copy((System.Array)values, (System.Array)array, i); array[i++] = obj; for (; i < values.Length; i++) { array[i] = FormatArgument(values[i]); } break; } } } return string.Format((IFormatProvider)(object)CultureInfo.InvariantCulture, _format, array ?? System.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((IFormatProvider)(object)CultureInfo.InvariantCulture, _format, values ?? System.Array.Empty<object>()); } internal string Format() { return _format; } internal string Format(object? arg0) { return string.Format((IFormatProvider)(object)CultureInfo.InvariantCulture, _format, FormatArgument(arg0)); } internal string Format(object? arg0, object? arg1) { return string.Format((IFormatProvider)(object)CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1)); } internal string Format(object? arg0, object? arg1, object? arg2) { return string.Format((IFormatProvider)(object)CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1), FormatArgument(arg2)); } public KeyValuePair<string, object?> GetValue(object?[] values, int index) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) 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}", (object)OriginalFormat); } public System.Collections.Generic.IEnumerable<KeyValuePair<string, object?>> GetValues(object[] values) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) 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[array.Length - 1] = new KeyValuePair<string, object>("{OriginalFormat}", (object)OriginalFormat); return array; } private object FormatArgument(object value) { if (value == null) { return "(null)"; } if (value is string) { return value; } if (value is System.Collections.IEnumerable enumerable) { System.Span<char> initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); bool flag = true; foreach (object item in enumerable) { if (!flag) { valueStringBuilder.Append(", "); } valueStringBuilder.Append((item != null) ? item.ToString() : "(null)"); flag = false; } return ((object)valueStringBuilder).ToString(); } return value; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { [field: CompilerGenerated] public static IExternalScopeProvider Instance { [CompilerGenerated] get; } = new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } System.IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : System.IDisposable { [field: CompilerGenerated] public static NullScope Instance { [CompilerGenerated] get; } = new NullScope(); private NullScope() { } public void Dispose() { } } } namespace Microsoft.Extensions.Logging.Abstractions { public readonly struct LogEntry<TState> { public LogLevel LogLevel { [CompilerGenerated] get; } public string Category { [CompilerGenerated] get; } public EventId EventId { [CompilerGenerated] get; } public TState State { [CompilerGenerated] get; } public System.Exception? Exception { [CompilerGenerated] get; } public Func<TState, System.Exception?, string> Formatter { [CompilerGenerated] get; } public LogEntry(LogLevel logLevel, string category, EventId eventId, TState state, System.Exception? exception, Func<TState, System.Exception?, string> formatter) { LogLevel = logLevel; Category = category; EventId = eventId; State = state; Exception = exception; Formatter = formatter; } } public class NullLogger : ILogger { [field: CompilerGenerated] public static NullLogger Instance { [CompilerGenerated] get; } = new NullLogger(); private NullLogger() { } public System.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, System.Exception? exception, Func<TState, System.Exception?, string> formatter) { } } public class NullLoggerFactory : ILoggerFactory, System.IDisposable { public static readonly NullLoggerFactory Instance = new NullLoggerFactory(); public ILogger CreateLogger(string name) { return NullLogger.Instance; } public void AddProvider(ILoggerProvider provider) { } public void Dispose() { } } public class NullLoggerProvider : ILoggerProvider, System.IDisposable { [field: CompilerGenerated] public static NullLoggerProvider Instance { [CompilerGenerated] 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 System.IDisposable BeginScope<TState>(TState state) where TState : notnull { return NullScope.Instance; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception? exception, Func<TState, System.Exception?, string> formatter) { } public bool IsEnabled(LogLevel logLevel) { return false; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Logging.Configuration.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using FxResources.Microsoft.Extensions.Logging.Configuration; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging.Configuration; using Microsoft.Extensions.Options; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Configuration")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Configuration support for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Configuration")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Logging.Configuration { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Logging.Configuration.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string ValueNotSupported => GetResourceString("ValueNotSupported"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.Logging { internal sealed class LoggerFilterConfigureOptions : IConfigureOptions<LoggerFilterOptions> { private const string LogLevelKey = "LogLevel"; private const string DefaultCategory = "Default"; private readonly IConfiguration _configuration; public LoggerFilterConfigureOptions(IConfiguration configuration) { _configuration = configuration; } public void Configure(LoggerFilterOptions options) { LoadDefaultConfigValues(options); } private void LoadDefaultConfigValues(LoggerFilterOptions options) { if (_configuration == null) { return; } options.CaptureScopes = GetCaptureScopesValue(options); System.Collections.Generic.IEnumerator<IConfigurationSection> enumerator = _configuration.GetChildren().GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IConfigurationSection current = enumerator.Current; if (current.Key.Equals("LogLevel", (StringComparison)5)) { LoadRules(options, current, null); continue; } IConfigurationSection section = ((IConfiguration)current).GetSection("LogLevel"); if (section != null) { string key = current.Key; LoadRules(options, section, key); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } [CompilerGenerated] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "IConfiguration.GetValue is safe when T is a bool.")] bool GetCaptureScopesValue(LoggerFilterOptions options) { return ConfigurationBinder.GetValue<bool>(_configuration, "CaptureScopes", options.CaptureScopes); } } private static void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator = ConfigurationExtensions.AsEnumerable((IConfiguration)(object)configurationSection, true).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, string> current = enumerator.Current; if (TryGetSwitch(current.Value, out var level)) { string text = current.Key; if (text.Equals("Default", (StringComparison)5)) { text = null; } LoggerFilterRule val = new LoggerFilterRule(logger, text, (LogLevel?)level, (Func<string, string, LogLevel, bool>)null); ((System.Collections.Generic.ICollection<LoggerFilterRule>)options.Rules).Add(val); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } private static bool TryGetSwitch(string value, out LogLevel level) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(value)) { level = (LogLevel)6; return false; } if (System.Enum.TryParse<LogLevel>(value, true, ref level)) { return true; } throw new InvalidOperationException(System.SR.Format(System.SR.ValueNotSupported, (object)value)); } } public static class LoggingBuilderExtensions { public static ILoggingBuilder AddConfiguration(this ILoggingBuilder builder, IConfiguration configuration) { builder.AddConfiguration(); ServiceCollectionServiceExtensions.AddSingleton<IConfigureOptions<LoggerFilterOptions>>(builder.Services, (IConfigureOptions<LoggerFilterOptions>)new LoggerFilterConfigureOptions(configuration)); ServiceCollectionServiceExtensions.AddSingleton<IOptionsChangeTokenSource<LoggerFilterOptions>>(builder.Services, (IOptionsChangeTokenSource<LoggerFilterOptions>)(object)new ConfigurationChangeTokenSource<LoggerFilterOptions>(configuration)); ServiceCollectionServiceExtensions.AddSingleton<LoggingConfiguration>(builder.Services, new LoggingConfiguration(configuration)); return builder; } } internal static class ProviderAliasUtilities { private const string AliasAttributeTypeFullName = "Microsoft.Extensions.Logging.ProviderAliasAttribute"; internal static string GetAlias(System.Type providerType) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) System.Collections.Generic.IList<CustomAttributeData> customAttributes = CustomAttributeData.GetCustomAttributes((MemberInfo)(object)providerType); for (int i = 0; i < ((System.Collections.Generic.ICollection<CustomAttributeData>)customAttributes).Count; i++) { CustomAttributeData val = customAttributes[i]; if (val.AttributeType.FullName == "Microsoft.Extensions.Logging.ProviderAliasAttribute" && ((System.Collections.Generic.ICollection<CustomAttributeTypedArgument>)val.ConstructorArguments).Count > 0) { CustomAttributeTypedArgument val2 = val.ConstructorArguments[0]; return ((CustomAttributeTypedArgument)(ref val2)).Value?.ToString(); } } return null; } } } namespace Microsoft.Extensions.Logging.Configuration { public interface ILoggerProviderConfiguration<T> { IConfiguration Configuration { get; } } public interface ILoggerProviderConfigurationFactory { IConfiguration GetConfiguration(System.Type providerType); } internal sealed class LoggerProviderConfiguration<T> : ILoggerProviderConfiguration<T> { public IConfiguration Configuration { [CompilerGenerated] get; } public LoggerProviderConfiguration(ILoggerProviderConfigurationFactory providerConfigurationFactory) { Configuration = providerConfigurationFactory.GetConfiguration(typeof(T)); } } public static class LoggerProviderOptions { internal const string RequiresDynamicCodeMessage = "Binding TOptions to configuration values may require generating dynamic code at runtime."; internal const string TrimmingRequiresUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved."; [RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static void RegisterProviderOptions<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions, TProvider>(IServiceCollection services) where TOptions : class { ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, ServiceDescriptor.Singleton<IConfigureOptions<TOptions>, LoggerProviderConfigureOptions<TOptions, TProvider>>()); ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, ServiceDescriptor.Singleton<IOptionsChangeTokenSource<TOptions>, LoggerProviderOptionsChangeTokenSource<TOptions, TProvider>>()); } } internal sealed class LoggerProviderConfigurationFactory : ILoggerProviderConfigurationFactory { private readonly System.Collections.Generic.IEnumerable<LoggingConfiguration> _configurations; public LoggerProviderConfigurationFactory(System.Collections.Generic.IEnumerable<LoggingConfiguration> configurations) { _configurations = configurations; } public IConfiguration GetConfiguration(System.Type providerType) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown ThrowHelper.ThrowIfNull(providerType, "providerType"); string fullName = providerType.FullName; string alias = ProviderAliasUtilities.GetAlias(providerType); ConfigurationBuilder val = new ConfigurationBuilder(); System.Collections.Generic.IEnumerator<LoggingConfiguration> enumerator = _configurations.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { LoggingConfiguration current = enumerator.Current; IConfigurationSection section = current.Configuration.GetSection(fullName); ChainedBuilderExtensions.AddConfiguration((IConfigurationBuilder)(object)val, (IConfiguration)(object)section); if (!string.IsNullOrWhiteSpace(alias)) { IConfigurationSection section2 = current.Configuration.GetSection(alias); ChainedBuilderExtensions.AddConfiguration((IConfigurationBuilder)(object)val, (IConfiguration)(object)section2); } } } finally { ((System.IDisposable)enumerator)?.Dispose(); } return (IConfiguration)(object)val.Build(); } } internal sealed class LoggerProviderConfigureOptions<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions, TProvider> : ConfigureFromConfigurationOptions<TOptions> where TOptions : class { [RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public LoggerProviderConfigureOptions(ILoggerProviderConfiguration<TProvider> providerConfiguration) : base(providerConfiguration.Configuration) { } } public class LoggerProviderOptionsChangeTokenSource<TOptions, TProvider> : ConfigurationChangeTokenSource<TOptions> { public LoggerProviderOptionsChangeTokenSource(ILoggerProviderConfiguration<TProvider> providerConfiguration) : base(providerConfiguration.Configuration) { } } public static class LoggingBuilderConfigurationExtensions { public static void AddConfiguration(this ILoggingBuilder builder) { ServiceCollectionDescriptorExtensions.TryAddSingleton<ILoggerProviderConfigurationFactory, LoggerProviderConfigurationFactory>(builder.Services); ServiceCollectionDescriptorExtensions.TryAddSingleton(builder.Services, typeof(ILoggerProviderConfiguration<>), typeof(LoggerProviderConfiguration<>)); } } internal sealed class LoggingConfiguration { [field: CompilerGenerated] public IConfiguration Configuration { [CompilerGenerated] get; } public LoggingConfiguration(IConfiguration configuration) { Configuration = configuration; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Logging.Console.dll
Decompiled a year agousing System; using System.Buffers; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.Logging.Console; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Configuration; using Microsoft.Extensions.Logging.Console; using Microsoft.Extensions.Options; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Console.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Console")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Console logger provider implementation for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Console")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(8, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class Interop { internal static class Libraries { internal const string Activeds = "activeds.dll"; internal const string Advapi32 = "advapi32.dll"; internal const string Authz = "authz.dll"; internal const string BCrypt = "BCrypt.dll"; internal const string Credui = "credui.dll"; internal const string Crypt32 = "crypt32.dll"; internal const string CryptUI = "cryptui.dll"; internal const string Dnsapi = "dnsapi.dll"; internal const string Dsrole = "dsrole.dll"; internal const string Gdi32 = "gdi32.dll"; internal const string HttpApi = "httpapi.dll"; internal const string IpHlpApi = "iphlpapi.dll"; internal const string Kernel32 = "kernel32.dll"; internal const string Logoncli = "logoncli.dll"; internal const string Mswsock = "mswsock.dll"; internal const string NCrypt = "ncrypt.dll"; internal const string Netapi32 = "netapi32.dll"; internal const string Netutils = "netutils.dll"; internal const string NtDll = "ntdll.dll"; internal const string Odbc32 = "odbc32.dll"; internal const string Ole32 = "ole32.dll"; internal const string OleAut32 = "oleaut32.dll"; internal const string Pdh = "pdh.dll"; internal const string Secur32 = "secur32.dll"; internal const string Shell32 = "shell32.dll"; internal const string SspiCli = "sspicli.dll"; internal const string User32 = "user32.dll"; internal const string Version = "version.dll"; internal const string WebSocket = "websocket.dll"; internal const string Wevtapi = "wevtapi.dll"; internal const string WinHttp = "winhttp.dll"; internal const string WinMM = "winmm.dll"; internal const string Wkscli = "wkscli.dll"; internal const string Wldap32 = "wldap32.dll"; internal const string Ws2_32 = "ws2_32.dll"; internal const string Wtsapi32 = "wtsapi32.dll"; internal const string CompressionNative = "System.IO.Compression.Native"; internal const string GlobalizationNative = "System.Globalization.Native"; internal const string MsQuic = "msquic.dll"; internal const string HostPolicy = "hostpolicy.dll"; internal const string Ucrtbase = "ucrtbase.dll"; internal const string Xolehlp = "xolehlp.dll"; } internal static class Kernel32 { internal const int ENABLE_PROCESSED_INPUT = 1; internal const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4u; internal const int STD_OUTPUT_HANDLE = -11; [LibraryImport("kernel32.dll", SetLastError = true)] [GeneratedCode("Microsoft.Interop.LibraryImportGenerator", "7.0.7.1805")] [SkipLocalsInit] [return: MarshalAs(2)] internal unsafe static bool GetConsoleMode(nint handle, out int mode) { System.Runtime.CompilerServices.Unsafe.SkipInit<int>(ref mode); int num; int lastSystemError; fixed (int* mode2 = &mode) { Marshal.SetLastSystemError(0); num = __PInvoke(handle, mode2); lastSystemError = Marshal.GetLastSystemError(); } bool result = num != 0; Marshal.SetLastPInvokeError(lastSystemError); return result; [DllImport("kernel32.dll", EntryPoint = "GetConsoleMode", ExactSpelling = true)] [CompilerGenerated] static extern unsafe int __PInvoke(nint handle, int* mode); } internal static bool IsGetConsoleModeCallSuccessful(nint handle) { int mode; return GetConsoleMode(handle, out mode); } [LibraryImport("kernel32.dll", SetLastError = true)] [GeneratedCode("Microsoft.Interop.LibraryImportGenerator", "7.0.7.1805")] [SkipLocalsInit] [return: MarshalAs(2)] internal static bool SetConsoleMode(nint handle, int mode) { Marshal.SetLastSystemError(0); int num = __PInvoke(handle, mode); int lastSystemError = Marshal.GetLastSystemError(); bool result = num != 0; Marshal.SetLastPInvokeError(lastSystemError); return result; [DllImport("kernel32.dll", EntryPoint = "SetConsoleMode", ExactSpelling = true)] [CompilerGenerated] static extern int __PInvoke(nint handle, int mode); } [DllImport("kernel32.dll", ExactSpelling = true)] [LibraryImport("kernel32.dll")] internal static extern nint GetStdHandle(int nStdHandle); } } namespace FxResources.Microsoft.Extensions.Logging.Console { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class ConsoleUtils { private static volatile int s_emitAnsiColorCodes = -1; private static volatile int s_useNet6KeyParser = -1; public static bool EmitAnsiColorCodes { get { int num = s_emitAnsiColorCodes; if (num != -1) { return Convert.ToBoolean(num); } bool flag; if (!Console.IsOutputRedirected) { flag = Environment.GetEnvironmentVariable("NO_COLOR") == null; } else { string environmentVariable = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_CONSOLE_ALLOW_ANSI_COLOR_REDIRECTION"); flag = environmentVariable != null && (environmentVariable == "1" || environmentVariable.Equals("true", (StringComparison)5)); } s_emitAnsiColorCodes = Convert.ToInt32(flag); return flag; } } internal static bool UseNet6KeyParser { get { int num = s_useNet6KeyParser; if (num == -1) { num = (s_useNet6KeyParser = (GetNet6CompatReadKeySetting() ? 1 : 0)); } return num == 1; [CompilerGenerated] static bool GetNet6CompatReadKeySetting() { bool result = default(bool); if (AppContext.TryGetSwitch("System.Console.UseNet6CompatReadKey", ref result)) { return result; } string environmentVariable = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_CONSOLE_USENET6COMPATREADKEY"); if (environmentVariable != null) { if (!(environmentVariable == "1")) { return environmentVariable.Equals("true", (StringComparison)5); } return true; } return false; } } } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Logging.Console.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded"); internal static string QueueModeNotSupported => GetResourceString("QueueModeNotSupported"); internal static string MaxQueueLengthBadValue => GetResourceString("MaxQueueLengthBadValue"); internal static string WarningMessageOnDrop => GetResourceString("WarningMessageOnDrop"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace System.Text.Json { internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, System.IDisposable { private byte[] _rentedBuffer; private int _index; private const int MinimumBufferSize = 256; public ReadOnlyMemory<byte> WrittenMemory => System.Memory<byte>.op_Implicit(MemoryExtensions.AsMemory<byte>(_rentedBuffer, 0, _index)); public int WrittenCount => _index; public int Capacity => _rentedBuffer.Length; public int FreeCapacity => _rentedBuffer.Length - _index; private PooledByteBufferWriter() { } public PooledByteBufferWriter(int initialCapacity) { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public void Clear() { ClearHelper(); } public void ClearAndReturnBuffers() { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer, false); } private void ClearHelper() { MemoryExtensions.AsSpan<byte>(_rentedBuffer, 0, _index).Clear(); _index = 0; } public void Dispose() { if (_rentedBuffer != null) { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer, false); } } public void InitializeEmptyInstance(int initialCapacity) { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public static PooledByteBufferWriter CreateEmptyInstanceForCaching() { return new PooledByteBufferWriter(); } public void Advance(int count) { _index += count; } public System.Memory<byte> GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return MemoryExtensions.AsMemory<byte>(_rentedBuffer, _index); } public System.Span<byte> GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return MemoryExtensions.AsSpan<byte>(_rentedBuffer, _index); } internal System.Threading.Tasks.ValueTask WriteToStreamAsync(Stream destination, CancellationToken cancellationToken) { //IL_0002: 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) return destination.WriteAsync(WrittenMemory, cancellationToken); } internal void WriteToStream(Stream destination) { //IL_0002: 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) destination.Write(WrittenMemory.Span); } private void CheckAndResizeBuffer(int sizeHint) { if (sizeHint == 0) { sizeHint = 256; } int num = _rentedBuffer.Length - _index; if (sizeHint <= num) { return; } int num2 = _rentedBuffer.Length; int num3 = Math.Max(sizeHint, num2); int num4 = num2 + num3; if ((uint)num4 > 2147483647u) { num4 = num2 + sizeHint; if ((uint)num4 > 2147483647u) { ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4); } } byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = ArrayPool<byte>.Shared.Rent(num4); System.Span<byte> span = MemoryExtensions.AsSpan<byte>(rentedBuffer, 0, _index); span.CopyTo(System.Span<byte>.op_Implicit(_rentedBuffer)); span.Clear(); ArrayPool<byte>.Shared.Return(rentedBuffer, false); } } internal static class ThrowHelper { [MethodImpl(8)] [DoesNotReturn] public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) throw new OutOfMemoryException(SR.Format(SR.BufferMaximumSizeExceeded, capacity)); } } } namespace Microsoft.Extensions.Logging { [UnsupportedOSPlatform("browser")] public static class ConsoleLoggerExtensions { internal const string RequiresDynamicCodeMessage = "Binding TOptions to configuration values may require generating dynamic code at runtime."; internal const string TrimmingRequiresUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved."; [UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "AddConsoleFormatter and RegisterProviderOptions are only called with Options types which only have simple properties.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "AddConsoleFormatter and RegisterProviderOptions are only dangerous when the Options type cannot be statically analyzed, but that is not the case here. The DynamicallyAccessedMembers annotations on them will make sure to preserve the right members from the different options objects.")] public static ILoggingBuilder AddConsole(this ILoggingBuilder builder) { LoggingBuilderConfigurationExtensions.AddConfiguration(builder); builder.AddConsoleFormatter<JsonConsoleFormatter, JsonConsoleFormatterOptions>(); builder.AddConsoleFormatter<SystemdConsoleFormatter, ConsoleFormatterOptions>(); builder.AddConsoleFormatter<SimpleConsoleFormatter, SimpleConsoleFormatterOptions>(); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<ILoggerProvider, ConsoleLoggerProvider>()); LoggerProviderOptions.RegisterProviderOptions<ConsoleLoggerOptions, ConsoleLoggerProvider>(builder.Services); return builder; } public static ILoggingBuilder AddConsole(this ILoggingBuilder builder, Action<ConsoleLoggerOptions> configure) { System.ThrowHelper.ThrowIfNull(configure, "configure"); builder.AddConsole(); OptionsServiceCollectionExtensions.Configure<ConsoleLoggerOptions>(builder.Services, configure); return builder; } public static ILoggingBuilder AddSimpleConsole(this ILoggingBuilder builder) { return builder.AddFormatterWithName("simple"); } public static ILoggingBuilder AddSimpleConsole(this ILoggingBuilder builder, Action<SimpleConsoleFormatterOptions> configure) { return builder.AddConsoleWithFormatter<SimpleConsoleFormatterOptions>("simple", configure); } public static ILoggingBuilder AddJsonConsole(this ILoggingBuilder builder) { return builder.AddFormatterWithName("json"); } public static ILoggingBuilder AddJsonConsole(this ILoggingBuilder builder, Action<JsonConsoleFormatterOptions> configure) { return builder.AddConsoleWithFormatter<JsonConsoleFormatterOptions>("json", configure); } public static ILoggingBuilder AddSystemdConsole(this ILoggingBuilder builder, Action<ConsoleFormatterOptions> configure) { return builder.AddConsoleWithFormatter<ConsoleFormatterOptions>("systemd", configure); } public static ILoggingBuilder AddSystemdConsole(this ILoggingBuilder builder) { return builder.AddFormatterWithName("systemd"); } internal static ILoggingBuilder AddConsoleWithFormatter<TOptions>(this ILoggingBuilder builder, string name, Action<TOptions> configure) where TOptions : ConsoleFormatterOptions { System.ThrowHelper.ThrowIfNull(configure, "configure"); builder.AddFormatterWithName(name); OptionsServiceCollectionExtensions.Configure<TOptions>(builder.Services, configure); return builder; } private static ILoggingBuilder AddFormatterWithName(this ILoggingBuilder builder, string name) { return builder.AddConsole(delegate(ConsoleLoggerOptions options) { options.FormatterName = name; }); } [RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFormatter, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this ILoggingBuilder builder) where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions { LoggingBuilderConfigurationExtensions.AddConfiguration(builder); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<ConsoleFormatter, TFormatter>()); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<IConfigureOptions<TOptions>, ConsoleLoggerFormatterConfigureOptions<TFormatter, TOptions>>()); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<IOptionsChangeTokenSource<TOptions>, ConsoleLoggerFormatterOptionsChangeTokenSource<TFormatter, TOptions>>()); return builder; } [RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TFormatter, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this ILoggingBuilder builder, Action<TOptions> configure) where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions { System.ThrowHelper.ThrowIfNull(configure, "configure"); builder.AddConsoleFormatter<TFormatter, TOptions>(); OptionsServiceCollectionExtensions.Configure<TOptions>(builder.Services, configure); return builder; } } [UnsupportedOSPlatform("browser")] internal sealed class ConsoleLoggerFormatterConfigureOptions<TFormatter, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : ConfigureFromConfigurationOptions<TOptions> where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions { [RequiresDynamicCode("Binding TOptions to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public ConsoleLoggerFormatterConfigureOptions(ILoggerProviderConfiguration<ConsoleLoggerProvider> providerConfiguration) { ((ConfigureFromConfigurationOptions<?>)(object)this)..ctor((IConfiguration)(object)providerConfiguration.Configuration.GetSection("FormatterOptions")); } } [UnsupportedOSPlatform("browser")] internal sealed class ConsoleLoggerFormatterOptionsChangeTokenSource<TFormatter, TOptions> : ConfigurationChangeTokenSource<TOptions> where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions { public ConsoleLoggerFormatterOptionsChangeTokenSource(ILoggerProviderConfiguration<ConsoleLoggerProvider> providerConfiguration) { ((ConfigurationChangeTokenSource<?>)(object)this)..ctor((IConfiguration)(object)providerConfiguration.Configuration.GetSection("FormatterOptions")); } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { [field: CompilerGenerated] public static IExternalScopeProvider Instance { [CompilerGenerated] get; } = (IExternalScopeProvider)(object)new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } System.IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : System.IDisposable { [field: CompilerGenerated] public static NullScope Instance { [CompilerGenerated] get; } = new NullScope(); private NullScope() { } public void Dispose() { } } } namespace Microsoft.Extensions.Logging.Console { internal sealed class AnsiLogConsole : IConsole { private readonly TextWriter _textWriter; public AnsiLogConsole(bool stdErr = false) { _textWriter = (stdErr ? Console.Error : Console.Out); } public void Write(string message) { _textWriter.Write(message); } } internal sealed class AnsiParser { private readonly Action<string, int, int, ConsoleColor?, ConsoleColor?> _onParseWrite; internal const string DefaultForegroundColor = "\u001b[39m\u001b[22m"; internal const string DefaultBackgroundColor = "\u001b[49m"; public AnsiParser(Action<string, int, int, ConsoleColor?, ConsoleColor?> onParseWrite) { System.ThrowHelper.ThrowIfNull(onParseWrite, "onParseWrite"); _onParseWrite = onParseWrite; } public unsafe void Parse(string message) { int num = -1; int num2 = 0; ConsoleColor? val = null; ConsoleColor? val2 = null; System.ReadOnlySpan<char> readOnlySpan = MemoryExtensions.AsSpan(message); ConsoleColor? color = null; bool isBright = false; int num3; for (num3 = 0; num3 < readOnlySpan.Length; num3++) { if (*(ushort*)readOnlySpan[num3] == 27 && readOnlySpan.Length >= num3 + 4 && *(ushort*)readOnlySpan[num3 + 1] == 91) { if (*(ushort*)readOnlySpan[num3 + 3] == 109) { if (IsDigit(*(char*)readOnlySpan[num3 + 2])) { int num4 = *(ushort*)readOnlySpan[num3 + 2] - 48; if (num != -1) { _onParseWrite.Invoke(message, num, num2, val2, val); num = -1; num2 = 0; } if (num4 == 1) { isBright = true; } num3 += 3; continue; } } else if (readOnlySpan.Length >= num3 + 5 && *(ushort*)readOnlySpan[num3 + 4] == 109 && IsDigit(*(char*)readOnlySpan[num3 + 2]) && IsDigit(*(char*)readOnlySpan[num3 + 3])) { int num4 = (*(ushort*)readOnlySpan[num3 + 2] - 48) * 10 + (*(ushort*)readOnlySpan[num3 + 3] - 48); if (num != -1) { _onParseWrite.Invoke(message, num, num2, val2, val); num = -1; num2 = 0; } if (TryGetForegroundColor(num4, isBright, out color)) { val = color; isBright = false; } else if (TryGetBackgroundColor(num4, out color)) { val2 = color; } num3 += 4; continue; } } if (num == -1) { num = num3; } int num5 = -1; if (num3 < message.Length - 1) { num5 = message.IndexOf('\u001b', num3 + 1); } if (num5 < 0) { num2 = message.Length - num; break; } num2 = num5 - num; num3 = num5 - 1; } if (num != -1) { _onParseWrite.Invoke(message, num, num2, val2, val); } } [MethodImpl(256)] private static bool IsDigit(char c) { return (uint)(c - 48) <= 9u; } internal static string GetForegroundColorEscapeCode(ConsoleColor color) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected I4, but got Unknown return (int)color switch { 0 => "\u001b[30m", 4 => "\u001b[31m", 2 => "\u001b[32m", 6 => "\u001b[33m", 1 => "\u001b[34m", 5 => "\u001b[35m", 3 => "\u001b[36m", 7 => "\u001b[37m", 12 => "\u001b[1m\u001b[31m", 10 => "\u001b[1m\u001b[32m", 14 => "\u001b[1m\u001b[33m", 9 => "\u001b[1m\u001b[34m", 13 => "\u001b[1m\u001b[35m", 11 => "\u001b[1m\u001b[36m", 15 => "\u001b[1m\u001b[37m", _ => "\u001b[39m\u001b[22m", }; } internal static string GetBackgroundColorEscapeCode(ConsoleColor color) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected I4, but got Unknown return (int)color switch { 0 => "\u001b[40m", 4 => "\u001b[41m", 2 => "\u001b[42m", 6 => "\u001b[43m", 1 => "\u001b[44m", 5 => "\u001b[45m", 3 => "\u001b[46m", 7 => "\u001b[47m", _ => "\u001b[49m", }; } private static bool TryGetForegroundColor(int number, bool isBright, out ConsoleColor? color) { color = number switch { 30 => (ConsoleColor)0, 31 => (ConsoleColor)(isBright ? 12 : 4), 32 => (ConsoleColor)(isBright ? 10 : 2), 33 => (ConsoleColor)(isBright ? 14 : 6), 34 => (ConsoleColor)((!isBright) ? 1 : 9), 35 => (ConsoleColor)(isBright ? 13 : 5), 36 => (ConsoleColor)(isBright ? 11 : 3), 37 => (ConsoleColor)(isBright ? 15 : 7), _ => null, }; if (!color.HasValue) { return number == 39; } return true; } private static bool TryGetBackgroundColor(int number, out ConsoleColor? color) { color = number switch { 40 => (ConsoleColor)0, 41 => (ConsoleColor)4, 42 => (ConsoleColor)2, 43 => (ConsoleColor)6, 44 => (ConsoleColor)1, 45 => (ConsoleColor)5, 46 => (ConsoleColor)3, 47 => (ConsoleColor)7, _ => null, }; if (!color.HasValue) { return number == 49; } return true; } } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] internal sealed class AnsiParsingLogConsole : IConsole { private readonly TextWriter _textWriter; private readonly AnsiParser _parser; public AnsiParsingLogConsole(bool stdErr = false) { _textWriter = (stdErr ? Console.Error : Console.Out); _parser = new AnsiParser(WriteToConsole); } public void Write(string message) { _parser.Parse(message); } private static bool SetColor(ConsoleColor? background, ConsoleColor? foreground) { bool flag = SetBackgroundColor(background); return SetForegroundColor(foreground) || flag; } private static bool SetBackgroundColor(ConsoleColor? background) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) if (background.HasValue) { Console.BackgroundColor = background.Value; return true; } return false; } private static bool SetForegroundColor(ConsoleColor? foreground) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) if (foreground.HasValue) { Console.ForegroundColor = foreground.Value; return true; } return false; } private static void ResetColor() { Console.ResetColor(); } private void WriteToConsole(string message, int startIndex, int length, ConsoleColor? background, ConsoleColor? foreground) { System.ReadOnlySpan<char> readOnlySpan = MemoryExtensions.AsSpan(message, startIndex, length); bool flag = SetColor(background, foreground); _textWriter.Write(readOnlySpan); if (flag) { ResetColor(); } } } public abstract class ConsoleFormatter { [field: CompilerGenerated] public string Name { [CompilerGenerated] get; } protected ConsoleFormatter(string name) { System.ThrowHelper.ThrowIfNull(name, "name"); Name = name; } public abstract void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter); } public static class ConsoleFormatterNames { public const string Simple = "simple"; public const string Json = "json"; public const string Systemd = "systemd"; } public class ConsoleFormatterOptions { [field: CompilerGenerated] public bool IncludeScopes { [CompilerGenerated] get; [CompilerGenerated] set; } [StringSyntax("DateTimeFormat")] [field: CompilerGenerated] public string? TimestampFormat { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public bool UseUtcTimestamp { [CompilerGenerated] get; [CompilerGenerated] set; } } [UnsupportedOSPlatform("browser")] internal sealed class ConsoleLogger : ILogger { private readonly string _name; private readonly ConsoleLoggerProcessor _queueProcessor; [ThreadStatic] private static StringWriter t_stringWriter; [field: CompilerGenerated] internal ConsoleFormatter Formatter { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] internal IExternalScopeProvider? ScopeProvider { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] internal ConsoleLoggerOptions Options { [CompilerGenerated] get; [CompilerGenerated] set; } internal ConsoleLogger(string name, ConsoleLoggerProcessor loggerProcessor, ConsoleFormatter formatter, IExternalScopeProvider? scopeProvider, ConsoleLoggerOptions options) { System.ThrowHelper.ThrowIfNull(name, "name"); _name = name; _queueProcessor = loggerProcessor; Formatter = formatter; ScopeProvider = scopeProvider; Options = options; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception? exception, Func<TState, System.Exception?, string> formatter) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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_0027: Expected O, but got Unknown //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) if (!IsEnabled(logLevel)) { return; } System.ThrowHelper.ThrowIfNull(formatter, "formatter"); if (t_stringWriter == null) { t_stringWriter = new StringWriter(); } LogEntry<TState> logEntry = default(LogEntry<TState>); logEntry..ctor(logLevel, _name, eventId, state, exception, formatter); Formatter.Write(in logEntry, ScopeProvider, (TextWriter)(object)t_stringWriter); StringBuilder stringBuilder = t_stringWriter.GetStringBuilder(); if (stringBuilder.Length != 0) { string message = ((object)stringBuilder).ToString(); stringBuilder.Clear(); if (stringBuilder.Capacity > 1024) { stringBuilder.Capacity = 1024; } _queueProcessor.EnqueueMessage(new LogMessageEntry(message, logLevel >= Options.LogToStandardErrorThreshold)); } } public bool IsEnabled(LogLevel logLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 return (int)logLevel != 6; } public System.IDisposable BeginScope<TState>(TState state) where TState : notnull { IExternalScopeProvider? scopeProvider = ScopeProvider; return ((scopeProvider != null) ? scopeProvider.Push((object)state) : null) ?? NullScope.Instance; } } [Obsolete("ConsoleLoggerFormat has been deprecated.")] public enum ConsoleLoggerFormat { Default, Systemd } public class ConsoleLoggerOptions { private ConsoleLoggerFormat _format; private ConsoleLoggerQueueFullMode _queueFullMode; internal const int DefaultMaxQueueLengthValue = 2500; private int _maxQueuedMessages = 2500; [Obsolete("ConsoleLoggerOptions.DisableColors has been deprecated. Use SimpleConsoleFormatterOptions.ColorBehavior instead.")] [field: CompilerGenerated] public bool DisableColors { [CompilerGenerated] get; [CompilerGenerated] set; } [Obsolete("ConsoleLoggerOptions.Format has been deprecated. Use ConsoleLoggerOptions.FormatterName instead.")] public ConsoleLoggerFormat Format { get { return _format; } set { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (value < ConsoleLoggerFormat.Default || value > ConsoleLoggerFormat.Systemd) { throw new ArgumentOutOfRangeException("value"); } _format = value; } } [field: CompilerGenerated] public string? FormatterName { [CompilerGenerated] get; [CompilerGenerated] set; } [Obsolete("ConsoleLoggerOptions.IncludeScopes has been deprecated. Use ConsoleFormatterOptions.IncludeScopes instead.")] [field: CompilerGenerated] public bool IncludeScopes { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public LogLevel LogToStandardErrorThreshold { [CompilerGenerated] get; [CompilerGenerated] set; } = (LogLevel)6; [Obsolete("ConsoleLoggerOptions.TimestampFormat has been deprecated. Use ConsoleFormatterOptions.TimestampFormat instead.")] [field: CompilerGenerated] public string? TimestampFormat { [CompilerGenerated] get; [CompilerGenerated] set; } [Obsolete("ConsoleLoggerOptions.UseUtcTimestamp has been deprecated. Use ConsoleFormatterOptions.UseUtcTimestamp instead.")] [field: CompilerGenerated] public bool UseUtcTimestamp { [CompilerGenerated] get; [CompilerGenerated] set; } public ConsoleLoggerQueueFullMode QueueFullMode { get { return _queueFullMode; } set { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (value != 0 && value != ConsoleLoggerQueueFullMode.DropWrite) { throw new ArgumentOutOfRangeException(System.SR.Format(System.SR.QueueModeNotSupported, (object?)"value")); } _queueFullMode = value; } } public int MaxQueueLength { get { return _maxQueuedMessages; } set { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value <= 0) { throw new ArgumentOutOfRangeException(System.SR.Format(System.SR.MaxQueueLengthBadValue, (object?)"value")); } _maxQueuedMessages = value; } } } [UnsupportedOSPlatform("browser")] internal class ConsoleLoggerProcessor : System.IDisposable { private readonly Queue<LogMessageEntry> _messageQueue; private volatile int _messagesDropped; private bool _isAddingCompleted; private int _maxQueuedMessages = 2500; private ConsoleLoggerQueueFullMode _fullMode; private readonly Thread _outputThread; public int MaxQueueLength { get { return _maxQueuedMessages; } set { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (value <= 0) { throw new ArgumentOutOfRangeException(System.SR.Format(System.SR.MaxQueueLengthBadValue, (object?)"value")); } lock (_messageQueue) { _maxQueuedMessages = value; Monitor.PulseAll((object)_messageQueue); } } } public ConsoleLoggerQueueFullMode FullMode { get { return _fullMode; } set { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (value != 0 && value != ConsoleLoggerQueueFullMode.DropWrite) { throw new ArgumentOutOfRangeException(System.SR.Format(System.SR.QueueModeNotSupported, (object?)"value")); } lock (_messageQueue) { _fullMode = value; Monitor.PulseAll((object)_messageQueue); } } } [field: CompilerGenerated] public IConsole Console { [CompilerGenerated] get; } [field: CompilerGenerated] public IConsole ErrorConsole { [CompilerGenerated] get; } public ConsoleLoggerProcessor(IConsole console, IConsole errorConsole, ConsoleLoggerQueueFullMode fullMode, int maxQueueLength) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown _messageQueue = new Queue<LogMessageEntry>(); FullMode = fullMode; MaxQueueLength = maxQueueLength; Console = console; ErrorConsole = errorConsole; _outputThread = new Thread(new ThreadStart(ProcessLogQueue)) { IsBackground = true, Name = "Console logger queue processing thread" }; _outputThread.Start(); } public virtual void EnqueueMessage(LogMessageEntry message) { if (!Enqueue(message)) { WriteMessage(message); } } internal void WriteMessage(LogMessageEntry entry) { try { IConsole console = (entry.LogAsError ? ErrorConsole : Console); console.Write(entry.Message); } catch { CompleteAdding(); } } private void ProcessLogQueue() { LogMessageEntry item; while (TryDequeue(out item)) { WriteMessage(item); } } public bool Enqueue(LogMessageEntry item) { lock (_messageQueue) { while (_messageQueue.Count >= MaxQueueLength && !_isAddingCompleted) { if (FullMode == ConsoleLoggerQueueFullMode.DropWrite) { _messagesDropped++; return true; } Monitor.Wait((object)_messageQueue); } if (!_isAddingCompleted) { bool flag = _messageQueue.Count == 0; if (_messagesDropped > 0) { _messageQueue.Enqueue(new LogMessageEntry(System.SR.Format(System.SR.WarningMessageOnDrop + Environment.NewLine, _messagesDropped), logAsError: true)); _messagesDropped = 0; } _messageQueue.Enqueue(item); if (flag) { Monitor.PulseAll((object)_messageQueue); } return true; } } return false; } public bool TryDequeue(out LogMessageEntry item) { lock (_messageQueue) { while (_messageQueue.Count == 0 && !_isAddingCompleted) { Monitor.Wait((object)_messageQueue); } if (_messageQueue.Count > 0 && !_isAddingCompleted) { item = _messageQueue.Dequeue(); if (_messageQueue.Count == MaxQueueLength - 1) { Monitor.PulseAll((object)_messageQueue); } return true; } item = default(LogMessageEntry); return false; } } public void Dispose() { CompleteAdding(); try { _outputThread.Join(1500); } catch (ThreadStateException) { } } private void CompleteAdding() { lock (_messageQueue) { _isAddingCompleted = true; Monitor.PulseAll((object)_messageQueue); } } } [UnsupportedOSPlatform("browser")] [ProviderAlias("Console")] public class ConsoleLoggerProvider : ILoggerProvider, System.IDisposable, ISupportExternalScope { private readonly IOptionsMonitor<ConsoleLoggerOptions> _options; private readonly ConcurrentDictionary<string, ConsoleLogger> _loggers; private ConcurrentDictionary<string, ConsoleFormatter> _formatters; private readonly ConsoleLoggerProcessor _messageQueue; private System.IDisposable _optionsReloadToken; private IExternalScopeProvider _scopeProvider = NullExternalScopeProvider.Instance; public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options) : this(options, System.Array.Empty<ConsoleFormatter>()) { } public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options, System.Collections.Generic.IEnumerable<ConsoleFormatter>? formatters) { _options = options; _loggers = new ConcurrentDictionary<string, ConsoleLogger>(); SetFormatters(formatters); IConsole console; IConsole errorConsole; if (DoesConsoleSupportAnsi()) { console = new AnsiLogConsole(); errorConsole = new AnsiLogConsole(stdErr: true); } else { console = new AnsiParsingLogConsole(); errorConsole = new AnsiParsingLogConsole(stdErr: true); } _messageQueue = new ConsoleLoggerProcessor(console, errorConsole, options.CurrentValue.QueueFullMode, options.CurrentValue.MaxQueueLength); ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = OptionsMonitorExtensions.OnChange<ConsoleLoggerOptions>(_options, (Action<ConsoleLoggerOptions>)ReloadLoggerOptions); } [UnsupportedOSPlatformGuard("windows")] private static bool DoesConsoleSupportAnsi() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return true; } nint stdHandle = Interop.Kernel32.GetStdHandle(-11); if (!Interop.Kernel32.GetConsoleMode(stdHandle, out var mode)) { return false; } return ((ulong)mode & 4uL) == 4; } [MemberNotNull("_formatters")] private void SetFormatters(System.Collections.Generic.IEnumerable<ConsoleFormatter> formatters = null) { ConcurrentDictionary<string, ConsoleFormatter> val = new ConcurrentDictionary<string, ConsoleFormatter>((IEqualityComparer<string>)(object)StringComparer.OrdinalIgnoreCase); bool flag = false; if (formatters != null) { System.Collections.Generic.IEnumerator<ConsoleFormatter> enumerator = formatters.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { ConsoleFormatter current = enumerator.Current; val.TryAdd(current.Name, current); flag = true; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } if (!flag) { val.TryAdd("simple", (ConsoleFormatter)new SimpleConsoleFormatter((IOptionsMonitor<SimpleConsoleFormatterOptions>)(object)new FormatterOptionsMonitor<SimpleConsoleFormatterOptions>(new SimpleConsoleFormatterOptions()))); val.TryAdd("systemd", (ConsoleFormatter)new SystemdConsoleFormatter((IOptionsMonitor<ConsoleFormatterOptions>)(object)new FormatterOptionsMonitor<ConsoleFormatterOptions>(new ConsoleFormatterOptions()))); val.TryAdd("json", (ConsoleFormatter)new JsonConsoleFormatter((IOptionsMonitor<JsonConsoleFormatterOptions>)(object)new FormatterOptionsMonitor<JsonConsoleFormatterOptions>(new JsonConsoleFormatterOptions()))); } _formatters = val; } private void ReloadLoggerOptions(ConsoleLoggerOptions options) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) ConsoleFormatter formatter = default(ConsoleFormatter); if (options.FormatterName == null || !_formatters.TryGetValue(options.FormatterName, ref formatter)) { ConsoleLoggerFormat format = options.Format; ConsoleFormatter consoleFormatter = ((format != ConsoleLoggerFormat.Systemd) ? _formatters["simple"] : _formatters["systemd"]); formatter = consoleFormatter; if (options.FormatterName == null) { UpdateFormatterOptions(formatter, options); } } _messageQueue.FullMode = options.QueueFullMode; _messageQueue.MaxQueueLength = options.MaxQueueLength; System.Collections.Generic.IEnumerator<KeyValuePair<string, ConsoleLogger>> enumerator = _loggers.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, ConsoleLogger> current = enumerator.Current; current.Value.Options = options; current.Value.Formatter = formatter; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } public ILogger CreateLogger(string name) { ConsoleFormatter formatter = default(ConsoleFormatter); if (_options.CurrentValue.FormatterName == null || !_formatters.TryGetValue(_options.CurrentValue.FormatterName, ref formatter)) { ConsoleLoggerFormat format = _options.CurrentValue.Format; ConsoleFormatter consoleFormatter = ((format != ConsoleLoggerFormat.Systemd) ? _formatters["simple"] : _formatters["systemd"]); formatter = consoleFormatter; if (_options.CurrentValue.FormatterName == null) { UpdateFormatterOptions(formatter, _options.CurrentValue); } } ConsoleLogger result = default(ConsoleLogger); if (!_loggers.TryGetValue(name, ref result)) { return (ILogger)(object)_loggers.GetOrAdd(name, new ConsoleLogger(name, _messageQueue, formatter, _scopeProvider, _options.CurrentValue)); } return (ILogger)(object)result; } private static void UpdateFormatterOptions(ConsoleFormatter formatter, ConsoleLoggerOptions deprecatedFromOptions) { if (formatter is SimpleConsoleFormatter simpleConsoleFormatter) { simpleConsoleFormatter.FormatterOptions = new SimpleConsoleFormatterOptions { ColorBehavior = (deprecatedFromOptions.DisableColors ? LoggerColorBehavior.Disabled : LoggerColorBehavior.Default), IncludeScopes = deprecatedFromOptions.IncludeScopes, TimestampFormat = deprecatedFromOptions.TimestampFormat, UseUtcTimestamp = deprecatedFromOptions.UseUtcTimestamp }; } else if (formatter is SystemdConsoleFormatter systemdConsoleFormatter) { systemdConsoleFormatter.FormatterOptions = new ConsoleFormatterOptions { IncludeScopes = deprecatedFromOptions.IncludeScopes, TimestampFormat = deprecatedFromOptions.TimestampFormat, UseUtcTimestamp = deprecatedFromOptions.UseUtcTimestamp }; } } public void Dispose() { _optionsReloadToken?.Dispose(); _messageQueue.Dispose(); } public void SetScopeProvider(IExternalScopeProvider scopeProvider) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) _scopeProvider = scopeProvider; System.Collections.Generic.IEnumerator<KeyValuePair<string, ConsoleLogger>> enumerator = _loggers.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { enumerator.Current.Value.ScopeProvider = _scopeProvider; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } } public enum ConsoleLoggerQueueFullMode { Wait, DropWrite } internal sealed class FormatterOptionsMonitor<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : IOptionsMonitor<TOptions> where TOptions : ConsoleFormatterOptions { private TOptions _options; public TOptions CurrentValue => _options; public FormatterOptionsMonitor(TOptions options) { _options = options; } public TOptions Get(string? name) { return _options; } public System.IDisposable? OnChange(Action<TOptions, string> listener) { return null; } } internal interface IConsole { void Write(string message); } internal sealed class JsonConsoleFormatter : ConsoleFormatter, System.IDisposable { private System.IDisposable _optionsReloadToken; [field: CompilerGenerated] internal JsonConsoleFormatterOptions FormatterOptions { [CompilerGenerated] get; [CompilerGenerated] set; } public JsonConsoleFormatter(IOptionsMonitor<JsonConsoleFormatterOptions> options) : base("json") { ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = OptionsMonitorExtensions.OnChange<JsonConsoleFormatterOptions>(options, (Action<JsonConsoleFormatterOptions>)ReloadLoggerOptions); } public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) string text = logEntry.Formatter.Invoke(logEntry.State, logEntry.Exception); if (logEntry.Exception == null && text == null) { return; } LogLevel logLevel = logEntry.LogLevel; string category = logEntry.Category; EventId eventId = logEntry.EventId; int id = ((EventId)(ref eventId)).Id; System.Exception exception = logEntry.Exception; using (PooledByteBufferWriter pooledByteBufferWriter = new PooledByteBufferWriter(1024)) { Utf8JsonWriter val = new Utf8JsonWriter((IBufferWriter<byte>)pooledByteBufferWriter, FormatterOptions.JsonWriterOptions); try { val.WriteStartObject(); string timestampFormat = FormatterOptions.TimestampFormat; if (timestampFormat != null) { DateTimeOffset val2 = (FormatterOptions.UseUtcTimestamp ? DateTimeOffset.UtcNow : DateTimeOffset.Now); val.WriteString("Timestamp", ((DateTimeOffset)(ref val2)).ToString(timestampFormat)); } val.WriteNumber("EventId", id); val.WriteString("LogLevel", GetLogLevelString(logLevel)); val.WriteString("Category", category); val.WriteString("Message", text); if (exception != null) { string text2 = ((object)exception).ToString(); JsonWriterOptions jsonWriterOptions = FormatterOptions.JsonWriterOptions; if (!((JsonWriterOptions)(ref jsonWriterOptions)).Indented) { text2 = text2.Replace(Environment.NewLine, " "); } val.WriteString("Exception", text2); } if (logEntry.State != null) { val.WriteStartObject("State"); val.WriteString("Message", ((object)logEntry.State).ToString()); if ((object)logEntry.State is System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> readOnlyCollection) { System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> enumerator = ((System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>)readOnlyCollection).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, object> current = enumerator.Current; WriteItem(val, current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } val.WriteEndObject(); } WriteScopeInformation(val, scopeProvider); val.WriteEndObject(); val.Flush(); } finally { ((System.IDisposable)val)?.Dispose(); } textWriter.Write(Encoding.UTF8.GetString(pooledByteBufferWriter.WrittenMemory.Span)); } textWriter.Write(Environment.NewLine); } private static string GetLogLevelString(LogLevel logLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) return (int)logLevel switch { 0 => "Trace", 1 => "Debug", 2 => "Information", 3 => "Warning", 4 => "Error", 5 => "Critical", _ => throw new ArgumentOutOfRangeException("logLevel"), }; } private void WriteScopeInformation(Utf8JsonWriter writer, IExternalScopeProvider scopeProvider) { if (!FormatterOptions.IncludeScopes || scopeProvider == null) { return; } writer.WriteStartArray("Scopes"); scopeProvider.ForEachScope<Utf8JsonWriter>((Action<object, Utf8JsonWriter>)delegate(object scope, Utf8JsonWriter state) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (scope is System.Collections.Generic.IEnumerable<KeyValuePair<string, object>> enumerable) { state.WriteStartObject(); state.WriteString("Message", scope.ToString()); System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> enumerator = enumerable.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, object> current = enumerator.Current; WriteItem(state, current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } state.WriteEndObject(); } else { state.WriteStringValue(ToInvariantString(scope)); } }, writer); writer.WriteEndArray(); } private static void WriteItem(Utf8JsonWriter writer, KeyValuePair<string, object> item) { string key = item.Key; object value = item.Value; if (!(value is bool flag)) { if (!(value is byte b)) { if (!(value is sbyte b2)) { if (!(value is char c)) { if (!(value is decimal num)) { if (!(value is double num2)) { if (!(value is float num3)) { if (!(value is int num4)) { if (!(value is uint num5)) { if (!(value is long num6)) { if (!(value is ulong num7)) { if (!(value is short num8)) { if (!(value is ushort num9)) { if (value == null) { writer.WriteNull(key); } else { writer.WriteString(key, ToInvariantString(item.Value)); } } else { writer.WriteNumber(key, (int)num9); } } else { writer.WriteNumber(key, (int)num8); } } else { writer.WriteNumber(key, num7); } } else { writer.WriteNumber(key, num6); } } else { writer.WriteNumber(key, num5); } } else { writer.WriteNumber(key, num4); } } else { writer.WriteNumber(key, num3); } } else { writer.WriteNumber(key, num2); } } else { writer.WriteNumber(key, num); } } else { writer.WriteString(key, System.Span<char>.op_Implicit(MemoryMarshal.CreateSpan<char>(ref c, 1))); } } else { writer.WriteNumber(key, (int)b2); } } else { writer.WriteNumber(key, (int)b); } } else { writer.WriteBoolean(key, flag); } } private static string ToInvariantString(object obj) { return Convert.ToString(obj, (IFormatProvider)(object)CultureInfo.InvariantCulture); } [MemberNotNull("FormatterOptions")] private void ReloadLoggerOptions(JsonConsoleFormatterOptions options) { FormatterOptions = options; } public void Dispose() { _optionsReloadToken?.Dispose(); } } public class JsonConsoleFormatterOptions : ConsoleFormatterOptions { [field: CompilerGenerated] public JsonWriterOptions JsonWriterOptions { [CompilerGenerated] get; [CompilerGenerated] set; } } public enum LoggerColorBehavior { Default, Enabled, Disabled } internal readonly struct LogMessageEntry { public readonly string Message; public readonly bool LogAsError; public LogMessageEntry(string message, bool logAsError = false) { Message = message; LogAsError = logAsError; } } internal sealed class SimpleConsoleFormatter : ConsoleFormatter, System.IDisposable { private readonly struct ConsoleColors { [field: CompilerGenerated] public ConsoleColor? Foreground { [CompilerGenerated] get; } [field: CompilerGenerated] public ConsoleColor? Background { [CompilerGenerated] get; } public ConsoleColors(ConsoleColor? foreground, ConsoleColor? background) { Foreground = foreground; Background = background; } } private const string LoglevelPadding = ": "; private static readonly string _messagePadding = new string(' ', GetLogLevelString((LogLevel)2).Length + ": ".Length); private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding; private System.IDisposable _optionsReloadToken; [field: CompilerGenerated] internal SimpleConsoleFormatterOptions FormatterOptions { [CompilerGenerated] get; [CompilerGenerated] set; } public SimpleConsoleFormatter(IOptionsMonitor<SimpleConsoleFormatterOptions> options) : base("simple") { ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = OptionsMonitorExtensions.OnChange<SimpleConsoleFormatterOptions>(options, (Action<SimpleConsoleFormatterOptions>)ReloadLoggerOptions); } [MemberNotNull("FormatterOptions")] private void ReloadLoggerOptions(SimpleConsoleFormatterOptions options) { FormatterOptions = options; } public void Dispose() { _optionsReloadToken?.Dispose(); } public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //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) string text = logEntry.Formatter.Invoke(logEntry.State, logEntry.Exception); if (logEntry.Exception != null || text != null) { LogLevel logLevel = logEntry.LogLevel; ConsoleColors logLevelConsoleColors = GetLogLevelConsoleColors(logLevel); string logLevelString = GetLogLevelString(logLevel); string text2 = null; string timestampFormat = FormatterOptions.TimestampFormat; if (timestampFormat != null) { DateTimeOffset currentDateTime = GetCurrentDateTime(); text2 = ((DateTimeOffset)(ref currentDateTime)).ToString(timestampFormat); } if (text2 != null) { textWriter.Write(text2); } if (logLevelString != null) { textWriter.WriteColoredMessage(logLevelString, logLevelConsoleColors.Background, logLevelConsoleColors.Foreground); } CreateDefaultLogMessage(textWriter, in logEntry, text, scopeProvider); } } private void CreateDefaultLogMessage<TState>(TextWriter textWriter, in LogEntry<TState> logEntry, string message, IExternalScopeProvider scopeProvider) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) bool singleLine = FormatterOptions.SingleLine; EventId eventId = logEntry.EventId; int id = ((EventId)(ref eventId)).Id; System.Exception exception = logEntry.Exception; textWriter.Write(": "); textWriter.Write(logEntry.Category); textWriter.Write('['); System.Span<char> span = stackalloc char[10]; int num = default(int); if (id.TryFormat(span, ref num, default(System.ReadOnlySpan<char>), (IFormatProvider)null)) { textWriter.Write(System.Span<char>.op_Implicit(span.Slice(0, num))); } else { textWriter.Write(id.ToString()); } textWriter.Write(']'); if (!singleLine) { textWriter.Write(Environment.NewLine); } WriteScopeInformation(textWriter, scopeProvider, singleLine); WriteMessage(textWriter, message, singleLine); if (exception != null) { WriteMessage(textWriter, ((object)exception).ToString(), singleLine); } if (singleLine) { textWriter.Write(Environment.NewLine); } } private static void WriteMessage(TextWriter textWriter, string message, bool singleLine) { if (!string.IsNullOrEmpty(message)) { if (singleLine) { textWriter.Write(' '); WriteReplacing(textWriter, Environment.NewLine, " ", message); } else { textWriter.Write(_messagePadding); WriteReplacing(textWriter, Environment.NewLine, _newLineWithMessagePadding, message); textWriter.Write(Environment.NewLine); } } [CompilerGenerated] static void WriteReplacing(TextWriter writer, string oldValue, string newValue, string message) { string text = message.Replace(oldValue, newValue); writer.Write(text); } } private DateTimeOffset GetCurrentDateTime() { //IL_0013: 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) if (!FormatterOptions.UseUtcTimestamp) { return DateTimeOffset.Now; } return DateTimeOffset.UtcNow; } private static string GetLogLevelString(LogLevel logLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) return (int)logLevel switch { 0 => "trce", 1 => "dbug", 2 => "info", 3 => "warn", 4 => "fail", 5 => "crit", _ => throw new ArgumentOutOfRangeException("logLevel"), }; } private ConsoleColors GetLogLevelConsoleColors(LogLevel logLevel) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected I4, but got Unknown if (FormatterOptions.ColorBehavior == LoggerColorBehavior.Disabled || (FormatterOptions.ColorBehavior == LoggerColorBehavior.Default && !ConsoleUtils.EmitAnsiColorCodes)) { return new ConsoleColors(null, null); } return (int)logLevel switch { 0 => new ConsoleColors((ConsoleColor)7, (ConsoleColor)0), 1 => new ConsoleColors((ConsoleColor)7, (ConsoleColor)0), 2 => new ConsoleColors((ConsoleColor)2, (ConsoleColor)0), 3 => new ConsoleColors((ConsoleColor)14, (ConsoleColor)0), 4 => new ConsoleColors((ConsoleColor)0, (ConsoleColor)4), 5 => new ConsoleColors((ConsoleColor)15, (ConsoleColor)4), _ => new ConsoleColors(null, null), }; } private void WriteScopeInformation(TextWriter textWriter, IExternalScopeProvider scopeProvider, bool singleLine) { if (!FormatterOptions.IncludeScopes || scopeProvider == null) { return; } bool paddingNeeded = !singleLine; scopeProvider.ForEachScope<TextWriter>((Action<object, TextWriter>)delegate(object scope, TextWriter state) { if (paddingNeeded) { paddingNeeded = false; state.Write(_messagePadding); state.Write("=> "); } else { state.Write(" => "); } state.Write(scope); }, textWriter); if (!paddingNeeded && !singleLine) { textWriter.Write(Environment.NewLine); } } } public class SimpleConsoleFormatterOptions : ConsoleFormatterOptions { [field: CompilerGenerated] public LoggerColorBehavior ColorBehavior { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public bool SingleLine { [CompilerGenerated] get; [CompilerGenerated] set; } } internal sealed class SystemdConsoleFormatter : ConsoleFormatter, System.IDisposable { private System.IDisposable _optionsReloadToken; [field: CompilerGenerated] internal ConsoleFormatterOptions FormatterOptions { [CompilerGenerated] get; [CompilerGenerated] set; } public SystemdConsoleFormatter(IOptionsMonitor<ConsoleFormatterOptions> options) : base("systemd") { ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = OptionsMonitorExtensions.OnChange<ConsoleFormatterOptions>(options, (Action<ConsoleFormatterOptions>)ReloadLoggerOptions); } [MemberNotNull("FormatterOptions")] private void ReloadLoggerOptions(ConsoleFormatterOptions options) { FormatterOptions = options; } public void Dispose() { _optionsReloadToken?.Dispose(); } public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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_0071: Unknown result type (might be due to invalid IL or missing references) string text = logEntry.Formatter.Invoke(logEntry.State, logEntry.Exception); if (logEntry.Exception != null || text != null) { LogLevel logLevel = logEntry.LogLevel; string category = logEntry.Category; EventId eventId = logEntry.EventId; int id = ((EventId)(ref eventId)).Id; System.Exception exception = logEntry.Exception; string syslogSeverityString = GetSyslogSeverityString(logLevel); textWriter.Write(syslogSeverityString); string timestampFormat = FormatterOptions.TimestampFormat; if (timestampFormat != null) { DateTimeOffset currentDateTime = GetCurrentDateTime(); textWriter.Write(((DateTimeOffset)(ref currentDateTime)).ToString(timestampFormat)); } textWriter.Write(category); textWriter.Write('['); textWriter.Write(id); textWriter.Write(']'); WriteScopeInformation(textWriter, scopeProvider); if (!string.IsNullOrEmpty(text)) { textWriter.Write(' '); WriteReplacingNewLine(textWriter, text); } if (exception != null) { textWriter.Write(' '); WriteReplacingNewLine(textWriter, ((object)exception).ToString()); } textWriter.Write(Environment.NewLine); } [CompilerGenerated] static void WriteReplacingNewLine(TextWriter writer, string message) { string text2 = message.Replace(Environment.NewLine, " "); writer.Write(text2); } } private DateTimeOffset GetCurrentDateTime() { //IL_0013: 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) if (!FormatterOptions.UseUtcTimestamp) { return DateTimeOffset.Now; } return DateTimeOffset.UtcNow; } private static string GetSyslogSeverityString(LogLevel logLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) return (int)logLevel switch { 0 => "<7>", 1 => "<7>", 2 => "<6>", 3 => "<4>", 4 => "<3>", 5 => "<2>", _ => throw new ArgumentOutOfRangeException("logLevel"), }; } private void WriteScopeInformation(TextWriter textWriter, IExternalScopeProvider scopeProvider) { if (FormatterOptions.IncludeScopes && scopeProvider != null) { scopeProvider.ForEachScope<TextWriter>((Action<object, TextWriter>)delegate(object scope, TextWriter state) { state.Write(" => "); state.Write(scope); }, textWriter); } } } internal static class TextWriterExtensions { public static void WriteColoredMessage(this TextWriter textWriter, string message, ConsoleColor? background, ConsoleColor? foreground) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (background.HasValue) { textWriter.Write(AnsiParser.GetBackgroundColorEscapeCode(background.Value)); } if (foreground.HasValue) { textWriter.Write(AnsiParser.GetForegroundColorEscapeCode(foreground.Value)); } textWriter.Write(message); if (foreground.HasValue) { textWriter.Write("\u001b[39m\u001b[22m"); } if (background.HasValue) { textWriter.Write("\u001b[49m"); } } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Logging.Debug.dll
Decompiled a year 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 Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging.Debug; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Debug")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Debug output logger provider implementation for Microsoft.Extensions.Logging. This logger logs messages to a debugger monitor by writing messages with System.Diagnostics.Debug.WriteLine().")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Debug")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } } namespace Microsoft.Extensions.Logging { public static class DebugLoggerFactoryExtensions { public static ILoggingBuilder AddDebug(this ILoggingBuilder builder) { ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<ILoggerProvider, DebugLoggerProvider>()); return builder; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { [field: CompilerGenerated] public static IExternalScopeProvider Instance { [CompilerGenerated] get; } = (IExternalScopeProvider)(object)new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } System.IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : System.IDisposable { [field: CompilerGenerated] public static NullScope Instance { [CompilerGenerated] get; } = new NullScope(); private NullScope() { } public void Dispose() { } } } namespace Microsoft.Extensions.Logging.Debug { internal sealed class DebugLogger : ILogger { private readonly string _name; public DebugLogger(string name) { _name = name; } public System.IDisposable BeginScope<TState>(TState state) { return NullScope.Instance; } public bool IsEnabled(LogLevel logLevel) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 if (Debugger.IsAttached) { return (int)logLevel != 6; } return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception exception, Func<TState, System.Exception, string> formatter) { //IL_0001: 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) if (!IsEnabled(logLevel)) { return; } ThrowHelper.ThrowIfNull(formatter, "formatter"); string text = formatter.Invoke(state, exception); if (!string.IsNullOrEmpty(text)) { text = $"{logLevel}: {text}"; if (exception != null) { text = text + Environment.NewLine + Environment.NewLine + (object)exception; } DebugWriteLine(text, _name); } } private static void DebugWriteLine(string message, string name) { Debug.WriteLine(message, name); } } [ProviderAlias("Debug")] public class DebugLoggerProvider : ILoggerProvider, System.IDisposable { public ILogger CreateLogger(string name) { return (ILogger)(object)new DebugLogger(name); } public void Dispose() { } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Logging.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using FxResources.Microsoft.Extensions.Logging; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Logging infrastructure default implementation for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Logging { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Logging.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string InvalidActivityTrackingOptions => GetResourceString("InvalidActivityTrackingOptions"); internal static string MoreThanOneWildcard => GetResourceString("MoreThanOneWildcard"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.DependencyInjection { public static class LoggingServiceCollectionExtensions { public static IServiceCollection AddLogging(this IServiceCollection services) { return services.AddLogging(delegate { }); } public static IServiceCollection AddLogging(this IServiceCollection services, Action<ILoggingBuilder> configure) { ThrowHelper.ThrowIfNull(services, "services"); OptionsServiceCollectionExtensions.AddOptions(services); ServiceCollectionDescriptorExtensions.TryAdd(services, ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>()); ServiceCollectionDescriptorExtensions.TryAdd(services, ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>))); ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>>((IConfigureOptions<LoggerFilterOptions>)(object)new DefaultLoggerLevelConfigureOptions((LogLevel)2))); configure.Invoke((ILoggingBuilder)new LoggingBuilder(services)); return services; } } } namespace Microsoft.Extensions.Logging { [Flags] public enum ActivityTrackingOptions { None = 0, SpanId = 1, TraceId = 2, ParentId = 4, TraceState = 8, TraceFlags = 0x10, Tags = 0x20, Baggage = 0x40 } internal sealed class DefaultLoggerLevelConfigureOptions : ConfigureOptions<LoggerFilterOptions> { public DefaultLoggerLevelConfigureOptions(LogLevel level) : base((Action<LoggerFilterOptions>)delegate(LoggerFilterOptions options) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) options.MinLevel = level; }) { }//IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) } public static class FilterLoggingBuilderExtensions { public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<string?, string?, LogLevel, bool> filter) { Func<string, string, LogLevel, bool> filter2 = filter; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(filter2); }); } public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<string?, LogLevel, bool> categoryLevelFilter) { Func<string, LogLevel, bool> categoryLevelFilter2 = categoryLevelFilter; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(categoryLevelFilter2); }); } public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, Func<string?, LogLevel, bool> categoryLevelFilter) where T : ILoggerProvider { Func<string, LogLevel, bool> categoryLevelFilter2 = categoryLevelFilter; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter<T>(categoryLevelFilter2); }); } public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<LogLevel, bool> levelFilter) { Func<LogLevel, bool> levelFilter2 = levelFilter; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(levelFilter2); }); } public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider { Func<LogLevel, bool> levelFilter2 = levelFilter; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter<T>(levelFilter2); }); } public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, string? category, LogLevel level) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) string category2 = category; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) options.AddFilter(category2, level); }); } public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, string? category, LogLevel level) where T : ILoggerProvider { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) string category2 = category; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) options.AddFilter<T>(category2, level); }); } public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, string? category, Func<LogLevel, bool> levelFilter) { string category2 = category; Func<LogLevel, bool> levelFilter2 = levelFilter; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(category2, levelFilter2); }); } public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, string? category, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider { string category2 = category; Func<LogLevel, bool> levelFilter2 = levelFilter; return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter<T>(category2, levelFilter2); }); } public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, Func<string?, string?, LogLevel, bool> filter) { return AddRule(builder, null, null, null, filter); } public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, Func<string?, LogLevel, bool> categoryLevelFilter) { Func<string, LogLevel, bool> categoryLevelFilter2 = categoryLevelFilter; return AddRule(builder, null, null, null, (string type, string name, LogLevel level) => categoryLevelFilter2.Invoke(name, level)); } public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, Func<string?, LogLevel, bool> categoryLevelFilter) where T : ILoggerProvider { Func<string, LogLevel, bool> categoryLevelFilter2 = categoryLevelFilter; return AddRule(builder, typeof(T).FullName, null, null, (string type, string name, LogLevel level) => categoryLevelFilter2.Invoke(name, level)); } public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, Func<LogLevel, bool> levelFilter) { Func<LogLevel, bool> levelFilter2 = levelFilter; return AddRule(builder, null, null, null, (string type, string name, LogLevel level) => levelFilter2.Invoke(level)); } public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider { Func<LogLevel, bool> levelFilter2 = levelFilter; return AddRule(builder, typeof(T).FullName, null, null, (string type, string name, LogLevel level) => levelFilter2.Invoke(level)); } public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, string? category, LogLevel level) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return AddRule(builder, null, category, level); } public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, string? category, LogLevel level) where T : ILoggerProvider { //IL_0011: Unknown result type (might be due to invalid IL or missing references) return AddRule(builder, typeof(T).FullName, category, level); } public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, string? category, Func<LogLevel, bool> levelFilter) { Func<LogLevel, bool> levelFilter2 = levelFilter; return AddRule(builder, null, category, null, (string type, string name, LogLevel level) => levelFilter2.Invoke(level)); } public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, string? category, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider { Func<LogLevel, bool> levelFilter2 = levelFilter; return AddRule(builder, typeof(T).FullName, category, null, (string type, string name, LogLevel level) => levelFilter2.Invoke(level)); } private static ILoggingBuilder ConfigureFilter(this ILoggingBuilder builder, Action<LoggerFilterOptions> configureOptions) { OptionsServiceCollectionExtensions.Configure<LoggerFilterOptions>(builder.Services, configureOptions); return builder; } private static LoggerFilterOptions AddRule(LoggerFilterOptions options, string type = null, string category = null, LogLevel? level = null, Func<string, string, LogLevel, bool> filter = null) { ((System.Collections.Generic.ICollection<LoggerFilterRule>)options.Rules).Add(new LoggerFilterRule(type, category, level, filter)); return options; } } public interface ILoggingBuilder { IServiceCollection Services { get; } } internal sealed class Logger : ILogger { private sealed class Scope : System.IDisposable { private bool _isDisposed; private System.IDisposable _disposable0; private System.IDisposable _disposable1; private readonly System.IDisposable[] _disposable; public Scope(int count) { if (count > 2) { _disposable = new System.IDisposable[count - 2]; } } public void SetDisposable(int index, System.IDisposable disposable) { switch (index) { case 0: _disposable0 = disposable; break; case 1: _disposable1 = disposable; break; default: _disposable[index - 2] = disposable; break; } } public void Dispose() { if (_isDisposed) { return; } _disposable0?.Dispose(); _disposable1?.Dispose(); if (_disposable != null) { int num = _disposable.Length; for (int i = 0; i != num; i++) { _disposable[i]?.Dispose(); } } _isDisposed = true; } } [field: CompilerGenerated] public LoggerInformation[] Loggers { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public MessageLogger[] MessageLoggers { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public ScopeLogger[] ScopeLoggers { [CompilerGenerated] get; [CompilerGenerated] set; } public Logger(LoggerInformation[] loggers) { Loggers = loggers; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception exception, Func<TState, System.Exception, string> formatter) { //IL_001a: 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_0023: Unknown result type (might be due to invalid IL or missing references) MessageLogger[] messageLoggers = MessageLoggers; if (messageLoggers == null) { return; } List<System.Exception> exceptions2 = null; for (int i = 0; i < messageLoggers.Length; i++) { ref MessageLogger reference = ref messageLoggers[i]; if (reference.IsEnabled(logLevel)) { LoggerLog(logLevel, eventId, reference.Logger, exception, formatter, ref exceptions2, in state); } } if (exceptions2 != null && exceptions2.Count > 0) { ThrowLoggingError(exceptions2); } [CompilerGenerated] static void LoggerLog(LogLevel logLevel, EventId eventId, ILogger logger, System.Exception exception, Func<TState, System.Exception, string> formatter, ref List<System.Exception> exceptions, in TState state) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) try { logger.Log<TState>(logLevel, eventId, state, exception, formatter); } catch (System.Exception ex) { if (exceptions == null) { exceptions = new List<System.Exception>(); } exceptions.Add(ex); } } } public bool IsEnabled(LogLevel logLevel) { //IL_001b: 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) MessageLogger[] messageLoggers = MessageLoggers; if (messageLoggers == null) { return false; } List<System.Exception> exceptions2 = null; int i; for (i = 0; i < messageLoggers.Length; i++) { ref MessageLogger reference = ref messageLoggers[i]; if (reference.IsEnabled(logLevel) && LoggerIsEnabled(logLevel, reference.Logger, ref exceptions2)) { break; } } if (exceptions2 != null && exceptions2.Count > 0) { ThrowLoggingError(exceptions2); } if (i >= messageLoggers.Length) { return false; } return true; [CompilerGenerated] static bool LoggerIsEnabled(LogLevel logLevel, ILogger logger, ref List<System.Exception> exceptions) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) try { if (logger.IsEnabled(logLevel)) { return true; } } catch (System.Exception ex) { if (exceptions == null) { exceptions = new List<System.Exception>(); } exceptions.Add(ex); } return false; } } public System.IDisposable BeginScope<TState>(TState state) { ScopeLogger[] scopeLoggers = ScopeLoggers; if (scopeLoggers == null) { return NullScope.Instance; } if (scopeLoggers.Length == 1) { return scopeLoggers[0].CreateScope(state); } Scope scope = new Scope(scopeLoggers.Length); List<System.Exception> val = null; for (int i = 0; i < scopeLoggers.Length; i++) { ref ScopeLogger reference = ref scopeLoggers[i]; try { scope.SetDisposable(i, reference.CreateScope(state)); } catch (System.Exception ex) { if (val == null) { val = new List<System.Exception>(); } val.Add(ex); } } if (val != null && val.Count > 0) { ThrowLoggingError(val); } return scope; } private static void ThrowLoggingError(List<System.Exception> exceptions) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) throw new AggregateException("An error occurred while writing to logger(s).", (System.Collections.Generic.IEnumerable<System.Exception>)exceptions); } } public class LoggerFactory : ILoggerFactory, System.IDisposable { private struct ProviderRegistration { public ILoggerProvider Provider; public bool ShouldDispose; } private sealed class DisposingLoggerFactory : ILoggerFactory, System.IDisposable { private readonly ILoggerFactory _loggerFactory; private readonly ServiceProvider _serviceProvider; public DisposingLoggerFactory(ILoggerFactory loggerFactory, ServiceProvider serviceProvider) { _loggerFactory = loggerFactory; _serviceProvider = serviceProvider; } public void Dispose() { _serviceProvider.Dispose(); } public ILogger CreateLogger(string categoryName) { return _loggerFactory.CreateLogger(categoryName); } public void AddProvider(ILoggerProvider provider) { _loggerFactory.AddProvider(provider); } } private readonly Dictionary<string, Logger> _loggers = new Dictionary<string, Logger>((IEqualityComparer<string>)(object)StringComparer.Ordinal); private readonly List<ProviderRegistration> _providerRegistrations = new List<ProviderRegistration>(); private readonly object _sync = new object(); private volatile bool _disposed; private System.IDisposable _changeTokenRegistration; private LoggerFilterOptions _filterOptions; private IExternalScopeProvider _scopeProvider; private LoggerFactoryOptions _factoryOptions; public LoggerFactory() : this(System.Array.Empty<ILoggerProvider>()) { } public LoggerFactory(System.Collections.Generic.IEnumerable<ILoggerProvider> providers) : this(providers, (IOptionsMonitor<LoggerFilterOptions>)(object)new StaticFilterOptionsMonitor(new LoggerFilterOptions())) { } public LoggerFactory(System.Collections.Generic.IEnumerable<ILoggerProvider> providers, LoggerFilterOptions filterOptions) : this(providers, (IOptionsMonitor<LoggerFilterOptions>)(object)new StaticFilterOptionsMonitor(filterOptions)) { } public LoggerFactory(System.Collections.Generic.IEnumerable<ILoggerProvider> providers, IOptionsMonitor<LoggerFilterOptions> filterOption) : this(providers, filterOption, null) { } public LoggerFactory(System.Collections.Generic.IEnumerable<ILoggerProvider> providers, IOptionsMonitor<LoggerFilterOptions> filterOption, IOptions<LoggerFactoryOptions>? options) : this(providers, filterOption, options, null) { } public LoggerFactory(System.Collections.Generic.IEnumerable<ILoggerProvider> providers, IOptionsMonitor<LoggerFilterOptions> filterOption, IOptions<LoggerFactoryOptions>? options = null, IExternalScopeProvider? scopeProvider = null) { //IL_0081: Unknown result type (might be due to invalid IL or missing references) _scopeProvider = scopeProvider; _factoryOptions = ((options == null || options.Value == null) ? new LoggerFactoryOptions() : options.Value); if (((uint)_factoryOptions.ActivityTrackingOptions & 0xFFFFFF80u) != 0) { throw new ArgumentException(System.SR.Format(System.SR.InvalidActivityTrackingOptions, _factoryOptions.ActivityTrackingOptions), "options"); } System.Collections.Generic.IEnumerator<ILoggerProvider> enumerator = providers.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { ILoggerProvider current = enumerator.Current; AddProviderRegistration(current, dispose: false); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } _changeTokenRegistration = OptionsMonitorExtensions.OnChange<LoggerFilterOptions>(filterOption, (Action<LoggerFilterOptions>)RefreshFilters); RefreshFilters(filterOption.CurrentValue); } [RequiresDynamicCode("LoggerFactory.Create uses Microsoft.Extensions.DependencyInjection, which may require generating code dynamically at runtime.")] public static ILoggerFactory Create(Action<ILoggingBuilder> configure) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ServiceCollection val = new ServiceCollection(); ((IServiceCollection)(object)val).AddLogging(configure); ServiceProvider val2 = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider((IServiceCollection)(object)val); ILoggerFactory requiredService = ServiceProviderServiceExtensions.GetRequiredService<ILoggerFactory>((IServiceProvider)(object)val2); return (ILoggerFactory)(object)new DisposingLoggerFactory(requiredService, val2); } [MemberNotNull("_filterOptions")] private void RefreshFilters(LoggerFilterOptions filterOptions) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) lock (_sync) { _filterOptions = filterOptions; Enumerator<string, Logger> enumerator = _loggers.GetEnumerator(); try { while (enumerator.MoveNext()) { Logger value = enumerator.Current.Value; Logger logger = value; ValueTuple<MessageLogger[], ScopeLogger[]> val = ApplyFilters(value.Loggers); MessageLogger[] array = (value.MessageLoggers = val.Item1); ScopeLogger[] array2 = (logger.ScopeLoggers = val.Item2); } } finally { ((System.IDisposable)enumerator).Dispose(); } } } public ILogger CreateLogger(string categoryName) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) if (CheckDisposed()) { throw new ObjectDisposedException("LoggerFactory"); } lock (_sync) { Logger logger = default(Logger); if (!_loggers.TryGetValue(categoryName, ref logger)) { logger = new Logger(CreateLoggers(categoryName)); Logger logger2 = logger; Logger logger3 = logger; ValueTuple<MessageLogger[], ScopeLogger[]> val = ApplyFilters(logger.Loggers); MessageLogger[] array = (logger2.MessageLoggers = val.Item1); ScopeLogger[] array2 = (logger3.ScopeLoggers = val.Item2); _loggers[categoryName] = logger; } return (ILogger)(object)logger; } } public void AddProvider(ILoggerProvider provider) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) if (CheckDisposed()) { throw new ObjectDisposedException("LoggerFactory"); } ThrowHelper.ThrowIfNull(provider, "provider"); lock (_sync) { AddProviderRegistration(provider, dispose: true); Enumerator<string, Logger> enumerator = _loggers.GetEnumerator(); try { while (enumerator.MoveNext()) { KeyValuePair<string, Logger> current = enumerator.Current; Logger value = current.Value; LoggerInformation[] loggers = value.Loggers; int num = loggers.Length; System.Array.Resize<LoggerInformation>(ref loggers, loggers.Length + 1); loggers[num] = new LoggerInformation(provider, current.Key); value.Loggers = loggers; Logger logger = value; ValueTuple<MessageLogger[], ScopeLogger[]> val = ApplyFilters(value.Loggers); MessageLogger[] array = (value.MessageLoggers = val.Item1); ScopeLogger[] array2 = (logger.ScopeLoggers = val.Item2); } } finally { ((System.IDisposable)enumerator).Dispose(); } } } private void AddProviderRegistration(ILoggerProvider provider, bool dispose) { _providerRegistrations.Add(new ProviderRegistration { Provider = provider, ShouldDispose = dispose }); ISupportExternalScope val = (ISupportExternalScope)(object)((provider is ISupportExternalScope) ? provider : null); if (val != null) { if (_scopeProvider == null) { _scopeProvider = (IExternalScopeProvider)(object)new LoggerFactoryScopeProvider(_factoryOptions.ActivityTrackingOptions); } val.SetScopeProvider(_scopeProvider); } } private LoggerInformation[] CreateLoggers(string categoryName) { LoggerInformation[] array = new LoggerInformation[_providerRegistrations.Count]; for (int i = 0; i < _providerRegistrations.Count; i++) { array[i] = new LoggerInformation(_providerRegistrations[i].Provider, categoryName); } return array; } private ValueTuple<MessageLogger[], ScopeLogger[]> ApplyFilters(LoggerInformation[] loggers) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Invalid comparison between Unknown and I4 //IL_00e2: Unknown result type (might be due to invalid IL or missing references) List<MessageLogger> val = new List<MessageLogger>(); List<ScopeLogger> val2 = (_filterOptions.CaptureScopes ? new List<ScopeLogger>() : null); for (int i = 0; i < loggers.Length; i++) { LoggerInformation loggerInformation = loggers[i]; LoggerRuleSelector.Select(_filterOptions, loggerInformation.ProviderType, loggerInformation.Category, out var minLevel, out var filter); if (!minLevel.HasValue || (int)minLevel.GetValueOrDefault() <= 5) { val.Add(new MessageLogger(loggerInformation.Logger, loggerInformation.Category, loggerInformation.ProviderType.FullName, minLevel, filter)); if (!loggerInformation.ExternalScope) { val2?.Add(new ScopeLogger(loggerInformation.Logger, null)); } } } if (_scopeProvider != null) { val2?.Add(new ScopeLogger(null, _scopeProvider)); } return new ValueTuple<MessageLogger[], ScopeLogger[]>(val.ToArray(), val2?.ToArray()); } protected virtual bool CheckDisposed() { return _disposed; } public void Dispose() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { return; } _disposed = true; _changeTokenRegistration?.Dispose(); Enumerator<ProviderRegistration> enumerator = _providerRegistrations.GetEnumerator(); try { while (enumerator.MoveNext()) { ProviderRegistration current = enumerator.Current; try { if (current.ShouldDispose) { ((System.IDisposable)current.Provider).Dispose(); } } catch { } } } finally { ((System.IDisposable)enumerator).Dispose(); } } } public class LoggerFactoryOptions { [field: CompilerGenerated] public ActivityTrackingOptions ActivityTrackingOptions { [CompilerGenerated] get; [CompilerGenerated] set; } } internal sealed class LoggerFactoryScopeProvider : IExternalScopeProvider { private sealed class Scope : System.IDisposable { private readonly LoggerFactoryScopeProvider _provider; private bool _isDisposed; [field: CompilerGenerated] public Scope Parent { [CompilerGenerated] get; } [field: CompilerGenerated] public object State { [CompilerGenerated] get; } internal Scope(LoggerFactoryScopeProvider provider, object state, Scope parent) { _provider = provider; State = state; Parent = parent; } public string ToString() { return State?.ToString(); } public void Dispose() { if (!_isDisposed) { _provider._currentScope.Value = Parent; _isDisposed = true; } } } [DefaultMember("Item")] private sealed class ActivityLogScope : System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>>, System.Collections.Generic.IEnumerable<KeyValuePair<string, object>>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>> { [CompilerGenerated] private sealed class <GetEnumerator>d__10 : System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private KeyValuePair<string, object> <>2__current; public ActivityLogScope <>4__this; private int <i>5__2; KeyValuePair<string, object> System.Collections.Generic.IEnumerator<KeyValuePair<string, object>>.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return <>2__current; } } [DebuggerHidden] public <GetEnumerator>d__10(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { //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) int num = <>1__state; ActivityLogScope activityLogScope = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <i>5__2 = 0; break; case 1: { <>1__state = -1; int num2 = <i>5__2 + 1; <i>5__2 = num2; break; } } if (<i>5__2 < activityLogScope.Count) { <>2__current = activityLogScope[<i>5__2]; <>1__state = 1; return true; } return false; } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } private string _cachedToString; private const int MaxItems = 5; private KeyValuePair<string, object>[] _items = new KeyValuePair<string, object>[5]; [field: CompilerGenerated] public int Count { [CompilerGenerated] get; } public KeyValuePair<string, object> this[int index] { get { //IL_001b: 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) if (index >= Count) { throw new ArgumentOutOfRangeException("index"); } return _items[index]; } } public ActivityLogScope(Activity activity, ActivityTrackingOptions activityTrackingOption) { //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) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) int num = 0; if ((activityTrackingOption & ActivityTrackingOptions.SpanId) != 0) { _items[num++] = new KeyValuePair<string, object>("SpanId", (object)activity.GetSpanId()); } if ((activityTrackingOption & ActivityTrackingOptions.TraceId) != 0) { _items[num++] = new KeyValuePair<string, object>("TraceId", (object)activity.GetTraceId()); } if ((activityTrackingOption & ActivityTrackingOptions.ParentId) != 0) { _items[num++] = new KeyValuePair<string, object>("ParentId", (object)activity.GetParentId()); } if ((activityTrackingOption & ActivityTrackingOptions.TraceState) != 0) { _items[num++] = new KeyValuePair<string, object>("TraceState", (object)activity.TraceStateString); } if ((activityTrackingOption & ActivityTrackingOptions.TraceFlags) != 0) { _items[num++] = new KeyValuePair<string, object>("TraceFlags", (object)activity.ActivityTraceFlags); } Count = num; } public string ToString() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown if (_cachedToString == null) { StringBuilder val = new StringBuilder(); val.Append(_items[0].Key); val.Append(':'); val.Append(_items[0].Value); for (int i = 1; i < Count; i++) { val.Append(", "); val.Append(_items[i].Key); val.Append(':'); val.Append(_items[i].Value); } _cachedToString = ((object)val).ToString(); } return _cachedToString; } [IteratorStateMachine(typeof(<GetEnumerator>d__10))] public System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)GetEnumerator(); } } private sealed class ActivityBaggageLogScopeWrapper : System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>, System.Collections.IEnumerable { private readonly System.Collections.Generic.IEnumerable<KeyValuePair<string, string>> _items; private StringBuilder _stringBuilder; public ActivityBaggageLogScopeWrapper(System.Collections.Generic.IEnumerable<KeyValuePair<string, string>> items) { _items = items; } public System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return _items.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)_items.GetEnumerator(); } public string ToString() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: 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_003f: Expected O, but got Unknown //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) lock (this) { System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator = _items.GetEnumerator(); if (!((System.Collections.IEnumerator)enumerator).MoveNext()) { return string.Empty; } if (_stringBuilder == null) { _stringBuilder = new StringBuilder(); } _stringBuilder.Append(enumerator.Current.Key); _stringBuilder.Append(':'); _stringBuilder.Append(enumerator.Current.Value); while (((System.Collections.IEnumerator)enumerator).MoveNext()) { _stringBuilder.Append(", "); _stringBuilder.Append(enumerator.Current.Key); _stringBuilder.Append(':'); _stringBuilder.Append(enumerator.Current.Value); } string result = ((object)_stringBuilder).ToString(); _stringBuilder.Clear(); return result; } } } private readonly AsyncLocal<Scope> _currentScope = new AsyncLocal<Scope>(); private readonly ActivityTrackingOptions _activityTrackingOption; public LoggerFactoryScopeProvider(ActivityTrackingOptions activityTrackingOption) { _activityTrackingOption = activityTrackingOption; } public void ForEachScope<TState>(Action<object, TState> callback, TState state) { if (_activityTrackingOption != 0) { Activity current2 = Activity.Current; if (current2 != null) { ActivityLogScope activityLogScope = current2.GetCustomProperty("__ActivityLogScope__") as ActivityLogScope; if (activityLogScope == null) { activityLogScope = new ActivityLogScope(current2, _activityTrackingOption); current2.SetCustomProperty("__ActivityLogScope__", (object)activityLogScope); } callback.Invoke((object)activityLogScope, state); if ((_activityTrackingOption & ActivityTrackingOptions.Tags) != 0 && ((System.Collections.IEnumerator)current2.TagObjects.GetEnumerator()).MoveNext()) { callback.Invoke((object)current2.TagObjects, state); } if ((_activityTrackingOption & ActivityTrackingOptions.Baggage) != 0) { System.Collections.Generic.IEnumerable<KeyValuePair<string, string>> baggage = current2.Baggage; if (((System.Collections.IEnumerator)baggage.GetEnumerator()).MoveNext()) { ActivityBaggageLogScopeWrapper orCreateActivityBaggageLogScopeWrapper = GetOrCreateActivityBaggageLogScopeWrapper(current2, baggage); callback.Invoke((object)orCreateActivityBaggageLogScopeWrapper, state); } } } } Report(_currentScope.Value); [CompilerGenerated] void Report(Scope current) { if (current != null) { Report(current.Parent); callback.Invoke(current.State, state); } } } private static ActivityBaggageLogScopeWrapper GetOrCreateActivityBaggageLogScopeWrapper(Activity activity, System.Collections.Generic.IEnumerable<KeyValuePair<string, string>> items) { ActivityBaggageLogScopeWrapper activityBaggageLogScopeWrapper = activity.GetCustomProperty("__ActivityBaggageItemsLogScope__") as ActivityBaggageLogScopeWrapper; if (activityBaggageLogScopeWrapper == null) { activityBaggageLogScopeWrapper = new ActivityBaggageLogScopeWrapper(items); activity.SetCustomProperty("__ActivityBaggageItemsLogScope__", (object)activityBaggageLogScopeWrapper); } return activityBaggageLogScopeWrapper; } public System.IDisposable Push(object state) { Scope value = _currentScope.Value; Scope scope = new Scope(this, state, value); _currentScope.Value = scope; return scope; } } internal static class ActivityExtensions { public static string GetSpanId(this Activity activity) { //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) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) ActivityIdFormat idFormat = activity.IdFormat; string text; if ((int)idFormat != 1) { if ((int)idFormat == 2) { ActivitySpanId spanId = activity.SpanId; text = ((ActivitySpanId)(ref spanId)).ToHexString(); } else { text = null; } } else { text = activity.Id; } return text ?? string.Empty; } public static string GetTraceId(this Activity activity) { //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) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) ActivityIdFormat idFormat = activity.IdFormat; string text; if ((int)idFormat != 1) { if ((int)idFormat == 2) { ActivityTraceId traceId = activity.TraceId; text = ((ActivityTraceId)(ref traceId)).ToHexString(); } else { text = null; } } else { text = activity.RootId; } return text ?? string.Empty; } public static string GetParentId(this Activity activity) { //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) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) ActivityIdFormat idFormat = activity.IdFormat; string text; if ((int)idFormat != 1) { if ((int)idFormat == 2) { ActivitySpanId parentSpanId = activity.ParentSpanId; text = ((ActivitySpanId)(ref parentSpanId)).ToHexString(); } else { text = null; } } else { text = activity.ParentId; } return text ?? string.Empty; } } public class LoggerFilterOptions { [field: CompilerGenerated] public bool CaptureScopes { [CompilerGenerated] get; [CompilerGenerated] set; } = true; [field: CompilerGenerated] public LogLevel MinLevel { [CompilerGenerated] get; [CompilerGenerated] set; } public System.Collections.Generic.IList<LoggerFilterRule> Rules => (System.Collections.Generic.IList<LoggerFilterRule>)RulesInternal; [field: CompilerGenerated] internal List<LoggerFilterRule> RulesInternal { [CompilerGenerated] get; } = new List<LoggerFilterRule>(); } public class LoggerFilterRule { [field: CompilerGenerated] public string? ProviderName { [CompilerGenerated] get; } [field: CompilerGenerated] public string? CategoryName { [CompilerGenerated] get; } [field: CompilerGenerated] public LogLevel? LogLevel { [CompilerGenerated] get; } [field: CompilerGenerated] public Func<string?, string?, LogLevel, bool>? Filter { [CompilerGenerated] get; } public LoggerFilterRule(string? providerName, string? categoryName, LogLevel? logLevel, Func<string?, string?, LogLevel, bool>? filter) { ProviderName = providerName; CategoryName = categoryName; LogLevel = logLevel; Filter = filter; } public virtual string ToString() { return $"{"ProviderName"}: '{ProviderName}', {"CategoryName"}: '{CategoryName}', {"LogLevel"}: '{LogLevel}', {"Filter"}: '{Filter}'"; } } internal readonly struct MessageLogger { [field: CompilerGenerated] public ILogger Logger { [CompilerGenerated] get; } [field: CompilerGenerated] public string Category { [CompilerGenerated] get; } [field: CompilerGenerated] private string ProviderTypeFullName { [CompilerGenerated] get; } [field: CompilerGenerated] public LogLevel? MinLevel { [CompilerGenerated] get; } [field: CompilerGenerated] public Func<string, string, LogLevel, bool> Filter { [CompilerGenerated] get; } public MessageLogger(ILogger logger, string category, string providerTypeFullName, LogLevel? minLevel, Func<string, string, LogLevel, bool> filter) { Logger = logger; Category = category; ProviderTypeFullName = providerTypeFullName; MinLevel = minLevel; Filter = filter; } public bool IsEnabled(LogLevel level) { //IL_0010: 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) //IL_0047: Unknown result type (might be due to invalid IL or missing references) if (MinLevel.HasValue && level < MinLevel) { return false; } if (Filter != null) { return Filter.Invoke(ProviderTypeFullName, Category, level); } return true; } } internal readonly struct ScopeLogger { [field: CompilerGenerated] public ILogger Logger { [CompilerGenerated] get; } [field: CompilerGenerated] public IExternalScopeProvider ExternalScopeProvider { [CompilerGenerated] get; } public ScopeLogger(ILogger logger, IExternalScopeProvider externalScopeProvider) { Logger = logger; ExternalScopeProvider = externalScopeProvider; } public System.IDisposable CreateScope<TState>(TState state) { if (ExternalScopeProvider != null) { return ExternalScopeProvider.Push((object)state); } return Logger.BeginScope<TState>(state); } } internal readonly struct LoggerInformation { [field: CompilerGenerated] public ILogger Logger { [CompilerGenerated] get; } [field: CompilerGenerated] public string Category { [CompilerGenerated] get; } [field: CompilerGenerated] public System.Type ProviderType { [CompilerGenerated] get; } [field: CompilerGenerated] public bool ExternalScope { [CompilerGenerated] get; } public LoggerInformation(ILoggerProvider provider, string category) { this = default(LoggerInformation); ProviderType = ((object)provider).GetType(); Logger = provider.CreateLogger(category); Category = category; ExternalScope = provider is ISupportExternalScope; } } internal static class LoggerRuleSelector { public static void Select(LoggerFilterOptions options, System.Type providerType, string category, out LogLevel? minLevel, out Func<string, string, LogLevel, bool> filter) { //IL_0006: 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_0029: Unknown result type (might be due to invalid IL or missing references) filter = null; minLevel = options.MinLevel; string alias = ProviderAliasUtilities.GetAlias(providerType); LoggerFilterRule loggerFilterRule = null; Enumerator<LoggerFilterRule> enumerator = options.RulesInternal.GetEnumerator(); try { while (enumerator.MoveNext()) { LoggerFilterRule current = enumerator.Current; if (IsBetter(current, loggerFilterRule, providerType.FullName, category) || (!string.IsNullOrEmpty(alias) && IsBetter(current, loggerFilterRule, alias, category))) { loggerFilterRule = current; } } } finally { ((System.IDisposable)enumerator).Dispose(); } if (loggerFilterRule != null) { filter = loggerFilterRule.Filter; minLevel = loggerFilterRule.LogLevel; } } private static bool IsBetter(LoggerFilterRule rule, LoggerFilterRule current, string logger, string category) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) if (rule.ProviderName != null && rule.ProviderName != logger) { return false; } string categoryName = rule.CategoryName; if (categoryName != null) { int num = categoryName.IndexOf('*'); if (num != -1 && categoryName.IndexOf('*', num + 1) != -1) { throw new InvalidOperationException(System.SR.MoreThanOneWildcard); } System.ReadOnlySpan<char> readOnlySpan; System.ReadOnlySpan<char> readOnlySpan2; if (num == -1) { readOnlySpan = MemoryExtensions.AsSpan(categoryName); readOnlySpan2 = default(System.ReadOnlySpan<char>); } else { readOnlySpan = MemoryExtensions.AsSpan(categoryName, 0, num); readOnlySpan2 = MemoryExtensions.AsSpan(categoryName, num + 1); } if (!MemoryExtensions.StartsWith(MemoryExtensions.AsSpan(category), readOnlySpan, (StringComparison)5) || !MemoryExtensions.EndsWith(MemoryExtensions.AsSpan(category), readOnlySpan2, (StringComparison)5)) { return false; } } if (current != null && current.ProviderName != null) { if (rule.ProviderName == null) { return false; } } else if (rule.ProviderName != null) { return true; } if (current != null && current.CategoryName != null) { if (rule.CategoryName == null) { return false; } if (current.CategoryName.Length > rule.CategoryName.Length) { return false; } } return true; } } internal sealed class LoggingBuilder : ILoggingBuilder { [field: CompilerGenerated] public IServiceCollection Services { [CompilerGenerated] get; } public LoggingBuilder(IServiceCollection services) { Services = services; } } public static class LoggingBuilderExtensions { public static ILoggingBuilder SetMinimumLevel(this ILoggingBuilder builder, LogLevel level) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) ((System.Collections.Generic.ICollection<ServiceDescriptor>)builder.Services).Add(ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>>((IConfigureOptions<LoggerFilterOptions>)(object)new DefaultLoggerLevelConfigureOptions(level))); return builder; } public static ILoggingBuilder AddProvider(this ILoggingBuilder builder, ILoggerProvider provider) { ServiceCollectionServiceExtensions.AddSingleton<ILoggerProvider>(builder.Services, provider); return builder; } public static ILoggingBuilder ClearProviders(this ILoggingBuilder builder) { ServiceCollectionDescriptorExtensions.RemoveAll<ILoggerProvider>(builder.Services); return builder; } public static ILoggingBuilder Configure(this ILoggingBuilder builder, Action<LoggerFactoryOptions> action) { OptionsServiceCollectionExtensions.Configure<LoggerFactoryOptions>(builder.Services, action); return builder; } } [AttributeUsage(/*Could not decode attribute arguments.*/)] public class ProviderAliasAttribute : System.Attribute { [field: CompilerGenerated] public string Alias { [CompilerGenerated] get; } public ProviderAliasAttribute(string alias) { Alias = alias; } } internal sealed class StaticFilterOptionsMonitor : IOptionsMonitor<LoggerFilterOptions> { [field: CompilerGenerated] public LoggerFilterOptions CurrentValue { [CompilerGenerated] get; } public StaticFilterOptionsMonitor(LoggerFilterOptions currentValue) { CurrentValue = currentValue; } public System.IDisposable OnChange(Action<LoggerFilterOptions, string> listener) { return null; } public LoggerFilterOptions Get(string name) { return CurrentValue; } } internal static class ProviderAliasUtilities { private const string AliasAttributeTypeFullName = "Microsoft.Extensions.Logging.ProviderAliasAttribute"; internal static string GetAlias(System.Type providerType) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) System.Collections.Generic.IList<CustomAttributeData> customAttributes = CustomAttributeData.GetCustomAttributes((MemberInfo)(object)providerType); for (int i = 0; i < ((System.Collections.Generic.ICollection<CustomAttributeData>)customAttributes).Count; i++) { CustomAttributeData val = customAttributes[i]; if (val.AttributeType.FullName == "Microsoft.Extensions.Logging.ProviderAliasAttribute" && ((System.Collections.Generic.ICollection<CustomAttributeTypedArgument>)val.ConstructorArguments).Count > 0) { CustomAttributeTypedArgument val2 = val.ConstructorArguments[0]; return ((CustomAttributeTypedArgument)(ref val2)).Value?.ToString(); } } return null; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { [field: CompilerGenerated] public static IExternalScopeProvider Instance { [CompilerGenerated] get; } = (IExternalScopeProvider)(object)new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } System.IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : System.IDisposable { [field: CompilerGenerated] public static NullScope Instance { [CompilerGenerated] get; } = new NullScope(); private NullScope() { } public void Dispose() { } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Logging.EventLog.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging.EventLog; using Microsoft.Extensions.Options; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.EventLog")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: SupportedOSPlatform("windows")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Windows Event Log logger provider implementation for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.EventLog")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } } namespace Microsoft.Extensions.Logging { public static class EventLoggerFactoryExtensions { public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder) { ThrowHelper.ThrowIfNull(builder, "builder"); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<ILoggerProvider, EventLogLoggerProvider>()); return builder; } public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, EventLogSettings settings) { ThrowHelper.ThrowIfNull(builder, "builder"); ThrowHelper.ThrowIfNull(settings, "settings"); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<ILoggerProvider>((ILoggerProvider)(object)new EventLogLoggerProvider(settings))); return builder; } public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, Action<EventLogSettings> configure) { ThrowHelper.ThrowIfNull(configure, "configure"); builder.AddEventLog(); OptionsServiceCollectionExtensions.Configure<EventLogSettings>(builder.Services, configure); return builder; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { [field: CompilerGenerated] public static IExternalScopeProvider Instance { [CompilerGenerated] get; } = (IExternalScopeProvider)(object)new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } System.IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : System.IDisposable { [field: CompilerGenerated] public static NullScope Instance { [CompilerGenerated] get; } = new NullScope(); private NullScope() { } public void Dispose() { } } } namespace Microsoft.Extensions.Logging.EventLog { internal sealed class EventLogLogger : ILogger { private readonly string _name; private readonly EventLogSettings _settings; private readonly IExternalScopeProvider _externalScopeProvider; private const string ContinuationString = "..."; private readonly int _beginOrEndMessageSegmentSize; private readonly int _intermediateMessageSegmentSize; [field: CompilerGenerated] public IEventLog EventLog { [CompilerGenerated] get; } public EventLogLogger(string name, EventLogSettings settings, IExternalScopeProvider? externalScopeProvider) { ThrowHelper.ThrowIfNull(name, "name"); ThrowHelper.ThrowIfNull(settings, "settings"); _name = name; _settings = settings; _externalScopeProvider = externalScopeProvider; EventLog = settings.EventLog; _beginOrEndMessageSegmentSize = EventLog.MaxMessageSize - "...".Length; _intermediateMessageSegmentSize = EventLog.MaxMessageSize - 2 * "...".Length; } public System.IDisposable? BeginScope<TState>(TState state) where TState : notnull { IExternalScopeProvider externalScopeProvider = _externalScopeProvider; if (externalScopeProvider == null) { return null; } return externalScopeProvider.Push((object)state); } public bool IsEnabled(LogLevel logLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0022: Unknown result type (might be due to invalid IL or missing references) if ((int)logLevel != 6) { if (_settings.Filter != null) { return _settings.Filter.Invoke(_name, logLevel); } return true; } return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception? exception, Func<TState, System.Exception?, string> formatter) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) if (!IsEnabled(logLevel)) { return; } ThrowHelper.ThrowIfNull(formatter, "formatter"); string text = formatter.Invoke(state, exception); if (string.IsNullOrEmpty(text)) { return; } StringBuilder val = new StringBuilder().Append("Category: ").AppendLine(_name).Append("EventId: ") .Append(((EventId)(ref eventId)).Id) .AppendLine(); IExternalScopeProvider externalScopeProvider = _externalScopeProvider; if (externalScopeProvider != null) { externalScopeProvider.ForEachScope<StringBuilder>((Action<object, StringBuilder>)delegate(object scope, StringBuilder sb) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (scope is System.Collections.Generic.IEnumerable<KeyValuePair<string, object>> enumerable) { System.Collections.Generic.IEnumerator<KeyValuePair<string, object>> enumerator = enumerable.GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, object> current = enumerator.Current; sb.Append(current.Key).Append(": ").AppendLine(current.Value?.ToString()); } return; } finally { ((System.IDisposable)enumerator)?.Dispose(); } } if (scope != null) { sb.AppendLine(scope.ToString()); } }, val); } val.AppendLine().AppendLine(text); if (exception != null) { val.AppendLine().AppendLine("Exception: ").Append((object)exception) .AppendLine(); } WriteMessage(((object)val).ToString(), GetEventLogEntryType(logLevel), EventLog.DefaultEventId ?? ((EventId)(ref eventId)).Id); } private void WriteMessage(string message, EventLogEntryType eventLogEntryType, int eventId) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) if (message.Length <= EventLog.MaxMessageSize) { EventLog.WriteEntry(message, eventLogEntryType, eventId, 0); return; } int num = 0; string text = null; while (true) { if (num == 0) { text = string.Concat(MemoryExtensions.AsSpan(message, num, _beginOrEndMessageSegmentSize), string.op_Implicit("...")); num += _beginOrEndMessageSegmentSize; } else { if (message.Length - (num + 1) <= _beginOrEndMessageSegmentSize) { break; } text = string.Concat(string.op_Implicit("..."), MemoryExtensions.AsSpan(message, num, _intermediateMessageSegmentSize), string.op_Implicit("...")); num += _intermediateMessageSegmentSize; } EventLog.WriteEntry(text, eventLogEntryType, eventId, 0); } text = string.Concat(string.op_Implicit("..."), MemoryExtensions.AsSpan(message, num)); EventLog.WriteEntry(text, eventLogEntryType, eventId, 0); } private static EventLogEntryType GetEventLogEntryType(LogLevel level) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown switch ((int)level) { case 0: case 1: case 2: return (EventLogEntryType)4; case 3: return (EventLogEntryType)2; case 4: case 5: return (EventLogEntryType)1; default: return (EventLogEntryType)4; } } } [ProviderAlias("EventLog")] public class EventLogLoggerProvider : ILoggerProvider, System.IDisposable, ISupportExternalScope { internal readonly EventLogSettings _settings; private IExternalScopeProvider _scopeProvider; public EventLogLoggerProvider() : this((EventLogSettings?)null) { } public EventLogLoggerProvider(EventLogSettings? settings) { _settings = settings ?? new EventLogSettings(); } public EventLogLoggerProvider(IOptions<EventLogSettings> options) : this(options.Value) { } public ILogger CreateLogger(string name) { return (ILogger)(object)new EventLogLogger(name, _settings, _scopeProvider); } public void Dispose() { if (_settings.EventLog is WindowsEventLog windowsEventLog) { ((Component)windowsEventLog.DiagnosticsEventLog).Dispose(); } } public void SetScopeProvider(IExternalScopeProvider scopeProvider) { _scopeProvider = scopeProvider; } } public class EventLogSettings { private IEventLog _eventLog; [field: CompilerGenerated] public string? LogName { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string? SourceName { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string? MachineName { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public Func<string, LogLevel, bool>? Filter { [CompilerGenerated] get; [CompilerGenerated] set; } internal IEventLog EventLog { get { return _eventLog ?? (_eventLog = CreateDefaultEventLog()); } set { _eventLog = value; } } private IEventLog CreateDefaultEventLog() { string logName = (string.IsNullOrEmpty(LogName) ? "Application" : LogName); string machineName = (string.IsNullOrEmpty(MachineName) ? "." : MachineName); string sourceName = (string.IsNullOrEmpty(SourceName) ? ".NET Runtime" : SourceName); int? defaultEventId = null; if (string.IsNullOrEmpty(SourceName)) { sourceName = ".NET Runtime"; defaultEventId = 1000; } return new WindowsEventLog(logName, machineName, sourceName) { DefaultEventId = defaultEventId }; } } internal interface IEventLog { int? DefaultEventId { get; } int MaxMessageSize { get; } void WriteEntry(string message, EventLogEntryType type, int eventID, short category); } [SupportedOSPlatform("windows")] internal sealed class WindowsEventLog : IEventLog { private const int MaximumMessageSize = 31839; private bool _enabled = true; [field: CompilerGenerated] public EventLog DiagnosticsEventLog { [CompilerGenerated] get; } public int MaxMessageSize => 31839; [field: CompilerGenerated] public int? DefaultEventId { [CompilerGenerated] get; [CompilerGenerated] set; } public WindowsEventLog(string logName, string machineName, string sourceName) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown DiagnosticsEventLog = new EventLog(logName, machineName, sourceName); } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) { //IL_002a: Expected O, but got Unknown //IL_0012: 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_0027: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown try { if (_enabled) { DiagnosticsEventLog.WriteEvent(new EventInstance((long)eventID, (int)category, type), new object[1] { message }); } } catch (SecurityException val) { SecurityException val2 = val; _enabled = false; try { EventLog val3 = new EventLog("Application", ".", "Application"); try { val3.WriteEvent(new EventInstance(0L, 0, (EventLogEntryType)1), new object[1] { "Unable to log .NET application events. " + ((System.Exception)(object)val2).Message }); } finally { ((System.IDisposable)val3)?.Dispose(); } } catch (System.Exception) { } } } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Logging.EventSource.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Json; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging.EventSource; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.EventSource.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.EventSource")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("EventSource/EventListener logger provider implementation for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.EventSource")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(8, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } } namespace Microsoft.Extensions.Logging { internal sealed class EventLogFiltersConfigureOptions : IConfigureOptions<LoggerFilterOptions> { private readonly LoggingEventSource _eventSource; public EventLogFiltersConfigureOptions(LoggingEventSource eventSource) { _eventSource = eventSource; } public void Configure(LoggerFilterOptions options) { LoggerFilterRule[] filterRules = _eventSource.GetFilterRules(); foreach (LoggerFilterRule val in filterRules) { ((System.Collections.Generic.ICollection<LoggerFilterRule>)options.Rules).Add(val); } } } internal sealed class EventLogFiltersConfigureOptionsChangeSource : IOptionsChangeTokenSource<LoggerFilterOptions> { private readonly LoggingEventSource _eventSource; [field: CompilerGenerated] public string? Name { [CompilerGenerated] get; } public EventLogFiltersConfigureOptionsChangeSource(LoggingEventSource eventSource) { _eventSource = eventSource; } public IChangeToken GetChangeToken() { return _eventSource.GetFilterChangeToken(); } } public static class EventSourceLoggerFactoryExtensions { public static ILoggingBuilder AddEventSourceLogger(this ILoggingBuilder builder) { ThrowHelper.ThrowIfNull(builder, "builder"); ServiceCollectionDescriptorExtensions.TryAddSingleton<LoggingEventSource>(builder.Services, LoggingEventSource.Instance); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<ILoggerProvider, EventSourceLoggerProvider>()); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>, EventLogFiltersConfigureOptions>()); ServiceCollectionDescriptorExtensions.TryAddEnumerable(builder.Services, ServiceDescriptor.Singleton<IOptionsChangeTokenSource<LoggerFilterOptions>, EventLogFiltersConfigureOptionsChangeSource>()); return builder; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { [field: CompilerGenerated] public static IExternalScopeProvider Instance { [CompilerGenerated] get; } = (IExternalScopeProvider)(object)new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } System.IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : System.IDisposable { [field: CompilerGenerated] public static NullScope Instance { [CompilerGenerated] get; } = new NullScope(); private NullScope() { } public void Dispose() { } } } namespace Microsoft.Extensions.Logging.EventSource { internal sealed class EventSourceLogger : ILogger { private sealed class ActivityScope : System.IDisposable { private readonly string _categoryName; private readonly int _activityID; private readonly int _factoryID; private readonly bool _isJsonStop; private readonly LoggingEventSource _eventSource; public ActivityScope(LoggingEventSource eventSource, string categoryName, int activityID, int factoryID, bool isJsonStop) { _categoryName = categoryName; _activityID = activityID; _factoryID = factoryID; _isJsonStop = isJsonStop; _eventSource = eventSource; } public void Dispose() { if (_isJsonStop) { _eventSource.ActivityJsonStop(_activityID, _factoryID, _categoryName); } else { _eventSource.ActivityStop(_activityID, _factoryID, _categoryName); } } } private static int _activityIds; private readonly LoggingEventSource _eventSource; private readonly int _factoryID; [field: CompilerGenerated] public string CategoryName { [CompilerGenerated] get; } [field: CompilerGenerated] public LogLevel Level { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public EventSourceLogger? Next { [CompilerGenerated] get; } public EventSourceLogger(string categoryName, int factoryID, LoggingEventSource eventSource, EventSourceLogger? next) { CategoryName = categoryName; Level = (LogLevel)0; _factoryID = factoryID; _eventSource = eventSource; Next = next; } public bool IsEnabled(LogLevel logLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: 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) if ((int)logLevel != 6) { return logLevel >= Level; } return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception? exception, Func<TState, System.Exception?, string> formatter) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0078: 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_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) if (!IsEnabled(logLevel)) { return; } string text = null; if (((EventSource)_eventSource).IsEnabled((EventLevel)1, (EventKeywords)4)) { text = formatter.Invoke(state, exception); _eventSource.FormattedMessage(logLevel, _factoryID, CategoryName, ((EventId)(ref eventId)).Id, ((EventId)(ref eventId)).Name, text); } if (((EventSource)_eventSource).IsEnabled((EventLevel)1, (EventKeywords)2)) { ExceptionInfo exceptionInfo = GetExceptionInfo(exception); System.Collections.Generic.IReadOnlyList<KeyValuePair<string, string>> properties = GetProperties(state); _eventSource.Message(logLevel, _factoryID, CategoryName, ((EventId)(ref eventId)).Id, ((EventId)(ref eventId)).Name, exceptionInfo, (System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>>)properties); } if (((EventSource)_eventSource).IsEnabled((EventLevel)1, (EventKeywords)8)) { string exceptionJson = "{}"; if (exception != null) { ExceptionInfo exceptionInfo2 = GetExceptionInfo(exception); KeyValuePair<string, string>[] keyValues = new KeyValuePair<string, string>[4] { new KeyValuePair<string, string>("TypeName", exceptionInfo2.TypeName), new KeyValuePair<string, string>("Message", exceptionInfo2.Message), new KeyValuePair<string, string>("HResult", exceptionInfo2.HResult.ToString()), new KeyValuePair<string, string>("VerboseMessage", exceptionInfo2.VerboseMessage) }; exceptionJson = ToJson(keyValues); } System.Collections.Generic.IReadOnlyList<KeyValuePair<string, string>> properties2 = GetProperties(state); if (text == null) { text = formatter.Invoke(state, exception); } _eventSource.MessageJson(logLevel, _factoryID, CategoryName, ((EventId)(ref eventId)).Id, ((EventId)(ref eventId)).Name, exceptionJson, ToJson(properties2), text); } } public System.IDisposable BeginScope<TState>(TState state) where TState : notnull { if (!IsEnabled((LogLevel)5)) { return NullScope.Instance; } int num = Interlocked.Increment(ref _activityIds); if (((EventSource)_eventSource).IsEnabled((EventLevel)1, (EventKeywords)8)) { System.Collections.Generic.IReadOnlyList<KeyValuePair<string, string>> properties = GetProperties(state); _eventSource.ActivityJsonStart(num, _factoryID, CategoryName, ToJson(properties)); return new ActivityScope(_eventSource, CategoryName, num, _factoryID, isJsonStop: true); } if (((EventSource)_eventSource).IsEnabled((EventLevel)1, (EventKeywords)2) || ((EventSource)_eventSource).IsEnabled((EventLevel)1, (EventKeywords)4)) { System.Collections.Generic.IReadOnlyList<KeyValuePair<string, string>> properties2 = GetProperties(state); _eventSource.ActivityStart(num, _factoryID, CategoryName, (System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>>)properties2); return new ActivityScope(_eventSource, CategoryName, num, _factoryID, isJsonStop: false); } return NullScope.Instance; } private static ExceptionInfo GetExceptionInfo(System.Exception exception) { if (exception == null) { return ExceptionInfo.Empty; } return new ExceptionInfo(exception); } private static System.Collections.Generic.IReadOnlyList<KeyValuePair<string, string>> GetProperties(object state) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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) if (state is System.Collections.Generic.IReadOnlyList<KeyValuePair<string, object>> readOnlyList) { KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[((System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>>)readOnlyList).Count]; for (int i = 0; i < ((System.Collections.Generic.IReadOnlyCollection<KeyValuePair<string, object>>)readOnlyList).Count; i++) { KeyValuePair<string, object> val = readOnlyList[i]; array[i] = new KeyValuePair<string, string>(val.Key, val.Value?.ToString()); } return array; } return System.Array.Empty<KeyValuePair<string, string>>(); } private static string ToJson(System.Collections.Generic.IReadOnlyList<KeyValuePair<string, string>> keyValues) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) MemoryStream val = new MemoryStream(); try { Utf8JsonWriter val2 = new Utf8JsonWriter((Stream)(object)val, default(JsonWriterOptions)); try { val2.WriteStartObject(); System.Collections.Generic.IEnumerator<KeyValuePair<string, string>> enumerator = ((System.Collections.Generic.IEnumerable<KeyValuePair<string, string>>)keyValues).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { KeyValuePair<string, string> current = enumerator.Current; val2.WriteString(current.Key, current.Value); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } val2.WriteEndObject(); val2.Flush(); ArraySegment<byte> val3 = default(ArraySegment<byte>); if (!val.TryGetBuffer(ref val3)) { val3 = new ArraySegment<byte>(val.ToArray()); } return Encoding.UTF8.GetString(val3.Array, val3.Offset, val3.Count); } finally { ((System.IDisposable)val2)?.Dispose(); } } finally { ((System.IDisposable)val)?.Dispose(); } } } [ProviderAlias("EventSource")] public class EventSourceLoggerProvider : ILoggerProvider, System.IDisposable { private static int _globalFactoryID; private readonly int _factoryID; private EventSourceLogger _loggers; private readonly LoggingEventSource _eventSource; public EventSourceLoggerProvider(LoggingEventSource eventSource) { ThrowHelper.ThrowIfNull(eventSource, "eventSource"); _eventSource = eventSource; _factoryID = Interlocked.Increment(ref _globalFactoryID); } public ILogger CreateLogger(string categoryName) { return (ILogger)(object)(_loggers = new EventSourceLogger(categoryName, _factoryID, _eventSource, _loggers)); } public void Dispose() { for (EventSourceLogger eventSourceLogger = _loggers; eventSourceLogger != null; eventSourceLogger = eventSourceLogger.Next) { eventSourceLogger.Level = (LogLevel)6; } } } [EventData(Name = "ExceptionInfo")] internal sealed class ExceptionInfo { [field: CompilerGenerated] public static ExceptionInfo Empty { [CompilerGenerated] get; } = new ExceptionInfo(); [field: CompilerGenerated] public string? TypeName { [CompilerGenerated] get; } [field: CompilerGenerated] public string? Message { [CompilerGenerated] get; } [field: CompilerGenerated] public int HResult { [CompilerGenerated] get; } [field: CompilerGenerated] public string? VerboseMessage { [CompilerGenerated] get; } private ExceptionInfo() { } public ExceptionInfo(System.Exception exception) { TypeName = exception.GetType().FullName; Message = exception.Message; HResult = exception.HResult; VerboseMessage = ((object)exception).ToString(); } } [EventSource(Name = "Microsoft-Extensions-Logging")] public sealed class LoggingEventSource : EventSource { public static class Keywords { public const EventKeywords Meta = 1L; public const EventKeywords Message = 2L; public const EventKeywords FormattedMessage = 4L; public const EventKeywords JsonMessage = 8L; } internal static readonly LoggingEventSource Instance = new LoggingEventSource(); private LoggerFilterRule[] _filterSpec = System.Array.Empty<LoggerFilterRule>(); private CancellationTokenSource _cancellationTokenSource; private const string UseAppFilters = "UseAppFilters"; private const string WriteEventCoreSuppressionJustification = "WriteEventCore is safe when eventData object is a primitive type which is in this case."; private const string WriteEventDynamicDependencySuppressionJustification = "DynamicDependency attribute will ensure that the required properties are not trimmed."; private LoggingEventSource() : base((EventSourceSettings)8) { } [Event(/*Could not decode attribute arguments.*/)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "WriteEventCore is safe when eventData object is a primitive type which is in this case.")] internal unsafe void FormattedMessage(LogLevel Level, int FactoryID, string LoggerName, int EventId, string? EventName, string FormattedMessage) { //The blocks IL_004e, IL_0051, IL_0063, IL_00ed are reachable both inside and outside the pinned region starting at IL_004b. ILSpy has duplicated these blocks in order to place them both within and outside the `fixed` statement. if (!((EventSource)this).IsEnabled()) { return; } if (LoggerName == null) { LoggerName = ""; } if (EventName == null) { EventName = ""; } if (FormattedMessage == null) { FormattedMessage = ""; } fixed (char* pinnedString3 = LoggerName) { char* intPtr; if (EventName == null) { char* pinnedString; intPtr = (pinnedString = null); fixed (char* ptr = FormattedMessage) { char* pinnedString2 = ptr; EventData* ptr2 = (EventData*)stackalloc EventData[6]; SetEventData(ref *ptr2, ref Level, null); SetEventData(ref *(EventData*)((byte*)ptr2 + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr2 + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString3); SetEventData(ref *(EventData*)((byte*)ptr2 + (nint)3 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventId, null); SetEventData(ref *(EventData*)((byte*)ptr2 + (nint)4 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventName, pinnedString); SetEventData(ref *(EventData*)((byte*)ptr2 + (nint)5 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FormattedMessage, pinnedString2); ((EventSource)this).WriteEventCore(1, 6, ptr2); } return; } fixed (char* ptr3 = EventName.GetPinnableReference()) { char* pinnedString; intPtr = (pinnedString = ptr3); fixed (char* ptr = FormattedMessage) { char* pinnedString2 = ptr; EventData* ptr2 = (EventData*)stackalloc EventData[6]; SetEventData(ref *ptr2, ref Level, null); SetEventData(ref *(EventData*)((byte*)ptr2 + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr2 + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString3); SetEventData(ref *(EventData*)((byte*)ptr2 + (nint)3 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventId, null); SetEventData(ref *(EventData*)((byte*)ptr2 + (nint)4 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventName, pinnedString); SetEventData(ref *(EventData*)((byte*)ptr2 + (nint)5 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FormattedMessage, pinnedString2); ((EventSource)this).WriteEventCore(1, 6, ptr2); } } } } [Event(/*Could not decode attribute arguments.*/)] [DynamicDependency(/*Could not decode attribute arguments.*/)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "DynamicDependency attribute will ensure that the required properties are not trimmed.")] internal void Message(LogLevel Level, int FactoryID, string LoggerName, int EventId, string? EventName, ExceptionInfo Exception, System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>> Arguments) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (((EventSource)this).IsEnabled()) { ((EventSource)this).WriteEvent(2, new object[7] { Level, FactoryID, LoggerName, EventId, EventName, Exception, Arguments }); } } [Event(/*Could not decode attribute arguments.*/)] [DynamicDependency(/*Could not decode attribute arguments.*/)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "DynamicDependency attribute will ensure that the required properties are not trimmed.")] internal void ActivityStart(int ID, int FactoryID, string LoggerName, System.Collections.Generic.IEnumerable<KeyValuePair<string, string?>> Arguments) { if (((EventSource)this).IsEnabled()) { ((EventSource)this).WriteEvent(3, new object[4] { ID, FactoryID, LoggerName, Arguments }); } } [Event(/*Could not decode attribute arguments.*/)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "WriteEventCore is safe when eventData object is a primitive type which is in this case.")] internal unsafe void ActivityStop(int ID, int FactoryID, string LoggerName) { if (((EventSource)this).IsEnabled()) { if (LoggerName == null) { LoggerName = ""; } fixed (char* pinnedString = LoggerName) { EventData* ptr = (EventData*)stackalloc EventData[3]; SetEventData(ref *ptr, ref ID, null); SetEventData(ref *(EventData*)((byte*)ptr + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString); ((EventSource)this).WriteEventCore(4, 3, ptr); } } } [Event(/*Could not decode attribute arguments.*/)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "WriteEventCore is safe when eventData object is a primitive type which is in this case.")] internal unsafe void MessageJson(LogLevel Level, int FactoryID, string LoggerName, int EventId, string? EventName, string ExceptionJson, string ArgumentsJson, string FormattedMessage) { //The blocks IL_0064, IL_0067, IL_0079, IL_007f, IL_0083, IL_008e, IL_008f, IL_0093, IL_00a5, IL_0159, IL_015d, IL_0161 are reachable both inside and outside the pinned region starting at IL_0061. ILSpy has duplicated these blocks in order to place them both within and outside the `fixed` statement. //The blocks IL_008f, IL_0093, IL_00a5, IL_0159 are reachable both inside and outside the pinned region starting at IL_008a. ILSpy has duplicated these blocks in order to place them both within and outside the `fixed` statement. //The blocks IL_008f, IL_0093, IL_00a5, IL_0159 are reachable both inside and outside the pinned region starting at IL_008a. ILSpy has duplicated these blocks in order to place them both within and outside the `fixed` statement. if (!((EventSource)this).IsEnabled()) { return; } if (LoggerName == null) { LoggerName = ""; } if (EventName == null) { EventName = ""; } if (ExceptionJson == null) { ExceptionJson = ""; } if (ArgumentsJson == null) { ArgumentsJson = ""; } if (FormattedMessage == null) { FormattedMessage = ""; } fixed (char* pinnedString5 = LoggerName) { char* intPtr; char* intPtr2; if (EventName == null) { char* pinnedString; intPtr = (pinnedString = null); fixed (char* ptr = ExceptionJson) { char* pinnedString2 = ptr; if (ArgumentsJson == null) { char* pinnedString3; intPtr2 = (pinnedString3 = null); fixed (char* ptr2 = FormattedMessage) { char* pinnedString4 = ptr2; EventData* ptr3 = (EventData*)stackalloc EventData[8]; SetEventData(ref *ptr3, ref Level, null); SetEventData(ref *(EventData*)((byte*)ptr3 + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString5); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)3 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventId, null); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)4 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventName, pinnedString); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)5 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ExceptionJson, pinnedString2); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)6 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ArgumentsJson, pinnedString3); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)7 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FormattedMessage, pinnedString4); ((EventSource)this).WriteEventCore(5, 8, ptr3); } return; } fixed (char* ptr4 = ArgumentsJson.GetPinnableReference()) { char* pinnedString3; intPtr2 = (pinnedString3 = ptr4); fixed (char* ptr2 = FormattedMessage) { char* pinnedString4 = ptr2; EventData* ptr3 = (EventData*)stackalloc EventData[8]; SetEventData(ref *ptr3, ref Level, null); SetEventData(ref *(EventData*)((byte*)ptr3 + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString5); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)3 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventId, null); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)4 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventName, pinnedString); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)5 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ExceptionJson, pinnedString2); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)6 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ArgumentsJson, pinnedString3); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)7 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FormattedMessage, pinnedString4); ((EventSource)this).WriteEventCore(5, 8, ptr3); } } } return; } fixed (char* ptr5 = EventName.GetPinnableReference()) { char* pinnedString; intPtr = (pinnedString = ptr5); fixed (char* ptr = ExceptionJson) { char* pinnedString2 = ptr; if (ArgumentsJson == null) { char* pinnedString3; intPtr2 = (pinnedString3 = null); fixed (char* ptr2 = FormattedMessage) { char* pinnedString4 = ptr2; EventData* ptr3 = (EventData*)stackalloc EventData[8]; SetEventData(ref *ptr3, ref Level, null); SetEventData(ref *(EventData*)((byte*)ptr3 + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString5); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)3 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventId, null); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)4 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventName, pinnedString); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)5 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ExceptionJson, pinnedString2); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)6 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ArgumentsJson, pinnedString3); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)7 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FormattedMessage, pinnedString4); ((EventSource)this).WriteEventCore(5, 8, ptr3); } return; } fixed (char* ptr4 = ArgumentsJson.GetPinnableReference()) { char* pinnedString3; intPtr2 = (pinnedString3 = ptr4); fixed (char* ptr2 = FormattedMessage) { char* pinnedString4 = ptr2; EventData* ptr3 = (EventData*)stackalloc EventData[8]; SetEventData(ref *ptr3, ref Level, null); SetEventData(ref *(EventData*)((byte*)ptr3 + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString5); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)3 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventId, null); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)4 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref EventName, pinnedString); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)5 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ExceptionJson, pinnedString2); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)6 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ArgumentsJson, pinnedString3); SetEventData(ref *(EventData*)((byte*)ptr3 + (nint)7 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FormattedMessage, pinnedString4); ((EventSource)this).WriteEventCore(5, 8, ptr3); } } } } } } [Event(/*Could not decode attribute arguments.*/)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "WriteEventCore is safe when eventData object is a primitive type which is in this case.")] internal unsafe void ActivityJsonStart(int ID, int FactoryID, string LoggerName, string ArgumentsJson) { //The blocks IL_0043 are reachable both inside and outside the pinned region starting at IL_0040. ILSpy has duplicated these blocks in order to place them both within and outside the `fixed` statement. if (!((EventSource)this).IsEnabled()) { return; } if (LoggerName == null) { LoggerName = ""; } if (ArgumentsJson == null) { ArgumentsJson = ""; } fixed (char* pinnedString2 = LoggerName) { char* intPtr; if (ArgumentsJson == null) { char* pinnedString; intPtr = (pinnedString = null); EventData* ptr = (EventData*)stackalloc EventData[4]; SetEventData(ref *ptr, ref ID, null); SetEventData(ref *(EventData*)((byte*)ptr + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString2); SetEventData(ref *(EventData*)((byte*)ptr + (nint)3 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ArgumentsJson, pinnedString); ((EventSource)this).WriteEventCore(6, 4, ptr); return; } fixed (char* ptr2 = ArgumentsJson.GetPinnableReference()) { char* pinnedString; intPtr = (pinnedString = ptr2); EventData* ptr = (EventData*)stackalloc EventData[4]; SetEventData(ref *ptr, ref ID, null); SetEventData(ref *(EventData*)((byte*)ptr + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString2); SetEventData(ref *(EventData*)((byte*)ptr + (nint)3 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref ArgumentsJson, pinnedString); ((EventSource)this).WriteEventCore(6, 4, ptr); } } } [Event(/*Could not decode attribute arguments.*/)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "WriteEventCore is safe when eventData object is a primitive type which is in this case.")] internal unsafe void ActivityJsonStop(int ID, int FactoryID, string LoggerName) { if (((EventSource)this).IsEnabled()) { if (LoggerName == null) { LoggerName = ""; } fixed (char* pinnedString = LoggerName) { EventData* ptr = (EventData*)stackalloc EventData[3]; SetEventData(ref *ptr, ref ID, null); SetEventData(ref *(EventData*)((byte*)ptr + System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref FactoryID, null); SetEventData(ref *(EventData*)((byte*)ptr + (nint)2 * (nint)System.Runtime.CompilerServices.Unsafe.SizeOf<EventData>()), ref LoggerName, pinnedString); ((EventSource)this).WriteEventCore(7, 3, ptr); } } } protected override void OnEventCommand(EventCommandEventArgs command) { //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) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 EventCommand command2 = command.Command; if ((int)command2 == 0 || (int)command2 == -2) { string empty = default(string); if (!command.Arguments.TryGetValue("FilterSpecs", ref empty)) { empty = string.Empty; } SetFilterSpec(empty); } else if ((int)command.Command == -3) { SetFilterSpec(null); } } [NonEvent] private void SetFilterSpec(string filterSpec) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) _filterSpec = ParseFilterSpec(filterSpec, GetDefaultLevel()); FireChangeToken(); } [NonEvent] internal IChangeToken GetFilterChangeToken() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown CancellationTokenSource val = LazyInitializer.EnsureInitialized<CancellationTokenSource>(ref _cancellationTokenSource, (Func<CancellationTokenSource>)(() => new CancellationTokenSource())); return (IChangeToken)new CancellationChangeToken(val.Token); } [NonEvent] private void FireChangeToken() { CancellationTokenSource val = Interlocked.Exchange<CancellationTokenSource>(ref _cancellationTokenSource, (CancellationTokenSource)null); if (val != null) { val.Cancel(); } } [NonEvent] private static LoggerFilterRule[] ParseFilterSpec(string filterSpec, LogLevel defaultLevel) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown //IL_0112: Unknown result type (might be due to invalid IL or missing references) if (filterSpec == string.Empty) { return (LoggerFilterRule[])(object)new LoggerFilterRule[1] { new LoggerFilterRule(typeof(EventSourceLoggerProvider).FullName, (string)null, (LogLevel?)defaultLevel, (Func<string, string, LogLevel, bool>)null) }; } if (filterSpec == null) { return (LoggerFilterRule[])(object)new LoggerFilterRule[1] { new LoggerFilterRule(typeof(EventSourceLoggerProvider).FullName, (string)null, (LogLevel?)(LogLevel)6, (Func<string, string, LogLevel, bool>)null) }; } List<LoggerFilterRule> val = new List<LoggerFilterRule>(); int num = 0; string[] array = filterSpec.Split(new char[1] { ';' }, (StringSplitOptions)1); if (array.Length != 0 && array[0].Equals("UseAppFilters", (StringComparison)5)) { num = 1; } else { val.Add(new LoggerFilterRule(typeof(EventSourceLoggerProvider).FullName, (string)null, (LogLevel?)(LogLevel)6, (Func<string, string, LogLevel, bool>)null)); } for (int i = num; i < array.Length; i++) { string text = array[i]; LogLevel ret = defaultLevel; string[] array2 = text.Split(new char[1] { ':' }, 2); string text2 = array2[0]; if (text2.Length != 0) { if (text2[text2.Length - 1] == '*') { text2 = text2.Substring(0, text2.Length - 1); } if (array2.Length != 2 || TryParseLevel(defaultLevel, array2[1], out ret)) { val.Add(new LoggerFilterRule(typeof(EventSourceLoggerProvider).FullName, text2, (LogLevel?)ret, (Func<string, string, LogLevel, bool>)null)); } } } return val.ToArray(); } [NonEvent] private static bool TryParseLevel(LogLevel defaultLevel, string levelString, out LogLevel ret) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Expected I4, but got Unknown //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected I4, but got Unknown ret = (LogLevel)(int)defaultLevel; if (levelString.Length == 0) { ret = (LogLevel)(int)defaultLevel; return true; } if (!(levelString == "Trace")) { if (!(levelString == "Debug")) { if (!(levelString == "Information")) { if (!(levelString == "Warning")) { if (!(levelString == "Error")) { if (levelString == "Critical") { ret = (LogLevel)5; } else { int num = default(int); if (!int.TryParse(levelString, ref num)) { return false; } if (0 > num || num > 6) { return false; } ret = (LogLevel)num; } } else { ret = (LogLevel)4; } } else { ret = (LogLevel)3; } } else { ret = (LogLevel)2; } } else { ret = (LogLevel)1; } } else { ret = (LogLevel)0; } return true; } [NonEvent] private LogLevel GetDefaultLevel() { //IL_0003: 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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) EventKeywords val = (EventKeywords)14; if (!((EventSource)this).IsEnabled((EventLevel)5, val)) { if (!((EventSource)this).IsEnabled((EventLevel)4, val)) { if (!((EventSource)this).IsEnabled((EventLevel)3, val)) { if (!((EventSource)this).IsEnabled((EventLevel)2, val)) { return (LogLevel)5; } return (LogLevel)4; } return (LogLevel)3; } return (LogLevel)2; } return (LogLevel)1; } [NonEvent] internal LoggerFilterRule[] GetFilterRules() { return _filterSpec; } [MethodImpl(256)] [NonEvent] private unsafe static void SetEventData<T>(ref EventData eventData, ref T value, void* pinnedString = null) { if (typeof(T) == typeof(string)) { string text = value as string; ((EventData)(ref eventData)).DataPointer = (nint)pinnedString; ((EventData)(ref eventData)).Size = checked((text.Length + 1) * 2); } else { ((EventData)(ref eventData)).DataPointer = (nint)System.Runtime.CompilerServices.Unsafe.AsPointer<T>(ref value); ((EventData)(ref eventData)).Size = System.Runtime.CompilerServices.Unsafe.SizeOf<T>(); } } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Options.ConfigurationExtensions.dll
Decompiled a year 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 Microsoft.CodeAnalysis; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Options.ConfigurationExtensions")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides additional configuration specific functionality related to Options.")] [assembly: AssemblyFileVersion("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Options.ConfigurationExtensions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } } namespace Microsoft.Extensions.DependencyInjection { public static class OptionsBuilderConfigurationExtensions { internal const string RequiresDynamicCodeMessage = "Binding strongly typed objects to configuration values may require generating dynamic code at runtime."; internal const string TrimmingRequiredUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved."; [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static OptionsBuilder<TOptions> Bind<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, IConfiguration config) where TOptions : class { return optionsBuilder.Bind<TOptions>(config, delegate { }); } [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static OptionsBuilder<TOptions> Bind<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, IConfiguration config, Action<BinderOptions>? configureBinder) where TOptions : class { ThrowHelper.ThrowIfNull(optionsBuilder, "optionsBuilder"); optionsBuilder.Services.Configure<TOptions>(optionsBuilder.Name, config, configureBinder); return optionsBuilder; } [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static OptionsBuilder<TOptions> BindConfiguration<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, string configSectionPath, Action<BinderOptions>? configureBinder = null) where TOptions : class { string configSectionPath2 = configSectionPath; Action<BinderOptions> configureBinder2 = configureBinder; ThrowHelper.ThrowIfNull(optionsBuilder, "optionsBuilder"); ThrowHelper.ThrowIfNull(configSectionPath2, "configSectionPath"); ((OptionsBuilder<IConfiguration>)(object)optionsBuilder).Configure<IConfiguration>((Action<IConfiguration, IConfiguration>)(object)(Action<TOptions, IConfiguration>)delegate(TOptions opts, IConfiguration config) { IConfiguration obj; if (!string.Equals("", configSectionPath2, (StringComparison)5)) { IConfiguration section = (IConfiguration)(object)config.GetSection(configSectionPath2); obj = section; } else { obj = config; } IConfiguration val = obj; ConfigurationBinder.Bind(val, (object)opts, configureBinder2); }); ServiceCollectionServiceExtensions.AddSingleton<IOptionsChangeTokenSource<TOptions>, ConfigurationChangeTokenSource<TOptions>>(optionsBuilder.Services); return optionsBuilder; } } public static class OptionsConfigurationServiceCollectionExtensions { [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static IServiceCollection Configure<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this IServiceCollection services, IConfiguration config) where TOptions : class { return services.Configure<TOptions>(Options.DefaultName, config); } [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static IServiceCollection Configure<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this IServiceCollection services, string? name, IConfiguration config) where TOptions : class { return services.Configure<TOptions>(name, config, delegate { }); } [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static IServiceCollection Configure<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this IServiceCollection services, IConfiguration config, Action<BinderOptions>? configureBinder) where TOptions : class { return services.Configure<TOptions>(Options.DefaultName, config, configureBinder); } [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static IServiceCollection Configure<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this IServiceCollection services, string? name, IConfiguration config, Action<BinderOptions>? configureBinder) where TOptions : class { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(config, "config"); OptionsServiceCollectionExtensions.AddOptions(services); ServiceCollectionServiceExtensions.AddSingleton<IOptionsChangeTokenSource<TOptions>>(services, (IOptionsChangeTokenSource<TOptions>)new ConfigurationChangeTokenSource<TOptions>(name, config)); return ServiceCollectionServiceExtensions.AddSingleton<IConfigureOptions<TOptions>>(services, (IConfigureOptions<TOptions>)(object)new NamedConfigureFromConfigurationOptions<TOptions>(name, config, configureBinder)); } } } namespace Microsoft.Extensions.Options { public class ConfigurationChangeTokenSource<TOptions> : IOptionsChangeTokenSource<TOptions> { private IConfiguration _config; public string Name { [CompilerGenerated] get; } public ConfigurationChangeTokenSource(IConfiguration config) : this(Options.DefaultName, config) { } public ConfigurationChangeTokenSource(string? name, IConfiguration config) { ThrowHelper.ThrowIfNull(config, "config"); _config = config; Name = name ?? Options.DefaultName; } public IChangeToken GetChangeToken() { return _config.GetReloadToken(); } } public class ConfigureFromConfigurationOptions<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : ConfigureOptions<TOptions> where TOptions : class { [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public ConfigureFromConfigurationOptions(IConfiguration config) { IConfiguration config2 = config; base..ctor((Action<TOptions>)delegate(TOptions options) { ConfigurationBinder.Bind(config2, (object)options); }); ThrowHelper.ThrowIfNull(config2, "config"); } } public class NamedConfigureFromConfigurationOptions<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : ConfigureNamedOptions<TOptions> where TOptions : class { [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public NamedConfigureFromConfigurationOptions(string? name, IConfiguration config) : this(name, config, (Action<BinderOptions>?)delegate { }) { } [RequiresDynamicCode("Binding strongly typed objects to configuration values may require generating dynamic code at runtime.")] [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public NamedConfigureFromConfigurationOptions(string? name, IConfiguration config, Action<BinderOptions>? configureBinder) { IConfiguration config2 = config; Action<BinderOptions> configureBinder2 = configureBinder; base..ctor(name, (Action<TOptions>)delegate(TOptions options) { ConfigurationBinder.Bind(config2, (object)options, configureBinder2); }); ThrowHelper.ThrowIfNull(config2, "config"); } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Options.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using FxResources.Microsoft.Extensions.Options; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Options.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Options")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides a strongly typed way of specifying and accessing settings using dependency injection.")] [assembly: AssemblyFileVersion("7.0.323.6910")] [assembly: AssemblyInformationalVersion("7.0.3+0a2bda10e81d901396c3cff95533529e3a93ad47")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Options")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("7.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Options { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Options.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } internal static string Error_CannotActivateAbstractOrInterface => GetResourceString("Error_CannotActivateAbstractOrInterface"); internal static string Error_FailedBinding => GetResourceString("Error_FailedBinding"); internal static string Error_FailedToActivate => GetResourceString("Error_FailedToActivate"); internal static string Error_MissingParameterlessConstructor => GetResourceString("Error_MissingParameterlessConstructor"); internal static string Error_NoConfigurationServices => GetResourceString("Error_NoConfigurationServices"); internal static string Error_NoConfigurationServicesAndAction => GetResourceString("Error_NoConfigurationServicesAndAction"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace Microsoft.Extensions.DependencyInjection { public static class OptionsServiceCollectionExtensions { [CompilerGenerated] private sealed class <FindConfigurationServices>d__8 : System.Collections.Generic.IEnumerable<System.Type>, System.Collections.IEnumerable, System.Collections.Generic.IEnumerator<System.Type>, System.Collections.IEnumerator, System.IDisposable { private int <>1__state; private System.Type <>2__current; private int <>l__initialThreadId; private System.Type type; public System.Type <>3__type; private System.Type[] <>7__wrap1; private int <>7__wrap2; System.Type System.Collections.Generic.IEnumerator<System.Type>.Current { [DebuggerHidden] get { return <>2__current; } } object System.Collections.IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <FindConfigurationServices>d__8(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void System.IDisposable.Dispose() { } private bool MoveNext() { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; goto IL_009e; } <>1__state = -1; <>7__wrap1 = <FindConfigurationServices>g__GetInterfacesOnType|8_0(this.type); <>7__wrap2 = 0; goto IL_00ac; IL_009e: <>7__wrap2++; goto IL_00ac; IL_00ac: if (<>7__wrap2 < <>7__wrap1.Length) { System.Type type = <>7__wrap1[<>7__wrap2]; if (type.IsGenericType) { System.Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(IConfigureOptions<>) || genericTypeDefinition == typeof(IPostConfigureOptions<>) || genericTypeDefinition == typeof(IValidateOptions<>)) { <>2__current = type; <>1__state = 1; return true; } } goto IL_009e; } <>7__wrap1 = null; return false; } bool System.Collections.IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } [DebuggerHidden] System.Collections.Generic.IEnumerator<System.Type> System.Collections.Generic.IEnumerable<System.Type>.GetEnumerator() { <FindConfigurationServices>d__8 <FindConfigurationServices>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <FindConfigurationServices>d__ = this; } else { <FindConfigurationServices>d__ = new <FindConfigurationServices>d__8(0); } <FindConfigurationServices>d__.type = <>3__type; return <FindConfigurationServices>d__; } [DebuggerHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (System.Collections.IEnumerator)((System.Collections.Generic.IEnumerable<System.Type>)this).GetEnumerator(); } } public static IServiceCollection AddOptions(this IServiceCollection services) { ThrowHelper.ThrowIfNull(services, "services"); ServiceCollectionDescriptorExtensions.TryAdd(services, ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(UnnamedOptionsManager<>))); ServiceCollectionDescriptorExtensions.TryAdd(services, ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>))); ServiceCollectionDescriptorExtensions.TryAdd(services, ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>))); ServiceCollectionDescriptorExtensions.TryAdd(services, ServiceDescriptor.Transient(typeof(IOptionsFactory<>), typeof(OptionsFactory<>))); ServiceCollectionDescriptorExtensions.TryAdd(services, ServiceDescriptor.Singleton(typeof(IOptionsMonitorCache<>), typeof(OptionsCache<>))); return services; } public static IServiceCollection Configure<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class { return services.Configure<TOptions>(Microsoft.Extensions.Options.Options.DefaultName, configureOptions); } public static IServiceCollection Configure<TOptions>(this IServiceCollection services, string? name, Action<TOptions> configureOptions) where TOptions : class { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(configureOptions, "configureOptions"); services.AddOptions(); ServiceCollectionServiceExtensions.AddSingleton<IConfigureOptions<TOptions>>(services, (IConfigureOptions<TOptions>)new ConfigureNamedOptions<TOptions>(name, configureOptions)); return services; } public static IServiceCollection ConfigureAll<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class { return services.Configure<TOptions>(null, configureOptions); } public static IServiceCollection PostConfigure<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class { return services.PostConfigure<TOptions>(Microsoft.Extensions.Options.Options.DefaultName, configureOptions); } public static IServiceCollection PostConfigure<TOptions>(this IServiceCollection services, string? name, Action<TOptions> configureOptions) where TOptions : class { ThrowHelper.ThrowIfNull(services, "services"); ThrowHelper.ThrowIfNull(configureOptions, "configureOptions"); services.AddOptions(); ServiceCollectionServiceExtensions.AddSingleton<IPostConfigureOptions<TOptions>>(services, (IPostConfigureOptions<TOptions>)new PostConfigureOptions<TOptions>(name, configureOptions)); return services; } public static IServiceCollection PostConfigureAll<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class { return services.PostConfigure<TOptions>(null, configureOptions); } public static IServiceCollection ConfigureOptions<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TConfigureOptions>(this IServiceCollection services) where TConfigureOptions : class { return services.ConfigureOptions(typeof(TConfigureOptions)); } [IteratorStateMachine(typeof(<FindConfigurationServices>d__8))] private static System.Collections.Generic.IEnumerable<System.Type> FindConfigurationServices(System.Type type) { System.Type[] array = GetInterfacesOnType(type); foreach (System.Type type2 in array) { if (type2.IsGenericType) { System.Type genericTypeDefinition = type2.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(IConfigureOptions<>) || genericTypeDefinition == typeof(IPostConfigureOptions<>) || genericTypeDefinition == typeof(IValidateOptions<>)) { yield return type2; } } } [CompilerGenerated] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This method only looks for interfaces referenced in its code. The trimmer will keep the interface and thus all of its implementations in that case. The call to GetInterfaces may return less results in trimmed apps, but it will include the interfaces this method looks for if they should be there.")] static System.Type[] GetInterfacesOnType(System.Type t) { return t.GetInterfaces(); } } private static void ThrowNoConfigServices(System.Type type) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) throw new InvalidOperationException((type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Action<>)) ? System.SR.Error_NoConfigurationServicesAndAction : System.SR.Error_NoConfigurationServices); } public static IServiceCollection ConfigureOptions(this IServiceCollection services, [DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] System.Type configureType) { services.AddOptions(); bool flag = false; System.Collections.Generic.IEnumerator<System.Type> enumerator = FindConfigurationServices(configureType).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { System.Type current = enumerator.Current; ServiceCollectionServiceExtensions.AddTransient(services, current, configureType); flag = true; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } if (!flag) { ThrowNoConfigServices(configureType); } return services; } public static IServiceCollection ConfigureOptions(this IServiceCollection services, object configureInstance) { services.AddOptions(); System.Type type = configureInstance.GetType(); bool flag = false; System.Collections.Generic.IEnumerator<System.Type> enumerator = FindConfigurationServices(type).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { System.Type current = enumerator.Current; ServiceCollectionServiceExtensions.AddSingleton(services, current, configureInstance); flag = true; } } finally { ((System.IDisposable)enumerator)?.Dispose(); } if (!flag) { ThrowNoConfigServices(type); } return services; } public static OptionsBuilder<TOptions> AddOptions<TOptions>(this IServiceCollection services) where TOptions : class { return services.AddOptions<TOptions>(Microsoft.Extensions.Options.Options.DefaultName); } public static OptionsBuilder<TOptions> AddOptions<TOptions>(this IServiceCollection services, string? name) where TOptions : class { ThrowHelper.ThrowIfNull(services, "services"); services.AddOptions(); return new OptionsBuilder<TOptions>(services, name); } [CompilerGenerated] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This method only looks for interfaces referenced in its code. The trimmer will keep the interface and thus all of its implementations in that case. The call to GetInterfaces may return less results in trimmed apps, but it will include the interfaces this method looks for if they should be there.")] internal static System.Type[] <FindConfigurationServices>g__GetInterfacesOnType|8_0(System.Type t) { return t.GetInterfaces(); } } } namespace Microsoft.Extensions.Options { public class ConfigureNamedOptions<TOptions> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions>? Action { [CompilerGenerated] get; } public ConfigureNamedOptions(string? name, Action<TOptions>? action) { Name = name; Action = action; } public virtual void Configure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options); } } public void Configure(TOptions options) { Configure(Options.DefaultName, options); } } public class ConfigureNamedOptions<TOptions, TDep> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep>? Action { [CompilerGenerated] get; } public TDep Dependency { [CompilerGenerated] get; } public ConfigureNamedOptions(string? name, TDep dependency, Action<TOptions, TDep>? action) { Name = name; Action = action; Dependency = dependency; } public virtual void Configure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency); } } public void Configure(TOptions options) { Configure(Options.DefaultName, options); } } public class ConfigureNamedOptions<TOptions, TDep1, TDep2> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep1, TDep2>? Action { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public ConfigureNamedOptions(string? name, TDep1 dependency, TDep2 dependency2, Action<TOptions, TDep1, TDep2>? action) { Name = name; Action = action; Dependency1 = dependency; Dependency2 = dependency2; } public virtual void Configure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency1, Dependency2); } } public void Configure(TOptions options) { Configure(Options.DefaultName, options); } } public class ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep1, TDep2, TDep3>? Action { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public ConfigureNamedOptions(string? name, TDep1 dependency, TDep2 dependency2, TDep3 dependency3, Action<TOptions, TDep1, TDep2, TDep3>? action) { Name = name; Action = action; Dependency1 = dependency; Dependency2 = dependency2; Dependency3 = dependency3; } public virtual void Configure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency1, Dependency2, Dependency3); } } public void Configure(TOptions options) { Configure(Options.DefaultName, options); } } public class ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep1, TDep2, TDep3, TDep4>? Action { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public TDep4 Dependency4 { [CompilerGenerated] get; } public ConfigureNamedOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Action<TOptions, TDep1, TDep2, TDep3, TDep4>? action) { Name = name; Action = action; Dependency1 = dependency1; Dependency2 = dependency2; Dependency3 = dependency3; Dependency4 = dependency4; } public virtual void Configure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4); } } public void Configure(TOptions options) { Configure(Options.DefaultName, options); } } public class ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>? Action { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public TDep4 Dependency4 { [CompilerGenerated] get; } public TDep5 Dependency5 { [CompilerGenerated] get; } public ConfigureNamedOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>? action) { Name = name; Action = action; Dependency1 = dependency1; Dependency2 = dependency2; Dependency3 = dependency3; Dependency4 = dependency4; Dependency5 = dependency5; } public virtual void Configure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4, Dependency5); } } public void Configure(TOptions options) { Configure(Options.DefaultName, options); } } public class ConfigureOptions<TOptions> : IConfigureOptions<TOptions> where TOptions : class { public Action<TOptions>? Action { [CompilerGenerated] get; } public ConfigureOptions(Action<TOptions>? action) { Action = action; } public virtual void Configure(TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); Action?.Invoke(options); } } public interface IConfigureNamedOptions<in TOptions> : IConfigureOptions<TOptions> where TOptions : class { void Configure(string? name, TOptions options); } public interface IConfigureOptions<in TOptions> where TOptions : class { void Configure(TOptions options); } public interface IOptions<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] out TOptions> where TOptions : class { TOptions Value { get; } } public interface IOptionsChangeTokenSource<out TOptions> { string? Name { get; } IChangeToken GetChangeToken(); } public interface IOptionsFactory<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> where TOptions : class { TOptions Create(string name); } public interface IOptionsMonitor<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] out TOptions> { TOptions CurrentValue { get; } TOptions Get(string? name); System.IDisposable? OnChange(Action<TOptions, string?> listener); } public interface IOptionsMonitorCache<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> where TOptions : class { TOptions GetOrAdd(string? name, Func<TOptions> createOptions); bool TryAdd(string? name, TOptions options); bool TryRemove(string? name); void Clear(); } public interface IOptionsSnapshot<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] out TOptions> : IOptions<TOptions> where TOptions : class { TOptions Get(string? name); } public interface IPostConfigureOptions<in TOptions> where TOptions : class { void PostConfigure(string? name, TOptions options); } public interface IValidateOptions<TOptions> where TOptions : class { ValidateOptionsResult Validate(string? name, TOptions options); } public static class Options { internal const DynamicallyAccessedMemberTypes DynamicallyAccessedMembers = 1; public static readonly string DefaultName = string.Empty; public static IOptions<TOptions> Create<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(TOptions options) where TOptions : class { return new OptionsWrapper<TOptions>(options); } } public class OptionsBuilder<TOptions> where TOptions : class { private const string DefaultValidationFailureMessage = "A validation error has occurred."; public string Name { [CompilerGenerated] get; } public IServiceCollection Services { [CompilerGenerated] get; } public OptionsBuilder(IServiceCollection services, string? name) { ThrowHelper.ThrowIfNull(services, "services"); Services = services; Name = name ?? Options.DefaultName; } public virtual OptionsBuilder<TOptions> Configure(Action<TOptions> configureOptions) { ThrowHelper.ThrowIfNull(configureOptions, "configureOptions"); ServiceCollectionServiceExtensions.AddSingleton<IConfigureOptions<TOptions>>(Services, (IConfigureOptions<TOptions>)new ConfigureNamedOptions<TOptions>(Name, configureOptions)); return this; } public virtual OptionsBuilder<TOptions> Configure<TDep>(Action<TOptions, TDep> configureOptions) where TDep : class { Action<TOptions, TDep> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2>(Action<TOptions, TDep1, TDep2> configureOptions) where TDep1 : class where TDep2 : class { Action<TOptions, TDep1, TDep2> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3>(Action<TOptions, TDep1, TDep2, TDep3> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class { Action<TOptions, TDep1, TDep2, TDep3> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3, TDep4>(Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class { Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep4>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2, TDep3, TDep4, TDep5>(Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class { Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep4>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep5>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> PostConfigure(Action<TOptions> configureOptions) { ThrowHelper.ThrowIfNull(configureOptions, "configureOptions"); ServiceCollectionServiceExtensions.AddSingleton<IPostConfigureOptions<TOptions>>(Services, (IPostConfigureOptions<TOptions>)new PostConfigureOptions<TOptions>(Name, configureOptions)); return this; } public virtual OptionsBuilder<TOptions> PostConfigure<TDep>(Action<TOptions, TDep> configureOptions) where TDep : class { Action<TOptions, TDep> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IPostConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IPostConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IPostConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2>(Action<TOptions, TDep1, TDep2> configureOptions) where TDep1 : class where TDep2 : class { Action<TOptions, TDep1, TDep2> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IPostConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IPostConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IPostConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3>(Action<TOptions, TDep1, TDep2, TDep3> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class { Action<TOptions, TDep1, TDep2, TDep3> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IPostConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IPostConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IPostConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4>(Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class { Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IPostConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IPostConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IPostConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep4>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4, TDep5>(Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class { Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions2 = configureOptions; ThrowHelper.ThrowIfNull(configureOptions2, "configureOptions"); ServiceCollectionServiceExtensions.AddTransient<IPostConfigureOptions<TOptions>>(Services, (Func<IServiceProvider, IPostConfigureOptions<TOptions>>)(object)(Func<IServiceProvider, IPostConfigureOptions<IServiceProvider>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep4>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep5>(sp), configureOptions2))); return this; } public virtual OptionsBuilder<TOptions> Validate(Func<TOptions, bool> validation) { return Validate(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate(Func<TOptions, bool> validation, string failureMessage) { ThrowHelper.ThrowIfNull(validation, "validation"); ServiceCollectionServiceExtensions.AddSingleton<IValidateOptions<TOptions>>(Services, (IValidateOptions<TOptions>)new ValidateOptions<TOptions>(Name, validation, failureMessage)); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep>(Func<TOptions, TDep, bool> validation) where TDep : notnull { return Validate<TDep>(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate<TDep>(Func<TOptions, TDep, bool> validation, string failureMessage) where TDep : notnull { Func<TOptions, TDep, bool> validation2 = validation; string failureMessage2 = failureMessage; ThrowHelper.ThrowIfNull(validation2, "validation"); ServiceCollectionServiceExtensions.AddTransient<IValidateOptions<TOptions>>(Services, (Func<IServiceProvider, IValidateOptions<TOptions>>)(object)(Func<IServiceProvider, IValidateOptions<IServiceProvider>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep>(sp), validation2, failureMessage2))); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2>(Func<TOptions, TDep1, TDep2, bool> validation) where TDep1 : notnull where TDep2 : notnull { return Validate<TDep1, TDep2>(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2>(Func<TOptions, TDep1, TDep2, bool> validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull { Func<TOptions, TDep1, TDep2, bool> validation2 = validation; string failureMessage2 = failureMessage; ThrowHelper.ThrowIfNull(validation2, "validation"); ServiceCollectionServiceExtensions.AddTransient<IValidateOptions<TOptions>>(Services, (Func<IServiceProvider, IValidateOptions<TOptions>>)(object)(Func<IServiceProvider, IValidateOptions<IServiceProvider>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), validation2, failureMessage2))); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3>(Func<TOptions, TDep1, TDep2, TDep3, bool> validation) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull { return Validate<TDep1, TDep2, TDep3>(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3>(Func<TOptions, TDep1, TDep2, TDep3, bool> validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull { Func<TOptions, TDep1, TDep2, TDep3, bool> validation2 = validation; string failureMessage2 = failureMessage; ThrowHelper.ThrowIfNull(validation2, "validation"); ServiceCollectionServiceExtensions.AddTransient<IValidateOptions<TOptions>>(Services, (Func<IServiceProvider, IValidateOptions<TOptions>>)(object)(Func<IServiceProvider, IValidateOptions<IServiceProvider>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), validation2, failureMessage2))); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull { return Validate<TDep1, TDep2, TDep3, TDep4>(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull { Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation2 = validation; string failureMessage2 = failureMessage; ThrowHelper.ThrowIfNull(validation2, "validation"); ServiceCollectionServiceExtensions.AddTransient<IValidateOptions<TOptions>>(Services, (Func<IServiceProvider, IValidateOptions<TOptions>>)(object)(Func<IServiceProvider, IValidateOptions<IServiceProvider>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep4>(sp), validation2, failureMessage2))); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4, TDep5>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull where TDep5 : notnull { return Validate<TDep1, TDep2, TDep3, TDep4, TDep5>(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4, TDep5>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull where TDep5 : notnull { Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation2 = validation; string failureMessage2 = failureMessage; ThrowHelper.ThrowIfNull(validation2, "validation"); ServiceCollectionServiceExtensions.AddTransient<IValidateOptions<TOptions>>(Services, (Func<IServiceProvider, IValidateOptions<TOptions>>)(object)(Func<IServiceProvider, IValidateOptions<IServiceProvider>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, ServiceProviderServiceExtensions.GetRequiredService<TDep1>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep2>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep3>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep4>(sp), ServiceProviderServiceExtensions.GetRequiredService<TDep5>(sp), validation2, failureMessage2))); return this; } } public class OptionsCache<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : IOptionsMonitorCache<TOptions> where TOptions : class { private readonly ConcurrentDictionary<string, Lazy<TOptions>> _cache = (ConcurrentDictionary<string, Lazy<TOptions>>)(object)new ConcurrentDictionary<string, Lazy<string>>(1, 31, (IEqualityComparer<string>)(object)StringComparer.Ordinal); public void Clear() { ((ConcurrentDictionary<string, Lazy<string>>)(object)_cache).Clear(); } public virtual TOptions GetOrAdd(string? name, Func<TOptions> createOptions) { ThrowHelper.ThrowIfNull(createOptions, "createOptions"); if (name == null) { name = Options.DefaultName; } Lazy<TOptions> orAdd = ((ConcurrentDictionary<string, Lazy<string>>)(object)_cache).GetOrAdd<Func<TOptions>>(name, (Func<string, Func<TOptions>, Lazy<string>>)(object)(Func<string, Func<string>, Lazy<string>>)((string name, Func<TOptions> createOptions) => new Lazy<TOptions>(createOptions)), createOptions); return orAdd.Value; } internal TOptions GetOrAdd<TArg>(string? name, Func<string, TArg, TOptions> createOptions, TArg factoryArgument) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) if (base.GetType() != typeof(OptionsCache<TOptions>)) { string localName = name; Func<string, TArg, TOptions> localCreateOptions = createOptions; TArg localFactoryArgument = factoryArgument; return GetOrAdd(name, () => ((Func<string, TArg, string>)(object)localCreateOptions).Invoke(localName ?? Options.DefaultName, localFactoryArgument)); } return ((ConcurrentDictionary<string, Lazy<string>>)(object)_cache).GetOrAdd<ValueTuple<Func<string, TArg, TOptions>, TArg>>(name ?? Options.DefaultName, (Func<string, ValueTuple<Func<string, TArg, TOptions>, TArg>, Lazy<string>>)(object)(Func<string, ValueTuple<Func<string, TArg, string>, TArg>, Lazy<string>>)((string name, ValueTuple<Func<string, TArg, TOptions>, TArg> arg) => new Lazy<TOptions>((Func<TOptions>)(() => ((Func<string, TArg, string>)(object)arg.Item1).Invoke(name, arg.Item2)))), (ValueTuple<Func<string, TArg, TOptions>, TArg>)new ValueTuple<Func<string, TArg, Func<string, TArg, TOptions>>, TArg>((Func<string, TArg, Func<string, TArg, TOptions>>)(object)createOptions, factoryArgument)).Value; } internal unsafe bool TryGetValue(string? name, [MaybeNullWhen(false)] out TOptions options) { Lazy<TOptions> val = default(Lazy<TOptions>); if (((ConcurrentDictionary<string, Lazy<string>>)(object)_cache).TryGetValue(name ?? Options.DefaultName, ref *(Lazy<string>*)(&val))) { options = val.Value; return true; } options = null; return false; } public virtual bool TryAdd(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); return ((ConcurrentDictionary<string, Lazy<string>>)(object)_cache).TryAdd(name ?? Options.DefaultName, (Lazy<string>)(object)new Lazy<TOptions>(options)); } public unsafe virtual bool TryRemove(string? name) { Lazy<TOptions> val = default(Lazy<TOptions>); return ((ConcurrentDictionary<string, Lazy<string>>)(object)_cache).TryRemove(name ?? Options.DefaultName, ref *(Lazy<string>*)(&val)); } } public class OptionsFactory<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : IOptionsFactory<TOptions> where TOptions : class { private readonly IConfigureOptions<TOptions>[] _setups; private readonly IPostConfigureOptions<TOptions>[] _postConfigures; private readonly IValidateOptions<TOptions>[] _validations; public OptionsFactory(System.Collections.Generic.IEnumerable<IConfigureOptions<TOptions>> setups, System.Collections.Generic.IEnumerable<IPostConfigureOptions<TOptions>> postConfigures) : this(setups, postConfigures, (System.Collections.Generic.IEnumerable<IValidateOptions<TOptions>>)System.Array.Empty<IValidateOptions<TOptions>>()) { } public OptionsFactory(System.Collections.Generic.IEnumerable<IConfigureOptions<TOptions>> setups, System.Collections.Generic.IEnumerable<IPostConfigureOptions<TOptions>> postConfigures, System.Collections.Generic.IEnumerable<IValidateOptions<TOptions>> validations) { _setups = (setups as IConfigureOptions<TOptions>[]) ?? new List<IConfigureOptions<IConfigureOptions<TOptions>>>((System.Collections.Generic.IEnumerable<IConfigureOptions<IConfigureOptions<TOptions>>>)setups).ToArray(); _postConfigures = (postConfigures as IPostConfigureOptions<TOptions>[]) ?? new List<IPostConfigureOptions<IPostConfigureOptions<TOptions>>>((System.Collections.Generic.IEnumerable<IPostConfigureOptions<IPostConfigureOptions<TOptions>>>)postConfigures).ToArray(); _validations = (validations as IValidateOptions<TOptions>[]) ?? new List<IValidateOptions<IValidateOptions<TOptions>>>((System.Collections.Generic.IEnumerable<IValidateOptions<IValidateOptions<TOptions>>>)validations).ToArray(); } public TOptions Create(string name) { TOptions val = CreateInstance(name); IConfigureOptions<TOptions>[] setups = _setups; foreach (IConfigureOptions<TOptions> configureOptions in setups) { if (configureOptions is IConfigureNamedOptions<TOptions> configureNamedOptions) { configureNamedOptions.Configure(name, val); } else if (name == Options.DefaultName) { configureOptions.Configure(val); } } IPostConfigureOptions<TOptions>[] postConfigures = _postConfigures; foreach (IPostConfigureOptions<TOptions> postConfigureOptions in postConfigures) { postConfigureOptions.PostConfigure(name, val); } if (_validations.Length != 0) { List<string> val2 = new List<string>(); IValidateOptions<TOptions>[] validations = _validations; foreach (IValidateOptions<TOptions> validateOptions in validations) { ValidateOptionsResult validateOptionsResult = validateOptions.Validate(name, val); if (validateOptionsResult != null && validateOptionsResult.Failed) { val2.AddRange(validateOptionsResult.Failures); } } if (val2.Count > 0) { throw new OptionsValidationException(name, typeof(TOptions), (System.Collections.Generic.IEnumerable<string>?)val2); } } return val; } protected virtual TOptions CreateInstance(string name) { return Activator.CreateInstance<TOptions>(); } } public class OptionsManager<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : IOptions<TOptions>, IOptionsSnapshot<TOptions> where TOptions : class { private readonly IOptionsFactory<TOptions> _factory; private readonly OptionsCache<TOptions> _cache = new OptionsCache<TOptions>(); public TOptions Value => Get(Options.DefaultName); public OptionsManager(IOptionsFactory<TOptions> factory) { _factory = factory; } public virtual TOptions Get(string? name) { if (name == null) { name = Options.DefaultName; } if (!_cache.TryGetValue(name, out var options)) { IOptionsFactory<TOptions> localFactory = _factory; string localName = name; return _cache.GetOrAdd(name, () => localFactory.Create(localName)); } return options; } } public class OptionsMonitor<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : IOptionsMonitor<TOptions>, System.IDisposable where TOptions : class { internal sealed class ChangeTrackerDisposable : System.IDisposable { private readonly Action<TOptions, string> _listener; private readonly OptionsMonitor<TOptions> _monitor; public ChangeTrackerDisposable(OptionsMonitor<TOptions> monitor, Action<TOptions, string> listener) { _listener = listener; _monitor = monitor; } public void OnChange(TOptions options, string name) { _listener.Invoke(options, name); } public void Dispose() { _monitor._onChange -= OnChange; } } private readonly IOptionsMonitorCache<TOptions> _cache; private readonly IOptionsFactory<TOptions> _factory; private readonly List<System.IDisposable> _registrations = new List<System.IDisposable>(); public TOptions CurrentValue => Get(Options.DefaultName); internal event Action<TOptions, string>? _onChange { [CompilerGenerated] add { Action<TOptions, string> val = this._onChange; Action<TOptions, string> val2; do { val2 = val; Action<TOptions, string> val3 = (Action<TOptions, string>)(object)System.Delegate.Combine((System.Delegate)(object)val2, (System.Delegate)(object)value); val = Interlocked.CompareExchange<Action<TOptions, string>>(ref this._onChange, val3, val2); } while (val != val2); } [CompilerGenerated] remove { Action<TOptions, string> val = this._onChange; Action<TOptions, string> val2; do { val2 = val; Action<TOptions, string> val3 = (Action<TOptions, string>)(object)System.Delegate.Remove((System.Delegate)(object)val2, (System.Delegate)(object)value); val = Interlocked.CompareExchange<Action<TOptions, string>>(ref this._onChange, val3, val2); } while (val != val2); } } public OptionsMonitor(IOptionsFactory<TOptions> factory, System.Collections.Generic.IEnumerable<IOptionsChangeTokenSource<TOptions>> sources, IOptionsMonitorCache<TOptions> cache) { _factory = factory; _cache = cache; if (sources is IOptionsChangeTokenSource<TOptions>[] array) { IOptionsChangeTokenSource<TOptions>[] array2 = array; foreach (IOptionsChangeTokenSource<TOptions> source2 in array2) { RegisterSource(source2); [CompilerGenerated] void RegisterSource(IOptionsChangeTokenSource<TOptions> source) { System.IDisposable disposable = ChangeToken.OnChange<string>((Func<IChangeToken>)source.GetChangeToken, (Action<string>)InvokeChanged, source.Name); _registrations.Add(disposable); } } return; } System.Collections.Generic.IEnumerator<IOptionsChangeTokenSource<TOptions>> enumerator = ((System.Collections.Generic.IEnumerable<IOptionsChangeTokenSource<IOptionsChangeTokenSource<TOptions>>>)sources).GetEnumerator(); try { while (((System.Collections.IEnumerator)enumerator).MoveNext()) { IOptionsChangeTokenSource<TOptions> current = ((System.Collections.Generic.IEnumerator<IOptionsChangeTokenSource<IOptionsChangeTokenSource<TOptions>>>)enumerator).Current; RegisterSource(current); } } finally { ((System.IDisposable)enumerator)?.Dispose(); } } private void InvokeChanged(string name) { if (name == null) { name = Options.DefaultName; } _cache.TryRemove(name); TOptions val = Get(name); this._onChange?.Invoke(val, name); } public virtual TOptions Get(string? name) { if (!(_cache is OptionsCache<TOptions> optionsCache)) { string localName = name ?? Options.DefaultName; IOptionsFactory<TOptions> localFactory = _factory; return _cache.GetOrAdd(localName, () => localFactory.Create(localName)); } return optionsCache.GetOrAdd(name, (Func<string, IOptionsFactory<TOptions>, TOptions>)(object)(Func<string, IOptionsFactory<string>, string>)((string name, IOptionsFactory<TOptions> factory) => factory.Create(name)), _factory); } public System.IDisposable OnChange(Action<TOptions, string> listener) { ChangeTrackerDisposable changeTrackerDisposable = new ChangeTrackerDisposable(this, listener); _onChange += changeTrackerDisposable.OnChange; return changeTrackerDisposable; } public void Dispose() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<System.IDisposable> enumerator = _registrations.GetEnumerator(); try { while (enumerator.MoveNext()) { System.IDisposable current = enumerator.Current; current.Dispose(); } } finally { ((System.IDisposable)enumerator).Dispose(); } _registrations.Clear(); } } public static class OptionsMonitorExtensions { public static System.IDisposable? OnChange<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions>(this IOptionsMonitor<TOptions> monitor, Action<TOptions> listener) { Action<TOptions> listener2 = listener; return monitor.OnChange(delegate(TOptions o, string _) { listener2.Invoke(o); }); } } public class OptionsValidationException : System.Exception { [field: CompilerGenerated] public string OptionsName { [CompilerGenerated] get; } [field: CompilerGenerated] public System.Type OptionsType { [CompilerGenerated] get; } [field: CompilerGenerated] public System.Collections.Generic.IEnumerable<string> Failures { [CompilerGenerated] get; } public override string Message => string.Join("; ", Failures); public OptionsValidationException(string optionsName, System.Type optionsType, System.Collections.Generic.IEnumerable<string>? failureMessages) { ThrowHelper.ThrowIfNull(optionsName, "optionsName"); ThrowHelper.ThrowIfNull(optionsType, "optionsType"); Failures = (System.Collections.Generic.IEnumerable<string>)(((object)failureMessages) ?? ((object)new List<string>())); OptionsType = optionsType; OptionsName = optionsName; } } public class OptionsWrapper<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : IOptions<TOptions> where TOptions : class { public TOptions Value { [CompilerGenerated] get; } public OptionsWrapper(TOptions options) { Value = options; } } public class PostConfigureOptions<TOptions> : IPostConfigureOptions<TOptions> where TOptions : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions>? Action { [CompilerGenerated] get; } public PostConfigureOptions(string? name, Action<TOptions>? action) { Name = name; Action = action; } public virtual void PostConfigure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options); } } } public class PostConfigureOptions<TOptions, TDep> : IPostConfigureOptions<TOptions> where TOptions : class where TDep : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep>? Action { [CompilerGenerated] get; } public TDep Dependency { [CompilerGenerated] get; } public PostConfigureOptions(string? name, TDep dependency, Action<TOptions, TDep>? action) { Name = name; Action = action; Dependency = dependency; } public virtual void PostConfigure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency); } } public void PostConfigure(TOptions options) { PostConfigure(Options.DefaultName, options); } } public class PostConfigureOptions<TOptions, TDep1, TDep2> : IPostConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep1, TDep2>? Action { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public PostConfigureOptions(string? name, TDep1 dependency, TDep2 dependency2, Action<TOptions, TDep1, TDep2>? action) { Name = name; Action = action; Dependency1 = dependency; Dependency2 = dependency2; } public virtual void PostConfigure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency1, Dependency2); } } public void PostConfigure(TOptions options) { PostConfigure(Options.DefaultName, options); } } public class PostConfigureOptions<TOptions, TDep1, TDep2, TDep3> : IPostConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep1, TDep2, TDep3>? Action { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public PostConfigureOptions(string? name, TDep1 dependency, TDep2 dependency2, TDep3 dependency3, Action<TOptions, TDep1, TDep2, TDep3>? action) { Name = name; Action = action; Dependency1 = dependency; Dependency2 = dependency2; Dependency3 = dependency3; } public virtual void PostConfigure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency1, Dependency2, Dependency3); } } public void PostConfigure(TOptions options) { PostConfigure(Options.DefaultName, options); } } public class PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4> : IPostConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep1, TDep2, TDep3, TDep4>? Action { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public TDep4 Dependency4 { [CompilerGenerated] get; } public PostConfigureOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Action<TOptions, TDep1, TDep2, TDep3, TDep4>? action) { Name = name; Action = action; Dependency1 = dependency1; Dependency2 = dependency2; Dependency3 = dependency3; Dependency4 = dependency4; } public virtual void PostConfigure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4); } } public void PostConfigure(TOptions options) { PostConfigure(Options.DefaultName, options); } } public class PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> : IPostConfigureOptions<TOptions> where TOptions : class where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class { public string? Name { [CompilerGenerated] get; } public Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>? Action { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public TDep4 Dependency4 { [CompilerGenerated] get; } public TDep5 Dependency5 { [CompilerGenerated] get; } public PostConfigureOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>? action) { Name = name; Action = action; Dependency1 = dependency1; Dependency2 = dependency2; Dependency3 = dependency3; Dependency4 = dependency4; Dependency5 = dependency5; } public virtual void PostConfigure(string? name, TOptions options) { ThrowHelper.ThrowIfNull(options, "options"); if (Name == null || name == Name) { Action?.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4, Dependency5); } } public void PostConfigure(TOptions options) { PostConfigure(Options.DefaultName, options); } } internal sealed class UnnamedOptionsManager<[DynamicallyAccessedMembers(/*Could not decode attribute arguments.*/)] TOptions> : IOptions<TOptions> where TOptions : class { private readonly IOptionsFactory<TOptions> _factory; private volatile object _syncObj; private volatile TOptions _value; public TOptions Value { get { TOptions value = _value; if (value != null) { return value; } lock (_syncObj ?? Interlocked.CompareExchange(ref _syncObj, new object(), (object)null) ?? _syncObj) { return _value ?? (_value = _factory.Create(Options.DefaultName)); } } } public UnnamedOptionsManager(IOptionsFactory<TOptions> factory) { _factory = factory; } } public class ValidateOptions<TOptions> : IValidateOptions<TOptions> where TOptions : class { public string? Name { [CompilerGenerated] get; } public Func<TOptions, bool> Validation { [CompilerGenerated] get; } public string FailureMessage { [CompilerGenerated] get; } public ValidateOptions(string? name, Func<TOptions, bool> validation, string failureMessage) { ThrowHelper.ThrowIfNull(validation, "validation"); Name = name; Validation = validation; FailureMessage = failureMessage; } public ValidateOptionsResult Validate(string? name, TOptions options) { if (Name == null || name == Name) { if (Validation.Invoke(options)) { return ValidateOptionsResult.Success; } return ValidateOptionsResult.Fail(FailureMessage); } return ValidateOptionsResult.Skip; } } public class ValidateOptions<TOptions, TDep> : IValidateOptions<TOptions> where TOptions : class { public string? Name { [CompilerGenerated] get; } public Func<TOptions, TDep, bool> Validation { [CompilerGenerated] get; } public string FailureMessage { [CompilerGenerated] get; } public TDep Dependency { [CompilerGenerated] get; } public ValidateOptions(string? name, TDep dependency, Func<TOptions, TDep, bool> validation, string failureMessage) { ThrowHelper.ThrowIfNull(validation, "validation"); Name = name; Validation = validation; FailureMessage = failureMessage; Dependency = dependency; } public ValidateOptionsResult Validate(string? name, TOptions options) { if (Name == null || name == Name) { if (Validation.Invoke(options, Dependency)) { return ValidateOptionsResult.Success; } return ValidateOptionsResult.Fail(FailureMessage); } return ValidateOptionsResult.Skip; } } public class ValidateOptions<TOptions, TDep1, TDep2> : IValidateOptions<TOptions> where TOptions : class { public string? Name { [CompilerGenerated] get; } public Func<TOptions, TDep1, TDep2, bool> Validation { [CompilerGenerated] get; } public string FailureMessage { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, Func<TOptions, TDep1, TDep2, bool> validation, string failureMessage) { ThrowHelper.ThrowIfNull(validation, "validation"); Name = name; Validation = validation; FailureMessage = failureMessage; Dependency1 = dependency1; Dependency2 = dependency2; } public ValidateOptionsResult Validate(string? name, TOptions options) { if (Name == null || name == Name) { if (Validation.Invoke(options, Dependency1, Dependency2)) { return ValidateOptionsResult.Success; } return ValidateOptionsResult.Fail(FailureMessage); } return ValidateOptionsResult.Skip; } } public class ValidateOptions<TOptions, TDep1, TDep2, TDep3> : IValidateOptions<TOptions> where TOptions : class { public string? Name { [CompilerGenerated] get; } public Func<TOptions, TDep1, TDep2, TDep3, bool> Validation { [CompilerGenerated] get; } public string FailureMessage { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, Func<TOptions, TDep1, TDep2, TDep3, bool> validation, string failureMessage) { ThrowHelper.ThrowIfNull(validation, "validation"); Name = name; Validation = validation; FailureMessage = failureMessage; Dependency1 = dependency1; Dependency2 = dependency2; Dependency3 = dependency3; } public ValidateOptionsResult Validate(string? name, TOptions options) { if (Name == null || name == Name) { if (Validation.Invoke(options, Dependency1, Dependency2, Dependency3)) { return ValidateOptionsResult.Success; } return ValidateOptionsResult.Fail(FailureMessage); } return ValidateOptionsResult.Skip; } } public class ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4> : IValidateOptions<TOptions> where TOptions : class { public string? Name { [CompilerGenerated] get; } public Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> Validation { [CompilerGenerated] get; } public string FailureMessage { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public TDep4 Dependency4 { [CompilerGenerated] get; } public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation, string failureMessage) { ThrowHelper.ThrowIfNull(validation, "validation"); Name = name; Validation = validation; FailureMessage = failureMessage; Dependency1 = dependency1; Dependency2 = dependency2; Dependency3 = dependency3; Dependency4 = dependency4; } public ValidateOptionsResult Validate(string? name, TOptions options) { if (Name == null || name == Name) { if (Validation.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4)) { return ValidateOptionsResult.Success; } return ValidateOptionsResult.Fail(FailureMessage); } return ValidateOptionsResult.Skip; } } public class ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> : IValidateOptions<TOptions> where TOptions : class { public string? Name { [CompilerGenerated] get; } public Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> Validation { [CompilerGenerated] get; } public string FailureMessage { [CompilerGenerated] get; } public TDep1 Dependency1 { [CompilerGenerated] get; } public TDep2 Dependency2 { [CompilerGenerated] get; } public TDep3 Dependency3 { [CompilerGenerated] get; } public TDep4 Dependency4 { [CompilerGenerated] get; } public TDep5 Dependency5 { [CompilerGenerated] get; } public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation, string failureMessage) { ThrowHelper.ThrowIfNull(validation, "validation"); Name = name; Validation = validation; FailureMessage = failureMessage; Dependency1 = dependency1; Dependency2 = dependency2; Dependency3 = dependency3; Dependency4 = dependency4; Dependency5 = dependency5; } public ValidateOptionsResult Validate(string? name, TOptions options) { if (Name == null || name == Name) { if (Validation.Invoke(options, Dependency1, Dependency2, Dependency3, Dependency4, Dependency5)) { return ValidateOptionsResult.Success; } return ValidateOptionsResult.Fail(FailureMessage); } return ValidateOptionsResult.Skip; } } public class ValidateOptionsResult { public static readonly ValidateOptionsResult Skip = new ValidateOptionsResult { Skipped = true }; public static readonly ValidateOptionsResult Success = new ValidateOptionsResult { Succeeded = true }; [field: CompilerGenerated] public bool Succeeded { [CompilerGenerated] get; [CompilerGenerated] protected set; } [field: CompilerGenerated] public bool Skipped { [CompilerGenerated] get; [CompilerGenerated] protected set; } [MemberNotNullWhen(true, "Failures")] [MemberNotNullWhen(true, "FailureMessage")] [field: CompilerGenerated] public bool Failed { [CompilerGenerated] [MemberNotNullWhen(true, "Failures")] [MemberNotNullWhen(true, "FailureMessage")] get; [CompilerGenerated] [MemberNotNullWhen(true, "Failures")] [MemberNotNullWhen(true, "FailureMessage")] protected set; } [field: CompilerGenerated] public string? FailureMessage { [CompilerGenerated] get; [CompilerGenerated] protected set; } [field: CompilerGenerated] public System.Collections.Generic.IEnumerable<string>? Failures { [CompilerGenerated] get; [CompilerGenerated] protected set; } public static ValidateOptionsResult Fail(string failureMessage) { ValidateOptionsResult validateOptionsResult = new ValidateOptionsResult(); validateOptionsResult.Failed = true; validateOptionsResult.FailureMessage = failureMessage; validateOptionsResult.Failures = new string[1] { failureMessage }; return validateOptionsResult; } public static ValidateOptionsResult Fail(System.Collections.Generic.IEnumerable<string> failures) { return new ValidateOptionsResult { Failed = true, FailureMessage = string.Join("; ", failures), Failures = failures }; } } }
AuriePack/AurieInstaller/Microsoft.Extensions.Primitives.dll
Decompiled a year agousing System; using System.Buffers; using System.Collections; using System.Collections.Generic; 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; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Primitives")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: DefaultDllImportSearchPaths(/*Could not decode attribute arguments.*/)] [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("7.0.22.51805")] [assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Primitives")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(8, SkipVerification = true)] [assembly: AssemblyVersion("7.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullablePublicOnlyAttribute : System.Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.Primitives { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager { get { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown object obj = s_resourceManager; if (obj == null) { ResourceManager val = new ResourceManager(typeof(FxResources.Microsoft.Extensions.Primitives.SR)); s_resourceManager = val; obj = (object)val; } return (ResourceManager)obj; } } 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 UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", new object[2] { resourceFormat, p1 }); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", new object[3] { 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(", ", new object[4] { 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(", ", new object[2] { 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(", ", new object[3] { 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(", ", new object[4] { 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; } static SR() { bool flag = default(bool); s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", ref flag) && flag; } } } namespace System.Numerics.Hashing { internal static class HashHelpers { public static int Combine(int h1, int h2) { uint num = (uint)(h1 << 5) | ((uint)h1 >> 27); return ((int)num + h1) ^ h2; } } } namespace Microsoft.Extensions.Primitives { public class CancellationChangeToken : IChangeToken { private sealed class NullDisposable : System.IDisposable { public static readonly NullDisposable Instance = new NullDisposable(); public void Dispose() { } } [field: CompilerGenerated] public bool ActiveChangeCallbacks { [CompilerGenerated] get; [CompilerGenerated] private set; } = true; public bool HasChanged { get { //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) CancellationToken token = Token; return ((CancellationToken)(ref token)).IsCancellationRequested; } } [field: CompilerGenerated] private CancellationToken Token { [CompilerGenerated] get; } public CancellationChangeToken(CancellationToken cancellationToken) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) Token = cancellationToken; } public System.IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { //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) //IL_000b: Unknown result type (might be due to invalid IL or missing references) try { CancellationToken token = Token; return (System.IDisposable)(object)((CancellationToken)(ref token)).UnsafeRegister(callback, state); } catch (ObjectDisposedException) { ActiveChangeCallbacks = false; } return NullDisposable.Instance; } } public static class ChangeToken { private sealed class ChangeTokenRegistration<TState> : System.IDisposable { private sealed class NoopDisposable : System.IDisposable { public void Dispose() { } } private readonly Func<IChangeToken> _changeTokenProducer; private readonly Action<TState> _changeTokenConsumer; private readonly TState _state; private System.IDisposable _disposable; private static readonly NoopDisposable _disposedSentinel = new NoopDisposable(); public ChangeTokenRegistration(Func<IChangeToken> changeTokenProducer, Action<TState> changeTokenConsumer, TState state) { _changeTokenProducer = changeTokenProducer; _changeTokenConsumer = changeTokenConsumer; _state = state; IChangeToken token = changeTokenProducer.Invoke(); RegisterChangeTokenCallback(token); } private void OnChangeTokenFired() { IChangeToken token = _changeTokenProducer.Invoke(); try { _changeTokenConsumer.Invoke(_state); } finally { RegisterChangeTokenCallback(token); } } private void RegisterChangeTokenCallback(IChangeToken token) { if (token != null) { System.IDisposable disposable = token.RegisterChangeCallback(delegate(object s) { ((ChangeTokenRegistration<TState>)s).OnChangeTokenFired(); }, this); SetDisposable(disposable); } } private void SetDisposable(System.IDisposable disposable) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) System.IDisposable disposable2 = Volatile.Read<System.IDisposable>(ref _disposable); if (disposable2 == _disposedSentinel) { disposable.Dispose(); return; } System.IDisposable disposable3 = Interlocked.CompareExchange<System.IDisposable>(ref _disposable, disposable, disposable2); if (disposable3 == _disposedSentinel) { disposable.Dispose(); } else if (disposable3 != disposable2) { throw new InvalidOperationException("Somebody else set the _disposable field"); } } public void Dispose() { Interlocked.Exchange<System.IDisposable>(ref _disposable, (System.IDisposable)_disposedSentinel)?.Dispose(); } } public static System.IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Action changeTokenConsumer) { if (changeTokenProducer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer); } if (changeTokenConsumer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer); } return new ChangeTokenRegistration<Action>(changeTokenProducer, delegate(Action callback) { callback.Invoke(); }, changeTokenConsumer); } public static System.IDisposable OnChange<TState>(Func<IChangeToken?> changeTokenProducer, Action<TState> changeTokenConsumer, TState state) { if (changeTokenProducer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer); } if (changeTokenConsumer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer); } return new ChangeTokenRegistration<TState>(changeTokenProducer, changeTokenConsumer, state); } } public class CompositeChangeToken : IChangeToken { private static readonly Action<object> _onChangeDelegate = OnChange; private readonly object _callbackLock = new object(); private CancellationTokenSource _cancellationTokenSource; private List<System.IDisposable> _disposables; [MemberNotNullWhen(true, "_cancellationTokenSource")] [MemberNotNullWhen(true, "_disposables")] [field: CompilerGenerated] private bool RegisteredCallbackProxy { [CompilerGenerated] [MemberNotNullWhen(true, "_cancellationTokenSource")] [MemberNotNullWhen(true, "_disposables")] get; [CompilerGenerated] [MemberNotNullWhen(true, "_cancellationTokenSource")] [MemberNotNullWhen(true, "_disposables")] set; } [field: CompilerGenerated] public System.Collections.Generic.IReadOnlyList<IChangeToken> ChangeTokens { [CompilerGenerated] get; } public bool HasChanged { get { //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) if (_cancellationTokenSource != null) { CancellationToken token = _cancellationTokenSource.Token; if (((CancellationToken)(ref token)).IsCancellationRequested) { return true; } } for (int i = 0; i < ((System.Collections.Generic.IReadOnlyCollection<IChangeToken>)ChangeTokens).Count; i++) { if (ChangeTokens[i].HasChanged) { OnChange(this); return true; } } return false; } } [field: CompilerGenerated] public bool ActiveChangeCallbacks { [CompilerGenerated] get; } public CompositeChangeToken(System.Collections.Generic.IReadOnlyList<IChangeToken> changeTokens) { if (changeTokens == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokens); } ChangeTokens = changeTokens; for (int i = 0; i < ((System.Collections.Generic.IReadOnlyCollection<IChangeToken>)ChangeTokens).Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { ActiveChangeCallbacks = true; break; } } } public System.IDisposable RegisterChangeCallback(Action<object?> callback, object? state) { //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_0016: Unknown result type (might be due to invalid IL or missing references) EnsureCallbacksInitialized(); CancellationToken token = _cancellationTokenSource.Token; return (System.IDisposable)(object)((CancellationToken)(ref token)).Register(callback, state); } [MemberNotNull("_cancellationTokenSource")] [MemberNotNull("_disposables")] private void EnsureCallbacksInitialized() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown if (RegisteredCallbackProxy) { return; } lock (_callbackLock) { if (RegisteredCallbackProxy) { return; } _cancellationTokenSource = new CancellationTokenSource(); _disposables = new List<System.IDisposable>(); for (int i = 0; i < ((System.Collections.Generic.IReadOnlyCollection<IChangeToken>)ChangeTokens).Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { System.IDisposable disposable = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this); if (_cancellationTokenSource.IsCancellationRequested) { disposable.Dispose(); break; } _disposables.Add(disposable); } } RegisteredCallbackProxy = true; } } private static void OnChange(object state) { CompositeChangeToken compositeChangeToken = (CompositeChangeToken)state; if (compositeChangeToken._cancellationTokenSource == null) { return; } lock (compositeChangeToken._callbackLock) { try { compositeChangeToken._cancellationTokenSource.Cancel(); } catch { } } List<System.IDisposable> disposables = compositeChangeToken._disposables; for (int i = 0; i < disposables.Count; i++) { disposables[i].Dispose(); } } } public static class Extensions { public static StringBuilder Append(this StringBuilder builder, StringSegment segment) { return builder.Append(segment.Buffer, segment.Offset, segment.Length); } } public interface IChangeToken { bool HasChanged { get; } bool ActiveChangeCallbacks { get; } System.IDisposable RegisterChangeCallback(Action<object?> callback, object? state); } [DefaultMember("Item")] public readonly struct StringSegment : IEquatable<StringSegment>, IEquatable<string?> { public static readonly StringSegment Empty = string.Empty; [field: CompilerGenerated] public string? Buffer { [CompilerGenerated] get; } [field: CompilerGenerated] public int Offset { [CompilerGenerated] get; } [field: CompilerGenerated] public int Length { [CompilerGenerated] get; } public string? Value { get { if (!HasValue) { return null; } return Buffer.Substring(Offset, Length); } } [MemberNotNullWhen(true, "Buffer")] [MemberNotNullWhen(true, "Value")] public bool HasValue { [MemberNotNullWhen(true, "Buffer")] [MemberNotNullWhen(true, "Value")] get { return Buffer != null; } } public char this[int index] { get { if ((uint)index >= (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return Buffer[Offset + index]; } } public StringSegment(string? buffer) { Buffer = buffer; Offset = 0; Length = buffer?.Length ?? 0; } [MethodImpl(256)] public StringSegment(string buffer, int offset, int length) { if (buffer == null || (uint)offset > (uint)buffer.Length || (uint)length > (uint)(buffer.Length - offset)) { ThrowInvalidArguments(buffer, offset, length); } Buffer = buffer; Offset = offset; Length = length; } public System.ReadOnlySpan<char> AsSpan() { return MemoryExtensions.AsSpan(Buffer, Offset, Length); } public System.ReadOnlySpan<char> AsSpan(int start) { if (!HasValue || start < 0) { ThrowInvalidArguments(start, Length - start, ExceptionArgument.start); } return MemoryExtensions.AsSpan(Buffer, Offset + start, Length - start); } public System.ReadOnlySpan<char> AsSpan(int start, int length) { if (!HasValue || start < 0 || length < 0 || (uint)(start + length) > (uint)Length) { ThrowInvalidArguments(start, length, ExceptionArgument.start); } return MemoryExtensions.AsSpan(Buffer, Offset + start, length); } public ReadOnlyMemory<char> AsMemory() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return MemoryExtensions.AsMemory(Buffer, Offset, Length); } public static int Compare(StringSegment a, StringSegment b, StringComparison comparisonType) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (a.HasValue && b.HasValue) { return MemoryExtensions.CompareTo(a.AsSpan(), b.AsSpan(), comparisonType); } CheckStringComparison(comparisonType); if (a.HasValue) { return 1; } if (!b.HasValue) { return 0; } return -1; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is StringSegment other) { return Equals(other); } return false; } public bool Equals(StringSegment other) { return Equals(other, (StringComparison)4); } public bool Equals(StringSegment other, StringComparison comparisonType) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (HasValue && other.HasValue) { return MemoryExtensions.Equals(AsSpan(), other.AsSpan(), comparisonType); } CheckStringComparison(comparisonType); if (!HasValue) { return !other.HasValue; } return false; } public static bool Equals(StringSegment a, StringSegment b, StringComparison comparisonType) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return a.Equals(b, comparisonType); } public bool Equals(string? text) { return Equals(text, (StringComparison)4); } [MethodImpl(256)] public bool Equals(string? text, StringComparison comparisonType) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (!HasValue || text == null) { CheckStringComparison(comparisonType); return text == Buffer; } return MemoryExtensions.Equals(AsSpan(), MemoryExtensions.AsSpan(text), comparisonType); } [MethodImpl(256)] public override int GetHashCode() { return string.GetHashCode(AsSpan()); } public static bool operator ==(StringSegment left, StringSegment right) { return left.Equals(right); } public static bool operator !=(StringSegment left, StringSegment right) { return !left.Equals(right); } public static implicit operator StringSegment(string? value) { return new StringSegment(value); } public static implicit operator System.ReadOnlySpan<char>(StringSegment segment) { return segment.AsSpan(); } public static implicit operator ReadOnlyMemory<char>(StringSegment segment) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return segment.AsMemory(); } [MethodImpl(256)] public bool StartsWith(string text, StringComparison comparisonType) { //IL_0025: 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) if (text == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } if (!HasValue) { CheckStringComparison(comparisonType); return false; } return MemoryExtensions.StartsWith(AsSpan(), MemoryExtensions.AsSpan(text), comparisonType); } [MethodImpl(256)] public bool EndsWith(string text, StringComparison comparisonType) { //IL_0025: 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) if (text == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } if (!HasValue) { CheckStringComparison(comparisonType); return false; } return MemoryExtensions.EndsWith(AsSpan(), MemoryExtensions.AsSpan(text), comparisonType); } public string Substring(int offset) { return Substring(offset, Length - offset); } [MethodImpl(256)] public string Substring(int offset, int length) { if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length) { ThrowInvalidArguments(offset, length, ExceptionArgument.offset); } return Buffer.Substring(Offset + offset, length); } public StringSegment Subsegment(int offset) { return Subsegment(offset, Length - offset); } public StringSegment Subsegment(int offset, int length) { if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length) { ThrowInvalidArguments(offset, length, ExceptionArgument.offset); } return new StringSegment(Buffer, Offset + offset, length); } [MethodImpl(256)] public int IndexOf(char c, int start, int count) { int num = -1; if (HasValue) { if ((uint)start > (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if ((uint)count > (uint)(Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } num = MemoryExtensions.IndexOf<char>(AsSpan(start, count), c); if (num >= 0) { num += start; } } return num; } public int IndexOf(char c, int start) { return IndexOf(c, start, Length - start); } public int IndexOf(char c) { return IndexOf(c, 0, Length); } [MethodImpl(256)] public int IndexOfAny(char[] anyOf, int startIndex, int count) { int num = -1; if (HasValue) { if ((uint)startIndex > (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if ((uint)count > (uint)(Length - startIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } num = Buffer.IndexOfAny(anyOf, Offset + startIndex, count); if (num != -1) { num -= Offset; } } return num; } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, Length - startIndex); } public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, Length); } public int LastIndexOf(char value) { return MemoryExtensions.LastIndexOf<char>(AsSpan(), value); } public StringSegment Trim() { return TrimStart().TrimEnd(); } public unsafe StringSegment TrimStart() { System.ReadOnlySpan<char> readOnlySpan = AsSpan(); int i; for (i = 0; i < readOnlySpan.Length && char.IsWhiteSpace(*(char*)readOnlySpan[i]); i++) { } return Subsegment(i); } public unsafe StringSegment TrimEnd() { System.ReadOnlySpan<char> readOnlySpan = AsSpan(); int num = readOnlySpan.Length - 1; while (num >= 0 && char.IsWhiteSpace(*(char*)readOnlySpan[num])) { num--; } return Subsegment(0, num + 1); } public StringTokenizer Split(char[] chars) { return new StringTokenizer(this, chars); } public static bool IsNullOrEmpty(StringSegment value) { bool result = false; if (!value.HasValue || value.Length == 0) { result = true; } return result; } public override string ToString() { return Value ?? string.Empty; } private static void CheckStringComparison(StringComparison comparisonType) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 if ((int)comparisonType > 5) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.comparisonType); } } [DoesNotReturn] private static void ThrowInvalidArguments(string buffer, int offset, int length) { throw GetInvalidArgumentsException(); [CompilerGenerated] System.Exception GetInvalidArgumentsException() { if (buffer == null) { return (System.Exception)(object)ThrowHelper.GetArgumentNullException(ExceptionArgument.buffer); } if (offset < 0) { return (System.Exception)(object)ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.offset); } if (length < 0) { return (System.Exception)(object)ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length); } return (System.Exception)(object)ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLength); } } [DoesNotReturn] private void ThrowInvalidArguments(int offset, int length, ExceptionArgument offsetOrStart) { throw GetInvalidArgumentsException(HasValue); [CompilerGenerated] System.Exception GetInvalidArgumentsException(bool hasValue) { if (!hasValue) { return (System.Exception)(object)ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart); } if (offset < 0) { return (System.Exception)(object)ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart); } if (length < 0) { return (System.Exception)(object)ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length); } return (System.Exception)(object)ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLengthStringSegment); } } } public class StringSegmentComparer : IComparer<StringSegment>, IEqualityComparer<StringSegment> { [field: CompilerGenerated] public static StringSegmentComparer Ordinal { [CompilerGenerated] get; } = new StringSegmentComparer((StringComparison)4, StringComparer.Ordinal); [field: CompilerGenerated] public static StringSegmentComparer OrdinalIgnoreCase { [CompilerGenerated] get; } = new StringSegmentComparer((StringComparison)5, StringComparer.OrdinalIgnoreCase); [field: CompilerGenerated] private StringComparison Comparison { [CompilerGenerated] get; } [field: CompilerGenerated] private StringComparer Comparer { [CompilerGenerated] get; } private StringSegmentComparer(StringComparison comparison, StringComparer comparer) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) Comparison = comparison; Comparer = comparer; } public int Compare(StringSegment x, StringSegment y) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return StringSegment.Compare(x, y, Comparison); } public bool Equals(StringSegment x, StringSegment y) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return StringSegment.Equals(x, y, Comparison); } public int GetHashCode(StringSegment obj) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) return string.GetHashCode(obj.AsSpan(), Comparison); } } public readonly struct StringTokenizer : System.Collections.Generic.IEnumerable<StringSegment>, System.Collections.IEnumerable { public struct Enumerator : System.Collections.Generic.IEnumerator<StringSegment>, System.Collections.IEnumerator, System.IDisposable { private readonly StringSegment _value; private readonly char[] _separators; private int _index; [field: CompilerGenerated] public StringSegment Current { [CompilerGenerated] get; [CompilerGenerated] private set; } object System.Collections.IEnumerator.Current => Current; internal Enumerator(in StringSegment value, char[] separators) { _value = value; _separators = separators; Current = default(StringSegment); _index = 0; } public Enumerator(ref StringTokenizer tokenizer) { _value = tokenizer._value; _separators = tokenizer._separators; Current = default(StringSegment); _index = 0; } public void Dispose() { } public bool MoveNext() { if (!_value.HasValue || _index > _value.Length) { Current = default(StringSegment); return false; } int num = _value.IndexOfAny(_separators, _index); if (num == -1) { num = _value.Length; } Current = _value.Subsegment(_index, num - _index); _index = num + 1; return true; } public void Reset() { Current = default(StringSegment); _index = 0; } } private readonly StringSegment _value; private readonly char[] _separators; public StringTokenizer(string value, char[] separators) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (separators == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators); } _value = value; _separators = separators; } public StringTokenizer(StringSegment value, char[] separators) { if (!value.HasValue) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (separators == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators); } _value = value; _separators = separators; } public Enumerator GetEnumerator() { return new Enumerator(in _value, _separators); } System.Collections.Generic.IEnumerator<StringSegment> System.Collections.Generic.IEnumerable<StringSegment>.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } [DefaultMember("Item")] public readonly struct StringValues : System.Collections.Generic.IList<string?>, System.Collections.Generic.ICollection<string?>, System.Collections.Generic.IEnumerable<string?>, System.Collections.IEnumerable, System.Collections.Generic.IReadOnlyList<string?>, System.Collections.Generic.IReadOnlyCollection<string?>, IEquatable<StringValues>, IEquatable<string?>, IEquatable<string?[]?> { public struct Enumerator : System.Collections.Generic.IEnumerator<string?>, System.Collections.IEnumerator, System.IDisposable { private readonly string[] _values; private int _index; private string _current; public string? Current => _current; object? System.Collections.IEnumerator.Current => _current; internal Enumerator(object value) { if (value is string current) { _values = null; _current = current; } else { _current = null; _values = System.Runtime.CompilerServices.Unsafe.As<string[]>(value); } _index = 0; } public Enumerator(ref StringValues values) : this(values._values) { } public bool MoveNext() { int index = _index; if (index < 0) { return false; } string[] values = _values; if (values != null) { if ((uint)index < (uint)values.Length) { _index = index + 1; _current = values[index]; return true; } _index = -1; return false; } _index = -1; return _current != null; } void System.Collections.IEnumerator.Reset() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } public void Dispose() { } } public static readonly StringValues Empty = new StringValues(System.Array.Empty<string>()); private readonly object _values; public int Count { [MethodImpl(256)] get { object values = _values; if (values == null) { return 0; } if (values is string) { return 1; } return System.Runtime.CompilerServices.Unsafe.As<string[]>(values).Length; } } bool System.Collections.Generic.ICollection<string>.IsReadOnly => true; string? System.Collections.Generic.IList<string>.this[int index] { get { return this[index]; } set { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } } public string? this[int index] { [MethodImpl(256)] get { object values = _values; if (values is string result) { if (index == 0) { return result; } } else if (values != null) { return System.Runtime.CompilerServices.Unsafe.As<string[]>(values)[index]; } return OutOfBounds(); } } public StringValues(string? value) { _values = value; } public StringValues(string?[]? values) { _values = values; } public static implicit operator StringValues(string? value) { return new StringValues(value); } public static implicit operator StringValues(string?[]? values) { return new StringValues(values); } public static implicit operator string?(StringValues values) { return values.GetStringValue(); } public static implicit operator string?[]?(StringValues value) { return value.GetArrayValue(); } [MethodImpl(8)] private static string OutOfBounds() { return System.Array.Empty<string>()[0]; } public override string ToString() { return GetStringValue() ?? string.Empty; } private string GetStringValue() { object values2 = _values; if (values2 is string result) { return result; } return GetStringValueFromArray(values2); [CompilerGenerated] static string GetJoinedStringValueFromArray(string[] values) { int num = 0; foreach (string text in values) { if (text != null && text.Length > 0) { if (num > 0) { num++; } num += text.Length; } } return string.Create<string[]>(num, values, (SpanAction<char, string[]>)delegate(System.Span<char> span, string[] strings) { int num2 = 0; foreach (string text2 in strings) { if (text2 != null && text2.Length > 0) { if (num2 > 0) { span[num2] = ','; num2++; } MemoryExtensions.AsSpan(text2).CopyTo(span.Slice(num2)); num2 += text2.Length; } } }); } [CompilerGenerated] static string GetStringValueFromArray(object value) { if (value == null) { return null; } string[] array = System.Runtime.CompilerServices.Unsafe.As<string[]>(value); return array.Length switch { 0 => null, 1 => array[0], _ => GetJoinedStringValueFromArray(array), }; } } public string?[] ToArray() { return GetArrayValue() ?? System.Array.Empty<string>(); } private string[] GetArrayValue() { object values = _values; if (values is string[] result) { return result; } if (values != null) { return new string[1] { System.Runtime.CompilerServices.Unsafe.As<string>(values) }; } return null; } int System.Collections.Generic.IList<string>.IndexOf(string item) { return IndexOf(item); } private int IndexOf(string item) { object values = _values; if (values is string[] array) { for (int i = 0; i < array.Length; i++) { if (string.Equals(array[i], item, (StringComparison)4)) { return i; } } return -1; } if (values != null) { if (!string.Equals(System.Runtime.CompilerServices.Unsafe.As<string>(values), item, (StringComparison)4)) { return -1; } return 0; } return -1; } bool System.Collections.Generic.ICollection<string>.Contains(string item) { return IndexOf(item) >= 0; } void System.Collections.Generic.ICollection<string>.CopyTo(string[] array, int arrayIndex) { CopyTo(array, arrayIndex); } private void CopyTo(string[] array, int arrayIndex) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) object values = _values; if (values is string[] array2) { System.Array.Copy((System.Array)array2, 0, (System.Array)array, arrayIndex, array2.Length); } else if (values != null) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex"); } if (array.Length - arrayIndex < 1) { throw new ArgumentException("'array' is not long enough to copy all the items in the collection. Check 'arrayIndex' and 'array' length."); } array[arrayIndex] = System.Runtime.CompilerServices.Unsafe.As<string>(values); } } void System.Collections.Generic.ICollection<string>.Add(string item) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } void System.Collections.Generic.IList<string>.Insert(int index, string item) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } bool System.Collections.Generic.ICollection<string>.Remove(string item) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } void System.Collections.Generic.IList<string>.RemoveAt(int index) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } void System.Collections.Generic.ICollection<string>.Clear() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) throw new NotSupportedException(); } public Enumerator GetEnumerator() { return new Enumerator(_values); } System.Collections.Generic.IEnumerator<string> System.Collections.Generic.IEnumerable<string>.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public static bool IsNullOrEmpty(StringValues value) { object values = value._values; if (values == null) { return true; } if (values is string[] array) { return array.Length switch { 0 => true, 1 => string.IsNullOrEmpty(array[0]), _ => false, }; } return string.IsNullOrEmpty(System.Runtime.CompilerServices.Unsafe.As<string>(values)); } public static StringValues Concat(StringValues values1, StringValues values2) { int count = values1.Count; int count2 = values2.Count; if (count == 0) { return values2; } if (count2 == 0) { return values1; } string[] array = new string[count + count2]; values1.CopyTo(array, 0); values2.CopyTo(array, count); return new StringValues(array); } public static StringValues Concat(in StringValues values, string? value) { if (value == null) { return values; } int count = values.Count; if (count == 0) { return new StringValues(value); } string[] array = new string[count + 1]; values.CopyTo(array, 0); array[count] = value; return new StringValues(array); } public static StringValues Concat(string? value, in StringValues values) { if (value == null) { return values; } int count = values.Count; if (count == 0) { return new StringValues(value); } string[] array = new string[count + 1]; array[0] = value; values.CopyTo(array, 1); return new StringValues(array); } public static bool Equals(StringValues left, StringValues right) { int count = left.Count; if (count != right.Count) { return false; } for (int i = 0; i < count; i++) { if (left[i] != right[i]) { return false; } } return true; } public static bool operator ==(StringValues left, StringValues right) { return Equals(left, right); } public static bool operator !=(StringValues left, StringValues right) { return !Equals(left, right); } public bool Equals(StringValues other) { return Equals(this, other); } public static bool Equals(string? left, StringValues right) { return Equals(new StringValues(left), right); } public static bool Equals(StringValues left, string? right) { return Equals(left, new StringValues(right)); } public bool Equals(string? other) { return Equals(this, new StringValues(other)); } public static bool Equals(string?[]? left, StringValues right) { return Equals(new StringValues(left), right); } public static bool Equals(StringValues left, string?[]? right) { return Equals(left, new StringValues(right)); } public bool Equals(string?[]? other) { return Equals(this, new StringValues(other)); } public static bool operator ==(StringValues left, string? right) { return Equals(left, new StringValues(right)); } public static bool operator !=(StringValues left, string? right) { return !Equals(left, new StringValues(right)); } public static bool operator ==(string? left, StringValues right) { return Equals(new StringValues(left), right); } public static bool operator !=(string? left, StringValues right) { return !Equals(new StringValues(left), right); } public static bool operator ==(StringValues left, string?[]? right) { return Equals(left, new StringValues(right)); } public static bool operator !=(StringValues left, string?[]? right) { return !Equals(left, new StringValues(right)); } public static bool operator ==(string?[]? left, StringValues right) { return Equals(new StringValues(left), right); } public static bool operator !=(string?[]? left, StringValues right) { return !Equals(new StringValues(left), right); } public static bool operator ==(StringValues left, object? right) { return ((object)left).Equals(right); } public static bool operator !=(StringValues left, object? right) { return !((object)left).Equals(right); } public static bool operator ==(object? left, StringValues right) { return ((object)right).Equals(left); } public static bool operator !=(object? left, StringValues right) { return !((object)right).Equals(left); } public override bool Equals(object? obj) { if (obj == null) { return Equals(this, Empty); } if (obj is string right) { return Equals(this, right); } if (obj is string[] right2) { return Equals(this, right2); } if (obj is StringValues right3) { return Equals(this, right3); } return false; } public override int GetHashCode() { object values = _values; if (values is string[] array) { if (Count == 1) { return ((object)System.Runtime.CompilerServices.Unsafe.As<string>((object)this[0]))?.GetHashCode() ?? Count.GetHashCode(); } int num = 0; for (int i = 0; i < array.Length; i++) { num = HashHelpers.Combine(num, ((object)array[i])?.GetHashCode() ?? 0); } return num; } return ((object)System.Runtime.CompilerServices.Unsafe.As<string>(values))?.GetHashCode() ?? Count.GetHashCode(); } } internal static class ThrowHelper { [DoesNotReturn] internal static void ThrowArgumentNullException(ExceptionArgument argument) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentNullException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentException(ExceptionResource resource) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) throw new ArgumentException(GetResourceText(resource)); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) throw new InvalidOperationException(GetResourceText(resource)); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource, params object[] args) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) string text = string.Format(GetResourceText(resource), args); throw new InvalidOperationException(text); } internal static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown return new ArgumentNullException(GetArgumentName(argument)); } internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown return new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static ArgumentException GetArgumentException(ExceptionResource resource) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown return new ArgumentException(GetResourceText(resource)); } private static string GetResourceText(ExceptionResource resource) { return System.SR.GetResourceString(GetResourceName(resource)); } private static string GetArgumentName(ExceptionArgument argument) { return ((object)argument).ToString(); } private static string GetResourceName(ExceptionResource resource) { return ((object)resource).ToString(); } } internal enum ExceptionArgument { buffer, offset, length, text, start, count, index, value, capacity, separators, comparisonType, changeTokens, changeTokenProducer, changeTokenConsumer, array } internal enum ExceptionResource { Argument_InvalidOffsetLength, Argument_InvalidOffsetLengthStringSegment, Capacity_CannotChangeAfterWriteStarted, Capacity_NotEnough, Capacity_NotUsedEntirely } }
AuriePack/AurieInstaller/Wpf.Ui.dll
Decompiled a year 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.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using System.Windows.Threading; using Microsoft.CodeAnalysis; using Microsoft.Win32; using Wpf.Ui.Animations; using Wpf.Ui.Appearance; using Wpf.Ui.Common; using Wpf.Ui.Contracts; using Wpf.Ui.Controls; using Wpf.Ui.Converters; using Wpf.Ui.Dpi; using Wpf.Ui.Extensions; using Wpf.Ui.Hardware; using Wpf.Ui.Interop; using Wpf.Ui.Interop.WinDef; using Wpf.Ui.Services.Internal; using Wpf.Ui.Syntax; using Wpf.Ui.TaskBar; using Wpf.Ui.Tray; using Wpf.Ui.Win32; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(/*Could not decode attribute arguments.*/)] [assembly: ComVisible(false)] [assembly: ThemeInfo(/*Could not decode attribute arguments.*/)] [assembly: Guid("072fb71f-784e-4113-9da0-a506ff1a0cd5")] [assembly: XmlnsPrefix("http://schemas.lepo.co/wpfui/2022/xaml", "ui")] [assembly: XmlnsDefinition("http://schemas.lepo.co/wpfui/2022/xaml", "Wpf.Ui")] [assembly: XmlnsDefinition("http://schemas.lepo.co/wpfui/2022/xaml", "Wpf.Ui.Controls")] [assembly: XmlnsDefinition("http://schemas.lepo.co/wpfui/2022/xaml", "Wpf.Ui.Common")] [assembly: XmlnsDefinition("http://schemas.lepo.co/wpfui/2022/xaml", "Wpf.Ui.Markup")] [assembly: XmlnsDefinition("http://schemas.lepo.co/wpfui/2022/xaml", "Wpf.Ui.Converters")] [assembly: TargetFramework(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")] [assembly: InternalsVisibleTo("Wpf.Ui.UnitTests")] [assembly: AssemblyCompany("lepo.co")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (C) 2021-2023 Leszek Pomianowski and WPF UI Contributors")] [assembly: AssemblyDescription("A simple way to make your application written in WPF keep up with modern design trends. Library changes the base elements like Page, ToggleButton or List, and also includes additional controls like Navigation, NumberBox, Dialog or Snackbar.")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyInformationalVersion("3.0.0-preview.4")] [assembly: AssemblyProduct("WPF UI")] [assembly: AssemblyTitle("Wpf.Ui")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/lepoco/wpfui")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: TargetPlatform("Windows7.0")] [assembly: SupportedOSPlatform("Windows7.0")] [assembly: SecurityPermission(8, SkipVerification = true)] [assembly: AssemblyVersion("3.0.0.0")] [assembly: TypeForwardedTo(typeof(IsExternalInit))] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : System.Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableAttribute : System.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] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class NullableContextAttribute : System.Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(/*Could not decode attribute arguments.*/)] internal sealed class RefSafetyRulesAttribute : System.Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Wpf.Ui { public static class UiAssembly { public static Assembly Asssembly => Assembly.GetExecutingAssembly(); } } namespace Wpf.Ui.Win32 { internal class Utilities { private static readonly PlatformID _osPlatform = Environment.OSVersion.Platform; private static readonly Version _osVersion = Environment.OSVersion.Version; public static bool IsNT => (int)_osPlatform == 2; public static bool IsOSVistaOrNewer => _osVersion >= new Version(6, 0); public static bool IsOSWindows7OrNewer => _osVersion >= new Version(6, 1); public static bool IsOSWindows8OrNewer => _osVersion >= new Version(6, 2); public static bool IsOSWindows10OrNewer => _osVersion.Build >= 10240; public static bool IsOSWindows11OrNewer => _osVersion.Build >= 22000; public static bool IsOSWindows11Insider1OrNewer => _osVersion.Build >= 22523; public static bool IsOSWindows11Insider2OrNewer => _osVersion.Build >= 22557; public static bool IsCompositionEnabled { get { if (!IsOSVistaOrNewer) { return false; } Dwmapi.DwmIsCompositionEnabled(out var pfEnabled); return pfEnabled != 0; } } public static void SafeDispose<T>(ref T disposable) where T : System.IDisposable { System.IDisposable disposable2 = disposable; disposable = default(T); disposable2?.Dispose(); } public static void SafeRelease<T>(ref T comObject) where T : class { T val = comObject; comObject = null; if (val != null) { Marshal.ReleaseComObject((object)val); } } } internal static class Win32Constant { public const int MAX_PATH = 260; public const int INFOTIPSIZE = 1024; public const int TRUE = 1; public const int FALSE = 0; } internal enum WindowsRelease { Windows95 = 950, Windows98 = 1998, Windows2000 = 2195, WindowsXP = 2600, WindowsMe = 3000, Windows7 = 7600, Windows7Sp1 = 7601, Windows8 = 9200, Windows81 = 9600, Windows10 = 10240, Windows10V1511 = 10586, Windows10V1607 = 14393, Windows10V1703 = 15063, Windows10V1809 = 17763, Windows10V19H1 = 18362, Windows10Insider1 = 18985, Windows10V20H1 = 19041, Windows10V20H2 = 19042, Windows10V21H1 = 19043, Windows10V21H2 = 19044, WindowsServer2022 = 20348, Windows11 = 22000, Windows11Insider1 = 22523, Windows11Insider2 = 22557 } } namespace Wpf.Ui.Tray { internal static class Hicon { public static nint FromApp() { try { ProcessModule mainModule = Process.GetCurrentProcess().MainModule; string text = ((mainModule != null) ? mainModule.FileName : null); if (string.IsNullOrEmpty(text)) { return System.IntPtr.Zero; } Icon val = Icon.ExtractAssociatedIcon(text); if (val == null) { return System.IntPtr.Zero; } return val.Handle; } catch (System.Exception) { return System.IntPtr.Zero; } } public static nint FromSource(ImageSource source) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) _ = System.IntPtr.Zero; BitmapSource val = (BitmapSource)(object)((source is BitmapSource) ? source : null); BitmapFrame val2 = (BitmapFrame)(object)((source is BitmapFrame) ? source : null); if (val == null) { return System.IntPtr.Zero; } int? obj; if (val2 == null) { obj = null; } else { BitmapDecoder decoder = val2.Decoder; obj = ((decoder == null) ? null : decoder.Frames?.Count); } int? num = obj; if (num.GetValueOrDefault() > 1) { val = (BitmapSource)(object)val2.Decoder.Frames[0]; } int pixelWidth = val.PixelWidth; PixelFormat format = val.Format; int num2 = pixelWidth * ((((PixelFormat)(ref format)).BitsPerPixel + 7) / 8); byte[] array = new byte[val.PixelHeight * num2]; val.CopyPixels((System.Array)array, num2, 0); GCHandle val3 = GCHandle.Alloc((object)array, (GCHandleType)3); if (!((GCHandle)(ref val3)).IsAllocated) { return System.IntPtr.Zero; } System.IntPtr hicon = new Bitmap(val.PixelWidth, val.PixelHeight, num2, (PixelFormat)925707, ((GCHandle)(ref val3)).AddrOfPinnedObject()).GetHicon(); ((GCHandle)(ref val3)).Free(); return hicon; } } internal interface INotifyIcon { Shell32.NOTIFYICONDATA ShellIconData { get; set; } bool IsRegistered { get; set; } int Id { get; set; } string TooltipText { get; set; } ImageSource Icon { get; set; } HwndSource HookWindow { get; set; } ContextMenu ContextMenu { get; set; } bool FocusOnLeftClick { get; set; } bool MenuOnRightClick { get; set; } nint WndProc(nint hWnd, int msg, nint wParam, nint lParam, ref bool handled); bool Register(); bool Register(Window parentWindow); bool ModifyIcon(); bool Unregister(); } internal delegate void NotifyIconEventHandler(); internal static class TrayData { [field: CompilerGenerated] public static List<INotifyIcon> NotifyIcons { [CompilerGenerated] get; [CompilerGenerated] set; } = new List<INotifyIcon>(); } internal class TrayHandler : HwndSource { [field: CompilerGenerated] public int ElementId { [CompilerGenerated] get; [CompilerGenerated] internal set; } public TrayHandler(string name, nint parent) : base(0, 67108864, 134742056, 0, 0, 0, 0, name, (System.IntPtr)parent) { } } internal static class TrayManager { public static bool Register(INotifyIcon notifyIcon) { return Register(notifyIcon, GetParentSource()); } public static bool Register(INotifyIcon notifyIcon, Window parentWindow) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (parentWindow == null) { return false; } return TrayManager.Register(notifyIcon, (HwndSource)PresentationSource.FromVisual((Visual)(object)parentWindow)); } public static bool Register(INotifyIcon notifyIcon, HwndSource parentSource) { //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Expected O, but got Unknown if (parentSource == null) { if (!notifyIcon.IsRegistered) { return false; } Unregister(notifyIcon); return false; } if (parentSource.Handle == System.IntPtr.Zero) { return false; } if (notifyIcon.IsRegistered) { Unregister(notifyIcon); } notifyIcon.Id = TrayData.NotifyIcons.Count + 1; notifyIcon.HookWindow = (HwndSource)(object)new TrayHandler($"wpfui_th_{parentSource.Handle}_{notifyIcon.Id}", parentSource.Handle) { ElementId = notifyIcon.Id }; notifyIcon.ShellIconData = new Shell32.NOTIFYICONDATA { uID = notifyIcon.Id, uFlags = Shell32.NIF.MESSAGE, uCallbackMessage = 2048, hWnd = notifyIcon.HookWindow.Handle, dwState = 2u }; if (!string.IsNullOrEmpty(notifyIcon.TooltipText)) { notifyIcon.ShellIconData.szTip = notifyIcon.TooltipText; notifyIcon.ShellIconData.uFlags |= Shell32.NIF.TIP; } ReloadHicon(notifyIcon); notifyIcon.HookWindow.AddHook(new HwndSourceHook(notifyIcon.WndProc)); Shell32.Shell_NotifyIcon(Shell32.NIM.ADD, notifyIcon.ShellIconData); TrayData.NotifyIcons.Add(notifyIcon); notifyIcon.IsRegistered = true; return true; } public static bool ModifyIcon(INotifyIcon notifyIcon) { if (!notifyIcon.IsRegistered) { return true; } ReloadHicon(notifyIcon); return Shell32.Shell_NotifyIcon(Shell32.NIM.MODIFY, notifyIcon.ShellIconData); } public static bool Unregister(INotifyIcon notifyIcon) { if (notifyIcon.ShellIconData == null || !notifyIcon.IsRegistered) { return false; } Shell32.Shell_NotifyIcon(Shell32.NIM.DELETE, notifyIcon.ShellIconData); notifyIcon.IsRegistered = false; return true; } private static HwndSource GetParentSource() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown Window mainWindow = Application.Current.MainWindow; if (mainWindow == null) { return null; } return (HwndSource)PresentationSource.FromVisual((Visual)(object)mainWindow); } private static void ReloadHicon(INotifyIcon notifyIcon) { nint num = System.IntPtr.Zero; if (notifyIcon.Icon != null) { num = Hicon.FromSource(notifyIcon.Icon); } if (num == (nint)System.IntPtr.Zero) { num = Hicon.FromApp(); } if (num != (nint)System.IntPtr.Zero) { notifyIcon.ShellIconData.hIcon = num; notifyIcon.ShellIconData.uFlags |= Shell32.NIF.ICON; } } } } namespace Wpf.Ui.TaskBar { public static class TaskBarProgress { private static bool IsSupported() { return Utilities.IsOSWindows7OrNewer; } public static bool SetState(Window window, TaskBarProgressState taskBarProgressState) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) Window window2 = window; if (window2 == null) { return false; } if (((FrameworkElement)window2).IsLoaded) { return SetState(new WindowInteropHelper(window2).Handle, taskBarProgressState); } ((FrameworkElement)window2).Loaded += (RoutedEventHandler)delegate { //IL_0006: Unknown result type (might be due to invalid IL or missing references) SetState(new WindowInteropHelper(window2).Handle, taskBarProgressState); }; return true; } public static bool SetState(nint hWnd, TaskBarProgressState taskBarProgressState) { if (!IsSupported()) { throw new System.Exception("Taskbar functions not available."); } return UnsafeNativeMethods.SetTaskbarState(hWnd, UnsafeReflection.Cast(taskBarProgressState)); } public static bool SetValue(Window window, TaskBarProgressState taskBarProgressState, int current) { if (current > 100) { current = 100; } if (current < 0) { current = 0; } return SetValue(window, taskBarProgressState, current, 100); } public static bool SetValue(Window window, TaskBarProgressState taskBarProgressState, int current, int total) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) Window window2 = window; if (window2 == null) { return false; } if (((FrameworkElement)window2).IsLoaded) { return SetValue(new WindowInteropHelper(window2).Handle, taskBarProgressState, current, total); } ((FrameworkElement)window2).Loaded += (RoutedEventHandler)delegate { //IL_0006: Unknown result type (might be due to invalid IL or missing references) SetValue(new WindowInteropHelper(window2).Handle, taskBarProgressState, current, total); }; return false; } public static bool SetValue(nint hWnd, TaskBarProgressState taskBarProgressState, int current) { if (current > 100) { current = 100; } if (current < 0) { current = 0; } return SetValue(hWnd, taskBarProgressState, current, 100); } public static bool SetValue(nint hWnd, TaskBarProgressState taskBarProgressState, int current, int total) { if (!IsSupported()) { throw new System.Exception("Taskbar functions not available."); } return UnsafeNativeMethods.SetTaskbarValue(hWnd, UnsafeReflection.Cast(taskBarProgressState), current, total); } } public enum TaskBarProgressState { None = 0, Indeterminate = 1, Normal = 2, Error = 4, Paused = 8 } } namespace Wpf.Ui.Syntax { internal static class Highlighter { private const string EndlinePattern = "(\n)"; private const string TabPattern = "(\t)"; private const string QuotePattern = "(\"(?:\\\"|[^\"])*\")|('(?:\\'|[^'])*')"; private const string CommentPattern = "(\\/\\/.*?(?:\\n|$)|\\/\\*.*?\\*\\/)"; private const string TagPattern = "(<\\/?)([a-zA-Z\\-:]+)(.*?)(\\/?>)"; private const string EntityPattern = "(&[a-zA-Z0-9#]+;)"; private const string PunctuationPattern = "(!==?|(?:[[\\\\] ()\\{\\}.:;,+\\\\-?=!]|<|>)+|&&|\\\\|\\\\|)"; private const string NumberPattern = "(-? (?:\\.\\d+|\\d+(?:\\.\\d+)?))"; private const string BooleanPattern = "\b(true|false)\b"; private const string AttributePattern = "(\\s*)([a-zA-Z\\d\\-:]+)=(\" | ')(.*?)\\3"; public static Paragraph FormatAsParagraph(string code, SyntaxLanguage language = SyntaxLanguage.Autodetect) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown Paragraph val = new Paragraph(); Regex val2 = new Regex(GetPattern(language, code)); bool flag = IsLightTheme(); foreach (Match item in val2.Matches(code)) { foreach (object group in item.Groups) { if (group is Match) { continue; } Group val3 = (Group)group; if (string.IsNullOrEmpty(((Capture)val3).Value)) { continue; } if (((Capture)val3).Value.Contains("\t")) { ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(" ", Brushes.Transparent)); } else if (((Capture)val3).Value.Contains("/*") || ((Capture)val3).Value.Contains("//")) { ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(((Capture)val3).Value, Brushes.Orange)); } else if (((Capture)val3).Value.Contains("<") || ((Capture)val3).Value.Contains(">")) { ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(((Capture)val3).Value, flag ? Brushes.DarkCyan : Brushes.CornflowerBlue)); } else if (((Capture)val3).Value.Contains("\"")) { string[] array = ((Capture)val3).Value.Split('"', (StringSplitOptions)0); array = Enumerable.ToArray<string>(Enumerable.Where<string>((System.Collections.Generic.IEnumerable<string>)array, (Func<string, bool>)((string x) => !string.IsNullOrEmpty(x.Trim())))); if (array.Length % 2 == 0) { for (int i = 0; i < array.Length; i += 2) { ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(array[i], flag ? Brushes.DarkSlateGray : Brushes.WhiteSmoke)); ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line("\"", flag ? Brushes.DarkCyan : Brushes.CornflowerBlue)); ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(array[i + 1], Brushes.Coral)); ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line("\"", flag ? Brushes.DarkCyan : Brushes.CornflowerBlue)); } } else { ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(((Capture)val3).Value, flag ? Brushes.DarkSlateGray : Brushes.WhiteSmoke)); } } else if (((Capture)val3).Value.Contains("'")) { string[] array2 = ((Capture)val3).Value.Split('\'', (StringSplitOptions)0); array2 = Enumerable.ToArray<string>(Enumerable.Where<string>((System.Collections.Generic.IEnumerable<string>)array2, (Func<string, bool>)((string x) => !string.IsNullOrEmpty(x.Trim())))); if (array2.Length % 2 == 0) { for (int j = 0; j < array2.Length; j += 2) { ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(array2[j], flag ? Brushes.DarkSlateGray : Brushes.WhiteSmoke)); ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line("'", flag ? Brushes.DarkCyan : Brushes.CornflowerBlue)); ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(array2[j + 1], Brushes.Coral)); ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line("'", flag ? Brushes.DarkCyan : Brushes.CornflowerBlue)); } } else { ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(((Capture)val3).Value, flag ? Brushes.DarkSlateGray : Brushes.WhiteSmoke)); } } else { ((TextElementCollection<Inline>)(object)val.Inlines).Add((Inline)(object)Line(((Capture)val3).Value, flag ? Brushes.CornflowerBlue : Brushes.Aqua)); } } } return val; } public static string Clean(string code) { code = code.Replace("\\n", "\n"); code = code.Replace("\\t", "\t"); code = code.Replace("<", "<"); code = code.Replace(">", ">"); code = code.Replace("&", "&"); code = code.Replace(""", "\""); code = code.Replace("'", "'"); return code; } private static Run Line(string line, SolidColorBrush brush) { //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) //IL_000e: Expected O, but got Unknown return new Run(line) { Foreground = (Brush)(object)brush }; } private static bool IsLightTheme() { return Theme.GetAppTheme() == ThemeType.Light; } private static string GetPattern(SyntaxLanguage language) { return GetPattern(language, string.Empty); } private static string GetPattern(SyntaxLanguage language, string code) { string text = string.Empty; if (language == SyntaxLanguage.Autodetect) { language = SyntaxLanguage.XAML; } switch (language) { case SyntaxLanguage.CSHARP: text += "(\n)"; text += "|(\t)"; text += "|(\"(?:\\\"|[^\"])*\")|('(?:\\'|[^'])*')"; text += "|(\\/\\/.*?(?:\\n|$)|\\/\\*.*?\\*\\/)"; text += "|(&[a-zA-Z0-9#]+;)"; text += "|(<\\/?)([a-zA-Z\\-:]+)(.*?)(\\/?>)"; break; case SyntaxLanguage.XAML: text += "(\n)"; text += "|(\t)"; text += "|(\"(?:\\\"|[^\"])*\")|('(?:\\'|[^'])*')"; text += "|(\\/\\/.*?(?:\\n|$)|\\/\\*.*?\\*\\/)"; text += "|(&[a-zA-Z0-9#]+;)"; text += "|(<\\/?)([a-zA-Z\\-:]+)(.*?)(\\/?>)"; break; } return text; } } internal enum SyntaxLanguage { Autodetect, XAML, CSHARP } } namespace Wpf.Ui.Styles.Controls { public class ContextMenu : ResourceDictionary, IComponentConnector { private bool _contentLoaded; public ContextMenu() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown Dispatcher.CurrentDispatcher.BeginInvoke((DispatcherPriority)9, (System.Delegate)new Action(OnResourceDictionaryLoaded)); } private void OnResourceDictionaryLoaded() { Assembly assembly = typeof(Application).Assembly; AddEditorContextMenuDefaultStyle(assembly); } private void AddEditorContextMenuDefaultStyle(Assembly currentAssembly) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown object obj = ((ResourceDictionary)this)[(object)"UiContextMenu"]; Style val = (Style)((obj is Style) ? obj : null); System.Type type = System.Type.GetType("System.Windows.Documents.TextEditorContextMenu+EditorContextMenu, " + (object)currentAssembly); if (!(type == (System.Type)null) && val != null) { Style val2 = new Style(type, val); ((ResourceDictionary)this).Add((object)type, (object)val2); } } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "7.0.7.0")] public void InitializeComponent() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (!_contentLoaded) { _contentLoaded = true; Uri val = new Uri("/Wpf.Ui;component/styles/controls/contextmenu.xaml", (UriKind)2); Application.LoadComponent((object)this, val); } } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "7.0.7.0")] [EditorBrowsable(/*Could not decode attribute arguments.*/)] void IComponentConnector.Connect(int connectionId, object target) { _contentLoaded = true; } } public class Menu : ResourceDictionary, IComponentConnector { private bool _contentLoaded; public Menu() { Initialize(); } private void Initialize() { if (SystemParameters.MenuDropAlignment) { FieldInfo field = typeof(SystemParameters).GetField("_menuDropAlignment", (BindingFlags)40); if (field != null) { field.SetValue((object)null, (object)false); } } } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "7.0.7.0")] public void InitializeComponent() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (!_contentLoaded) { _contentLoaded = true; Uri val = new Uri("/Wpf.Ui;component/styles/controls/menu.xaml", (UriKind)2); Application.LoadComponent((object)this, val); } } [DebuggerNonUserCode] [GeneratedCode("PresentationBuildTasks", "7.0.7.0")] [EditorBrowsable(/*Could not decode attribute arguments.*/)] void IComponentConnector.Connect(int connectionId, object target) { _contentLoaded = true; } } } namespace Wpf.Ui.Services { public class ContentDialogService : IContentDialogService { private ContentPresenter? _contentPresenter; private ContentDialog? _dialog; public void SetContentPresenter(ContentPresenter contentPresenter) { _contentPresenter = contentPresenter; } public ContentPresenter GetContentPresenter() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_contentPresenter == null) { throw new ArgumentNullException("The ContentPresenter didn't set previously."); } return _contentPresenter; } public System.Threading.Tasks.Task<ContentDialogResult> ShowAlertAsync(string title, string message, string closeButtonText, CancellationToken cancellationToken = default(CancellationToken)) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (_contentPresenter == null) { throw new ArgumentNullException("The ContentPresenter didn't set previously."); } if (_dialog == null) { _dialog = new ContentDialog(_contentPresenter); } _dialog.Title = title; ((ContentControl)_dialog).Content = message; _dialog.CloseButtonText = closeButtonText; return _dialog.ShowAsync(cancellationToken); } public System.Threading.Tasks.Task<ContentDialogResult> ShowSimpleDialogAsync(SimpleContentDialogCreateOptions options, CancellationToken cancellationToken = default(CancellationToken)) { //IL_005a: 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) if (_contentPresenter == null) { throw new ArgumentNullException("The ContentPresenter didn't set previously."); } ContentDialog obj = new ContentDialog(_contentPresenter) { Title = options.Title }; ((ContentControl)obj).Content = options.Content; obj.CloseButtonText = options.CloseButtonText; obj.PrimaryButtonText = options.PrimaryButtonText; obj.SecondaryButtonText = options.SecondaryButtonText; return obj.ShowAsync(cancellationToken); } } public class NavigationService : INavigationService { private readonly IServiceProvider _serviceProvider; private IPageService? _pageService; protected INavigationView? NavigationControl; public NavigationService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public INavigationView GetNavigationControl() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) return NavigationControl ?? throw new ArgumentNullException("NavigationControl"); } public void SetNavigationControl(INavigationView navigation) { NavigationControl = navigation; if (_pageService != null) { NavigationControl.SetPageService(_pageService); } else { NavigationControl.SetServiceProvider(_serviceProvider); } } public void SetPageService(IPageService pageService) { if (NavigationControl == null) { _pageService = pageService; return; } ThrowIfPageServiceIsNull(); NavigationControl.SetPageService(_pageService); } public bool Navigate(System.Type pageType) { ThrowIfNavigationControlIsNull(); return NavigationControl.Navigate(pageType); } public bool Navigate(string pageTag) { ThrowIfNavigationControlIsNull(); return NavigationControl.Navigate(pageTag); } public bool GoBack() { ThrowIfNavigationControlIsNull(); return NavigationControl.GoBack(); } public bool NavigateWithHierarchy(System.Type pageType) { ThrowIfNavigationControlIsNull(); return NavigationControl.NavigateWithHierarchy(pageType); } private void ThrowIfNavigationControlIsNull() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (NavigationControl == null) { throw new ArgumentNullException("NavigationControl"); } } private void ThrowIfPageServiceIsNull() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_pageService == null) { throw new ArgumentNullException("_pageService"); } } } public class NotifyIconService : INotifyIconService { private readonly Wpf.Ui.Services.Internal.NotifyIconService _notifyIconService; [field: CompilerGenerated] public Window ParentWindow { [CompilerGenerated] get; [CompilerGenerated] internal set; } public int Id => _notifyIconService.Id; public bool IsRegistered => _notifyIconService.IsRegistered; public string TooltipText { get { return _notifyIconService.TooltipText; } set { _notifyIconService.TooltipText = value; } } public ContextMenu ContextMenu { get { return _notifyIconService.ContextMenu; } set { _notifyIconService.ContextMenu = value; } } public ImageSource Icon { get { return _notifyIconService.Icon; } set { _notifyIconService.Icon = value; } } public NotifyIconService() { _notifyIconService = new Wpf.Ui.Services.Internal.NotifyIconService(); RegisterHandlers(); } public bool Register() { if (ParentWindow != null) { return _notifyIconService.Register(ParentWindow); } return _notifyIconService.Register(); } public bool Unregister() { return _notifyIconService.Unregister(); } public void SetParentWindow(Window parentWindow) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (ParentWindow != null) { ParentWindow.Closing -= new CancelEventHandler(OnParentWindowClosing); } ParentWindow = parentWindow; ParentWindow.Closing += new CancelEventHandler(OnParentWindowClosing); } protected virtual void OnLeftClick() { } protected virtual void OnLeftDoubleClick() { } protected virtual void OnRightClick() { } protected virtual void OnRightDoubleClick() { } protected virtual void OnMiddleClick() { } protected virtual void OnMiddleDoubleClick() { } private void OnParentWindowClosing(object sender, CancelEventArgs e) { _notifyIconService.Dispose(); } private void RegisterHandlers() { _notifyIconService.LeftClick += OnLeftClick; _notifyIconService.LeftDoubleClick += OnLeftDoubleClick; _notifyIconService.RightClick += OnRightClick; _notifyIconService.RightDoubleClick += OnRightDoubleClick; _notifyIconService.MiddleClick += OnMiddleClick; _notifyIconService.MiddleDoubleClick += OnMiddleDoubleClick; } } public class SnackbarService : ISnackbarService { private SnackbarPresenter? _presenter; private Snackbar? _snackbar; [field: CompilerGenerated] public TimeSpan DefaultTimeOut { [CompilerGenerated] get; [CompilerGenerated] set; } = TimeSpan.FromSeconds(2.0); public void SetSnackbarPresenter(SnackbarPresenter contentPresenter) { _presenter = contentPresenter; } public SnackbarPresenter GetSnackbarPresenter() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (_presenter == null) { throw new ArgumentNullException("The SnackbarPresenter didn't set previously."); } return _presenter; } public void Show(string title, string message, ControlAppearance appearance = ControlAppearance.Secondary, IconElement? icon = null, TimeSpan timeout = default(TimeSpan)) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) if (_presenter == null) { throw new ArgumentNullException("The SnackbarPresenter didn't set previously."); } if (_snackbar == null) { _snackbar = new Snackbar(_presenter); } _snackbar.Title = title; ((ContentControl)_snackbar).Content = message; _snackbar.Appearance = appearance; _snackbar.Icon = icon; _snackbar.Timeout = ((((TimeSpan)(ref timeout)).TotalSeconds == 0.0) ? DefaultTimeOut : timeout); _snackbar.Show(immediately: true); } } public class TaskBarService : ITaskBarService { private volatile Dictionary<nint, TaskBarProgressState> _progressStates; public TaskBarService() { _progressStates = new Dictionary<nint, TaskBarProgressState>(); } public virtual TaskBarProgressState GetState(nint hWnd) { TaskBarProgressState result = default(TaskBarProgressState); if (!_progressStates.TryGetValue(hWnd, ref result)) { return TaskBarProgressState.None; } return result; } public virtual TaskBarProgressState GetState(Window window) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (window == null) { return TaskBarProgressState.None; } nint handle = new WindowInteropHelper(window).Handle; TaskBarProgressState result = default(TaskBarProgressState); if (!_progressStates.TryGetValue(handle, ref result)) { return TaskBarProgressState.None; } return result; } public virtual bool SetState(Window window, TaskBarProgressState taskBarProgressState) { if (window == null) { return false; } return TaskBarProgress.SetState(window, taskBarProgressState); } public virtual bool SetValue(Window window, TaskBarProgressState taskBarProgressState, int current, int total) { if (window == null) { return false; } return TaskBarProgress.SetValue(window, taskBarProgressState, current, total); } public virtual bool SetValue(Window window, int current, int total) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (window == null) { return false; } nint handle = new WindowInteropHelper(window).Handle; TaskBarProgressState taskBarProgressState = default(TaskBarProgressState); if (!_progressStates.TryGetValue(handle, ref taskBarProgressState)) { return TaskBarProgress.SetValue(window, TaskBarProgressState.Normal, current, total); } return TaskBarProgress.SetValue(window, taskBarProgressState, current, total); } public virtual bool SetState(nint hWnd, TaskBarProgressState taskBarProgressState) { return TaskBarProgress.SetState(hWnd, taskBarProgressState); } public virtual bool SetValue(nint hWnd, TaskBarProgressState taskBarProgressState, int current, int total) { return TaskBarProgress.SetValue(hWnd, taskBarProgressState, current, total); } public virtual bool SetValue(nint hWnd, int current, int total) { TaskBarProgressState taskBarProgressState = default(TaskBarProgressState); if (!_progressStates.TryGetValue(hWnd, ref taskBarProgressState)) { return TaskBarProgress.SetValue(hWnd, TaskBarProgressState.Normal, current, total); } return TaskBarProgress.SetValue(hWnd, taskBarProgressState, current, total); } } public class ThemeService : IThemeService { public virtual ThemeType GetTheme() { return Theme.GetAppTheme(); } public virtual SystemThemeType GetNativeSystemTheme() { return Theme.GetSystemTheme(); } public virtual ThemeType GetSystemTheme() { return Theme.GetSystemTheme() switch { SystemThemeType.Light => ThemeType.Light, SystemThemeType.Dark => ThemeType.Dark, SystemThemeType.Glow => ThemeType.Dark, SystemThemeType.CapturedMotion => ThemeType.Dark, SystemThemeType.Sunrise => ThemeType.Light, SystemThemeType.Flow => ThemeType.Light, _ => ThemeType.Unknown, }; } public virtual bool SetTheme(ThemeType themeType) { if (Theme.GetAppTheme() == themeType) { return false; } Theme.Apply(themeType); return true; } public bool SetSystemAccent() { Accent.ApplySystemAccent(); return true; } public bool SetAccent(Color accentColor) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) Accent.Apply(accentColor); return true; } public bool SetAccent(SolidColorBrush accentSolidBrush) { //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) //IL_0024: Unknown result type (might be due to invalid IL or missing references) Color color = accentSolidBrush.Color; ((Color)(ref color)).A = (byte)Math.Round(((Brush)accentSolidBrush).Opacity * 255.0); Accent.Apply(color); return true; } } } namespace Wpf.Ui.Services.Internal { internal class NotifyIconService : System.IDisposable, INotifyIcon { protected bool Disposed; [CompilerGenerated] private NotifyIconEventHandler m_LeftClick; [CompilerGenerated] private NotifyIconEventHandler m_LeftDoubleClick; [CompilerGenerated] private NotifyIconEventHandler m_RightClick; [CompilerGenerated] private NotifyIconEventHandler m_RightDoubleClick; [CompilerGenerated] private NotifyIconEventHandler m_MiddleClick; [CompilerGenerated] private NotifyIconEventHandler m_MiddleDoubleClick; [field: CompilerGenerated] public int Id { [CompilerGenerated] get; [CompilerGenerated] set; } = -1; [field: CompilerGenerated] public bool IsRegistered { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public string TooltipText { [CompilerGenerated] get; [CompilerGenerated] set; } = string.Empty; [field: CompilerGenerated] public ImageSource Icon { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public HwndSource HookWindow { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public ContextMenu ContextMenu { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public bool FocusOnLeftClick { [CompilerGenerated] get; [CompilerGenerated] set; } = true; [field: CompilerGenerated] public bool MenuOnRightClick { [CompilerGenerated] get; [CompilerGenerated] set; } = true; [field: CompilerGenerated] public Shell32.NOTIFYICONDATA ShellIconData { [CompilerGenerated] get; [CompilerGenerated] set; } public event NotifyIconEventHandler LeftClick { [CompilerGenerated] add { NotifyIconEventHandler notifyIconEventHandler = this.m_LeftClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Combine((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_LeftClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } [CompilerGenerated] remove { NotifyIconEventHandler notifyIconEventHandler = this.m_LeftClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Remove((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_LeftClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } } public event NotifyIconEventHandler LeftDoubleClick { [CompilerGenerated] add { NotifyIconEventHandler notifyIconEventHandler = this.m_LeftDoubleClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Combine((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_LeftDoubleClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } [CompilerGenerated] remove { NotifyIconEventHandler notifyIconEventHandler = this.m_LeftDoubleClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Remove((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_LeftDoubleClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } } public event NotifyIconEventHandler RightClick { [CompilerGenerated] add { NotifyIconEventHandler notifyIconEventHandler = this.m_RightClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Combine((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_RightClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } [CompilerGenerated] remove { NotifyIconEventHandler notifyIconEventHandler = this.m_RightClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Remove((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_RightClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } } public event NotifyIconEventHandler RightDoubleClick { [CompilerGenerated] add { NotifyIconEventHandler notifyIconEventHandler = this.m_RightDoubleClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Combine((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_RightDoubleClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } [CompilerGenerated] remove { NotifyIconEventHandler notifyIconEventHandler = this.m_RightDoubleClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Remove((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_RightDoubleClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } } public event NotifyIconEventHandler MiddleClick { [CompilerGenerated] add { NotifyIconEventHandler notifyIconEventHandler = this.m_MiddleClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Combine((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_MiddleClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } [CompilerGenerated] remove { NotifyIconEventHandler notifyIconEventHandler = this.m_MiddleClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Remove((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_MiddleClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } } public event NotifyIconEventHandler MiddleDoubleClick { [CompilerGenerated] add { NotifyIconEventHandler notifyIconEventHandler = this.m_MiddleDoubleClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Combine((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_MiddleDoubleClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } [CompilerGenerated] remove { NotifyIconEventHandler notifyIconEventHandler = this.m_MiddleDoubleClick; NotifyIconEventHandler notifyIconEventHandler2; do { notifyIconEventHandler2 = notifyIconEventHandler; NotifyIconEventHandler notifyIconEventHandler3 = (NotifyIconEventHandler)System.Delegate.Remove((System.Delegate)notifyIconEventHandler2, (System.Delegate)value); notifyIconEventHandler = Interlocked.CompareExchange<NotifyIconEventHandler>(ref this.m_MiddleDoubleClick, notifyIconEventHandler3, notifyIconEventHandler2); } while (notifyIconEventHandler != notifyIconEventHandler2); } } public NotifyIconService() { Theme.Changed += OnThemeChanged; } virtual ~NotifyIconService() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize((object)this); } public virtual bool Register() { IsRegistered = TrayManager.Register(this); return IsRegistered; } public virtual bool Register(Window parentWindow) { IsRegistered = TrayManager.Register(this, parentWindow); return IsRegistered; } public virtual bool ModifyIcon() { return TrayManager.ModifyIcon(this); } public virtual bool Unregister() { return TrayManager.Unregister(this); } protected virtual void OnThemeChanged(ThemeType currentTheme, Color systemAccent) { ContextMenu contextMenu = ContextMenu; if (contextMenu != null) { ((FrameworkElement)contextMenu).UpdateDefaultStyle(); } ContextMenu contextMenu2 = ContextMenu; if (contextMenu2 != null) { ((UIElement)contextMenu2).UpdateLayout(); } } protected virtual void FocusApp() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 Window mainWindow = Application.Current.MainWindow; if (mainWindow != null) { if ((int)mainWindow.WindowState == 1) { mainWindow.WindowState = (WindowState)0; } mainWindow.Show(); if (mainWindow.Topmost) { mainWindow.Topmost = false; mainWindow.Topmost = true; } else { mainWindow.Topmost = true; mainWindow.Topmost = false; } ((UIElement)mainWindow).Focus(); } } protected virtual void OpenMenu() { if (ContextMenu != null) { User32.SetForegroundWindow(HookWindow.Handle); ContextMenuService.SetPlacement((DependencyObject)(object)ContextMenu, (PlacementMode)8); ContextMenu.ApplyMica(); ContextMenu.IsOpen = true; } } protected virtual void OnLeftClick() { this.LeftClick?.Invoke(); } protected virtual void OnLeftDoubleClick() { this.LeftDoubleClick?.Invoke(); } protected virtual void OnRightClick() { this.RightClick?.Invoke(); } protected virtual void OnRightDoubleClick() { this.RightDoubleClick?.Invoke(); } protected virtual void OnMiddleClick() { this.MiddleClick?.Invoke(); } protected virtual void OnMiddleDoubleClick() { this.MiddleDoubleClick?.Invoke(); } protected virtual void Dispose(bool disposing) { if (!Disposed) { Disposed = true; if (disposing) { Unregister(); } } } public nint WndProc(nint hWnd, int msg, nint wParam, nint lParam, ref bool handled) { switch ((User32.WM)msg) { case User32.WM.DESTROY: Dispose(); handled = true; return System.IntPtr.Zero; case User32.WM.NCDESTROY: handled = false; return System.IntPtr.Zero; case User32.WM.CLOSE: handled = true; return System.IntPtr.Zero; default: handled = false; return System.IntPtr.Zero; case User32.WM.TRAYMOUSEMESSAGE: switch ((User32.WM)lParam) { case User32.WM.LBUTTONDOWN: OnLeftClick(); if (FocusOnLeftClick) { FocusApp(); } break; case User32.WM.LBUTTONDBLCLK: OnLeftDoubleClick(); break; case User32.WM.RBUTTONDOWN: OnRightClick(); if (MenuOnRightClick) { OpenMenu(); } break; case User32.WM.RBUTTONDBLCLK: OnRightDoubleClick(); break; case User32.WM.MBUTTONDOWN: OnMiddleClick(); break; case User32.WM.MBUTTONDBLCLK: OnMiddleDoubleClick(); break; } handled = true; return System.IntPtr.Zero; } } } } namespace Wpf.Ui.Notifications { internal class Toast { } } namespace Wpf.Ui.Markup { [Localizability(/*Could not decode attribute arguments.*/)] [Ambient] [UsableDuringInitialization(true)] public class ControlsDictionary : ResourceDictionary { public ControlsDictionary() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown ((ResourceDictionary)this).Source = new Uri("pack://application:,,,/Wpf.Ui;component/Styles/Wpf.Ui.xaml", (UriKind)1); } } public static class Design { private static readonly string DesignProcessName = "devenv"; private static bool? _inDesignMode; public static DependencyProperty BackgroundProperty = DependencyProperty.RegisterAttached("Background", typeof(Brush), typeof(Design), new PropertyMetadata(new PropertyChangedCallback(OnBackgroundPropertyChanged))); public static DependencyProperty ForegroundProperty = DependencyProperty.RegisterAttached("Foreground", typeof(Brush), typeof(Design), new PropertyMetadata(new PropertyChangedCallback(OnForegroundPropertyChanged))); private static bool InDesignMode { get { if (_inDesignMode.HasValue) { return _inDesignMode.GetValueOrDefault(); } _inDesignMode = (bool)DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty, typeof(FrameworkElement)).Metadata.DefaultValue; if (!_inDesignMode.GetValueOrDefault() && Process.GetCurrentProcess().ProcessName.StartsWith(DesignProcessName, (StringComparison)4)) { _inDesignMode = true; } return _inDesignMode.GetValueOrDefault(); } } public static Brush GetBackground(DependencyObject dependencyObject) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown return (Brush)dependencyObject.GetValue(BackgroundProperty); } public static void SetBackground(DependencyObject dependencyObject, Brush value) { dependencyObject.SetValue(BackgroundProperty, (object)value); } public static Brush GetForeground(DependencyObject dependencyObject) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown return (Brush)dependencyObject.GetValue(ForegroundProperty); } public static void SetForeground(DependencyObject dependencyObject, Brush value) { dependencyObject.SetValue(ForegroundProperty, (object)value); } private static void OnBackgroundPropertyChanged(DependencyObject? d, DependencyPropertyChangedEventArgs e) { if (!InDesignMode || d == null) { return; } System.Type type = ((object)d).GetType(); if (type != null) { PropertyInfo property = type.GetProperty("Background"); if (property != null) { property.SetValue((object)d, ((DependencyPropertyChangedEventArgs)(ref e)).NewValue, (object[])null); } } } private static void OnForegroundPropertyChanged(DependencyObject? d, DependencyPropertyChangedEventArgs e) { if (!InDesignMode || d == null) { return; } System.Type type = ((object)d).GetType(); if (type != null) { PropertyInfo property = type.GetProperty("Foreground"); if (property != null) { property.SetValue((object)d, ((DependencyPropertyChangedEventArgs)(ref e)).NewValue, (object[])null); } } } } [ContentProperty("Symbol")] [MarkupExtensionReturnType(typeof(SymbolIcon))] public class SymbolIconExtension : MarkupExtension { [ConstructorArgument("symbol")] [field: CompilerGenerated] public SymbolRegular Symbol { [CompilerGenerated] get; [CompilerGenerated] set; } [ConstructorArgument("filled")] [field: CompilerGenerated] public bool Filled { [CompilerGenerated] get; [CompilerGenerated] set; } [field: CompilerGenerated] public double FontSize { [CompilerGenerated] get; [CompilerGenerated] set; } public SymbolIconExtension(SymbolRegular symbol) { Symbol = symbol; } public SymbolIconExtension(SymbolRegular symbol, bool filled) : this(symbol) { Filled = filled; } public override object ProvideValue(IServiceProvider serviceProvider) { SymbolIcon symbolIcon = new SymbolIcon { Symbol = Symbol, Filled = Filled }; if (FontSize > 0.0) { symbolIcon.FontSize = FontSize; } return symbolIcon; } } public enum ThemeResource { Unknown, SystemAccentColor, SystemAccentColorPrimary, SystemAccentColorSecondary, SystemAccentColorTertiary, SystemAccentColorPrimaryBrush, SystemAccentColorSecondaryBrush, SystemAccentColorTertiaryBrush, AccentTextFillColorPrimaryBrush, AccentTextFillColorSecondaryBrush, AccentTextFillColorTertiaryBrush, ApplicationBackgroundColor, ApplicationBackgroundBrush, KeyboardFocusBorderColor, KeyboardFocusBorderColorBrush, TextFillColorPrimary, TextFillColorSecondary, TextFillColorTertiary, TextFillColorDisabled, TextPlaceholderColor, TextFillColorInverse, AccentTextFillColorDisabled, TextOnAccentFillColorSelectedText, TextOnAccentFillColorPrimary, TextOnAccentFillColorSecondary, TextOnAccentFillColorDisabled, ControlFillColorDefault, ControlFillColorSecondary, ControlFillColorTertiary, ControlFillColorDisabled, ControlFillColorTransparent, ControlFillColorInputActive, ControlStrongFillColorDefault, ControlStrongFillColorDisabled, ControlSolidFillColorDefault, SubtleFillColorTransparent, SubtleFillColorSecondary, SubtleFillColorTertiary, SubtleFillColorDisabled, ControlAltFillColorTransparent, ControlAltFillColorSecondary, ControlAltFillColorTertiary, ControlAltFillColorQuarternary, ControlAltFillColorDisabled, ControlOnImageFillColorDefault, ControlOnImageFillColorSecondary, ControlOnImageFillColorTertiary, ControlOnImageFillColorDisabled, AccentFillColorDisabled, ControlStrokeColorDefault, ControlStrokeColorSecondary, ControlStrokeColorTertiary, ControlStrokeColorOnAccentDefault, ControlStrokeColorOnAccentSecondary, ControlStrokeColorOnAccentTertiary, ControlStrokeColorOnAccentDisabled, ControlStrokeColorForStrongFillWhenOnImage, CardStrokeColorDefault, CardStrokeColorDefaultSolid, ControlStrongStrokeColorDefault, ControlStrongStrokeColorDisabled, SurfaceStrokeColorDefault, SurfaceStrokeColorFlyout, SurfaceStrokeColorInverse, DividerStrokeColorDefault, FocusStrokeColorOuter, FocusStrokeColorInner, CardBackgroundFillColorDefault, CardBackgroundFillColorSecondary, SmokeFillColorDefault, LayerFillColorDefault, LayerFillColorAlt, LayerOnAcrylicFillColorDefault, LayerOnAccentAcrylicFillColorDefault, LayerOnMicaBaseAltFillColorDefault, LayerOnMicaBaseAltFillColorSecondary, LayerOnMicaBaseAltFillColorTertiary, LayerOnMicaBaseAltFillColorTransparent, SolidBackgroundFillColorBase, SolidBackgroundFillColorSecondary, SolidBackgroundFillColorTertiary, SolidBackgroundFillColorQuarternary, SolidBackgroundFillColorTransparent, SolidBackgroundFillColorBaseAlt, SystemFillColorSuccess, SystemFillColorCaution, SystemFillColorCritical, SystemFillColorNeutral, SystemFillColorSolidNeutral, SystemFillColorAttentionBackground, SystemFillColorSuccessBackground, SystemFillColorCautionBackground, SystemFillColorCriticalBackground, SystemFillColorNeutralBackground, SystemFillColorSolidAttentionBackground, SystemFillColorSolidNeutralBackground, TextFillColorPrimaryBrush, TextFillColorSecondaryBrush, TextFillColorTertiaryBrush, TextFillColorDisabledBrush, TextPlaceholderColorBrush, TextFillColorInverseBrush, AccentTextFillColorDisabledBrush, TextOnAccentFillColorSelectedTextBrush, TextOnAccentFillColorPrimaryBrush, TextOnAccentFillColorSecondaryBrush, TextOnAccentFillColorDisabledBrush, ControlFillColorDefaultBrush, ControlFillColorSecondaryBrush, ControlFillColorTertiaryBrush, ControlFillColorDisabledBrush, ControlFillColorTransparentBrush, ControlFillColorInputActiveBrush, ControlStrongFillColorDefaultBrush, ControlStrongFillColorDisabledBrush, ControlSolidFillColorDefaultBrush, SubtleFillColorTransparentBrush, SubtleFillColorSecondaryBrush, SubtleFillColorTertiaryBrush, SubtleFillColorDisabledBrush, ControlAltFillColorTransparentBrush, ControlAltFillColorSecondaryBrush, ControlAltFillColorTertiaryBrush, ControlAltFillColorQuarternaryBrush, ControlAltFillColorDisabledBrush, ControlOnImageFillColorDefaultBrush, ControlOnImageFillColorSecondaryBrush, ControlOnImageFillColorTertiaryBrush, ControlOnImageFillColorDisabledBrush, AccentFillColorDisabledBrush, ControlStrokeColorDefaultBrush, ControlStrokeColorSecondaryBrush, ControlStrokeColorTertiaryBrush, ControlStrokeColorOnAccentDefaultBrush, ControlStrokeColorOnAccentSecondaryBrush, ControlStrokeColorOnAccentTertiaryBrush, ControlStrokeColorOnAccentDisabledBrush, ControlStrokeColorForStrongFillWhenOnImageBrush, CardStrokeColorDefaultBrush, CardStrokeColorDefaultSolidBrush, ControlStrongStrokeColorDefaultBrush, ControlStrongStrokeColorDisabledBrush, SurfaceStrokeColorDefaultBrush, SurfaceStrokeColorFlyoutBrush, SurfaceStrokeColorInverseBrush, DividerStrokeColorDefaultBrush, FocusStrokeColorOuterBrush, FocusStrokeColorInnerBrush, CardBackgroundFillColorDefaultBrush, CardBackgroundFillColorSecondaryBrush, SmokeFillColorDefaultBrush, LayerFillColorDefaultBrush, LayerFillColorAltBrush, LayerOnAcrylicFillColorDefaultBrush, LayerOnAccentAcrylicFillColorDefaultBrush, LayerOnMicaBaseAltFillColorDefaultBrush, LayerOnMicaBaseAltFillColorSecondaryBrush, LayerOnMicaBaseAltFillColorTertiaryBrush, LayerOnMicaBaseAltFillColorTransparentBrush, SolidBackgroundFillColorBaseBrush, SolidBackgroundFillColorSecondaryBrush, SolidBackgroundFillColorTertiaryBrush, SolidBackgroundFillColorQuarternaryBrush, SolidBackgroundFillColorBaseAltBrush, SystemFillColorSuccessBrush, SystemFillColorCautionBrush, SystemFillColorCriticalBrush, SystemFillColorNeutralBrush, SystemFillColorSolidNeutralBrush, SystemFillColorAttentionBackgroundBrush, SystemFillColorSuccessBackgroundBrush, SystemFillColorCautionBackgroundBrush, SystemFillColorCriticalBackgroundBrush, SystemFillColorNeutralBackgroundBrush, SystemFillColorSolidAttentionBackgroundBrush, SystemFillColorSolidNeutralBackgroundBrush, ControlElevationBorderBrush, CircleElevationBorderBrush, AccentControlElevationBorderBrush } [TypeConverter(typeof(DynamicResourceExtensionConverter))] [MarkupExtensionReturnType(typeof(object))] public class ThemeResourceExtension : DynamicResourceExtension { public ThemeResourceExtension() { ((DynamicResourceExtension)this).ResourceKey = ((object)ThemeResource.ApplicationBackgroundBrush).ToString(); } public ThemeResourceExtension(ThemeResource resourceKey) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (resourceKey == ThemeResource.Unknown) { throw new ArgumentNullException("resourceKey"); } ((DynamicResourceExtension)this).ResourceKey = ((object)resourceKey).ToString(); } } [Localizability(/*Could not decode attribute arguments.*/)] [Ambient] [UsableDuringInitialization(true)] public class ThemesDictionary : ResourceDictionary { public ThemeType Theme { set { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown ((ResourceDictionary)this).Source = new Uri("pack://application:,,,/Wpf.Ui;component/Styles/Theme/" + value switch { ThemeType.Dark => "Dark", ThemeType.HighContrast => "HighContrast", _ => "Light", } + ".xaml", (UriKind)1); } } } } namespace Wpf.Ui.Interop { internal static class Dwmapi { public enum DWM_CLOAKED { DWM_CLOAKED_APP = 1, DWM_CLOAKED_SHELL = 2, DWM_CLOAKED_INHERITED = 4 } public enum GESTURE_TYPE { GT_PEN_TAP, GT_PEN_DOUBLETAP, GT_PEN_RIGHTTAP, GT_PEN_PRESSANDHOLD, GT_PEN_PRESSANDHOLDABORT, GT_TOUCH_TAP, GT_TOUCH_DOUBLETAP, GT_TOUCH_RIGHTTAP, GT_TOUCH_PRESSANDHOLD, GT_TOUCH_PRESSANDHOLDABORT, GT_TOUCH_PRESSANDTAP } public enum DWM_TAB_WINDOW_REQUIREMENTS { DWMTWR_NONE = 0, DWMTWR_IMPLEMENTED_BY_SYSTEM = 1, DWMTWR_WINDOW_RELATIONSHIP = 2, DWMTWR_WINDOW_STYLES = 4, DWMTWR_WINDOW_REGION = 8, DWMTWR_WINDOW_DWM_ATTRIBUTES = 0x10, DWMTWR_WINDOW_MARGINS = 0x20, DWMTWR_TABBING_ENABLED = 0x40, DWMTWR_USER_POLICY = 0x80, DWMTWR_GROUP_POLICY = 0x100, DWMTWR_APP_COMPAT = 0x200 } [Flags] public enum DWM_WINDOW_CORNER_PREFERENCE { DEFAULT = 0, DONOTROUND = 1, ROUND = 2, ROUNDSMALL = 3 } [Flags] public enum DWMSBT : uint { DWMSBT_AUTO = 0u, DWMSBT_DISABLE = 1u, DWMSBT_MAINWINDOW = 2u, DWMSBT_TRANSIENTWINDOW = 3u, DWMSBT_TABBEDWINDOW = 4u } public enum DWMNCRENDERINGPOLICY { DWMNCRP_USEWINDOWSTYLE, DWMNCRP_DISABLED, DWMNCRP_ENABLED, DWMNCRP_LAST } public enum DWMFLIP3DWINDOWPOLICY { DWMFLIP3D_DEFAULT, DWMFLIP3D_EXCLUDEBELOW, DWMFLIP3D_EXCLUDEABOVE, DWMFLIP3D_LAST } [Flags] public enum DWMWINDOWATTRIBUTE { DWMWA_NCRENDERING_ENABLED = 1, DWMWA_NCRENDERING_POLICY = 2, DWMWA_TRANSITIONS_FORCEDISABLED = 3, DWMWA_ALLOW_NCPAINT = 4, DWMWA_CAPTION_BUTTON_BOUNDS = 5, DWMWA_NONCLIENT_RTL_LAYOUT = 6, DWMWA_FORCE_ICONIC_REPRESENTATION = 7, DWMWA_FLIP3D_POLICY = 8, DWMWA_EXTENDED_FRAME_BOUNDS = 9, DWMWA_HAS_ICONIC_BITMAP = 0xA, DWMWA_DISALLOW_PEEK = 0xB, DWMWA_EXCLUDED_FROM_PEEK = 0xC, DWMWA_CLOAK = 0xD, DWMWA_CLOAKED = 0xE, DWMWA_FREEZE_REPRESENTATION = 0xF, DWMWA_PASSIVE_UPDATE_MODE = 0x10, DWMWA_USE_HOSTBACKDROPBRUSH = 0x11, DMWA_USE_IMMERSIVE_DARK_MODE_OLD = 0x13, DWMWA_USE_IMMERSIVE_DARK_MODE = 0x14, DWMWA_WINDOW_CORNER_PREFERENCE = 0x21, DWMWA_BORDER_COLOR = 0x22, DWMWA_CAPTION_COLOR = 0x23, DWMWA_TEXT_COLOR = 0x24, DWMWA_VISIBLE_FRAME_BORDER_THICKNESS = 0x25, DWMWA_SYSTEMBACKDROP_TYPE = 0x26, DWMWA_MICA_EFFECT = 0x405 } public struct DWMCOLORIZATIONPARAMS { public uint clrColor; public uint clrAfterGlow; public uint nIntensity; public uint clrAfterGlowBalance; public uint clrBlurBalance; public uint clrGlassReflectionIntensity; public bool fOpaque; } public struct UNSIGNED_RATIO { public uint uiNumerator; public uint uiDenominator; } public enum DWM_SHOWCONTACT { DWMSC_DOWN, DWMSC_UP, DWMSC_DRAG, DWMSC_HOLD, DWMSC_PENBARREL, DWMSC_NONE, DWMSC_ALL } public enum DWM_SOURCE_FRAME_SAMPLING { DWM_SOURCE_FRAME_SAMPLING_POINT, DWM_SOURCE_FRAME_SAMPLING_COVERAGE, DWM_SOURCE_FRAME_SAMPLING_LAST } [StructLayout(0, Pack = 1)] public struct DWM_TIMING_INFO { public int cbSize; public UNSIGNED_RATIO rateRefresh; public ulong qpcRefreshPeriod; public UNSIGNED_RATIO rateCompose; public ulong qpcVBlank; public ulong cRefresh; public uint cDXRefresh; public ulong qpcCompose; public ulong cFrame; public uint cDXPresent; public ulong cRefreshFrame; public ulong cFrameSubmitted; public uint cDXPresentSubmitted; public ulong cFrameConfirmed; public uint cDXPresentConfirmed; public ulong cRefreshConfirmed; public uint cDXRefreshConfirmed; public ulong cFramesLate; public uint cFramesOutstanding; public ulong cFrameDisplayed; public ulong qpcFrameDisplayed; public ulong cRefreshFrameDisplayed; public ulong cFrameComplete; public ulong qpcFrameComplete; public ulong cFramePending; public ulong qpcFramePending; public ulong cFramesDisplayed; public ulong cFramesComplete; public ulong cFramesPending; public ulong cFramesAvailable; public ulong cFramesDropped; public ulong cFramesMissed; public ulong cRefreshNextDisplayed; public ulong cRefreshNextPresented; public ulong cRefreshesDisplayed; public ulong cRefreshesPresented; public ulong cRefreshStarted; public ulong cPixelsReceived; public ulong cPixelsDrawn; public ulong cBuffersEmpty; } public enum DWM_SIT { NONE, DISPLAYFRAME } [DllImport("dwmapi.dll", BestFitMapping = false)] public static extern int DwmIsCompositionEnabled(out int pfEnabled); [DllImport("dwmapi.dll", PreserveSig = false)] public static extern void DwmExtendFrameIntoClientArea([In] nint hWnd, [In] ref UxTheme.MARGINS pMarInset); [DllImport("dwmapi.dll")] public static extern void DwmGetCompositionTimingInfo([In] nint hWnd, [In] ref DWM_TIMING_INFO pTimingInfo); [DllImport("dwmapi.dll", PreserveSig = false)] public static extern void DwmInvalidateIconicBitmaps([In] nint hWnd); [DllImport("dwmapi.dll", PreserveSig = false)] public static extern void DwmSetIconicThumbnail([In] nint hWnd, [In] nint hbmp, [In] DWM_SIT dwSITFlags); [DllImport("dwmapi.dll", PreserveSig = false)] public static extern int DwmSetIconicLivePreviewBitmap([In] nint hWnd, [In] nint hbmp, [Optional][In] POINT pptClient, [In] DWM_SIT dwSITFlags); [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute([In] nint hWnd, [In] int dwAttribute, [In] ref int pvAttribute, [In] int cbAttribute); [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute([In] nint hWnd, [In] DWMWINDOWATTRIBUTE dwAttribute, [In] ref int pvAttribute, [In] int cbAttribute); [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute([In] nint hWnd, [In] DWMWINDOWATTRIBUTE dwAttributeToGet, [In] ref int pvAttributeValue, [In] int cbAttribute); [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute([In] nint hWnd, [In] int dwAttributeToGet, [In] ref int pvAttributeValue, [In] int cbAttribute); [DllImport("dwmapi.dll", CharSet = 3, EntryPoint = "#127", PreserveSig = false)] public static extern void DwmGetColorizationParameters(out DWMCOLORIZATIONPARAMS dwParameters); } [StructLayout(0, Size = 1)] internal struct HRESULT { public const int S_OK = 0; public const int NO_ERROR = 0; public const int NOERROR = 0; public const int S_FALSE = 1; public static void Check(int hr) { if (hr < 0) { Marshal.ThrowExceptionForHR(hr, (System.IntPtr)(-1)); } } } internal class Kernel32 { [DllImport("kernel32.dll")] public static extern int GetLastError(); [DllImport("kernel32.dll", CharSet = 4, ExactSpelling = true)] public static extern void SetLastError([In] int dwErrorCode); [DllImport("kernel32.dll", CharSet = 4, ExactSpelling = true)] [return: MarshalAs(2)] public static extern bool IsDebuggerPresent(); } internal static class Libraries { internal const string Dwmapi = "dwmapi.dll"; internal const string Kernel32 = "kernel32.dll"; internal const string Shell32 = "shell32.dll"; internal const string User32 = "user32.dll"; internal const string UxTheme = "uxtheme.dll"; internal const string Version = "version.dll"; } internal static class Shell32 { public enum DOGIF { DEFAULT = 0, TRAVERSE_LINK = 1, NO_HDROP = 2, NO_URL = 4, ONLY_IF_ONE = 8 } public enum NIM : uint { ADD, MODIFY, DELETE, SETFOCUS, SETVERSION } [Flags] public enum NIF : uint { MESSAGE = 1u, ICON = 2u, TIP = 4u, STATE = 8u, INFO = 0x10u, GUID = 0x20u, REALTIME = 0x40u, SHOWTIP = 0x80u, XP_MASK = 0x3Bu, VISTA_MASK = 0xFBu } [StructLayout(0)] public class NOTIFYICONDATA { public int cbSize = Marshal.SizeOf(typeof(NOTIFYICONDATA)); public nint hWnd; public int uID; public NIF uFlags; public int uCallbackMessage; public nint hIcon; [MarshalAs(23, SizeConst = 128)] public string szTip; public uint dwState; public uint dwStateMask; [MarshalAs(23, SizeConst = 256)] public string szInfo; public uint uVersion; [MarshalAs(23, SizeConst = 64)] public string szInfoTitle; public uint dwInfoFlags; public Guid guidItem; private nint hBalloonIcon; } [DllImport("shell32.dll", PreserveSig = false)] public static extern void SHGetItemFromDataObject(IDataObject pdtobj, DOGIF dwFlags, [In] ref Guid riid, [MarshalAs(28)] out object ppv); [DllImport("shell32.dll")] public static extern int SHCreateItemFromParsingName([MarshalAs(21)] string pszPath, IBindCtx pbc, [In] ref Guid riid, [MarshalAs(28)] out object ppv); [DllImport("shell32.dll")] [return: MarshalAs(2)] public static extern bool Shell_NotifyIcon([In] NIM dwMessage, [In] NOTIFYICONDATA lpdata); [DllImport("shell32.dll", PreserveSig = false)] public static extern void SetCurrentProcessExplicitAppUserModelID([MarshalAs(21)] string AppID); [DllImport("shell32.dll")] public static extern int GetCurrentProcessExplicitAppUserModelID([MarshalAs(21)] out string AppID); } internal static class ShObjIdl { [Flags] public enum THUMBBUTTONFLAGS { THBF_ENABLED = 0, THBF_DISABLED = 1, THBF_DISMISSONCLICK = 2, THBF_NOBACKGROUND = 4, THBF_HIDDEN = 8, THBF_NONINTERACTIVE = 0x10 } [Flags] public enum THUMBBUTTONMASK { THB_BITMAP = 1, THB_ICON = 2, THB_TOOLTIP = 4, THB_FLAGS = 8 } [Flags] public enum TBPFLAG { TBPF_NOPROGRESS = 0, TBPF_INDETERMINATE = 1, TBPF_NORMAL = 2, TBPF_ERROR = 4, TBPF_PAUSED = 8 } [Flags] public enum STPFLAG { STPF_NONE = 0, STPF_USEAPPTHUMBNAILALWAYS = 1, STPF_USEAPPTHUMBNAILWHENACTIVE = 2, STPF_USEAPPPEEKALWAYS = 4, STPF_USEAPPPEEKWHENACTIVE = 8 } public enum EXPLORER_BROWSER_OPTIONS { EBO_NONE = 0, EBO_NAVIGATEONCE = 1, EBO_SHOWFRAMES = 2, EBO_ALWAYSNAVIGATE = 4, EBO_NOTRAVELLOG = 8, EBO_NOWRAPPERWINDOW = 0x10, EBO_HTMLSHAREPOINTVIEW = 0x20, EBO_NOBORDER = 0x40, EBO_NOPERSISTVIEWSTATE = 0x80 } public enum EXPLORER_BROWSER_FILL_FLAGS { EBF_NONE = 0, EBF_SELECTFROMDATAOBJECT = 0x100, EBF_NODROPTARGET = 0x200 } [StructLayout(0, CharSet = 3, Pack = 8)] public struct THUMBBUTTON { public const int THBN_CLICKED = 6144; public THUMBBUTTONMASK dwMask; public uint iId; public uint iBitmap; public nint hIcon; [MarshalAs(23, SizeConst = 260)] public string szTip; public THUMBBUTTONFLAGS dwFlags; } [ComImport] [Guid("56FDF344-FD6D-11d0-958A-006097C9A090")] [ClassInterface(/*Could not decode attribute arguments.*/)] public class CTaskbarList { } [ComImport] [Guid("9ac9fbe1-e0a2-4ad6-b4ee-e212013ea917")] [ClassInterface(/*Could not decode attribute arguments.*/)] public class ShellItem { } [ComImport] [Guid("c43dc798-95d1-4bea-9030-bb99e2983a1a")] [InterfaceType(/*Could not decode attribute arguments.*/)] public interface ITaskbarList4 { [PreserveSig] void HrInit(); [PreserveSig] void AddTab(nint hwnd); [PreserveSig] void DeleteTab(nint hwnd); [PreserveSig] void ActivateTab(nint hwnd); [PreserveSig] void SetActiveAlt(nint hwnd); [PreserveSig] void MarkFullscreenWindow(nint hwnd, [MarshalAs(2)] bool fFullscreen); [PreserveSig] void SetProgressValue(nint hwnd, ulong ullCompleted, ulong ullTotal); [PreserveSig] void SetProgressState(nint hwnd, TBPFLAG tbpFlags); [PreserveSig] void RegisterTab(nint hwndTab, nint hwndMDI); [PreserveSig] void UnregisterTab(nint hwndTab); [PreserveSig] void SetTabOrder(nint hwndTab, nint hwndInsertBefore); [PreserveSig] void SetTabActive(nint hwndTab, nint hwndInsertBefore, uint dwReserved); [PreserveSig] int ThumbBarAddButtons(nint hwnd, uint cButtons, [MarshalAs(42)] THUMBBUTTON[] pButtons); [PreserveSig] int ThumbBarUpdateButtons(nint hwnd, uint cButtons, [MarshalAs(42)] THUMBBUTTON[] pButtons); [PreserveSig] void ThumbBarSetImageList(nint hWnd, nint himl); [PreserveSig] void SetOverlayIcon(nint hwnd, nint hIcon, [MarshalAs(21)] string pszDescription); [PreserveSig] void SetThumbnailTooltip(nint hwnd, [MarshalAs(21)] string pszTip); [PreserveSig] void SetThumbnailClip(nint hwnd, nint prcClip); void SetTabProperties(nint hwndTab, STPFLAG stpFlags); } } public static class UnsafeNativeMethods { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static RoutedEventHandler <>9__6_0; internal void <RemoveWindowTitlebarContents>b__6_0(object sender, RoutedEventArgs _) { GetHandle((Window?)((sender is Window) ? sender : null), out var windowHandle); RemoveWindowTitlebarContents(windowHandle); } } public static bool ApplyWindowCornerPreference(Window window, WindowCornerPreference cornerPreference) { if (GetHandle(window, out var windowHandle)) { return ApplyWindowCornerPreference(windowHandle, cornerPreference); } return false; } public static bool ApplyWindowCornerPreference(nint handle, WindowCornerPreference cornerPreference) { if (handle == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(handle)) { return false; } int pvAttribute = (int)UnsafeReflection.Cast(cornerPreference); Dwmapi.DwmSetWindowAttribute(handle, Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_WINDOW_CORNER_PREFERENCE, ref pvAttribute, Marshal.SizeOf(typeof(int))); return true; } public static bool RemoveWindowDarkMode(Window? window) { if (GetHandle(window, out var windowHandle)) { return RemoveWindowDarkMode(windowHandle); } return false; } public static bool RemoveWindowDarkMode(nint handle) { if (handle == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(handle)) { return false; } int pvAttribute = 0; Dwmapi.DWMWINDOWATTRIBUTE dwAttribute = Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_USE_IMMERSIVE_DARK_MODE; if (!Utilities.IsOSWindows11Insider1OrNewer) { dwAttribute = Dwmapi.DWMWINDOWATTRIBUTE.DMWA_USE_IMMERSIVE_DARK_MODE_OLD; } Dwmapi.DwmSetWindowAttribute(handle, dwAttribute, ref pvAttribute, Marshal.SizeOf(typeof(int))); return true; } public static bool ApplyWindowDarkMode(Window? window) { if (GetHandle(window, out var windowHandle)) { return ApplyWindowDarkMode(windowHandle); } return false; } public static bool ApplyWindowDarkMode(nint handle) { if (handle == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(handle)) { return false; } int pvAttribute = 1; Dwmapi.DWMWINDOWATTRIBUTE dwAttribute = Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_USE_IMMERSIVE_DARK_MODE; if (!Utilities.IsOSWindows11Insider1OrNewer) { dwAttribute = Dwmapi.DWMWINDOWATTRIBUTE.DMWA_USE_IMMERSIVE_DARK_MODE_OLD; } Dwmapi.DwmSetWindowAttribute(handle, dwAttribute, ref pvAttribute, Marshal.SizeOf(typeof(int))); return true; } public static bool RemoveWindowTitlebarContents(Window? window) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown if (window == null) { return false; } if (((FrameworkElement)window).IsLoaded) { if (GetHandle(window, out var windowHandle)) { return RemoveWindowTitlebarContents(windowHandle); } return false; } object obj = <>c.<>9__6_0; if (obj == null) { RoutedEventHandler val = delegate(object sender, RoutedEventArgs _) { GetHandle((Window?)((sender is Window) ? sender : null), out var windowHandle2); RemoveWindowTitlebarContents(windowHandle2); }; <>c.<>9__6_0 = val; obj = (object)val; } ((FrameworkElement)window).Loaded += (RoutedEventHandler)obj; return true; } public static bool RemoveWindowTitlebarContents(nint handle) { if (handle == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(handle)) { return false; } long windowLong = User32.GetWindowLong(handle, User32.GWL.GWL_STYLE); windowLong &= -524289; return User32.SetWindowLong(handle, User32.GWL.GWL_STYLE, windowLong) > 0; } public static bool ApplyWindowBackdrop(nint handle, WindowBackdropType backgroundType) { if (handle == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(handle)) { return false; } int pvAttribute = (int)UnsafeReflection.Cast(backgroundType); if (pvAttribute == 1) { return false; } Dwmapi.DwmSetWindowAttribute(handle, Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_SYSTEMBACKDROP_TYPE, ref pvAttribute, Marshal.SizeOf(typeof(int))); return true; } public static bool IsWindowHasBackdrop(nint handle, WindowBackdropType backdropType) { if (!User32.IsWindow(handle)) { return false; } int pvAttributeValue = 0; Dwmapi.DwmGetWindowAttribute(handle, Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_SYSTEMBACKDROP_TYPE, ref pvAttributeValue, Marshal.SizeOf(typeof(int))); return pvAttributeValue == (int)UnsafeReflection.Cast(backdropType); } public static bool IsWindowHasLegacyMica(Window? window) { if (GetHandle(window, out var windowHandle)) { return IsWindowHasLegacyMica(windowHandle); } return false; } public static bool IsWindowHasLegacyMica(nint handle) { if (!User32.IsWindow(handle)) { return false; } int pvAttributeValue = 0; Dwmapi.DwmGetWindowAttribute(handle, Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_MICA_EFFECT, ref pvAttributeValue, Marshal.SizeOf(typeof(int))); return pvAttributeValue == 1; } public static bool ApplyWindowLegacyMicaEffect(Window? window) { if (GetHandle(window, out var windowHandle)) { return ApplyWindowLegacyMicaEffect(windowHandle); } return false; } public static bool ApplyWindowLegacyMicaEffect(nint handle) { int pvAttribute = 1; Dwmapi.DwmSetWindowAttribute(handle, Dwmapi.DWMWINDOWATTRIBUTE.DWMWA_MICA_EFFECT, ref pvAttribute, Marshal.SizeOf(typeof(int))); return true; } public static bool ApplyWindowLegacyAcrylicEffect(Window? window) { if (GetHandle(window, out var windowHandle)) { return ApplyWindowLegacyAcrylicEffect(windowHandle); } return false; } public static bool ApplyWindowLegacyAcrylicEffect(nint handle) { User32.ACCENT_POLICY aCCENT_POLICY = default(User32.ACCENT_POLICY); aCCENT_POLICY.nAccentState = User32.ACCENT_STATE.ACCENT_ENABLE_ACRYLICBLURBEHIND; aCCENT_POLICY.nColor = 10027008u; User32.ACCENT_POLICY aCCENT_POLICY2 = aCCENT_POLICY; int num = Marshal.SizeOf<User32.ACCENT_POLICY>(aCCENT_POLICY2); nint num2 = Marshal.AllocHGlobal(num); Marshal.StructureToPtr<User32.ACCENT_POLICY>(aCCENT_POLICY2, (System.IntPtr)num2, false); User32.WINCOMPATTRDATA wINCOMPATTRDATA = default(User32.WINCOMPATTRDATA); wINCOMPATTRDATA.Attribute = User32.WCA.WCA_ACCENT_POLICY; wINCOMPATTRDATA.SizeOfData = num; wINCOMPATTRDATA.Data = num2; User32.WINCOMPATTRDATA data = wINCOMPATTRDATA; User32.SetWindowCompositionAttribute(handle, ref data); Marshal.FreeHGlobal((System.IntPtr)num2); return true; } public static Color GetDwmColor() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) Dwmapi.DwmGetColorizationParameters(out var dwParameters); byte[] bytes = BitConverter.GetBytes(dwParameters.clrColor); return Color.FromArgb((byte)255, bytes[2], bytes[1], bytes[0]); } internal static bool SetTaskbarState(nint hWnd, ShObjIdl.TBPFLAG taskbarFlag) { if (hWnd == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(hWnd)) { return false; } if (!(new ShObjIdl.CTaskbarList() is ShObjIdl.ITaskbarList4 taskbarList)) { return false; } taskbarList.HrInit(); taskbarList.SetProgressState(hWnd, taskbarFlag); return true; } internal static bool SetTaskbarValue(nint hWnd, ShObjIdl.TBPFLAG taskbarFlag, int current, int total) { if (hWnd == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(hWnd)) { return false; } if (!(new ShObjIdl.CTaskbarList() is ShObjIdl.ITaskbarList4 taskbarList)) { return false; } taskbarList.HrInit(); taskbarList.SetProgressState(hWnd, taskbarFlag); if (taskbarFlag != ShObjIdl.TBPFLAG.TBPF_INDETERMINATE && taskbarFlag != 0) { taskbarList.SetProgressValue(hWnd, Convert.ToUInt64(current), Convert.ToUInt64(total)); } return true; } public static bool RemoveWindowCaption(Window window) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (window == null) { return false; } return RemoveWindowCaption(new WindowInteropHelper(window).Handle); } public static bool RemoveWindowCaption(nint hWnd) { if (hWnd == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(hWnd)) { return false; } UxTheme.WTA_OPTIONS wTA_OPTIONS = default(UxTheme.WTA_OPTIONS); wTA_OPTIONS.dwFlags = UxTheme.WTNCA.NODRAWCAPTION; wTA_OPTIONS.dwMask = UxTheme.WTNCA.VALIDBITS; UxTheme.WTA_OPTIONS pvAttribute = wTA_OPTIONS; UxTheme.SetWindowThemeAttribute(hWnd, UxTheme.WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT, ref pvAttribute, (uint)Marshal.SizeOf(typeof(UxTheme.WTA_OPTIONS))); return true; } public static bool ExtendClientAreaIntoTitleBar(Window window) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (window == null) { return false; } return ExtendClientAreaIntoTitleBar(new WindowInteropHelper(window).Handle); } public static bool ExtendClientAreaIntoTitleBar(nint hWnd) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) if (hWnd == (nint)System.IntPtr.Zero) { return false; } if (!User32.IsWindow(hWnd)) { return false; } UxTheme.WTA_OPTIONS wTA_OPTIONS = default(UxTheme.WTA_OPTIONS); wTA_OPTIONS.dwFlags = UxTheme.WTNCA.NODRAWCAPTION | UxTheme.WTNCA.NODRAWICON | UxTheme.WTNCA.NOSYSMENU; wTA_OPTIONS.dwMask = UxTheme.WTNCA.VALIDBITS; UxTheme.WTA_OPTIONS pvAttribute = wTA_OPTIONS; UxTheme.SetWindowThemeAttribute(hWnd, UxTheme.WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT, ref pvAttribute, (uint)Marshal.SizeOf(typeof(UxTheme.WTA_OPTIONS))); Wpf.Ui.Dpi.Dpi windowDpi = DpiHelper.GetWindowDpi(hWnd); Thickness val = DpiHelper.LogicalThicknessToDevice(new Thickness(-1.0, -1.0, -1.0, -1.0), windowDpi.DpiScaleX, windowDpi.DpiScaleY); UxTheme.MARGINS mARGINS = default(UxTheme.MARGINS); mARGINS.cxLeftWidth = (int)Math.Ceiling(((Thickness)(ref val)).Left); mARGINS.cxRightWidth = (int)Math.Ceiling(((Thickness)(ref val)).Right); mARGINS.cyTopHeight = (int)Math.Ceiling(((Thickness)(ref val)).Top); mARGINS.cyBottomHeight = (int)Math.Ceiling(((Thickness)(ref val)).Bottom); UxTheme.MARGINS pMarInset = mARGINS; Dwmapi.DwmExtendFrameIntoClientArea(hWnd, ref pMarInset); User32.SetWindowRgn(hWnd, System.IntPtr.Zero, User32.IsWindowVisible(hWnd)); return true; } public static bool IsCompositionEnabled() { Dwmapi.DwmIsCompositionEnabled(out var pfEnabled); return pfEnabled == 1; } public static bool IsValidWindow(nint hWnd) { return User32.IsWindow(hWnd); } private static bool GetHandle(Window? window, out nint windowHandle) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (window == null) { windowHandle = System.IntPtr.Zero; return false; } windowHandle = new WindowInteropHelper(window).Handle; return windowHandle != (nint)System.IntPtr.Zero; } } internal static class UnsafeReflection { public static Dwmapi.DWMSBT Cast(WindowBackdropType backgroundType) { return backgroundType switch { WindowBackdropType.Auto => Dwmapi.DWMSBT.DWMSBT_AUTO, WindowBackdropType.Mica => Dwmapi.DWMSBT.DWMSBT_MAINWINDOW, WindowBackdropType.Acrylic => Dwmapi.DWMSBT.DWMSBT_TRANSIENTWINDOW, WindowBackdropType.Tabbed => Dwmapi.DWMSBT.DWMSBT_TABBEDWINDOW, _ => Dwmapi.DWMSBT.DWMSBT_DISABLE, }; } public static Dwmapi.DWM_WINDOW_CORNER_PREFERENCE Cast(WindowCornerPreference cornerPreference) { return cornerPreference switch { WindowCornerPreference.Round => Dwmapi.DWM_WINDOW_CORNER_PREFERENCE.ROUND, WindowCornerPreference.RoundSmall => Dwmapi.DWM_WINDOW_CORNER_PREFERENCE.ROUNDSMALL, WindowCornerPreference.DoNotRound => Dwmapi.DWM_WINDOW_CORNER_PREFERENCE.DONOTROUND, _ => Dwmapi.DWM_WINDOW_CORNER_PREFERENCE.DEFAULT, }; } public static ShObjIdl.TBPFLAG Cast(TaskBarProgressState taskBarProgressState) { return taskBarProgressState switch { TaskBarProgressState.Indeterminate => ShObjIdl.TBPFLAG.TBPF_INDETERMINATE, TaskBarProgressState.Error => ShObjIdl.TBPFLAG.TBPF_ERROR, TaskBarProgressState.Paused => ShObjIdl.TBPFLAG.TBPF_PAUSED, TaskBarProgressState.Normal => ShObjIdl.TBPFLAG.TBPF_NORMAL, _ => ShObjIdl.TBPFLAG.TBPF_NOPROGRESS, }; } public static TaskBarProgressState Cast(ShObjIdl.TBPFLAG progressState) { return progressState switch { ShObjIdl.TBPFLAG.TBPF_INDETERMINATE => TaskBarProgressState.Indeterminate, ShObjIdl.TBPFLAG.TBPF_ERROR => TaskBarProgressState.Error, ShObjIdl.TBPFLAG.TBPF_PAUSED => TaskBarProgressState.Paused, ShObjIdl.TBPFLAG.TBPF_NORMAL => TaskBarProgressState.Normal, _ => TaskBarProgressState.None, }; } } internal static class User32 { [Flags] public enum SWP { ASYNCWINDOWPOS = 0x4000, DEFERERASE = 0x2000, DRAWFRAME = 0x20, FRAMECHANGED = 0x20, HIDEWINDOW = 0x80, NOACTIVATE = 0x10, NOCOPYBITS = 0x100, NOMOVE = 2, NOOWNERZORDER = 0x200, NOREDRAW = 8, NOREPOSITION = 0x200, NOSENDCHANGING = 0x400, NOSIZE = 1, NOZORDER = 4, SHOWWINDOW = 0x40 } [Flags] public enum MF : uint { DOES_NOT_EXIST = 0xFFFFFFFFu, ENABLED = 0u, BYCOMMAND = 0u, GRAYED = 1u, DISABLED = 2u } public enum SC { SIZE = 61440, MOVE = 61456, MINIMIZE = 61472, MAXIMIZE = 61488, NEXTWINDOW = 61504, PREVWINDOW = 61520, CLOSE = 61536, VSCROLL = 61552, HSCROLL = 61568, MOUSEMENU = 61584, KEYMENU = 61696, ARRANGE = 61712, RESTORE = 61728, TASKLIST = 61744, SCREENSAVE = 61760, HOTKEY = 61776, DEFAULT = 61792, MONITORPOWER = 61808, CONTEXTHELP = 61824, SEPARATOR = 61455, F_ISSECURE = 1, ICON = 61472, ZOOM = 61488 } public enum WM_NCHITTEST { HTERROR = -2, HTTRANSPARENT = -1, HTNOWHERE = 0, HTCLIENT = 1, HTCAPTION = 2, HTSYSMENU = 3, HTGROWBOX = 4, HTSIZE = 4, HTMENU = 5, HTHSCROLL = 6, HTVSCROLL = 7, HTMINBUTTON = 8, HTMAXBUTTON = 9, HTLEFT = 10, HTRIGHT = 11, HTTOP = 12, HTTOPLEFT = 13, HTTOPRIGHT = 14, HTBOTTOM = 15, HTBOTTOMLEFT = 16, HTBOTTOMRIGHT = 17, HTBORDER = 18, HTREDUCE = 8, HTZOOM = 9, HTSIZEFIRST = 10, HTSIZELAST = 17, HTOBJECT = 19, HTCLOSE = 20, HTHELP = 21 } [Flags] public enum GWL { GWL_EXSTYLE = -20, GWLP_HINSTANCE = -6, GWLP_HWNDPARENT = -8, GWL_ID = -12, GWL_STYLE = -16, GWL_USERDATA = -21, GWL_WNDPROC = -4, DWLP_USER = 8, DWLP_MSGRESULT = 0, DWLP_DLGPROC = 4 } public enum WCA { WCA_UNDEFINED, WCA_NCRENDERING_ENABLED, WCA_NCRENDERING_POLICY, WCA_TRANSITIONS_FORCEDISABLED, WCA_ALLOW_NCPAINT, WCA_CAPTION_BUTTON_BOUNDS, WCA_NONCLIENT_RTL_LAYOUT, WCA_FORCE_ICONIC_REPRESENTATION, WCA_EXTENDED_FRAME_BOUNDS, WCA_HAS_ICONIC_BITMAP, WCA_THEME_ATTRIBUTES, WCA_NCRENDERING_EXILED, WCA_NCADORNMENTINFO, WCA_EXCLUDED_FROM_LIVEPREVIEW, WCA_VIDEO_OVERLAY_ACTIVE, WCA_FORCE_ACTIVEWINDOW_APPEARANCE, WCA_DISALLOW_PEEK, WCA_CLOAK, WCA_CLOAKED, WCA_ACCENT_POLICY, WCA_FREEZE_REPRESENTATION, WCA_EVER_UNCLOAKED, WCA_VISUAL_OWNER, WCA_HOLOGRAPHIC, WCA_EXCLUDED_FROM_DDA, WCA_PASSIVEUPDATEMODE, WCA_USEDARKMODECOLORS, WCA_CORNER_STYLE, WCA_PART_COLOR, WCA_DISABLE_MOVESIZE_FEEDBACK, WCA_LAST } [Flags] public enum ACCENT_FLAGS { DrawLeftBorder = 0x20, DrawTopBorder = 0x40, DrawRightBorder = 0x80, DrawBottomBorder = 0x100, DrawAllBorders = 0x1E0 } public enum ACCENT_STATE { ACCENT_DISABLED, ACCENT_ENABLE_GRADIENT, ACCENT_ENABLE_TRANSPARENTGRADIENT, ACCENT_ENABLE_BLURBEHIND, ACCENT_ENABLE_ACRYLICBLURBEHIND, ACCENT_INVALID_STATE } public struct ACCENT_POLICY { public ACCENT_STATE nAccentState; public uint nFlags; public uint nColor; public uint nAnimationId; } public struct WINCOMPATTRDATA { public WCA Attribute; public nint Data; public int SizeOfData; } [Flags] public enum CS : uint { VREDRAW = 1u, HREDRAW = 2u, DBLCLKS = 8u, OWNDC = 0x20u, CLASSDC = 0x40u, PARENTDC = 0x80u, NOCLOSE = 0x200u, SAVEBITS = 0x800u, BYTEALIGNCLIENT = 0x1000u, BYTEALIGNWINDOW = 0x2000u, GLOBALCLASS = 0x4000u, IME = 0x10000u, DROPSHADOW = 0x20000u } public enum MSGFLT { RESET, ALLOW, DISALLOW } public enum MSGFLTINFO { NONE, ALREADYALLOWED_FORWND, ALREADYDISALLOWED_FORWND, ALLOWED_HIGHER } public struct CHANGEFILTERSTRUCT { public uint cbSize; public MSGFLTINFO ExtStatus; } public enum WM { NULL = 0, CREATE = 1, DESTROY = 2, MOVE = 3, SIZE = 5, ACTIVATE = 6, SETFOCUS = 7, KILLFOCUS = 8, ENABLE = 10, SETREDRAW = 11, SETTEXT = 12, GETTEXT = 13, GETTEXTLENGTH = 14, PAINT = 15, CLOSE = 16, QUERYENDSESSION = 17, QUIT = 18, QUERYOPEN = 19, ERASEBKGND = 20, SYSCOLORCHANGE = 21, SHOWWINDOW = 24, CTLCOLOR = 25, WININICHANGE = 26, SETTINGCHANGE = 26, ACTIVATEAPP = 28, SETCURSOR = 32, MOUSEACTIVATE = 33, CHILDACTIVATE = 34, QUEUESYNC = 35, GETMINMAXINFO = 36, WINDOWPOSCHANGING = 70, WINDOWPOSCHANGED = 71, CONTEXTMENU = 123, STYLECHANGING = 124, STYLECHANGED = 125, DISPLAYCHANGE = 126, GETICON = 127, SETICON = 128, NCCREATE = 129, NCDESTROY = 130, NCCALCSIZE = 131, NCHITTEST = 132, NCPAINT = 133, NCACTIVATE = 134, GETDLGCODE = 135, SYNCPAINT = 136, NCMOUSEMOVE = 160, NCLBUTTONDOWN = 161, NCLBUTTONUP = 162, NCLBUTTONDBLCLK = 163, NCRBUTTONDOWN = 164, NCRBUTTONUP = 165, NCRBUTTONDBLCLK = 166, NCMBUTTONDOWN = 167, NCMBUTTONUP = 168, NCMBUTTONDBLCLK = 169, SYSKEYDOWN = 260, SYSKEYUP = 261, SYSCHAR = 262, SYSDEADCHAR = 263, COMMAND = 273, SYSCOMMAND = 274, MOUSEMOVE = 512, LBUTTONDOWN = 513, LBUTTONUP = 514, LBUTTONDBLCLK = 515, RBUTTONDOWN = 516, RBUTTONUP = 517, RBUTTONDBLCLK = 518, MBUTTONDOWN = 519, MBUTTONUP = 520, MBUTTONDBLCLK = 521, MOUSEWHEEL = 522, XBUTTONDOWN = 523, XBUTTONUP = 524, XBUTTONDBLCLK = 525, MOUSEHWHEEL = 526, PARENTNOTIFY = 528, CAPTURECHANGED = 533, POWERBROADCAST = 536, DEVICECHANGE = 537, ENTERSIZEMOVE = 561, EXITSIZEMOVE = 562, IME_SETCONTEXT = 641, IME_NOTIFY = 642, IME_CONTROL = 643, IME_COMPOSITIONFULL = 644, IME_SELECT = 645, IME_CHAR = 646, IME_REQUEST = 648, IME_KEYDOWN = 656, IME_KEYUP = 657, NCMOUSELEAVE = 674, TABLET_DEFBASE = 704, TABLET_ADDED = 712, TABLET_DELETED = 713, TABLET_FLICK = 715, TABLET_QUERYSYSTEMGESTURESTATUS = 716, CUT = 768, COPY = 769, PASTE = 770, CLEAR = 771, UNDO = 772, RENDERFORMAT = 773, RENDERALLFORMATS = 774, DESTROYCLIPBOARD = 775, DRAWCLIPBOARD = 776, PAINTCLIPBOARD = 777, VSCROLLCLIPBOARD = 778, SIZECLIPBOARD = 779, ASKCBFORMATNAME = 780, CHANGECBCHAIN = 781, HSCROLLCLIPBOARD = 782, QUERYNEWPALETTE = 783, PALETTEISCHANGING = 784, PALETTECHANGED = 785, HOTKEY = 786, PRINT = 791, PRINTCLIENT = 792, APPCOMMAND = 793, THEMECHANGED = 794, DWMCOMPOSITIONCHANGED = 798, DWMNCRENDERINGCHANGED = 799, DWMCOLORIZATIONCOLORCHANGED = 800, DWMWINDOWMAXIMIZEDCHANGE = 801, GETTITLEBARINFOEX = 831, DWMSENDICONICTHUMBNAIL = 803, DWMSENDICONICLIVEPREVIEWBITMAP = 806, USER = 1024, TRAYMOUSEMESSAGE = 2048, APP = 32768 } [Flags] public enum WS : long { OVERLAPPED = 0L, POPUP = 0x80000000L, CHILD = 0x40000000L, MINIMIZE = 0x20000000L, VISIBLE = 0x10000000L, DISABLED = 0x8000000L, CLIPSIBLINGS = 0x4000000L, CLIPCHILDREN = 0x2000000L, MAXIMIZE = 0x1000000L, BORDER = 0x800000L, DLGFRAME = 0x400000L, VSCROLL = 0x200000L, HSCROLL = 0x100000L, SYSMENU = 0x80000L, THICKFRAME = 0x40000L, GROUP = 0x20000L, TABSTOP = 0x10000L, MINIMIZEBOX = 0x20000L, MAXIMIZEBOX = 0x10000L, CAPTION = 0xC00000L, TILED = 0L, ICONIC = 0x20000000L, SIZEBOX = 0x40000L, TILEDWINDOW = 0xCF0000L, OVERLAPPEDWINDOW = 0xCF0000L, POPUPWINDOW = 0x80880000L, CHILDWINDOW = 0x40000000L } [Flags] public enum WS_EX : long { NONE = 0L, DLGMODALFRAME = 1L, NOPARENTNOTIFY = 4L, TOPMOST = 8L, ACCEPTFILES = 0x10L, TRANSPARENT = 0x20L, MDICHILD = 0x40L, TOOLWINDOW = 0x80L, WINDOWEDGE = 0x100L, CLIENTEDGE = 0x200L, CONTEXTHELP = 0x400L, RIGHT = 0x1000L, LEFT = 0L, RTLREADING = 0x2000L, LTRREADING = 0L, LEFTSCROLLBAR = 0x4000L, RIGHTSCROLLBAR = 0L, CONTROLPARENT = 0x10000L, STATICEDGE = 0x20000L, APPWINDOW = 0x40000L, LAYERED = 0x80000L, NOINHERITLAYOUT = 0x100000L, LAYOUTRTL = 0x400000L, COMPOSITED = 0x2000000L, NOACTIVATE = 0x8000000L, OVERLAPPEDWINDOW = 0x300L, PALETTEWINDOW = 0x188L } public enum SM { CXSCREEN = 0, CYSCREEN = 1, CXVSCROLL = 2, CYHSCROLL = 3, CYCAPTION = 4, CXBORDER = 5, CYBORDER = 6, CXFIXEDFRAME = 7, CYFIXEDFRAME = 8, CYVTHUMB = 9, CXHTHUMB = 10, CXICON = 11, CYICON = 12, CXCURSOR = 13, CYCURSOR = 14, CYMENU = 15, CXFULLSCREEN = 16, CYFULLSCREEN = 17, CYKANJIWINDOW = 18, MOUSEPRESENT = 19, CYVSCROLL = 20, CXHSCROLL = 21, DEBUG = 22, SWAPBUTTON = 23, CXMIN = 28, CYMIN = 29, CXSIZE = 30, CYSIZE = 31, CXFRAME = 32, CXSIZEFRAME = 32, CYFRAME = 33, CYSIZEFRAME = 33, CXMINTRACK = 34, CYMINTRACK = 35, CXDOUBLECLK = 36, CYDOUBLECLK = 37, CXICONSPACING = 38, CYICONSPACING = 39, MENUDROPALIGNMENT = 40, PENWINDOWS = 41, DBCSENABLED = 42, CMOUSEBUTTONS = 43, SECURE = 44, CXEDGE = 45, CYEDGE = 46, CXMINSPACING = 47, CYMINSPACING = 48, CXSMICON = 49, CYSMICON = 50, CYSMCAPTION = 51, CXSMSIZE = 52, CYSMSIZE = 53, CXMENUSIZE = 54, CYMENUSIZE = 55, ARRANGE = 56, CXMINIMIZED = 57, CYMINIMIZED = 58, CXMAXTRACK = 59, CYMAXTRACK = 60, CXMAXIMIZED = 61, CYMAXIMIZED = 62, NETWORK = 63, CLEANBOOT = 67, CXDRAG = 68, CYDRAG = 69, SHOWSOUNDS = 70, CXMENUCHECK = 71, CYMENUCHECK = 72, SLOWMACHINE = 73, MIDEASTENABLED = 74, MOUSEWHEELPRESENT = 75, XVIRTUALSCREEN = 76, YVIRTUALSCREEN = 77, CXVIRTUALSCREEN = 78, CYVIRTUALSCREEN = 79, CMONITORS = 80, SAMEDISPLAYFORMAT = 81, IMMENABLED = 82, CXFOCUSBORDER = 83, CYFOCUSBORDER = 84, TABLETPC = 86, MEDIACENTER = 87, CXPADDEDBORDER = 92, REMOTESESSION = 4096, REMOTECONTROL = 8193 } public enum SW { HIDE = 0, SHOWNORMAL = 1, NORMAL = 1, SHOWMINIMIZED = 2, SHOWMAXIMIZED = 3, MAXIMIZE = 3, SHOWNOACTIVATE = 4, SHOW = 5, MINIMIZE = 6, SHOWMINNOACTIVE = 7, SHOWNA = 8, RESTORE = 9, SHOWDEFAULT = 10, FORCEMINIMIZE = 11 } [StructLayout(0)] public class WINDOWPLACEMENT { public int length = Marshal.SizeOf(typeof(WINDOWPLACEMENT)); public int flags; public SW showCmd; public POINT ptMinPosition; public POINT ptMaxPosition; public RECT rcNormalPosition; } [StructLayout(0, CharSet = 3)] public struct WNDCLASSEX { public int cbSize; public CS style; public WndProc lpfnWndProc; public int cbClsExtra; public int cbWndExtra; public nint hInstance; public nint hIcon; public nint hCursor; public nint hbrBackground; [MarshalAs(21)] public string lpszMenuName; [MarshalAs(21)] public string lpszClassName; public nint hIconSm; } public delegate nint WndProc(nint hWnd, WM uMsg, nint wParam, nint lParam); public delegate nint WndProcHook(nint hWnd, WM uMsg, nint wParam, nint lParam, ref bool handled); public delegate nint MessageHandler(WM uMsg, nint wParam, nint lParam, out bool handled); [DllImport("user32.dll", CharSet = 4)] public static extern int ReleaseDC([In] nint hWnd, [In] nint hDC); [DllImport("user32.dll", CharSet = 4, SetLastError = true)] [return: MarshalAs(2)] public static extern bool AdjustWindowRectEx([In] ref Rect lpRec