Decompiled source of MegabonkTogether v2.0.0
MegabonkTogether/Microsoft.Extensions.Configuration.FileExtensions.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.FileExtensions.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.FileExtensions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.FileExtensions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.FileExtensions { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace 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) { if (builder == null) { throw new ArgumentNullException("builder"); } builder.Properties[FileProviderKey] = fileProvider ?? throw new ArgumentNullException("fileProvider"); return builder; } public static IFileProvider GetFileProvider(this IConfigurationBuilder builder) { if (builder == null) { throw new ArgumentNullException("builder"); } if (builder.Properties.TryGetValue(FileProviderKey, out var value)) { return value as IFileProvider; } return new PhysicalFileProvider(AppContext.BaseDirectory ?? string.Empty); } public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder builder, string basePath) { if (builder == null) { throw new ArgumentNullException("builder"); } if (basePath == null) { throw new ArgumentNullException("basePath"); } return builder.SetFileProvider(new PhysicalFileProvider(basePath)); } public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurationBuilder builder, Action<FileLoadExceptionContext> handler) { if (builder == null) { throw new ArgumentNullException("builder"); } builder.Properties[FileLoadExceptionHandlerKey] = handler; return builder; } public static Action<FileLoadExceptionContext> GetFileLoadExceptionHandler(this IConfigurationBuilder builder) { if (builder == null) { throw new ArgumentNullException("builder"); } if (builder.Properties.TryGetValue(FileLoadExceptionHandlerKey, out var value)) { return value as Action<FileLoadExceptionContext>; } return null; } } public abstract class FileConfigurationProvider : ConfigurationProvider, IDisposable { private readonly IDisposable _changeTokenRegistration; public FileConfigurationSource Source { get; } public FileConfigurationProvider(FileConfigurationSource source) { Source = source ?? throw new ArgumentNullException("source"); if (Source.ReloadOnChange && Source.FileProvider != null) { _changeTokenRegistration = ChangeToken.OnChange(() => Source.FileProvider.Watch(Source.Path), delegate { Thread.Sleep(Source.ReloadDelay); Load(reload: true); }); } } public override string ToString() { return GetType().Name + " for '" + Source.Path + "' (" + (Source.Optional ? "Optional" : "Required") + ")"; } private void Load(bool reload) { IFileInfo fileInfo2 = Source.FileProvider?.GetFileInfo(Source.Path); if (fileInfo2 == null || !fileInfo2.Exists) { if (Source.Optional || reload) { base.Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } else { StringBuilder stringBuilder = new StringBuilder(System.SR.Format(System.SR.Error_FileNotFound, Source.Path)); if (!string.IsNullOrEmpty(fileInfo2?.PhysicalPath)) { stringBuilder.Append(System.SR.Format(System.SR.Error_ExpectedPhysicalPath, fileInfo2.PhysicalPath)); } HandleException(ExceptionDispatchInfo.Capture(new FileNotFoundException(stringBuilder.ToString()))); } } else { using Stream stream = OpenRead(fileInfo2); try { Load(stream); } catch (Exception innerException) { if (reload) { base.Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } InvalidDataException source = new InvalidDataException(System.SR.Format(System.SR.Error_FailedToLoad, fileInfo2.PhysicalPath), innerException); HandleException(ExceptionDispatchInfo.Capture(source)); } } OnReload(); static Stream OpenRead(IFileInfo fileInfo) { if (fileInfo.PhysicalPath != null) { return new FileStream(fileInfo.PhysicalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1, FileOptions.SequentialScan); } 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(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 { public IFileProvider FileProvider { get; set; } public string Path { get; set; } public bool Optional { get; set; } public bool ReloadOnChange { get; set; } public int ReloadDelay { get; set; } = 250; public Action<FileLoadExceptionContext> OnLoadException { get; set; } public abstract IConfigurationProvider Build(IConfigurationBuilder builder); public void EnsureDefaults(IConfigurationBuilder builder) { FileProvider = FileProvider ?? builder.GetFileProvider(); OnLoadException = OnLoadException ?? builder.GetFileLoadExceptionHandler(); } public void ResolveFileProvider() { if (FileProvider == null && !string.IsNullOrEmpty(Path) && System.IO.Path.IsPathRooted(Path)) { string directoryName = System.IO.Path.GetDirectoryName(Path); string text = System.IO.Path.GetFileName(Path); while (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { text = System.IO.Path.Combine(System.IO.Path.GetFileName(directoryName), text); directoryName = System.IO.Path.GetDirectoryName(directoryName); } if (Directory.Exists(directoryName)) { FileProvider = new PhysicalFileProvider(directoryName); Path = text; } } } } public class FileLoadExceptionContext { public FileConfigurationProvider Provider { get; set; } public Exception Exception { get; set; } public bool Ignore { get; set; } } }
MegabonkTogether/Microsoft.Extensions.Primitives.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; 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; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Primitives")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Primitives")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] namespace FxResources.Microsoft.Extensions.Primitives { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string Argument_InvalidOffsetLength => GetResourceString("Argument_InvalidOffsetLength"); internal static string Argument_InvalidOffsetLengthStringSegment => GetResourceString("Argument_InvalidOffsetLengthStringSegment"); internal static string Capacity_CannotChangeAfterWriteStarted => GetResourceString("Capacity_CannotChangeAfterWriteStarted"); internal static string Capacity_NotEnough => GetResourceString("Capacity_NotEnough"); internal static string Capacity_NotUsedEntirely => GetResourceString("Capacity_NotUsedEntirely"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.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 : IDisposable { public static readonly NullDisposable Instance = new NullDisposable(); public void Dispose() { } } public bool ActiveChangeCallbacks { get; private set; } = true; public bool HasChanged => Token.IsCancellationRequested; private CancellationToken Token { get; } public CancellationChangeToken(CancellationToken cancellationToken) { Token = cancellationToken; } public IDisposable RegisterChangeCallback(Action<object> callback, object state) { try { return Token.UnsafeRegister(callback, state); } catch (ObjectDisposedException) { ActiveChangeCallbacks = false; } return NullDisposable.Instance; } } public static class ChangeToken { private sealed class ChangeTokenRegistration<TState> : IDisposable { private sealed class NoopDisposable : IDisposable { public void Dispose() { } } private readonly Func<IChangeToken> _changeTokenProducer; private readonly Action<TState> _changeTokenConsumer; private readonly TState _state; private IDisposable _disposable; private static readonly NoopDisposable _disposedSentinel = new NoopDisposable(); public ChangeTokenRegistration(Func<IChangeToken> changeTokenProducer, Action<TState> changeTokenConsumer, TState state) { _changeTokenProducer = changeTokenProducer; _changeTokenConsumer = changeTokenConsumer; _state = state; IChangeToken token = changeTokenProducer(); RegisterChangeTokenCallback(token); } private void OnChangeTokenFired() { IChangeToken token = _changeTokenProducer(); try { _changeTokenConsumer(_state); } finally { RegisterChangeTokenCallback(token); } } private void RegisterChangeTokenCallback(IChangeToken token) { if (token != null) { IDisposable disposable = token.RegisterChangeCallback(delegate(object s) { ((ChangeTokenRegistration<TState>)s).OnChangeTokenFired(); }, this); SetDisposable(disposable); } } private void SetDisposable(IDisposable disposable) { IDisposable disposable2 = Volatile.Read(ref _disposable); if (disposable2 == _disposedSentinel) { disposable.Dispose(); return; } IDisposable disposable3 = Interlocked.CompareExchange(ref _disposable, disposable, disposable2); if (disposable3 == _disposedSentinel) { disposable.Dispose(); } else if (disposable3 != disposable2) { throw new InvalidOperationException("Somebody else set the _disposable field"); } } public void Dispose() { Interlocked.Exchange(ref _disposable, _disposedSentinel).Dispose(); } } public static IDisposable OnChange(Func<IChangeToken> changeTokenProducer, Action changeTokenConsumer) { if (changeTokenProducer == null) { throw new ArgumentNullException("changeTokenProducer"); } if (changeTokenConsumer == null) { throw new ArgumentNullException("changeTokenConsumer"); } return new ChangeTokenRegistration<Action>(changeTokenProducer, delegate(Action callback) { callback(); }, changeTokenConsumer); } public static IDisposable OnChange<TState>(Func<IChangeToken> changeTokenProducer, Action<TState> changeTokenConsumer, TState state) { if (changeTokenProducer == null) { throw new ArgumentNullException("changeTokenProducer"); } if (changeTokenConsumer == null) { throw new ArgumentNullException("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 bool _registeredCallbackProxy; private List<IDisposable> _disposables; public IReadOnlyList<IChangeToken> ChangeTokens { get; } public bool HasChanged { get { if (_cancellationTokenSource != null && _cancellationTokenSource.Token.IsCancellationRequested) { return true; } for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].HasChanged) { OnChange(this); return true; } } return false; } } public bool ActiveChangeCallbacks { get; } public CompositeChangeToken(IReadOnlyList<IChangeToken> changeTokens) { ChangeTokens = changeTokens ?? throw new ArgumentNullException("changeTokens"); for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { ActiveChangeCallbacks = true; break; } } } public IDisposable RegisterChangeCallback(Action<object> callback, object state) { EnsureCallbacksInitialized(); return _cancellationTokenSource.Token.Register(callback, state); } private void EnsureCallbacksInitialized() { if (_registeredCallbackProxy) { return; } lock (_callbackLock) { if (_registeredCallbackProxy) { return; } _cancellationTokenSource = new CancellationTokenSource(); _disposables = new List<IDisposable>(); for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) { IDisposable item = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this); _disposables.Add(item); } } _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<IDisposable> disposables = compositeChangeToken._disposables; for (int i = 0; i < disposables.Count; i++) { disposables[i].Dispose(); } } } public static class Extensions { public static StringBuilder Append(this StringBuilder builder, StringSegment segment) { return builder.Append(segment.Buffer, segment.Offset, segment.Length); } } public interface IChangeToken { bool HasChanged { get; } bool ActiveChangeCallbacks { get; } IDisposable RegisterChangeCallback(Action<object> callback, object state); } public readonly struct StringSegment : IEquatable<StringSegment>, IEquatable<string> { public static readonly StringSegment Empty = string.Empty; public string Buffer { get; } public int Offset { get; } public int Length { get; } public string Value { get { if (!HasValue) { return null; } return Buffer.Substring(Offset, Length); } } public bool HasValue => Buffer != null; public char this[int index] { get { if ((uint)index >= (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return Buffer[Offset + index]; } } public StringSegment(string buffer) { Buffer = buffer; Offset = 0; Length = buffer?.Length ?? 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public StringSegment(string buffer, int offset, int length) { if (buffer == null || (uint)offset > (uint)buffer.Length || (uint)length > (uint)(buffer.Length - offset)) { ThrowInvalidArguments(buffer, offset, length); } Buffer = buffer; Offset = offset; Length = length; } public ReadOnlySpan<char> AsSpan() { return Buffer.AsSpan(Offset, Length); } public ReadOnlySpan<char> AsSpan(int start) { if (!HasValue || start < 0) { ThrowInvalidArguments(start, Length - start, ExceptionArgument.start); } return Buffer.AsSpan(Offset + start, Length - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { if (!HasValue || start < 0 || length < 0 || (uint)(start + length) > (uint)Length) { ThrowInvalidArguments(start, length, ExceptionArgument.start); } return Buffer.AsSpan(Offset + start, length); } public ReadOnlyMemory<char> AsMemory() { return Buffer.AsMemory(Offset, Length); } public static int Compare(StringSegment a, StringSegment b, StringComparison comparisonType) { if (a.HasValue && b.HasValue) { return a.AsSpan().CompareTo(b.AsSpan(), comparisonType); } CheckStringComparison(comparisonType); if (a.HasValue) { return 1; } if (!b.HasValue) { return 0; } return -1; } public override bool Equals(object obj) { if (obj is StringSegment other) { return Equals(other); } return false; } public bool Equals(StringSegment other) { return Equals(other, StringComparison.Ordinal); } public bool Equals(StringSegment other, StringComparison comparisonType) { if (HasValue && other.HasValue) { return MemoryExtensions.Equals(AsSpan(), other.AsSpan(), comparisonType); } CheckStringComparison(comparisonType); if (!HasValue) { return !other.HasValue; } return false; } public static bool Equals(StringSegment a, StringSegment b, StringComparison comparisonType) { return a.Equals(b, comparisonType); } public bool Equals(string text) { return Equals(text, StringComparison.Ordinal); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(string text, StringComparison comparisonType) { if (text == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } if (!HasValue) { CheckStringComparison(comparisonType); return false; } return MemoryExtensions.Equals(AsSpan(), text.AsSpan(), comparisonType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] 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 ReadOnlySpan<char>(StringSegment segment) { return segment.AsSpan(); } public static implicit operator ReadOnlyMemory<char>(StringSegment segment) { return segment.AsMemory(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool StartsWith(string text, StringComparison comparisonType) { if (text == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } if (!HasValue) { CheckStringComparison(comparisonType); return false; } return AsSpan().StartsWith(text.AsSpan(), comparisonType); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool EndsWith(string text, StringComparison comparisonType) { if (text == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } if (!HasValue) { CheckStringComparison(comparisonType); return false; } return AsSpan().EndsWith(text.AsSpan(), comparisonType); } public string Substring(int offset) { return Substring(offset, Length - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string Substring(int offset, int length) { if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length) { ThrowInvalidArguments(offset, length, ExceptionArgument.offset); } return Buffer.Substring(Offset + offset, length); } public StringSegment Subsegment(int offset) { return Subsegment(offset, Length - offset); } public StringSegment Subsegment(int offset, int length) { if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length) { ThrowInvalidArguments(offset, length, ExceptionArgument.offset); } return new StringSegment(Buffer, Offset + offset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int IndexOf(char c, int start, int count) { int num = -1; if (HasValue) { if ((uint)start > (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if ((uint)count > (uint)(Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } num = AsSpan(start, count).IndexOf(c); if (num >= 0) { num += start; } } return num; } public int IndexOf(char c, int start) { return IndexOf(c, start, Length - start); } public int IndexOf(char c) { return IndexOf(c, 0, Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int IndexOfAny(char[] anyOf, int startIndex, int count) { int num = -1; if (HasValue) { if ((uint)startIndex > (uint)Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if ((uint)count > (uint)(Length - startIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } num = Buffer.IndexOfAny(anyOf, Offset + startIndex, count); if (num != -1) { num -= Offset; } } return num; } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, Length - startIndex); } public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, Length); } public int LastIndexOf(char value) { return AsSpan().LastIndexOf(value); } public StringSegment Trim() { return TrimStart().TrimEnd(); } public StringSegment TrimStart() { ReadOnlySpan<char> readOnlySpan = AsSpan(); int i; for (i = 0; i < readOnlySpan.Length && char.IsWhiteSpace(readOnlySpan[i]); i++) { } return Subsegment(i); } public StringSegment TrimEnd() { ReadOnlySpan<char> readOnlySpan = AsSpan(); int num = readOnlySpan.Length - 1; while (num >= 0 && char.IsWhiteSpace(readOnlySpan[num])) { num--; } return Subsegment(0, num + 1); } public StringTokenizer Split(char[] chars) { return new StringTokenizer(this, chars); } public static bool IsNullOrEmpty(StringSegment value) { bool result = false; if (!value.HasValue || value.Length == 0) { result = true; } return result; } public override string ToString() { return Value ?? string.Empty; } private static void CheckStringComparison(StringComparison comparisonType) { if ((uint)comparisonType > 5u) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.comparisonType); } } private static void ThrowInvalidArguments(string buffer, int offset, int length) { throw GetInvalidArgumentsException(); Exception GetInvalidArgumentsException() { if (buffer == null) { return ThrowHelper.GetArgumentNullException(ExceptionArgument.buffer); } if (offset < 0) { return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.offset); } if (length < 0) { return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length); } return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLength); } } private void ThrowInvalidArguments(int offset, int length, ExceptionArgument offsetOrStart) { throw GetInvalidArgumentsException(HasValue); Exception GetInvalidArgumentsException(bool hasValue) { if (!hasValue) { return ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart); } if (offset < 0) { return ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart); } if (length < 0) { return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length); } return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLengthStringSegment); } } bool IEquatable<string>.Equals(string other) { if (other != null) { return Equals(other); } return false; } } public class StringSegmentComparer : IComparer<StringSegment>, IEqualityComparer<StringSegment> { public static StringSegmentComparer Ordinal { get; } = new StringSegmentComparer(StringComparison.Ordinal, StringComparer.Ordinal); public static StringSegmentComparer OrdinalIgnoreCase { get; } = new StringSegmentComparer(StringComparison.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); private StringComparison Comparison { get; } private StringComparer Comparer { get; } private StringSegmentComparer(StringComparison comparison, StringComparer comparer) { Comparison = comparison; Comparer = comparer; } public int Compare(StringSegment x, StringSegment y) { return StringSegment.Compare(x, y, Comparison); } public bool Equals(StringSegment x, StringSegment y) { return StringSegment.Equals(x, y, Comparison); } public int GetHashCode(StringSegment obj) { return string.GetHashCode(obj.AsSpan(), Comparison); } } public readonly struct StringTokenizer : IEnumerable<StringSegment>, IEnumerable { public struct Enumerator : IEnumerator<StringSegment>, IEnumerator, IDisposable { private readonly StringSegment _value; private readonly char[] _separators; private int _index; public StringSegment Current { get; private set; } object IEnumerator.Current => Current; internal Enumerator(in StringSegment value, char[] separators) { _value = value; _separators = separators; Current = default(StringSegment); _index = 0; } public Enumerator(ref StringTokenizer tokenizer) { _value = tokenizer._value; _separators = tokenizer._separators; Current = default(StringSegment); _index = 0; } public void Dispose() { } public bool MoveNext() { if (!_value.HasValue || _index > _value.Length) { Current = default(StringSegment); return false; } int num = _value.IndexOfAny(_separators, _index); if (num == -1) { num = _value.Length; } Current = _value.Subsegment(_index, num - _index); _index = num + 1; return true; } public void Reset() { Current = default(StringSegment); _index = 0; } } private readonly StringSegment _value; private readonly char[] _separators; public StringTokenizer(string value, char[] separators) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (separators == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators); } _value = value; _separators = separators; } public StringTokenizer(StringSegment value, char[] separators) { if (!value.HasValue) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (separators == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators); } _value = value; _separators = separators; } public Enumerator GetEnumerator() { return new Enumerator(in _value, _separators); } IEnumerator<StringSegment> IEnumerable<StringSegment>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public readonly struct StringValues : IList<string>, ICollection<string>, IEnumerable<string>, IEnumerable, IReadOnlyList<string>, IReadOnlyCollection<string>, IEquatable<StringValues>, IEquatable<string>, IEquatable<string[]> { public struct Enumerator : IEnumerator<string>, IEnumerator, IDisposable { private readonly string[] _values; private string _current; private int _index; public string Current => _current; object IEnumerator.Current => _current; internal Enumerator(object value) { if (value is string current) { _values = null; _current = current; } else { _current = null; _values = Unsafe.As<string[]>(value); } _index = 0; } public Enumerator(ref StringValues values) : this(values._values) { } public bool MoveNext() { int index = _index; if (index < 0) { return false; } string[] values = _values; if (values != null) { if ((uint)index < (uint)values.Length) { _index = index + 1; _current = values[index]; return true; } _index = -1; return false; } _index = -1; return _current != null; } void IEnumerator.Reset() { throw new NotSupportedException(); } public void Dispose() { } } public static readonly StringValues Empty = new StringValues(Array.Empty<string>()); private readonly object _values; public int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object values = _values; if (values == null) { return 0; } if (values is string) { return 1; } return Unsafe.As<string[]>(values).Length; } } bool ICollection<string>.IsReadOnly => true; string IList<string>.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } public string this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object values = _values; if (values is string result) { if (index == 0) { return result; } } else if (values != null) { return Unsafe.As<string[]>(values)[index]; } return OutOfBounds(); } } public StringValues(string value) { _values = value; } public StringValues(string[] values) { _values = values; } public static implicit operator StringValues(string value) { return new StringValues(value); } public static implicit operator StringValues(string[] values) { return new StringValues(values); } public static implicit operator string(StringValues values) { return values.GetStringValue(); } public static implicit operator string[](StringValues value) { return value.GetArrayValue(); } [MethodImpl(MethodImplOptions.NoInlining)] private static string OutOfBounds() { return Array.Empty<string>()[0]; } public override string ToString() { return GetStringValue() ?? string.Empty; } private string GetStringValue() { object values2 = _values; if (values2 is string result) { return result; } return GetStringValueFromArray(values2); static string GetJoinedStringValueFromArray(string[] values) { int num = 0; foreach (string text in values) { if (text != null && text.Length > 0) { if (num > 0) { num++; } num += text.Length; } } return string.Create(num, values, delegate(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++; } text2.AsSpan().CopyTo(span.Slice(num2)); num2 += text2.Length; } } }); } static string GetStringValueFromArray(object value) { if (value == null) { return null; } string[] array = Unsafe.As<string[]>(value); return array.Length switch { 0 => null, 1 => array[0], _ => GetJoinedStringValueFromArray(array), }; } } public string[] ToArray() { return GetArrayValue() ?? Array.Empty<string>(); } private string[] GetArrayValue() { object values = _values; if (values is string[] result) { return result; } if (values != null) { return new string[1] { Unsafe.As<string>(values) }; } return null; } int IList<string>.IndexOf(string item) { return IndexOf(item); } private int IndexOf(string item) { object values = _values; if (values is string[] array) { for (int i = 0; i < array.Length; i++) { if (string.Equals(array[i], item, StringComparison.Ordinal)) { return i; } } return -1; } if (values != null) { if (!string.Equals(Unsafe.As<string>(values), item, StringComparison.Ordinal)) { return -1; } return 0; } return -1; } bool ICollection<string>.Contains(string item) { return IndexOf(item) >= 0; } void ICollection<string>.CopyTo(string[] array, int arrayIndex) { CopyTo(array, arrayIndex); } private void CopyTo(string[] array, int arrayIndex) { object values = _values; if (values is string[] array2) { Array.Copy(array2, 0, array, arrayIndex, array2.Length); } else if (values != null) { if (array == null) { throw new ArgumentNullException("array"); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex"); } if (array.Length - arrayIndex < 1) { throw new ArgumentException("'array' is not long enough to copy all the items in the collection. Check 'arrayIndex' and 'array' length."); } array[arrayIndex] = Unsafe.As<string>(values); } } void ICollection<string>.Add(string item) { throw new NotSupportedException(); } void IList<string>.Insert(int index, string item) { throw new NotSupportedException(); } bool ICollection<string>.Remove(string item) { throw new NotSupportedException(); } void IList<string>.RemoveAt(int index) { throw new NotSupportedException(); } void ICollection<string>.Clear() { throw new NotSupportedException(); } public Enumerator GetEnumerator() { return new Enumerator(_values); } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public static bool IsNullOrEmpty(StringValues value) { object values = value._values; if (values == null) { return true; } if (values is string[] array) { return array.Length switch { 0 => true, 1 => string.IsNullOrEmpty(array[0]), _ => false, }; } return string.IsNullOrEmpty(Unsafe.As<string>(values)); } public static StringValues Concat(StringValues values1, StringValues values2) { int count = values1.Count; int count2 = values2.Count; if (count == 0) { return values2; } if (count2 == 0) { return values1; } string[] array = new string[count + count2]; values1.CopyTo(array, 0); values2.CopyTo(array, count); return new StringValues(array); } public static StringValues Concat(in StringValues values, string value) { if (value == null) { return values; } int count = values.Count; if (count == 0) { return new StringValues(value); } string[] array = new string[count + 1]; values.CopyTo(array, 0); array[count] = value; return new StringValues(array); } public static StringValues Concat(string value, in StringValues values) { if (value == null) { return values; } int count = values.Count; if (count == 0) { return new StringValues(value); } string[] array = new string[count + 1]; array[0] = value; values.CopyTo(array, 1); return new StringValues(array); } public static bool Equals(StringValues left, StringValues right) { int count = left.Count; if (count != right.Count) { return false; } for (int i = 0; i < count; i++) { if (left[i] != right[i]) { return false; } } return true; } public static bool operator ==(StringValues left, StringValues right) { return Equals(left, right); } public static bool operator !=(StringValues left, StringValues right) { return !Equals(left, right); } public bool Equals(StringValues other) { return Equals(this, other); } public static bool Equals(string left, StringValues right) { return Equals(new StringValues(left), right); } public static bool Equals(StringValues left, string right) { return Equals(left, new StringValues(right)); } public bool Equals(string other) { return Equals(this, new StringValues(other)); } public static bool Equals(string[] left, StringValues right) { return Equals(new StringValues(left), right); } public static bool Equals(StringValues left, string[] right) { return Equals(left, new StringValues(right)); } public bool Equals(string[] other) { return Equals(this, new StringValues(other)); } public static bool operator ==(StringValues left, string right) { return Equals(left, new StringValues(right)); } public static bool operator !=(StringValues left, string right) { return !Equals(left, new StringValues(right)); } public static bool operator ==(string left, StringValues right) { return Equals(new StringValues(left), right); } public static bool operator !=(string left, StringValues right) { return !Equals(new StringValues(left), right); } public static bool operator ==(StringValues left, string[] right) { return Equals(left, new StringValues(right)); } public static bool operator !=(StringValues left, string[] right) { return !Equals(left, new StringValues(right)); } public static bool operator ==(string[] left, StringValues right) { return Equals(new StringValues(left), right); } public static bool operator !=(string[] left, StringValues right) { return !Equals(new StringValues(left), right); } public static bool operator ==(StringValues left, object right) { return left.Equals(right); } public static bool operator !=(StringValues left, object right) { return !left.Equals(right); } public static bool operator ==(object left, StringValues right) { return right.Equals(left); } public static bool operator !=(object left, StringValues right) { return !right.Equals(left); } public override bool Equals(object obj) { if (obj == null) { return Equals(this, Empty); } if (obj is string) { return Equals(this, (string)obj); } if (obj is string[]) { return Equals(this, (string[])obj); } if (obj is StringValues) { return Equals(this, (StringValues)obj); } return false; } public override int GetHashCode() { object values = _values; if (values is string[] array) { if (Count == 1) { return Unsafe.As<string>(this[0])?.GetHashCode() ?? Count.GetHashCode(); } int num = 0; for (int i = 0; i < array.Length; i++) { num = HashHelpers.Combine(num, array[i]?.GetHashCode() ?? 0); } return num; } return Unsafe.As<string>(values)?.GetHashCode() ?? Count.GetHashCode(); } } internal static class ThrowHelper { internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw new ArgumentNullException(GetArgumentName(argument)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static void ThrowArgumentException(ExceptionResource resource) { throw new ArgumentException(GetResourceText(resource)); } internal static void ThrowInvalidOperationException(ExceptionResource resource) { throw new InvalidOperationException(GetResourceText(resource)); } internal static void ThrowInvalidOperationException(ExceptionResource resource, params object[] args) { string message = string.Format(GetResourceText(resource), args); throw new InvalidOperationException(message); } internal static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument) { return new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceText(resource)); } private static string GetResourceText(ExceptionResource resource) { return System.SR.GetResourceString(GetResourceName(resource)); } private static string GetArgumentName(ExceptionArgument argument) { return argument.ToString(); } private static string GetResourceName(ExceptionResource resource) { return resource.ToString(); } } internal enum ExceptionArgument { buffer, offset, length, text, start, count, index, value, capacity, separators, comparisonType } internal enum ExceptionResource { Argument_InvalidOffsetLength, Argument_InvalidOffsetLengthStringSegment, Capacity_CannotChangeAfterWriteStarted, Capacity_NotEnough, Capacity_NotUsedEntirely } }
MegabonkTogether/Microsoft.Extensions.DependencyInjection.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("MicroBenchmarks, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Default implementation of dependency injection for Microsoft.Extensions.DependencyInjection.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [assembly: TypeForwardedTo(typeof(ServiceCollection))] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.DependencyInjection { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace Microsoft.Extensions.DependencyInjection { internal sealed class CallSiteJsonFormatter : CallSiteVisitor<CallSiteJsonFormatter.CallSiteFormatterContext, object> { internal struct CallSiteFormatterContext { private readonly HashSet<ServiceCallSite> _processedCallSites; private bool _firstItem; public int Offset { get; } public StringBuilder Builder { 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}\":", 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) { StringBuilder stringBuilder = new StringBuilder(); CallSiteFormatterContext argument = new CallSiteFormatterContext(stringBuilder, 0, new HashSet<ServiceCallSite>()); VisitCallSite(callSite, argument); return stringBuilder.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", factoryCallSite.Factory.Method); return null; } } public class DefaultServiceProviderFactory : IServiceProviderFactory<IServiceCollection> { private readonly ServiceProviderOptions _options; public DefaultServiceProviderFactory() : this(ServiceProviderOptions.Default) { } public DefaultServiceProviderFactory(ServiceProviderOptions options) { if (options == null) { throw new ArgumentNullException("options"); } _options = options; } public IServiceCollection CreateBuilder(IServiceCollection services) { return services; } public IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder) { return containerBuilder.BuildServiceProvider(_options); } } [EventSource(Name = "Microsoft-Extensions-DependencyInjection")] internal sealed class DependencyInjectionEventSource : EventSource { public static class Keywords { public const EventKeywords ServiceProviderInitialized = (EventKeywords)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.EtwSelfDescribingEventFormat) { } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")] [Event(1, Level = EventLevel.Verbose)] private void CallSiteBuilt(string serviceType, string callSite, int chunkIndex, int chunkCount, int serviceProviderHashCode) { WriteEvent(1, serviceType, callSite, chunkIndex, chunkCount, serviceProviderHashCode); } [Event(2, Level = EventLevel.Verbose)] public void ServiceResolved(string serviceType, int serviceProviderHashCode) { WriteEvent(2, serviceType, serviceProviderHashCode); } [Event(3, Level = EventLevel.Verbose)] public void ExpressionTreeGenerated(string serviceType, int nodeCount, int serviceProviderHashCode) { WriteEvent(3, serviceType, nodeCount, serviceProviderHashCode); } [Event(4, Level = EventLevel.Verbose)] public void DynamicMethodBuilt(string serviceType, int methodSize, int serviceProviderHashCode) { WriteEvent(4, serviceType, methodSize, serviceProviderHashCode); } [Event(5, Level = EventLevel.Verbose)] public void ScopeDisposed(int serviceProviderHashCode, int scopedServicesResolved, int disposableServices) { WriteEvent(5, serviceProviderHashCode, scopedServicesResolved, disposableServices); } [Event(6, Level = EventLevel.Error)] public void ServiceRealizationFailed(string? exceptionMessage, int serviceProviderHashCode) { WriteEvent(6, exceptionMessage, serviceProviderHashCode); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")] [Event(7, Level = EventLevel.Informational, Keywords = (EventKeywords)1L)] private void ServiceProviderBuilt(int serviceProviderHashCode, int singletonServices, int scopedServices, int transientServices, int closedGenericsServices, int openGenericsServices) { WriteEvent(7, serviceProviderHashCode, singletonServices, scopedServices, transientServices, closedGenericsServices, openGenericsServices); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe.")] [Event(8, Level = EventLevel.Informational, Keywords = (EventKeywords)1L)] private void ServiceProviderDescriptors(int serviceProviderHashCode, string descriptors, int chunkIndex, int chunkCount) { WriteEvent(8, serviceProviderHashCode, descriptors, chunkIndex, chunkCount); } [NonEvent] public void ServiceResolved(ServiceProvider provider, Type serviceType) { if (IsEnabled(EventLevel.Verbose, EventKeywords.All)) { ServiceResolved(serviceType.ToString(), provider.GetHashCode()); } } [NonEvent] public void CallSiteBuilt(ServiceProvider provider, Type serviceType, ServiceCallSite callSite) { if (IsEnabled(EventLevel.Verbose, EventKeywords.All)) { string text = CallSiteJsonFormatter.Instance.Format(callSite); int num = text.Length / 10240 + ((text.Length % 10240 > 0) ? 1 : 0); int hashCode = provider.GetHashCode(); for (int i = 0; i < num; i++) { CallSiteBuilt(serviceType.ToString(), text.Substring(i * 10240, Math.Min(10240, text.Length - i * 10240)), i, num, hashCode); } } } [NonEvent] public void DynamicMethodBuilt(ServiceProvider provider, Type serviceType, int methodSize) { if (IsEnabled(EventLevel.Verbose, EventKeywords.All)) { DynamicMethodBuilt(serviceType.ToString(), methodSize, provider.GetHashCode()); } } [NonEvent] public void ServiceRealizationFailed(Exception exception, int serviceProviderHashCode) { if (IsEnabled(EventLevel.Error, EventKeywords.All)) { ServiceRealizationFailed(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) { for (int num = _providers.Count - 1; num >= 0; num--) { WeakReference<ServiceProvider> weakReference = _providers[num]; if (!weakReference.TryGetTarget(out var target) || target == provider) { _providers.RemoveAt(num); } } } } [NonEvent] private void WriteServiceProviderBuilt(ServiceProvider provider) { if (!IsEnabled(EventLevel.Informational, (EventKeywords)1L)) { return; } int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = 0; StringBuilder stringBuilder = new StringBuilder("{ \"descriptors\":[ "); bool flag = true; ServiceDescriptor[] descriptors = provider.CallSiteFactory.Descriptors; foreach (ServiceDescriptor serviceDescriptor in descriptors) { if (flag) { flag = false; } else { stringBuilder.Append(", "); } AppendServiceDescriptor(stringBuilder, serviceDescriptor); switch (serviceDescriptor.Lifetime) { case ServiceLifetime.Singleton: num++; break; case ServiceLifetime.Scoped: num2++; break; case ServiceLifetime.Transient: num3++; break; } if (serviceDescriptor.ServiceType.IsGenericType) { if (serviceDescriptor.ServiceType.IsConstructedGenericType) { num4++; } else { num5++; } } } stringBuilder.Append(" ] }"); int hashCode = provider.GetHashCode(); ServiceProviderBuilt(hashCode, num, num2, num3, num4, num5); string text = stringBuilder.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) { builder.Append("{ \"serviceType\": \""); builder.Append(descriptor.ServiceType); builder.Append("\", \"lifetime\": \""); builder.Append(descriptor.Lifetime); builder.Append("\", "); if ((object)descriptor.ImplementationType != null) { builder.Append("\"implementationType\": \""); builder.Append(descriptor.ImplementationType); } else if (descriptor.ImplementationFactory != null) { builder.Append("\"implementationFactory\": \""); builder.Append(descriptor.ImplementationFactory.Method); } else if (descriptor.ImplementationInstance != null) { builder.Append("\"implementationInstance\": \""); builder.Append(descriptor.ImplementationInstance.GetType()); builder.Append(" (instance)"); } else { builder.Append("\"unknown\": \""); } builder.Append("\" }"); } protected override void OnEventCommand(EventCommandEventArgs command) { if (command.Command != EventCommand.Enable) { return; } lock (_providers) { foreach (WeakReference<ServiceProvider> provider in _providers) { if (provider.TryGetTarget(out var target)) { WriteServiceProviderBuilt(target); } } } } } internal static class DependencyInjectionEventSourceExtensions { private sealed class NodeCountingVisitor : ExpressionVisitor { public int NodeCount { get; private set; } public override Expression Visit(Expression e) { base.Visit(e); NodeCount++; return e; } } public static void ExpressionTreeGenerated(this DependencyInjectionEventSource source, ServiceProvider provider, Type serviceType, Expression expression) { if (source.IsEnabled(EventLevel.Verbose, EventKeywords.All)) { NodeCountingVisitor nodeCountingVisitor = new NodeCountingVisitor(); nodeCountingVisitor.Visit(expression); source.ExpressionTreeGenerated(serviceType.ToString(), nodeCountingVisitor.NodeCount, provider.GetHashCode()); } } } public static class ServiceCollectionContainerBuilderExtensions { public static ServiceProvider BuildServiceProvider(this IServiceCollection services) { return services.BuildServiceProvider(ServiceProviderOptions.Default); } public static ServiceProvider BuildServiceProvider(this IServiceCollection services, bool validateScopes) { return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = validateScopes }); } public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options) { if (services == null) { throw new ArgumentNullException("services"); } if (options == null) { throw new ArgumentNullException("options"); } return new ServiceProvider(services, options); } } public sealed class ServiceProvider : IServiceProvider, IDisposable, IAsyncDisposable { private readonly CallSiteValidator _callSiteValidator; private readonly Func<Type, Func<ServiceProviderEngineScope, object>> _createServiceAccessor; internal ServiceProviderEngine _engine; private bool _disposed; private ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object>> _realizedServices; internal CallSiteFactory CallSiteFactory { get; } internal ServiceProviderEngineScope Root { get; } internal static bool VerifyOpenGenericServiceTrimmability { get; } = AppContext.TryGetSwitch("Microsoft.Extensions.DependencyInjection.VerifyOpenGenericServiceTrimmability", out var isEnabled) && isEnabled; internal ServiceProvider(ICollection<ServiceDescriptor> serviceDescriptors, ServiceProviderOptions options) { Root = new ServiceProviderEngineScope(this, isRootScope: true); _engine = GetEngine(); _createServiceAccessor = CreateServiceAccessor; _realizedServices = new ConcurrentDictionary<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<Exception> list = null; foreach (ServiceDescriptor serviceDescriptor in serviceDescriptors) { try { ValidateService(serviceDescriptor); } catch (Exception item) { list = list ?? new List<Exception>(); list.Add(item); } } if (list != null) { throw new AggregateException("Some services are not able to be constructed", list.ToArray()); } } DependencyInjectionEventSource.Log.ServiceProviderBuilt(this); } public object GetService(Type serviceType) { return GetService(serviceType, Root); } public void Dispose() { DisposeCore(); Root.Dispose(); } public 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(Type serviceType, IServiceScope scope) { _callSiteValidator?.ValidateResolution(serviceType, scope, Root); } internal object GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) { if (_disposed) { ThrowHelper.ThrowObjectDisposedException(); } Func<ServiceProviderEngineScope, object> orAdd = _realizedServices.GetOrAdd(serviceType, _createServiceAccessor); OnResolve(serviceType, serviceProviderEngineScope); DependencyInjectionEventSource.Log.ServiceResolved(this, serviceType); return orAdd(serviceProviderEngineScope); } private void ValidateService(ServiceDescriptor descriptor) { if (descriptor.ServiceType.IsGenericType && !descriptor.ServiceType.IsConstructedGenericType) { return; } try { ServiceCallSite callSite = CallSiteFactory.GetCallSite(descriptor, new CallSiteChain()); if (callSite != null) { OnCreate(callSite); } } catch (Exception ex) { throw new InvalidOperationException($"Error while validating the service descriptor '{descriptor}': {ex.Message}", ex); } } private Func<ServiceProviderEngineScope, object> CreateServiceAccessor(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 new ServiceProviderEngineScope(this, isRootScope: false); } private ServiceProviderEngine GetEngine() { if (RuntimeFeature.IsDynamicCodeCompiled) { return new DynamicServiceProviderEngine(this); } return RuntimeServiceProviderEngine.Instance; } } public class ServiceProviderOptions { internal static readonly ServiceProviderOptions Default = new ServiceProviderOptions(); public bool ValidateScopes { get; set; } public bool ValidateOnBuild { get; set; } } } namespace Microsoft.Extensions.DependencyInjection.ServiceLookup { internal sealed class CallSiteChain { private readonly struct ChainItemInfo { public int Order { get; } public Type ImplementationType { get; } public ChainItemInfo(int order, Type implementationType) { Order = order; ImplementationType = implementationType; } } private readonly Dictionary<Type, ChainItemInfo> _callSiteChain; public CallSiteChain() { _callSiteChain = new Dictionary<Type, ChainItemInfo>(); } public void CheckCircularDependency(Type serviceType) { if (_callSiteChain.ContainsKey(serviceType)) { throw new InvalidOperationException(CreateCircularDependencyExceptionMessage(serviceType)); } } public void Remove(Type serviceType) { _callSiteChain.Remove(serviceType); } public void Add(Type serviceType, Type implementationType = null) { _callSiteChain[serviceType] = new ChainItemInfo(_callSiteChain.Count, implementationType); } private string CreateCircularDependencyExceptionMessage(Type type) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(System.SR.Format(System.SR.CircularDependencyException, TypeNameHelper.GetTypeDisplayName(type))); stringBuilder.AppendLine(); AppendResolutionPath(stringBuilder, type); return stringBuilder.ToString(); } private void AppendResolutionPath(StringBuilder builder, Type currentlyResolving) { List<KeyValuePair<Type, ChainItemInfo>> list = new List<KeyValuePair<Type, ChainItemInfo>>(_callSiteChain); list.Sort((KeyValuePair<Type, ChainItemInfo> a, KeyValuePair<Type, ChainItemInfo> b) => a.Value.Order.CompareTo(b.Value.Order)); foreach (KeyValuePair<Type, ChainItemInfo> item in list) { Type key = item.Key; Type implementationType = item.Value.ImplementationType; if (implementationType == null || key == implementationType) { builder.Append(TypeNameHelper.GetTypeDisplayName(key)); } else { builder.AppendFormat("{0}({1})", TypeNameHelper.GetTypeDisplayName(key), TypeNameHelper.GetTypeDisplayName(implementationType)); } builder.Append(" -> "); } builder.Append(TypeNameHelper.GetTypeDisplayName(currentlyResolving)); } } internal sealed class CallSiteFactory : IServiceProviderIsService { private struct ServiceDescriptorCacheItem { private ServiceDescriptor _item; 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 { if (index >= Count) { throw new ArgumentOutOfRangeException("index"); } if (index == 0) { return _item; } return _items[index - 1]; } } public int GetSlot(ServiceDescriptor descriptor) { 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<Type, ServiceDescriptorCacheItem> _descriptorLookup = new Dictionary<Type, ServiceDescriptorCacheItem>(); private readonly ConcurrentDictionary<Type, object> _callSiteLocks = new ConcurrentDictionary<Type, object>(); private readonly StackGuard _stackGuard; internal ServiceDescriptor[] Descriptors => _descriptors; public CallSiteFactory(ICollection<ServiceDescriptor> descriptors) { _stackGuard = new StackGuard(); _descriptors = new ServiceDescriptor[descriptors.Count]; descriptors.CopyTo(_descriptors, 0); Populate(); } private void Populate() { ServiceDescriptor[] descriptors = _descriptors; foreach (ServiceDescriptor serviceDescriptor in descriptors) { Type serviceType = serviceDescriptor.ServiceType; if (serviceType.IsGenericTypeDefinition) { Type implementationType = serviceDescriptor.ImplementationType; if (implementationType == 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)); } Type[] genericArguments = serviceType.GetGenericArguments(); 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 (serviceDescriptor.ImplementationInstance == null && serviceDescriptor.ImplementationFactory == null) { Type implementationType2 = serviceDescriptor.ImplementationType; if (implementationType2.IsGenericTypeDefinition || implementationType2.IsAbstract || implementationType2.IsInterface) { throw new ArgumentException(System.SR.Format(System.SR.TypeCannotBeActivated, implementationType2, serviceType)); } } Type key = serviceType; _descriptorLookup.TryGetValue(key, out var value); _descriptorLookup[key] = value.Add(serviceDescriptor); } } private static void ValidateTrimmingAnnotations(Type serviceType, Type[] serviceTypeGenericArguments, Type implementationType, Type[] implementationTypeGenericArguments) { for (int i = 0; i < serviceTypeGenericArguments.Length; i++) { Type type = serviceTypeGenericArguments[i]; 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, implementationType.FullName, serviceType.FullName)); } bool flag = type.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint); if (type2.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint) && !flag) { throw new ArgumentException(System.SR.Format(System.SR.TrimmingAnnotationsDoNotMatch_NewConstraint, implementationType.FullName, serviceType.FullName)); } } } private static DynamicallyAccessedMemberTypes GetDynamicallyAccessedMemberTypes(Type serviceGenericType) { foreach (CustomAttributeData customAttributesDatum in serviceGenericType.GetCustomAttributesData()) { if (customAttributesDatum.AttributeType.FullName == "System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute" && customAttributesDatum.ConstructorArguments.Count == 1 && customAttributesDatum.ConstructorArguments[0].ArgumentType.FullName == "System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes") { return (DynamicallyAccessedMemberTypes)(int)customAttributesDatum.ConstructorArguments[0].Value; } } return DynamicallyAccessedMemberTypes.None; } private static bool AreCompatible(DynamicallyAccessedMemberTypes serviceDynamicallyAccessedMembers, DynamicallyAccessedMemberTypes implementationDynamicallyAccessedMembers) { return serviceDynamicallyAccessedMembers.HasFlag(implementationDynamicallyAccessedMembers); } internal int? GetSlot(ServiceDescriptor serviceDescriptor) { if (_descriptorLookup.TryGetValue(serviceDescriptor.ServiceType, out var value)) { return value.GetSlot(serviceDescriptor); } return null; } internal ServiceCallSite GetCallSite(Type serviceType, CallSiteChain callSiteChain) { if (!_callSiteCache.TryGetValue(new ServiceCacheKey(serviceType, 0), out var value)) { return CreateCallSite(serviceType, callSiteChain); } return value; } internal ServiceCallSite GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain) { if (_descriptorLookup.TryGetValue(serviceDescriptor.ServiceType, out var value)) { return TryCreateExact(serviceDescriptor, serviceDescriptor.ServiceType, callSiteChain, value.GetSlot(serviceDescriptor)); } return null; } private ServiceCallSite CreateCallSite(Type serviceType, CallSiteChain callSiteChain) { if (!_stackGuard.TryEnterOnCurrentStack()) { return _stackGuard.RunOnEmptyStack((Type type, CallSiteChain chain) => CreateCallSite(type, chain), serviceType, callSiteChain); } object orAdd = _callSiteLocks.GetOrAdd(serviceType, (Type _) => new object()); lock (orAdd) { callSiteChain.CheckCircularDependency(serviceType); return TryCreateExact(serviceType, callSiteChain) ?? TryCreateOpenGeneric(serviceType, callSiteChain) ?? TryCreateEnumerable(serviceType, callSiteChain); } } private ServiceCallSite TryCreateExact(Type serviceType, CallSiteChain callSiteChain) { if (_descriptorLookup.TryGetValue(serviceType, out var value)) { return TryCreateExact(value.Last, serviceType, callSiteChain, 0); } return null; } private ServiceCallSite TryCreateOpenGeneric(Type serviceType, CallSiteChain callSiteChain) { if (serviceType.IsConstructedGenericType && _descriptorLookup.TryGetValue(serviceType.GetGenericTypeDefinition(), out var value)) { return TryCreateOpenGeneric(value.Last, serviceType, callSiteChain, 0, throwOnConstraintViolation: true); } return null; } private ServiceCallSite TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain) { ServiceCacheKey serviceCacheKey = new ServiceCacheKey(serviceType, 0); if (_callSiteCache.TryGetValue(serviceCacheKey, out var value)) { return value; } ServiceCallSite serviceCallSite4; try { callSiteChain.Add(serviceType); if (serviceType.IsConstructedGenericType && serviceType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { Type type = serviceType.GenericTypeArguments[0]; CallSiteResultCacheLocation callSiteResultCacheLocation = CallSiteResultCacheLocation.Root; List<ServiceCallSite> list = new List<ServiceCallSite>(); if (!type.IsConstructedGenericType && _descriptorLookup.TryGetValue(type, out var value2)) { for (int i = 0; i < value2.Count; i++) { ServiceDescriptor descriptor = value2[i]; int slot = value2.Count - i - 1; ServiceCallSite serviceCallSite = TryCreateExact(descriptor, type, callSiteChain, slot); callSiteResultCacheLocation = GetCommonCacheLocation(callSiteResultCacheLocation, serviceCallSite.Cache.Location); list.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); list.Add(serviceCallSite2); } } list.Reverse(); } ResultCache cache = ResultCache.None; if (callSiteResultCacheLocation == CallSiteResultCacheLocation.Scope || callSiteResultCacheLocation == CallSiteResultCacheLocation.Root) { cache = new ResultCache(callSiteResultCacheLocation, serviceCacheKey); } serviceCallSite4 = (_callSiteCache[serviceCacheKey] = new IEnumerableCallSite(cache, type, list.ToArray())); serviceCallSite4 = serviceCallSite4; } else { serviceCallSite4 = null; } } finally { callSiteChain.Remove(serviceType); } return serviceCallSite4; } private CallSiteResultCacheLocation GetCommonCacheLocation(CallSiteResultCacheLocation locationA, CallSiteResultCacheLocation locationB) { return (CallSiteResultCacheLocation)Math.Max((int)locationA, (int)locationB); } private ServiceCallSite TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, int slot) { if (serviceType == descriptor.ServiceType) { ServiceCacheKey key = new ServiceCacheKey(serviceType, slot); if (_callSiteCache.TryGetValue(key, out var value)) { return value; } 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 != null)) { throw new InvalidOperationException(System.SR.InvalidServiceDescriptor); } serviceCallSite = CreateConstructorCallSite(resultCache, descriptor.ServiceType, descriptor.ImplementationType, callSiteChain); } return _callSiteCache[key] = 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, Type serviceType, CallSiteChain callSiteChain, int slot, bool throwOnConstraintViolation) { if (serviceType.IsConstructedGenericType && serviceType.GetGenericTypeDefinition() == descriptor.ServiceType) { ServiceCacheKey key = new ServiceCacheKey(serviceType, slot); if (_callSiteCache.TryGetValue(key, out var value)) { return value; } ResultCache lifetime = new ResultCache(descriptor.Lifetime, serviceType, slot); Type implementationType; try { implementationType = descriptor.ImplementationType.MakeGenericType(serviceType.GenericTypeArguments); } catch (ArgumentException) { if (throwOnConstraintViolation) { throw; } return null; } return _callSiteCache[key] = CreateConstructorCallSite(lifetime, serviceType, implementationType, callSiteChain); } return null; } private ServiceCallSite CreateConstructorCallSite(ResultCache lifetime, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, CallSiteChain callSiteChain) { 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 constructorInfo = constructors[0]; ParameterInfo[] parameters = constructorInfo.GetParameters(); if (parameters.Length == 0) { return new ConstructorCallSite(lifetime, serviceType, constructorInfo); } parameterCallSites = CreateArgumentCallSites(implementationType, callSiteChain, parameters, throwIfCallSiteNotFound: true); return new ConstructorCallSite(lifetime, serviceType, constructorInfo, parameterCallSites); } Array.Sort(constructors, (ConstructorInfo a, ConstructorInfo b) => b.GetParameters().Length.CompareTo(a.GetParameters().Length)); ConstructorInfo constructorInfo2 = null; HashSet<Type> hashSet = null; for (int i = 0; i < constructors.Length; i++) { ParameterInfo[] parameters2 = constructors[i].GetParameters(); ServiceCallSite[] array = CreateArgumentCallSites(implementationType, callSiteChain, parameters2, throwIfCallSiteNotFound: false); if (array == null) { continue; } if (constructorInfo2 == null) { constructorInfo2 = constructors[i]; parameterCallSites = array; continue; } if (hashSet == null) { hashSet = new HashSet<Type>(); ParameterInfo[] parameters3 = constructorInfo2.GetParameters(); foreach (ParameterInfo parameterInfo in parameters3) { hashSet.Add(parameterInfo.ParameterType); } } ParameterInfo[] array2 = parameters2; foreach (ParameterInfo parameterInfo2 in array2) { if (!hashSet.Contains(parameterInfo2.ParameterType)) { throw new InvalidOperationException(string.Join(Environment.NewLine, System.SR.Format(System.SR.AmbiguousConstructorException, implementationType), constructorInfo2, constructors[i])); } } } if (constructorInfo2 == null) { throw new InvalidOperationException(System.SR.Format(System.SR.UnableToActivateTypeException, implementationType)); } return new ConstructorCallSite(lifetime, serviceType, constructorInfo2, parameterCallSites); } finally { callSiteChain.Remove(serviceType); } } private ServiceCallSite[] CreateArgumentCallSites(Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound) { ServiceCallSite[] array = new ServiceCallSite[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { Type parameterType = parameters[i].ParameterType; ServiceCallSite serviceCallSite = GetCallSite(parameterType, callSiteChain); if (serviceCallSite == null && Microsoft.Extensions.Internal.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(Type type, ServiceCallSite serviceCallSite) { _callSiteCache[new ServiceCacheKey(type, 0)] = serviceCallSite; } public bool IsService(Type serviceType) { if ((object)serviceType == null) { throw new ArgumentNullException("serviceType"); } if (serviceType.IsGenericTypeDefinition) { return false; } if (_descriptorLookup.ContainsKey(serviceType)) { return true; } if (serviceType.IsConstructedGenericType) { Type genericTypeDefinition = serviceType.GetGenericTypeDefinition(); if ((object)genericTypeDefinition != null) { if (!(genericTypeDefinition == typeof(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, Scope, Transient, Singleton } internal enum CallSiteResultCacheLocation { Root, Scope, Dispose, None } internal sealed class CallSiteRuntimeResolver : CallSiteVisitor<RuntimeResolverContext, object> { public static CallSiteRuntimeResolver Instance { 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 = 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.DoNotWrapExceptions, null, array, 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; } value2 = VisitCallSiteMain(callSite, new RuntimeResolverContext { Scope = root, AcquiredLocks = (context.AcquiredLocks | runtimeResolverLock) }); root.CaptureDisposable(value2); callSite.Value = value2; return value2; } } 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 lockTaken = false; object sync = serviceProviderEngine.Sync; Dictionary<ServiceCacheKey, object> resolvedServices = serviceProviderEngine.ResolvedServices; if ((context.AcquiredLocks & lockType) == 0) { Monitor.Enter(sync, ref lockTaken); } try { if (resolvedServices.TryGetValue(callSite.Cache.Key, out var value)) { return value; } value = VisitCallSiteMain(callSite, new RuntimeResolverContext { Scope = serviceProviderEngine, AcquiredLocks = (context.AcquiredLocks | lockType) }); serviceProviderEngine.CaptureDisposable(value); resolvedServices.Add(callSite.Cache.Key, value); return value; } finally { if (lockTaken) { 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) { Array array = Array.CreateInstance(enumerableCallSite.ItemType, enumerableCallSite.ServiceCallSites.Length); for (int i = 0; i < enumerableCallSite.ServiceCallSites.Length; i++) { object value = VisitCallSite(enumerableCallSite.ServiceCallSites[i], context); array.SetValue(value, i); } return array; } protected override object VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context) { return factoryCallSite.Factory(context.Scope); } } internal struct RuntimeResolverContext { public ServiceProviderEngineScope Scope { get; set; } public RuntimeResolverLock AcquiredLocks { get; set; } } [Flags] internal enum RuntimeResolverLock { Scope = 1, Root = 2 } internal sealed class CallSiteValidator : CallSiteVisitor<CallSiteValidator.CallSiteValidatorState, Type> { internal struct CallSiteValidatorState { public ServiceCallSite Singleton { get; set; } } private readonly ConcurrentDictionary<Type, Type> _scopedServices = new ConcurrentDictionary<Type, Type>(); public void ValidateCallSite(ServiceCallSite callSite) { Type type = VisitCallSite(callSite, default(CallSiteValidatorState)); if (type != null) { _scopedServices[callSite.ServiceType] = type; } } public void ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope) { if (scope == rootScope && _scopedServices.TryGetValue(serviceType, out var value)) { if (serviceType == value) { throw new InvalidOperationException(System.SR.Format(System.SR.DirectScopedResolvedFromRootException, serviceType, "Scoped".ToLowerInvariant())); } throw new InvalidOperationException(System.SR.Format(System.SR.ScopedResolvedFromRootException, serviceType, value, "Scoped".ToLowerInvariant())); } } protected override Type VisitConstructor(ConstructorCallSite constructorCallSite, CallSiteValidatorState state) { Type type = null; ServiceCallSite[] parameterCallSites = constructorCallSite.ParameterCallSites; foreach (ServiceCallSite callSite in parameterCallSites) { Type type2 = VisitCallSite(callSite, state); if (type == null) { type = type2; } } return type; } protected override Type VisitIEnumerable(IEnumerableCallSite enumerableCallSite, CallSiteValidatorState state) { Type type = null; ServiceCallSite[] serviceCallSites = enumerableCallSite.ServiceCallSites; foreach (ServiceCallSite callSite in serviceCallSites) { Type type2 = VisitCallSite(callSite, state); if (type == null) { type = type2; } } return type; } protected override Type VisitRootCache(ServiceCallSite singletonCallSite, CallSiteValidatorState state) { state.Singleton = singletonCallSite; return VisitCallSiteMain(singletonCallSite, state); } protected override Type VisitScopeCache(ServiceCallSite scopedCallSite, CallSiteValidatorState state) { 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 Type VisitConstant(ConstantCallSite constantCallSite, CallSiteValidatorState state) { return null; } protected override Type VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, CallSiteValidatorState state) { return null; } protected override 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) { if (!_stackGuard.TryEnterOnCurrentStack()) { return _stackGuard.RunOnEmptyStack((ServiceCallSite c, TArgument a) => VisitCallSite(c, a), 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) { 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, 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 { public ILEmitResolverBuilder ResolverBuilder { get; } 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 Type _serviceType; internal object DefaultValue => base.Value; public override Type ServiceType => _serviceType; public override Type ImplementationType => DefaultValue?.GetType() ?? _serviceType; public override CallSiteKind Kind { get; } = CallSiteKind.Constant; public ConstantCallSite(Type serviceType, object defaultValue) : base(ResultCache.None) { _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 { internal ConstructorInfo ConstructorInfo { get; } internal ServiceCallSite[] ParameterCallSites { get; } public override Type ServiceType { get; } public override Type ImplementationType => ConstructorInfo.DeclaringType; public override CallSiteKind Kind { get; } = CallSiteKind.Constructor; public ConstructorCallSite(ResultCache cache, Type serviceType, ConstructorInfo constructorInfo) : this(cache, serviceType, constructorInfo, Array.Empty<ServiceCallSite>()) { } public ConstructorCallSite(ResultCache cache, Type serviceType, ConstructorInfo constructorInfo, ServiceCallSite[] parameterCallSites) : base(cache) { if (!serviceType.IsAssignableFrom(constructorInfo.DeclaringType)) { throw new ArgumentException(System.SR.Format(System.SR.ImplementationTypeCantBeConvertedToServiceType, constructorInfo.DeclaringType, serviceType)); } ServiceType = serviceType; ConstructorInfo = constructorInfo; ParameterCallSites = parameterCallSites; } } 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; return delegate(ServiceProviderEngineScope scope) { object result = CallSiteRuntimeResolver.Instance.Resolve(callSite2, scope); if (Interlocked.Increment(ref callCount) == 2) { ThreadPool.UnsafeQueueUserWorkItem(delegate { try { _serviceProvider.ReplaceServiceAccessor(callSite2, base.RealizeService(callSite2)); } catch (Exception exception) { DependencyInjectionEventSource.Log.ServiceRealizationFailed(exception, _serviceProvider.GetHashCode()); } }, null); } return result; }; } } 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(ResolvedServices, Expression.Property(ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("ResolvedServices", BindingFlags.Instance | BindingFlags.NonPublic))); private static readonly BinaryExpression SyncVariableAssignment = Expression.Assign(Sync, Expression.Property(ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("Sync", BindingFlags.Instance | BindingFlags.NonPublic))); private static readonly ParameterExpression CaptureDisposableParameter = Expression.Parameter(typeof(object)); private static readonly LambdaExpression CaptureDisposable = Expression.Lambda(Expression.Call(ScopeParameter, ServiceLookupHelpers.CaptureDisposableMethodInfo, CaptureDisposableParameter), CaptureDisposableParameter); private static readonly ConstantExpression CallSiteRuntimeResolverInstanceExpression = Expression.Constant(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 = (ServiceCacheKey key, ServiceCallSite cs) => BuildNoCache(cs); } public Func<ServiceProviderEngineScope, object> Build(ServiceCallSite callSite) { if (callSite.Cache.Location == CallSiteResultCacheLocation.Scope) { return _scopeResolverCache.GetOrAdd(callSite.Cache.Key, _buildTypeDelegate, callSite); } return BuildNoCache(callSite); } public Func<ServiceProviderEngineScope, object> BuildNoCache(ServiceCallSite callSite) { Expression<Func<ServiceProviderEngineScope, object>> expression = BuildExpression(callSite); DependencyInjectionEventSource.Log.ExpressionTreeGenerated(_rootScope.RootProvider, callSite.ServiceType, expression); return expression.Compile(); } private Expression<Func<ServiceProviderEngineScope, object>> BuildExpression(ServiceCallSite callSite) { if (callSite.Cache.Location == CallSiteResultCacheLocation.Scope) { return Expression.Lambda<Func<ServiceProviderEngineScope, object>>(Expression.Block(new ParameterExpression[2] { ResolvedServices, Sync }, ResolvedServicesVariableAssignment, SyncVariableAssignment, BuildScopedExpression(callSite)), new ParameterExpression[1] { ScopeParameter }); } return Expression.Lambda<Func<ServiceProviderEngineScope, object>>(Convert(VisitCallSite(callSite, null), typeof(object), forceValueTypeConversion: true), new ParameterExpression[1] { ScopeParameter }); } protected override Expression VisitRootCache(ServiceCallSite singletonCallSite, object context) { return Expression.Constant(CallSiteRuntimeResolver.Instance.Resolve(singletonCallSite, _rootScope)); } protected override Expression VisitConstant(ConstantCallSite constantCallSite, object context) { return Expression.Constant(constantCallSite.DefaultValue); } protected override Expression VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, object context) { return ScopeParameter; } protected override Expression VisitFactory(FactoryCallSite factoryCallSite, object context) { return Expression.Invoke(Expression.Constant(factoryCallSite.Factory), ScopeParameter); } protected override Expression VisitIEnumerable(IEnumerableCallSite callSite, object context) { object context2 = context; IEnumerableCallSite callSite2 = callSite; if (callSite2.ServiceCallSites.Length == 0) { return Expression.Constant(ServiceLookupHelpers.GetArrayEmptyMethodInfo(callSite2.ItemType).Invoke(null, Array.Empty<object>())); } return Expression.NewArrayInit(callSite2.ItemType, callSite2.ServiceCallSites.Select((ServiceCallSite cs) => Convert(VisitCallSite(cs, context2), callSite2.ItemType))); } protected override Expression VisitDisposeCache(ServiceCallSite callSite, object context) { return TryCaptureDisposable(callSite, ScopeParameter, VisitCallSiteMain(callSite, context)); } private Expression TryCaptureDisposable(ServiceCallSite callSite, ParameterExpression scope, Expression service) { if (!callSite.CaptureDisposable) { return service; } return Expression.Invoke(GetCaptureDisposable(scope), service); } protected override Expression VisitConstructor(ConstructorCallSite callSite, object context) { ParameterInfo[] parameters = callSite.ConstructorInfo.GetParameters(); Expression[] array; if (callSite.ParameterCallSites.Length == 0) { array = Array.Empty<Expression>(); } else { array = new Expression[callSite.ParameterCallSites.Length]; for (int i = 0; i < array.Length; i++) { array[i] = Convert(VisitCallSite(callSite.ParameterCallSites[i], context), parameters[i].ParameterType); } } return Expression.New(callSite.ConstructorInfo, array); } private static Expression Convert(Expression expression, Type type, bool forceValueTypeConversion = false) { if (type.IsAssignableFrom(expression.Type) && (!expression.Type.IsValueType || !forceValueTypeConversion)) { return expression; } return Expression.Convert(expression, type); } protected override Expression VisitScopeCache(ServiceCallSite callSite, object context) { Func<ServiceProviderEngineScope, object> value = Build(callSite); return Expression.Invoke(Expression.Constant(value), ScopeParameter); } private Expression BuildScopedExpression(ServiceCallSite callSite) { ConstantExpression arg = Expression.Constant(callSite, typeof(ServiceCallSite)); MethodCallExpression ifTrue = Expression.Call(CallSiteRuntimeResolverInstanceExpression, ServiceLookupHelpers.ResolveCallSiteAndScopeMethodInfo, arg, ScopeParameter); ConstantExpression arg2 = Expression.Constant(callSite.Cache.Key, typeof(ServiceCacheKey)); ParameterExpression parameterExpression = Expression.Variable(typeof(object), "resolved"); ParameterExpression resolvedServices = ResolvedServices; MethodCallExpression expression = Expression.Call(resolvedServices, ServiceLookupHelpers.TryGetValueMethodInfo, arg2, parameterExpression); Expression right = TryCaptureDisposable(callSite, ScopeParameter, VisitCallSiteMain(callSite, null)); BinaryExpression arg3 = Expression.Assign(parameterExpression, right); MethodCallExpression arg4 = Expression.Call(resolvedServices, ServiceLookupHelpers.AddMethodInfo, arg2, parameterExpression); BlockExpression arg5 = Expression.Block(typeof(object), new ParameterExpression[1] { parameterExpression }, Expression.IfThen(Expression.Not(expression), Expression.Block(arg3, arg4)), parameterExpression); ParameterExpression parameterExpression2 = Expression.Variable(typeof(bool), "lockWasTaken"); ParameterExpression sync = Sync; MethodCallExpression arg6 = Expression.Call(ServiceLookupHelpers.MonitorEnterMethodInfo, sync, parameterExpression2); MethodCallExpression ifTrue2 = Expression.Call(ServiceLookupHelpers.MonitorExitMethodInfo, sync); BlockExpression body = Expression.Block(arg6, arg5); ConditionalExpression @finally = Expression.IfThen(parameterExpression2, ifTrue2); return Expression.Condition(Expression.Property(ScopeParameter, typeof(ServiceProviderEngineScope).GetProperty("IsRootScope", BindingFlags.Instance | BindingFlags.Public)), ifTrue, Expression.Block(typeof(object), new ParameterExpression[1] { parameterExpression2 }, Expression.TryFinally(body, @finally))); } public Expression GetCaptureDisposable(ParameterExpression scope) { if (scope != ScopeParameter) { throw new NotSupportedException(System.SR.GetCaptureDisposableNotSupported); } return CaptureDisposable; } } internal sealed class ExpressionsServiceProviderEngine : ServiceProviderEngine { private readonly ExpressionResolverBuilder _expressionResolverBuilder; 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 { public Func<IServiceProvider, object> Factory { get; } public override Type ServiceType { get; } public override Type ImplementationType => null; public override CallSiteKind Kind { get; } public FactoryCallSite(ResultCache cache, Type serviceType, Func<IServiceProvider, object> factory) : base(cache) { Factory = factory; ServiceType = serviceType; } } internal sealed class IEnumerableCallSite : ServiceCallSite { internal Type ItemType { get; } internal ServiceCallSite[] ServiceCallSites { get; } public override Type ServiceType => typeof(IEnumerable<>).MakeGenericType(ItemType); public override Type ImplementationType => ItemType.MakeArrayType(); public override CallSiteKind Kind { get; } = CallSiteKind.IEnumerable; public IEnumerableCallSite(ResultCache cache, Type itemType, ServiceCallSite[] serviceCallSites) : base(cache) { ItemType = itemType; ServiceCallSites = serviceCallSites; } } internal struct ResultCache { public static ResultCache None { get; } = new ResultCache(CallSiteResultCacheLocation.None, ServiceCacheKey.Empty); public CallSiteResultCacheLocation Location { get; set; } public ServiceCacheKey Key { get; set; } internal ResultCache(CallSiteResultCacheLocation lifetime, ServiceCacheKey cacheKey) { Location = lifetime; Key = cacheKey; } public ResultCache(ServiceLifetime lifetime, Type type, int slot) { switch (lifetime) { case ServiceLifetime.Singleton: Location = CallSiteResultCacheLocation.Root; break; case ServiceLifetime.Scoped: Location = CallSiteResultCacheLocation.Scope; break; case ServiceLifetime.Transient: Location = CallSiteResultCacheLocation.Dispose; break; default: Location = CallSiteResultCacheLocation.None; break; } Key = new ServiceCacheKey(type, slot); } } internal sealed class RuntimeServiceProviderEngine : ServiceProviderEngine { public static RuntimeServiceProviderEngine Instance { 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> { public static ServiceCacheKey Empty { get; } = new ServiceCacheKey(null, 0); public Type Type { get; } public int Slot { get; } public ServiceCacheKey(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 int GetHashCode() { return ((Type?.GetHashCode() ?? 23) * 397) ^ Slot; } } internal abstract class ServiceCallSite { public abstract Type ServiceType { get; } public abstract Type ImplementationType { get; } public abstract CallSiteKind Kind { get; } public ResultCache Cache { get; } public object Value { get; set; } public bool CaptureDisposable { get { if (!(ImplementationType == null) && !typeof(IDisposable).IsAssignableFrom(ImplementationType)) { return typeof(IAsyncDisposable).IsAssignableFrom(ImplementationType); } return true; } } protected ServiceCallSite(ResultCache cache) { Cache = cache; } } internal static class ServiceLookupHelpers { private const BindingFlags LookupFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private static readonly MethodInfo ArrayEmptyMethodInfo = typeof(Array).GetMethod("Empty"); internal static readonly MethodInfo InvokeFactoryMethodInfo = typeof(Func<IServiceProvider, object>).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); internal static readonly MethodInfo CaptureDisposableMethodInfo = typeof(ServiceProviderEngineScope).GetMethod("CaptureDisposable", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); internal static readonly MethodInfo TryGetValueMethodInfo = typeof(IDictionary<ServiceCacheKey, object>).GetMethod("TryGetValue", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); internal static readonly MethodInfo ResolveCallSiteAndScopeMethodInfo = typeof(CallSiteRuntimeResolver).GetMethod("Resolve", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); internal static readonly MethodInfo AddMethodInfo = typeof(IDictionary<ServiceCacheKey, object>).GetMethod("Add", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); internal static readonly MethodInfo MonitorEnterMethodInfo = typeof(Monitor).GetMethod("Enter", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { typeof(object), typeof(bool).MakeByRefType() }, null); internal static readonly MethodInfo MonitorExitMethodInfo = typeof(Monitor).GetMethod("Exit", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(object) }, null); [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "Calling Array.Empty<T>() is safe since the T doesn't have trimming annotations.")] internal static MethodInfo GetArrayEmptyMethodInfo(Type itemType) { return ArrayEmptyMethodInfo.MakeGenericMethod(itemType); } } internal sealed class ServiceProviderCallSite : ServiceCallSite { public override Type ServiceType { get; } = typeof(IServiceProvider); public override Type ImplementationType { get; } = typeof(ServiceProvider); public override CallSiteKind Kind { 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, IDisposable, IServiceProvider, IAsyncDisposable, IServiceScopeFactory { private bool _disposed; private List<object> _disposables; internal IList<object> Disposables { get { IList<object> disposables = _disposables; return disposables ?? Array.Empty<object>(); } } internal Dictionary<ServiceCacheKey, object> ResolvedServices { get; } internal object Sync => ResolvedServices; public bool IsRootScope { get; } internal ServiceProvider RootProvider { get; } public IServiceProvider ServiceProvider => this; public ServiceProviderEngineScope(ServiceProvider provider, bool isRootScope) { ResolvedServices = new Dictionary<ServiceCacheKey, object>(); RootProvider = provider; IsRootScope = isRootScope; } public object GetService(Type serviceType) { if (_disposed) { ThrowHelper.ThrowObjectDisposedException(); } return RootProvider.GetService(serviceType, this); } public IServiceScope CreateScope() { return RootProvider.CreateScope(); } internal object CaptureDisposable(object service) { object service2 = service; if (this == service2 || (!(service2 is IDisposable) && !(service2 is IAsyncDisposable))) { return service2; } bool flag = false; lock (Sync) { if (_disposed) { flag = true; } else { if (_disposables == null) { _disposables = new List<object>(); } _disposables.Add(service2); } } if (flag) { if (service2 is IDisposable disposable) { disposable.Dispose(); } else { Task.Run(() => ((IAsyncDisposable)service2).DisposeAsync().AsTask()).GetAwaiter().GetResult(); } ThrowHelper.ThrowObjectDisposedException(); } return service2; } public void Dispose() { List<object> list = BeginDispose(); if (list == null) { return; } int num = list.Count - 1; while (num >= 0) { if (list[num] is IDisposable disposable) { disposable.Dispose(); num--; continue; } throw new InvalidOperationException(System.SR.Format(System.SR.AsyncDisposableServiceDispose, TypeNameHelper.GetTypeDisplayName(list[num]))); } } public ValueTask DisposeAsync() { List<object> list = BeginDispose(); if (list != null) { try { for (int num = list.Count - 1; num >= 0; num--) { object obj = list[num]; if (obj is IAsyncDisposable asyncDisposable) { ValueTask vt2 = asyncDisposable.DisposeAsync(); if (!vt2.IsCompletedSuccessfully) { return Await(num, vt2, list); } vt2.GetAwaiter().GetResult(); } else { ((IDisposable)obj).Dispose(); } } } catch (Exception exception) { return new ValueTask(Task.FromException(exception)); } } return default(ValueTask); static async ValueTask Await(int i, ValueTask vt, List<object> toDispose) { await vt.ConfigureAwait(continueOnCapturedContext: false); i--; while (i >= 0) { object obj2 = toDispose[i]; if (obj2 is IAsyncDisposable asyncDisposable2) { await asyncDisposable2.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } else { ((IDisposable)obj2).Dispose(); } i--; } } } private List<object> BeginDispose() { lock (Sync) { if (_disposed) { return null; } DependencyInjectionEventSource.Log.ScopeDisposed(RootProvider.GetHashCode(), ResolvedServices.Count, _disposables?.Count ?? 0); _disposed = true; return _disposables; } } } internal sealed class StackGuard { private const int MaxExecutionStackCount = 1024; private int _executionStackCount; public bool TryEnterOnCurrentStack() { if (RuntimeHelpers.TryEnsureSufficientExecutionStack()) { return true; } if (_executionStackCount < 1024) { return false; } throw new InsufficientExecutionStackException(); } public TR RunOnEmptyStack<T1, T2, TR>(Func<T1, T2, TR> action, T1 arg1, T2 arg2) { return RunOnEmptyStackCore(delegate(object s) { (Func<T1, T2, TR>, T1, T2) tuple = ((Func<T1, T2, TR>, T1, T2))s; return tuple.Item1(tuple.Item2, tuple.Item3); }, (action, arg1, arg2)); } private R RunOnEmptyStackCore<R>(Func<object, R> action, object state) { _executionStackCount++; try { Task<R> task = Task.Factory.StartNew(action, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); if (!task.IsCompleted) { ((IAsyncResult)task).AsyncWaitHandle.WaitOne(); } return task.GetAwaiter().GetResult(); } finally { _executionStackCount--; } } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.NoInlining)] internal static void ThrowObjectDisposedException() { throw new ObjectDisposedException("IServiceProvider"); } } internal sealed class ILEmitResolverBuilder : CallSiteVisitor<ILEmitResolverBuilderContext, object> { private sealed class ILEmitResolverBuilderRuntimeContext { public object[] Constants; public Func<IServiceProvider, object>[] Factories; } private struct GeneratedMethod { public Func<ServiceProviderEngineScope, object> Lambda; public ILEmitResolverBuilderRuntimeContext Context; public DynamicMethod DynamicMethod; } private static readonly MethodInfo ResolvedServicesGetter = typeof(ServiceProviderEngineScope).GetProperty("ResolvedServices", BindingFlags.Instance | BindingFlags.NonPublic).GetMethod; private static readonly MethodInfo ScopeLockGetter = typeof(ServiceProviderEngineScope).GetProperty("Sync", BindingFlags.Instance | BindingFlags.NonPublic).GetMethod; private static readonly MethodInfo ScopeIsRootScope = typeof(ServiceProviderEngineScope).GetProperty("IsRootScope", BindingFlags.Instance | BindingFlags.Public).GetMethod; private static readonly MethodInfo CallSiteRuntimeResolverResolveMethod = typeof(CallSiteRuntimeResolver).GetMethod("Resolve", BindingFlags.Instance | BindingFlags.Public); private static readonly MethodInfo CallSiteRuntimeResolverInstanceField = typeof(CallSiteRuntimeResolver).GetProperty("Instance", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).GetMethod; private static readonly FieldInfo FactoriesField = typeof(ILEmitResolverBuilderRuntimeContext).GetField("Factories"); private static readonly FieldInfo ConstantsField = typeof(ILEmitResolverBuilderRuntimeContext).GetField("Constants"); private static readonly MethodInfo GetTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle"); private static readonly ConstructorInfo CacheKeyCtor = typeof(ServiceCacheKey).GetConstructors()[0]; private readonly ServiceProviderEngineScope _rootScope; private readonly ConcurrentDictionary<ServiceCacheKey, GeneratedMethod> _scopeResolverCache; private readonly Func<ServiceCacheKey, ServiceCallSite, GeneratedMethod> _buildTypeDelegate; public ILEmitResolverBuilder(ServiceProvider serviceProvider) { _rootScope = serviceProvider.Root; _scopeResolverCache = new ConcurrentDictionary<ServiceCacheKey, GeneratedMethod>(); _buildTypeDelegate = (ServiceCacheKey key, ServiceCallSite cs) => BuildTypeNoCache(cs); } public Func<ServiceProviderEngineScope, object> Build(ServiceCallSite callSite) { return BuildType(callSite).Lambda; } private GeneratedMethod BuildType(ServiceCallSite callSite) { if (callSite.Cache.Location == CallSiteResultCacheLocation.Scope) { return _scopeResolverCache.GetOrAdd(callSite.Cache.Key, _buildTypeDelegate, callSite); } return BuildTypeNoCache(callSite); } private GeneratedMethod BuildTypeNoCache(ServiceCallSite callSite) { DynamicMethod dynamicMethod = new DynamicMethod("ResolveService", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(object), new Type[2] { typeof(ILEmitResolverBuilderRuntimeContext), typeof(ServiceProviderEngineScope) }, GetType(), skipVisibility: true); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(512); ILEmitResolverBuilderRuntimeContext iLEmitResolverBuilderRuntimeContext = GenerateMethodBody(callSite, iLGenerator); DependencyInjectionEventSource.Log.DynamicMethodBuilt(_rootScope.RootProvider, callSite.ServiceType, iLGenerator.ILOffset); GeneratedMethod result = default(GeneratedMethod); result.Lambda = (Func<ServiceProviderEngineScope, object>)dynamicMethod.CreateDelegate(typeof(Func<ServiceProviderEngineScope, object>), iLEmitResolverBuilderRuntimeContext); result.Context = iLEmitResolverBuilderRuntimeContext; result.DynamicMethod = dynamicMethod; return result; } protected override object VisitDisposeCache(ServiceCallSite transientCallSite, ILEmitResolverBuilderContext argument) { if (transientCallSite.CaptureDisposable) { BeginCaptureDisposable(argument); VisitCallSiteMain(transientCallSite, argument); EndCaptureDisposable(argument); } else { VisitCallSiteMain(transientCallSite, argument); } return null; } protected override object VisitConstructor(ConstructorCallSite constructorCallSite, ILEmitResolverBuilderContext argument) { ServiceCallSite[] parameterCallSites = constructorCallSite.ParameterCallSites; foreach (ServiceCallSite serviceCallSite in parameterCallSites) { VisitCallSite(serviceCallSite, argument); if (serviceCallSite.ServiceType.IsValueType) { argument.Generator.Emit(OpCodes.Unbox_Any, serviceCallSite.ServiceType); } } argument.Generator.Emit(OpCodes.Newobj, constructorCallSite.ConstructorInfo); return null; } protected override object VisitRootCache(ServiceCallSite callSite, ILEmitResolverBuilderContext argument) { AddConstant(argument, CallSiteRuntimeResolver.Instance.Resolve(callSite, _rootScope)); return null; } protected override object VisitScopeCache(ServiceCallSite scopedCallSite, ILEmitResolverBuilderContext argument) { GeneratedMethod generatedMethod = BuildType(scopedCallSite); AddConstant(argument, generatedMethod.Context); argument.Generator.Emit(OpCodes.Ldarg_1); argument.Generator.Emit(OpCodes.Call, generatedMethod.DynamicMethod); return null; } protected override object VisitConstant(ConstantCallSite constantCallSite, ILEmitResolverBuilderContext argument) { AddConstant(argument, constantCallSite.DefaultValue); return null; } protected override object VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, ILEmitResolverBuilderContext argument) { argument.Generator.Emit(OpCodes.Ldarg_1); return null; } protected override object VisitIEnumerable(IEnumerableCallSite enumerableCallSite, ILEmitResolverBuilderContext argument) { if (enumerableCallSite.ServiceCallSites.Length == 0) { argument.Generator.Emit(OpCodes.Call, ServiceLookupHelpers.GetArrayEmptyMethodInfo(enumerableCallSite.ItemType)); } else { argument.Generator.Emit(OpCodes.Ldc_I4, enumerableCallSite.ServiceCallSites.Length); argument.Generator.Emit(OpCodes.Newarr, enumerableCallSite.ItemType); for (int i = 0; i < enumerableCallSite.ServiceCallSites.Length; i++) { argument.Generator.Emit(OpCodes.Dup); argument.Generator.Emit(OpCodes.Ldc_I4, i); ServiceCallSite serviceCallSite = enumerableCallSite.ServiceCallSites[i]; VisitCallSite(serviceCallSite, argument); if (serviceCallSite.ServiceType.IsValueType) { argument.Generator.Emit(OpCodes.Unbox_Any, serviceCallSite.ServiceType); } argument.Generator.Emit(OpCodes.Stelem, enumerableCallSite.ItemType); } } return null; } protected override object VisitFactory(FactoryCallSite factoryCallSite, ILEmitResolverBuilderContext argument) { if (argument.Factories == null) { argument.Factories = new List<Func<IServiceProvider, object>>(); } argument.Generator.Emit(OpCodes.Ldarg_0); argument.Generator.Emit(OpCodes.Ldfld, FactoriesField); argument.Generator.Emit(OpCodes.Ldc_I4, argument.Factories.Count); argument.Generator.Emit(OpCodes.Ldelem, typeof(Func<IServiceProvider, object>)); argument.Generator.Emit(OpCodes.Ldarg_1); argument.Generator.Emit(OpCodes.Call, ServiceLookupHelpers.InvokeFactoryMethodInfo); argument.Factories.Add(factoryCallSite.Factory); return null; } private void AddConstant(ILEmitResolverBuilderContext argument, object value) { if (argument.Constants == null) { argument.Constants = new List<object>(); } argument.Generator.Emit(OpCodes.Ldarg_0); argument.Generator.Emit(OpCodes.Ldfld, ConstantsField); argument.Generator.Emit(OpCodes.Ldc_I4, argument.Constants.Count); argument.Generator.Emit(OpCodes.Ldelem, typeof(object)); argument.Constants.Add(value); } private void AddCacheKey(ILEmitResolverBuilderContext argument, ServiceCacheKey key) { argument.Generator.Emit(OpCodes.Ldtoken, key.Type); argument.Generator.Emit(OpCodes.Call, GetTypeFromHandleMethod); argument.Generator.Emit(OpCodes.Ldc_I4, key.Slot); argument.Generator.Emit(OpCodes.Newobj, CacheKeyCtor); } private ILEmitResolverBuilderRuntimeContext GenerateMethodBody(ServiceCallSite callSite, ILGenerator generator) { ILEmitResolverBuilderContext iLEmitResolverBuilderContext = new ILEmitResolverBuilderContext { Generator = generator, Constants = null, Factories = null }; if (callSite.Cache.Location == CallSiteResultCacheLocation.Scope) { LocalBuilder localBuilder = iLEmitResolverBuilderContext.Generator.DeclareLocal(typeof(ServiceCacheKey)); LocalBuilder localBuilder2 = iLEmitResolverBuilderContext.Generator.DeclareLocal(typeof(IDictionary<ServiceCacheKey, object>)); LocalBuilder localBuilder3 = iLEmitResolverBuilderContext.Generator.DeclareLocal(typeof(object)); LocalBuilder localBuilder4 = iLEmitResolverBuilderContext.Generator.DeclareLocal(typeof(bool)); LocalBuilder localBuilder5 = iLEmitResolverBuilderContext.Generator.DeclareLocal(typeof(object)); Label label = iLEmitResolverBuilderContext.Generator.DefineLabel(); Label label2 = iLEmitResolverBuilderContext.Generator.DefineLabel(); Label label3 = iLEmitResolverBuilderContext.Generator.DefineLabel(); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ldarg_1); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Callvirt, ScopeIsRootScope); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Brfalse_S, label3); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Call, CallSiteRuntimeResolverInstanceField); AddConstant(iLEmitResolverBuilderContext, callSite); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ldarg_1); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Callvirt, CallSiteRuntimeResolverResolveMethod); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ret); iLEmitResolverBuilderContext.Generator.MarkLabel(label3); AddCacheKey(iLEmitResolverBuilderContext, callSite.Cache.Key); Stloc(iLEmitResolverBuilderContext.Generator, localBuilder.LocalIndex); iLEmitResolverBuilderContext.Generator.BeginExceptionBlock(); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ldarg_1); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Callvirt, ResolvedServicesGetter); Stloc(iLEmitResolverBuilderContext.Generator, localBuilder2.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ldarg_1); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Callvirt, ScopeLockGetter); Stloc(iLEmitResolverBuilderContext.Generator, localBuilder3.LocalIndex); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder3.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ldloca_S, localBuilder4.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Call, ServiceLookupHelpers.MonitorEnterMethodInfo); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder2.LocalIndex); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ldloca_S, localBuilder5.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Callvirt, ServiceLookupHelpers.TryGetValueMethodInfo); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Brtrue, label); VisitCallSiteMain(callSite, iLEmitResolverBuilderContext); Stloc(iLEmitResolverBuilderContext.Generator, localBuilder5.LocalIndex); if (callSite.CaptureDisposable) { BeginCaptureDisposable(iLEmitResolverBuilderContext); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder5.LocalIndex); EndCaptureDisposable(iLEmitResolverBuilderContext); generator.Emit(OpCodes.Pop); } Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder2.LocalIndex); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder.LocalIndex); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder5.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Callvirt, ServiceLookupHelpers.AddMethodInfo); iLEmitResolverBuilderContext.Generator.MarkLabel(label); iLEmitResolverBuilderContext.Generator.BeginFinallyBlock(); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder4.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Brfalse, label2); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder3.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Call, ServiceLookupHelpers.MonitorExitMethodInfo); iLEmitResolverBuilderContext.Generator.MarkLabel(label2); iLEmitResolverBuilderContext.Generator.EndExceptionBlock(); Ldloc(iLEmitResolverBuilderContext.Generator, localBuilder5.LocalIndex); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ret); } else { VisitCallSite(callSite, iLEmitResolverBuilderContext); iLEmitResolverBuilderContext.Generator.Emit(OpCodes.Ret); } return new ILEmitResolverBuilderRuntimeContext { Constants = iLEmitResolverBuilderContext.Constants?.ToArray(), Factories = iLEmitResolverBuilderContext.Factories?.ToArray() }; } private static void BeginCaptureDisposable(ILEmitResolverBuilderContext argument) { argument.Generator.Emit(OpCodes.Ldarg_1); } private static void EndCaptureDisposable(ILEmitResolverBuilderContext argument) { argument.Generator.Emit(OpCodes.Callvirt, ServiceLookupHelpers.CaptureDisposableMethodInfo); } private void Ldloc(ILGenerator generator, int index) { switch (index) { case 0: generator.Emit(OpCodes.Ldloc_0); return; case 1: generator.Emit(OpCodes.Ldloc_1); return; case 2: generator.Emit(OpCodes.Ldloc_2); return; case 3: generator.Emit(OpCodes.Ldloc_3); return; } if (index < 255) { generator.Emit(OpCodes.Ldloc_S, (byte)index); } else { generator.Emit(OpCodes.Ldloc, index); } } private void Stloc(ILGenerator generator, int index) { switch (index) { case 0: generator.Emit(OpCodes.Stloc_0); return; case 1: generator.Emit(OpCodes.Stloc_1); return; case 2: generator.Emit(OpCodes.Stloc_2); return; case 3: generator.Emit(OpCodes.Stloc_3); return; } if (index < 255) { generator.Emit(OpCodes.Stloc_S, (byte)index); } else { generator.Emit(OpCodes.Stloc, index); } } } internal sealed class ILEmitResolverBuilderContext { public ILGenerator Generator { get; set; } public List<object> Constants { get; set; } public List<Func<IServiceProvider, object>> Factories { get; set; } } internal sealed class ILEmitServiceProviderEngine : ServiceProviderEngine { private readonly ILEmitResolverBuilder _expressionResolverBuilder; public ILEmitServiceProviderEngine(ServiceProvider serviceProvider) { _expressionResolverBuilder = new ILEmitResolverBuilder(serviceProvider); } public override Func<ServiceProviderEngineScope, object> RealizeService(ServiceCallSite callSite) { return _expressionResolverBuilder.Build(callSite); } } } namespace Microsoft.Extensions.Internal { internal static class ParameterDefaultValue { public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue) { tryToGetDefaultValue = true; return parameter.HasDefaultValue; } public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue) { bool tryToGetDefaultValue; bool flag = CheckHasDefaultValue(parameter, out tryToGetDefaultValue); defaultValue = null; if (flag) { if (tryToGetDefaultValue) { defaultValue = parameter.DefaultValue; } bool flag2 = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>); if (defaultValue == null && parameter.ParameterType.IsValueType && !flag2) { defaultValue = CreateValueType(parameter.ParameterType); } if (defaultValue != null && flag2) { Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType != null && underlyingType.IsEnum) { defaultValue = Enum.ToObject(underlyingType, defaultValue); } } } return flag; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")] static object? CreateValueType(Type t) { return RuntimeHelpers.GetUninitializedObject(t); } } } internal static class TypeNameHelper { private readonly struct DisplayNameOptions { public bool FullName { get; } public bool IncludeGenericParameters { get; } public bool IncludeGenericParameterNames { get; } public char NestedTypeDelimiter { get; } public DisplayNameOptions(bool fullName, bool includeGenericParameterNames, bool inc
MegabonkTogether/Microsoft.Extensions.Configuration.Binder.dll
Decompiled 2 hours agousing System; 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; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Binder.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.Binder")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.Binder")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.Binder { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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_MissingConfig => GetResourceString("Error_MissingConfig"); internal static string Error_MissingParameterlessConstructor => GetResourceString("Error_MissingParameterlessConstructor"); 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } } namespace Microsoft.Extensions.Configuration { public class BinderOptions { public bool BindNonPublicProperties { get; set; } public bool ErrorOnUnknownConfiguration { get; set; } } public static class ConfigurationBinder { private const BindingFlags DeclaredOnlyLookup = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; 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."; [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(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration) { return configuration.Get<T>(delegate { }); } [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(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration, Action<BinderOptions> configureOptions) { if (configuration == null) { throw new ArgumentNullException("configuration"); } object obj = configuration.Get(typeof(T), configureOptions); if (obj == null) { return default(T); } return (T)obj; } [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, Type type) { return configuration.Get(type, delegate { }); } [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(DynamicallyAccessedMemberTypes.All)] Type type, Action<BinderOptions> configureOptions) { if (configuration == null) { throw new ArgumentNullException("configuration"); } BinderOptions binderOptions = new BinderOptions(); configureOptions?.Invoke(binderOptions); return BindInstance(type, null, configuration, binderOptions); } [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) { configuration.GetSection(key).Bind(instance); } [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 { }); } [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) { if (configuration == null) { throw new ArgumentNullException("configuration"); } if (instance != null) { BinderOptions binderOptions = new BinderOptions(); configureOptions?.Invoke(binderOptions); BindInstance(instance.GetType(), instance, 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(DynamicallyAccessedMemberTypes.All)] 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(DynamicallyAccessedMemberTypes.All)] 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(DynamicallyAccessedMemberTypes.All)] 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(DynamicallyAccessedMemberTypes.All)] 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; } [RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")] private static void BindNonScalar(this IConfiguration configuration, object instance, BinderOptions options) { if (instance == null) { return; } List<PropertyInfo> allProperties = GetAllProperties(instance.GetType()); if (options.ErrorOnUnknownConfiguration) { HashSet<string> propertyNames = new HashSet<string>(allProperties.Select((PropertyInfo mp) => mp.Name), StringComparer.OrdinalIgnoreCase); IEnumerable<IConfigurationSection> children = configuration.GetChildren(); List<string> list = (from cs in children where !propertyNames.Contains(cs.Key) select cs into mp select "'" + mp.Key + "'").ToList(); if (list.Count > 0) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_MissingConfig, "ErrorOnUnknownConfiguration", "BinderOptions", instance.GetType(), string.Join(", ", list))); } } foreach (PropertyInfo item in allProperties) { BindProperty(item, instance, configuration, options); } } [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 == null || (!options.BindNonPublicProperties && !property.GetMethod.IsPublic) || property.GetMethod.GetParameters().Length != 0) { return; } object value = property.GetValue(instance); bool flag = property.SetMethod != null && (property.SetMethod.IsPublic || options.BindNonPublicProperties); if (value != null || flag) { value = GetPropertyValue(property, instance, config, options); if (value != null && flag) { property.SetValue(instance, value); } } } [RequiresUnreferencedCode("Cannot statically analyze what the element type is of the object collection in type so its members may be trimmed.")] private static object BindToCollection(Type type, IConfiguration config, BinderOptions options) { Type type2 = typeof(List<>).MakeGenericType(type.GenericTypeArguments[0]); object obj = Activator.CreateInstance(type2); BindCollection(obj, type2, config, options); return obj; } [RequiresUnreferencedCode("In case type is a Dictionary, cannot statically analyze what the element type is of the value objects in the dictionary so its members may be trimmed.")] private static object AttemptBindToCollectionInterfaces([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, IConfiguration config, BinderOptions options) { if (!type.IsInterface) { return null; } Type type2 = FindOpenGenericInterface(typeof(IReadOnlyList<>), type); if (type2 != null) { return BindToCollection(type, config, options); } type2 = FindOpenGenericInterface(typeof(IReadOnlyDictionary<, >), type); if (type2 != null) { Type type3 = typeof(Dictionary<, >).MakeGenericType(type.GenericTypeArguments[0], type.GenericTypeArguments[1]); object obj = Activator.CreateInstance(type3); BindDictionary(obj, type3, config, options); return obj; } type2 = FindOpenGenericInterface(typeof(IDictionary<, >), type); if (type2 != null) { object obj2 = Activator.CreateInstance(typeof(Dictionary<, >).MakeGenericType(type.GenericTypeArguments[0], type.GenericTypeArguments[1])); BindDictionary(obj2, type2, config, options); return obj2; } type2 = FindOpenGenericInterface(typeof(IReadOnlyCollection<>), type); if (type2 != null) { return BindToCollection(type, config, options); } type2 = FindOpenGenericInterface(typeof(ICollection<>), type); if (type2 != null) { return BindToCollection(type, config, options); } type2 = FindOpenGenericInterface(typeof(IEnumerable<>), type); if (type2 != null) { return BindToCollection(type, config, options); } return null; } [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 BindInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, object instance, IConfiguration config, BinderOptions options) { if (type == typeof(IConfigurationSection)) { return config; } IConfigurationSection configurationSection = config as IConfigurationSection; string text = configurationSection?.Value; if (text != null && TryConvertValue(type, text, configurationSection.Path, out var result, out var error)) { if (error != null) { throw error; } return result; } if (config != null && config.GetChildren().Any()) { if (instance == null) { instance = AttemptBindToCollectionInterfaces(type, config, options); if (instance != null) { return instance; } instance = CreateInstance(type); } Type type2 = FindOpenGenericInterface(typeof(IDictionary<, >), type); if (type2 != null) { BindDictionary(instance, type2, config, options); } else if (type.IsArray) { instance = BindArray((Array)instance, config, options); } else { type2 = FindOpenGenericInterface(typeof(ICollection<>), type); if (type2 != null) { BindCollection(instance, type2, config, options); } else { config.BindNonScalar(instance, options); } } } return instance; } private static object CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type) { if (type.IsInterface || type.IsAbstract) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_CannotActivateAbstractOrInterface, type)); } if (type.IsArray) { if (type.GetArrayRank() > 1) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_UnsupportedMultidimensionalArray, type)); } return Array.CreateInstance(type.GetElementType(), 0); } if (!type.IsValueType && !type.GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Any((ConstructorInfo ctor) => ctor.IsPublic && ctor.GetParameters().Length == 0)) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_MissingParameterlessConstructor, type)); } try { return Activator.CreateInstance(type); } catch (Exception innerException) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_FailedToActivate, type), innerException); } } [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(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type dictionaryType, IConfiguration config, BinderOptions options) { Type type = dictionaryType.GenericTypeArguments[0]; Type type2 = dictionaryType.GenericTypeArguments[1]; bool isEnum = type.IsEnum; if (type != typeof(string) && !isEnum) { return; } PropertyInfo property = dictionaryType.GetProperty("Item", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (IConfigurationSection child in config.GetChildren()) { object obj = BindInstance(type2, null, child, options); if (obj != null) { if (type == typeof(string)) { string key = child.Key; property.SetValue(dictionary, obj, new object[1] { key }); } else if (isEnum) { object obj2 = Enum.Parse(type, child.Key); property.SetValue(dictionary, obj, new object[1] { obj2 }); } } } } [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(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type collectionType, IConfiguration config, BinderOptions options) { Type type = collectionType.GenericTypeArguments[0]; MethodInfo method = collectionType.GetMethod("Add", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (IConfigurationSection child in config.GetChildren()) { try { object obj = BindInstance(type, null, child, options); if (obj != null) { method.Invoke(collection, new object[1] { obj }); } } catch { } } } [RequiresUnreferencedCode("Cannot statically analyze what the element type is of the Array so its members may be trimmed.")] private static Array BindArray(Array source, IConfiguration config, BinderOptions options) { IConfigurationSection[] array = config.GetChildren().ToArray(); int length = source.Length; Type elementType = source.GetType().GetElementType(); Array array2 = Array.CreateInstance(elementType, length + array.Length); if (length > 0) { Array.Copy(source, array2, length); } for (int i = 0; i < array.Length; i++) { try { object obj = BindInstance(elementType, null, array[i], options); if (obj != null) { array2.SetValue(obj, length + i); } } catch { } } return array2; } [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(DynamicallyAccessedMemberTypes.All)] Type type, string value, string path, out object result, out Exception error) { error = null; result = null; if (type == typeof(object)) { result = value; return true; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(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 (Exception innerException) { error = new InvalidOperationException(System.SR.Format(System.SR.Error_FailedBinding, path, type), innerException); } return true; } if (type == typeof(byte[])) { try { result = Convert.FromBase64String(value); } catch (FormatException innerException2) { error = new InvalidOperationException(System.SR.Format(System.SR.Error_FailedBinding, path, type), innerException2); } 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(DynamicallyAccessedMemberTypes.All)] 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 Type FindOpenGenericInterface(Type expected, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] Type actual) { if (actual.IsGenericType && actual.GetGenericTypeDefinition() == expected) { return actual; } Type[] interfaces = actual.GetInterfaces(); Type[] array = interfaces; foreach (Type type in array) { if (type.IsGenericType && type.GetGenericTypeDefinition() == expected) { return type; } } return null; } private static List<PropertyInfo> GetAllProperties([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) { List<PropertyInfo> list = new List<PropertyInfo>(); do { list.AddRange(type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)); type = type.BaseType; } while (type != typeof(object)); return list; } [RequiresUnreferencedCode("Cannot statically analyze property.PropertyType so its members may be trimmed.")] private static object GetPropertyValue(PropertyInfo property, object instance, IConfiguration config, BinderOptions options) { string propertyName = GetPropertyName(property); return BindInstance(property.PropertyType, property.GetValue(instance), config.GetSection(propertyName), options); } private static string GetPropertyName(MemberInfo property) { if (property == null) { throw new ArgumentNullException("property"); } foreach (CustomAttributeData customAttributesDatum in property.GetCustomAttributesData()) { if (!(customAttributesDatum.AttributeType != typeof(ConfigurationKeyNameAttribute))) { if (customAttributesDatum.ConstructorArguments.Count != 1) { break; } string text = customAttributesDatum.ConstructorArguments[0].Value?.ToString(); return (!string.IsNullOrWhiteSpace(text)) ? text : property.Name; } } return property.Name; } } }
MegabonkTogether/Microsoft.Extensions.FileProviders.Physical.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.FileProviders.Physical.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.FileProviders.Physical")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("File provider for physical files for Microsoft.Extensions.FileProviders.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.FileProviders.Physical")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.FileProviders.Physical { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace Microsoft.Extensions.Internal { internal static class NonCapturingTimer { public static Timer Create(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period) { 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, 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 { if (_fileWatcher != null) { throw new InvalidOperationException(System.SR.Format(System.SR.CannotModifyWhenFileWatcherInitialized, "UsePollingFileWatcher")); } _usePollingFileWatcher = value; } } public bool UseActivePolling { get { if (!_useActivePolling.HasValue) { ReadPollingEnvironmentVariables(); } return _useActivePolling.Value; } set { _useActivePolling = value; } } internal PhysicalFilesWatcher FileWatcher { get { return LazyInitializer.EnsureInitialized(ref _fileWatcher, ref _fileWatcherInitialized, ref _fileWatcherLock, _fileWatcherFactory); } set { _fileWatcherInitialized = true; _fileWatcher = value; } } public string Root { get; } public PhysicalFileProvider(string root) : this(root, ExclusionFilters.Sensitive) { } public PhysicalFileProvider(string root, ExclusionFilters filters) { 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() { 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) ? null : new FileSystemWatcher(text)); } return new PhysicalFilesWatcher(text, fileSystemWatcher, UsePollingFileWatcher, _filters) { UseActivePolling = UseActivePolling }; } private void ReadPollingEnvironmentVariables() { string environmentVariable = Environment.GetEnvironmentVariable("DOTNET_USE_POLLING_FILE_WATCHER"); bool value = string.Equals(environmentVariable, "1", StringComparison.Ordinal) || string.Equals(environmentVariable, "true", StringComparison.OrdinalIgnoreCase); _usePollingFileWatcher = value; _useActivePolling = value; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(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.OrdinalIgnoreCase); } public IFileInfo GetFileInfo(string subpath) { if (string.IsNullOrEmpty(subpath) || PathUtils.HasInvalidPathChars(subpath)) { return new NotFoundFileInfo(subpath); } subpath = subpath.TrimStart(_pathSeparators); if (Path.IsPathRooted(subpath)) { return new NotFoundFileInfo(subpath); } string fullPath = GetFullPath(subpath); if (fullPath == null) { return new NotFoundFileInfo(subpath); } FileInfo fileInfo = new FileInfo(fullPath); if (FileSystemInfoHelper.IsExcluded(fileInfo, _filters)) { return new NotFoundFileInfo(subpath); } return new PhysicalFileInfo(fileInfo); } public IDirectoryContents GetDirectoryContents(string subpath) { try { if (subpath == null || PathUtils.HasInvalidPathChars(subpath)) { return NotFoundDirectoryContents.Singleton; } subpath = subpath.TrimStart(_pathSeparators); if (Path.IsPathRooted(subpath)) { return NotFoundDirectoryContents.Singleton; } string fullPath = GetFullPath(subpath); if (fullPath == null || !Directory.Exists(fullPath)) { return NotFoundDirectoryContents.Singleton; } return new PhysicalDirectoryContents(fullPath, _filters); } catch (DirectoryNotFoundException) { } catch (IOException) { } return NotFoundDirectoryContents.Singleton; } public IChangeToken Watch(string filter) { if (filter == null || PathUtils.HasInvalidFilterChars(filter)) { return NullChangeToken.Singleton; } filter = filter.TrimStart(_pathSeparators); return FileWatcher.CreateFileChangeToken(filter); } } internal sealed class EmptyDisposable : IDisposable { public static Microsoft.Extensions.FileProviders.EmptyDisposable Instance { get; } = new Microsoft.Extensions.FileProviders.EmptyDisposable(); private EmptyDisposable() { } public void Dispose() { } } } namespace Microsoft.Extensions.FileProviders.Internal { public class PhysicalDirectoryContents : IDirectoryContents, IEnumerable<IFileInfo>, IEnumerable { private 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) { _directory = directory ?? throw new ArgumentNullException("directory"); _filters = filters; } public IEnumerator<IFileInfo> GetEnumerator() { EnsureInitialized(); return _entries.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { EnsureInitialized(); return _entries.GetEnumerator(); } private void EnsureInitialized() { try { _entries = (from info in new DirectoryInfo(_directory).EnumerateFileSystemInfos() where !FileSystemInfoHelper.IsExcluded(info, _filters) select info).Select((Func<FileSystemInfo, IFileInfo>)delegate(FileSystemInfo info) { if (info is FileInfo info2) { return new PhysicalFileInfo(info2); } if (info is DirectoryInfo info3) { return new PhysicalDirectoryInfo(info3); } throw new InvalidOperationException(System.SR.UnexpectedFileSystemInfo); }); } catch (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 DateTime UtcNow => DateTime.UtcNow; private Clock() { } } internal static class FileSystemInfoHelper { public static bool IsExcluded(FileSystemInfo fileSystemInfo, ExclusionFilters filters) { if (filters == ExclusionFilters.None) { return false; } if (fileSystemInfo.Name.StartsWith(".", StringComparison.Ordinal) && (filters & ExclusionFilters.DotPrefixed) != 0) { return true; } if (fileSystemInfo.Exists && (((fileSystemInfo.Attributes & FileAttributes.Hidden) != 0 && (filters & ExclusionFilters.Hidden) != 0) || ((fileSystemInfo.Attributes & FileAttributes.System) != 0 && (filters & ExclusionFilters.System) != 0))) { return true; } return false; } public static DateTime? GetFileLinkTargetLastWriteTimeUtc(string filePath) { FileInfo fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { return GetFileLinkTargetLastWriteTimeUtc(fileInfo); } return null; } public static DateTime? GetFileLinkTargetLastWriteTimeUtc(FileInfo fileInfo) { if (fileInfo.LinkTarget != null) { try { FileSystemInfo fileSystemInfo = fileInfo.ResolveLinkTarget(returnFinalTarget: true); if (fileSystemInfo != null && fileSystemInfo.Exists) { return fileSystemInfo.LastWriteTimeUtc; } } catch (FileNotFoundException) { } return DateTime.MinValue; } return null; } } internal interface IClock { DateTime UtcNow { get; } } public class PhysicalDirectoryInfo : IFileInfo { private readonly DirectoryInfo _info; public bool Exists => _info.Exists; public long Length => -1L; public string PhysicalPath => _info.FullName; public string Name => _info.Name; public DateTimeOffset LastModified => _info.LastWriteTimeUtc; public bool IsDirectory => true; public PhysicalDirectoryInfo(DirectoryInfo info) { _info = info; } public Stream CreateReadStream() { throw new InvalidOperationException(System.SR.CannotCreateStream); } } public class PhysicalFileInfo : IFileInfo { private readonly FileInfo _info; public bool Exists => _info.Exists; public long Length => _info.Length; public string PhysicalPath => _info.FullName; public string Name => _info.Name; public DateTimeOffset LastModified => _info.LastWriteTimeUtc; public bool IsDirectory => false; public PhysicalFileInfo(FileInfo info) { _info = info; } public Stream CreateReadStream() { int bufferSize = 1; return new FileStream(PhysicalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); } } public class PhysicalFilesWatcher : IDisposable { private readonly struct ChangeTokenInfo { public CancellationTokenSource TokenSource { get; } public CancellationChangeToken ChangeToken { get; } public Matcher Matcher { 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; } } private static readonly Action<object> _cancelTokenSource = delegate(object state) { ((CancellationTokenSource)state).Cancel(); }; internal static TimeSpan DefaultPollingInterval = TimeSpan.FromSeconds(4.0); private readonly ConcurrentDictionary<string, ChangeTokenInfo> _filePathTokenLookup = new ConcurrentDictionary<string, ChangeTokenInfo>(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary<string, ChangeTokenInfo> _wildcardTokenLookup = new ConcurrentDictionary<string, ChangeTokenInfo>(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 _timerInitialzed; private object _timerLock = new object(); private Func<Timer> _timerFactory; private bool _disposed; internal bool PollForChanges { get; } internal bool UseActivePolling { get; set; } internal ConcurrentDictionary<IPollingChangeToken, IPollingChangeToken> PollingChangeTokens { 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) { 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 += OnChanged; _fileWatcher.Changed += OnChanged; _fileWatcher.Renamed += OnRenamed; _fileWatcher.Deleted += OnChanged; _fileWatcher.Error += OnError; } PollForChanges = pollForChanges; _filters = filters; PollingChangeTokens = new ConcurrentDictionary<IPollingChangeToken, IPollingChangeToken>(); _timerFactory = () => NonCapturingTimer.Create(RaiseChangeEvents, PollingChangeTokens, TimeSpan.Zero, DefaultPollingInterval); } public IChangeToken CreateFileChangeToken(string filter) { if (filter == null) { throw new ArgumentNullException("filter"); } filter = NormalizePath(filter); if (Path.IsPathRooted(filter) || PathUtils.PathNavigatesAboveRoot(filter)) { return NullChangeToken.Singleton; } IChangeToken orAddChangeToken = GetOrAddChangeToken(filter); TryEnableFileSystemWatcher(); return orAddChangeToken; } private IChangeToken GetOrAddChangeToken(string pattern) { if (UseActivePolling) { LazyInitializer.EnsureInitialized(ref _timer, ref _timerInitialzed, ref _timerLock, _timerFactory); } if (pattern.IndexOf('*') != -1 || IsDirectoryPath(pattern)) { return GetOrAddWildcardChangeToken(pattern); } return GetOrAddFilePathChangeToken(pattern); } internal IChangeToken GetOrAddFilePathChangeToken(string filePath) { if (!_filePathTokenLookup.TryGetValue(filePath, out var value)) { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationChangeToken changeToken = new CancellationChangeToken(cancellationTokenSource.Token); value = new ChangeTokenInfo(cancellationTokenSource, changeToken); value = _filePathTokenLookup.GetOrAdd(filePath, value); } IChangeToken changeToken2 = value.ChangeToken; if (PollForChanges) { PollingFileChangeToken pollingFileChangeToken = new PollingFileChangeToken(new FileInfo(Path.Combine(_root, filePath))); if (UseActivePolling) { pollingFileChangeToken.ActiveChangeCallbacks = true; pollingFileChangeToken.CancellationTokenSource = new CancellationTokenSource(); PollingChangeTokens.TryAdd(pollingFileChangeToken, pollingFileChangeToken); } changeToken2 = new CompositeChangeToken(new IChangeToken[2] { changeToken2, pollingFileChangeToken }); } return changeToken2; } internal IChangeToken GetOrAddWildcardChangeToken(string pattern) { if (!_wildcardTokenLookup.TryGetValue(pattern, out var value)) { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationChangeToken changeToken = new CancellationChangeToken(cancellationTokenSource.Token); Matcher matcher = new Matcher(StringComparison.OrdinalIgnoreCase); matcher.AddInclude(pattern); value = new ChangeTokenInfo(cancellationTokenSource, changeToken, matcher); value = _wildcardTokenLookup.GetOrAdd(pattern, value); } IChangeToken changeToken2 = value.ChangeToken; if (PollForChanges) { PollingWildCardChangeToken pollingWildCardChangeToken = new PollingWildCardChangeToken(_root, pattern); if (UseActivePolling) { pollingWildCardChangeToken.ActiveChangeCallbacks = true; pollingWildCardChangeToken.CancellationTokenSource = new CancellationTokenSource(); PollingChangeTokens.TryAdd(pollingWildCardChangeToken, pollingWildCardChangeToken); } changeToken2 = new CompositeChangeToken(new IChangeToken[2] { changeToken2, pollingWildCardChangeToken }); } return changeToken2; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _fileWatcher?.Dispose(); _timer?.Dispose(); } _disposed = true; } } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void OnRenamed(object sender, RenamedEventArgs e) { OnFileSystemEntryChange(e.OldFullPath); OnFileSystemEntryChange(e.FullPath); if (!Directory.Exists(e.FullPath)) { return; } try { foreach (string item in Directory.EnumerateFileSystemEntries(e.FullPath, "*", SearchOption.AllDirectories)) { string fullPath = Path.Combine(e.OldFullPath, item.Substring(e.FullPath.Length + 1)); OnFileSystemEntryChange(fullPath); OnFileSystemEntryChange(item); } } catch (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) { foreach (string key in _filePathTokenLookup.Keys) { ReportChangeForMatchedEntries(key); } } [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] private void OnFileSystemEntryChange(string fullPath) { try { FileInfo fileSystemInfo = new FileInfo(fullPath); if (!FileSystemInfoHelper.IsExcluded(fileSystemInfo, _filters)) { string path = fullPath.Substring(_root.Length); ReportChangeForMatchedEntries(path); } } catch (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) { if (string.IsNullOrEmpty(path)) { return; } path = NormalizePath(path); bool flag = false; if (_filePathTokenLookup.TryRemove(path, out var value)) { CancelToken(value); flag = true; } foreach (KeyValuePair<string, ChangeTokenInfo> item in _wildcardTokenLookup) { PatternMatchingResult patternMatchingResult = item.Value.Matcher.Match(path); if (patternMatchingResult.HasMatches && _wildcardTokenLookup.TryRemove(item.Key, out value)) { CancelToken(value); flag = true; } } 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 = 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) { if (!matchInfo.TokenSource.IsCancellationRequested) { Task.Factory.StartNew(_cancelTokenSource, matchInfo.TokenSource, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } } internal static void RaiseChangeEvents(object state) { ConcurrentDictionary<IPollingChangeToken, IPollingChangeToken> concurrentDictionary = (ConcurrentDictionary<IPollingChangeToken, IPollingChangeToken>)state; foreach (KeyValuePair<IPollingChangeToken, IPollingChangeToken> item in concurrentDictionary) { IPollingChangeToken key = item.Key; if (key.HasChanged && concurrentDictionary.TryRemove(key, out var _)) { try { key.CancellationTokenSource.Cancel(); } catch { } } } } } public class PollingFileChangeToken : IPollingChangeToken, IChangeToken { private readonly FileInfo _fileInfo; private DateTime _previousWriteTimeUtc; private DateTime _lastCheckedTimeUtc; private bool _hasChanged; private CancellationTokenSource _tokenSource; private CancellationChangeToken _changeToken; internal static TimeSpan PollingInterval { get; set; } = PhysicalFilesWatcher.DefaultPollingInterval; public bool ActiveChangeCallbacks { get; internal set; } internal CancellationTokenSource CancellationTokenSource { get { return _tokenSource; } set { _tokenSource = value; _changeToken = new CancellationChangeToken(_tokenSource.Token); } } CancellationTokenSource IPollingChangeToken.CancellationTokenSource => CancellationTokenSource; public bool HasChanged { get { if (_hasChanged) { return _hasChanged; } DateTime utcNow = DateTime.UtcNow; if (utcNow - _lastCheckedTimeUtc < PollingInterval) { return _hasChanged; } DateTime lastWriteTimeUtc = GetLastWriteTimeUtc(); if (_previousWriteTimeUtc != lastWriteTimeUtc) { _previousWriteTimeUtc = lastWriteTimeUtc; _hasChanged = true; } _lastCheckedTimeUtc = utcNow; return _hasChanged; } } public PollingFileChangeToken(FileInfo fileInfo) { _fileInfo = fileInfo; _previousWriteTimeUtc = GetLastWriteTimeUtc(); } private DateTime GetLastWriteTimeUtc() { _fileInfo.Refresh(); if (!_fileInfo.Exists) { return DateTime.MinValue; } return FileSystemInfoHelper.GetFileLinkTargetLastWriteTimeUtc(_fileInfo) ?? _fileInfo.LastWriteTimeUtc; } public IDisposable RegisterChangeCallback(Action<object> callback, object state) { if (!ActiveChangeCallbacks) { return Microsoft.Extensions.FileProviders.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 DateTime? _lastScanTimeUtc; private byte[] _byteBuffer; private byte[] _previousHash; private CancellationTokenSource _tokenSource; private CancellationChangeToken _changeToken; public bool ActiveChangeCallbacks { get; internal set; } internal TimeSpan PollingInterval { get; set; } = PhysicalFilesWatcher.DefaultPollingInterval; internal CancellationTokenSource CancellationTokenSource { get { return _tokenSource; } set { _tokenSource = value; _changeToken = new CancellationChangeToken(_tokenSource.Token); } } CancellationTokenSource IPollingChangeToken.CancellationTokenSource => CancellationTokenSource; private IClock Clock { get; } public bool HasChanged { get { if (_changed) { return _changed; } DateTime utcNow = Clock.UtcNow; DateTime? lastScanTimeUtc = _lastScanTimeUtc; if (utcNow - lastScanTimeUtc >= PollingInterval) { lock (_enumerationLock) { _changed = CalculateChanges(); } } return _changed; } } public PollingWildCardChangeToken(string root, string pattern) : this(new DirectoryInfoWrapper(new DirectoryInfo(root)), pattern, Microsoft.Extensions.FileProviders.Physical.Clock.Instance) { } internal PollingWildCardChangeToken(DirectoryInfoBase directoryInfo, string pattern, IClock clock) { _directoryInfo = directoryInfo; Clock = clock; _matcher = new Matcher(StringComparison.OrdinalIgnoreCase); _matcher.AddInclude(pattern); CalculateChanges(); } private bool CalculateChanges() { PatternMatchingResult patternMatchingResult = _matcher.Execute(_directoryInfo); IOrderedEnumerable<FilePatternMatch> orderedEnumerable = patternMatchingResult.Files.OrderBy<FilePatternMatch, string>((FilePatternMatch f) => f.Path, StringComparer.Ordinal); using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { foreach (FilePatternMatch item in orderedEnumerable) { DateTime lastWriteUtc = GetLastWriteUtc(item.Path); if (_lastScanTimeUtc.HasValue && _lastScanTimeUtc < lastWriteUtc) { return true; } ComputeHash(incrementalHash, item.Path, lastWriteUtc); } byte[] hashAndReset = incrementalHash.GetHashAndReset(); if (!ArrayEquals(_previousHash, hashAndReset)) { return true; } _previousHash = hashAndReset; _lastScanTimeUtc = Clock.UtcNow; } return false; } protected virtual DateTime GetLastWriteUtc(string path) { string text = Path.Combine(_directoryInfo.FullName, path); return FileSystemInfoHelper.GetFileLinkTargetLastWriteTimeUtc(text) ?? File.GetLastWriteTimeUtc(text); } private static bool ArrayEquals(byte[] previousHash, byte[] currentHash) { if (previousHash == null) { return true; } for (int i = 0; i < previousHash.Length; i++) { if (previousHash[i] != currentHash[i]) { return false; } } return true; } private unsafe void ComputeHash(IncrementalHash sha256, string path, 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); } IDisposable IChangeToken.RegisterChangeCallback(Action<object> callback, object state) { if (!ActiveChangeCallbacks) { return Microsoft.Extensions.FileProviders.EmptyDisposable.Instance; } return _changeToken.RegisterChangeCallback(callback, state); } } } namespace Microsoft.Extensions.FileProviders.Physical.Internal { internal static class PathUtils { private static readonly char[] _invalidFileNameChars = (from c in Path.GetInvalidFileNameChars() where c != Path.DirectorySeparatorChar && c != Path.AltDirectorySeparatorChar select c).ToArray(); private static readonly char[] _invalidFilterChars = _invalidFileNameChars.Where((char c) => c != '*' && c != '|' && c != '?').ToArray(); 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) { StringTokenizer stringTokenizer = new StringTokenizer(path, _pathSeparators); int num = 0; foreach (StringSegment item in stringTokenizer) { if (item.Equals(".") || item.Equals("")) { continue; } if (item.Equals("..")) { num--; if (num == -1) { return true; } } else { num++; } } return false; } } }
MegabonkTogether/Microsoft.Extensions.Hosting.Abstractions.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Hosting.Abstractions")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Hosting and startup abstractions for applications.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Hosting.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } } namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionHostedServiceExtensions { public static IServiceCollection AddHostedService<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THostedService>(this IServiceCollection services) where THostedService : class, IHostedService { services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, THostedService>()); return services; } public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services, Func<IServiceProvider, THostedService> implementationFactory) where THostedService : class, IHostedService { services.TryAddEnumerable(ServiceDescriptor.Singleton((Func<IServiceProvider, IHostedService>)implementationFactory)); return services; } } } namespace Microsoft.Extensions.Hosting { public abstract class BackgroundService : IHostedService, IDisposable { private Task _executeTask; private CancellationTokenSource _stoppingCts; public virtual Task ExecuteTask => _executeTask; protected abstract Task ExecuteAsync(CancellationToken stoppingToken); public virtual Task StartAsync(CancellationToken cancellationToken) { _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { cancellationToken }); _executeTask = ExecuteAsync(_stoppingCts.Token); if (_executeTask.IsCompleted) { return _executeTask; } return Task.CompletedTask; } public virtual async Task StopAsync(CancellationToken cancellationToken) { if (_executeTask != null) { try { _stoppingCts.Cancel(); } finally { await Task.WhenAny(new Task[2] { _executeTask, Task.Delay(-1, cancellationToken) }).ConfigureAwait(continueOnCapturedContext: false); } } } public virtual void Dispose() { _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"; } public class HostBuilderContext { public IHostEnvironment HostingEnvironment { get; set; } public IConfiguration Configuration { get; set; } public IDictionary<object, object> Properties { get; } public HostBuilderContext(IDictionary<object, object> properties) { Properties = properties ?? throw new ArgumentNullException("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) { if (hostEnvironment == null) { throw new ArgumentNullException("hostEnvironment"); } return hostEnvironment.IsEnvironment(Environments.Development); } public static bool IsStaging(this IHostEnvironment hostEnvironment) { if (hostEnvironment == null) { throw new ArgumentNullException("hostEnvironment"); } return hostEnvironment.IsEnvironment(Environments.Staging); } public static bool IsProduction(this IHostEnvironment hostEnvironment) { if (hostEnvironment == null) { throw new ArgumentNullException("hostEnvironment"); } return hostEnvironment.IsEnvironment(Environments.Production); } public static bool IsEnvironment(this IHostEnvironment hostEnvironment, string environmentName) { if (hostEnvironment == null) { throw new ArgumentNullException("hostEnvironment"); } return string.Equals(hostEnvironment.EnvironmentName, environmentName, StringComparison.OrdinalIgnoreCase); } } public static class HostingAbstractionsHostBuilderExtensions { public static IHost Start(this IHostBuilder hostBuilder) { return hostBuilder.StartAsync().GetAwaiter().GetResult(); } public static async Task<IHost> StartAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default(CancellationToken)) { IHost host = hostBuilder.Build(); await host.StartAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); return host; } } public static class HostingAbstractionsHostExtensions { public static void Start(this IHost host) { host.StartAsync().GetAwaiter().GetResult(); } public static async Task StopAsync(this IHost host, TimeSpan timeout) { using CancellationTokenSource cts = new CancellationTokenSource(timeout); await host.StopAsync(cts.Token).ConfigureAwait(continueOnCapturedContext: false); } public static void WaitForShutdown(this IHost host) { host.WaitForShutdownAsync().GetAwaiter().GetResult(); } public static void Run(this IHost host) { host.RunAsync().GetAwaiter().GetResult(); } public static async Task RunAsync(this IHost host, CancellationToken token = default(CancellationToken)) { try { await host.StartAsync(token).ConfigureAwait(continueOnCapturedContext: false); await host.WaitForShutdownAsync(token).ConfigureAwait(continueOnCapturedContext: false); } finally { if (host is IAsyncDisposable asyncDisposable) { await asyncDisposable.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } else { host.Dispose(); } } } public static async Task WaitForShutdownAsync(this IHost host, CancellationToken token = default(CancellationToken)) { IHostApplicationLifetime service = host.Services.GetService<IHostApplicationLifetime>(); token.Register(delegate(object state) { ((IHostApplicationLifetime)state).StopApplication(); }, service); TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); service.ApplicationStopping.Register(delegate(object obj) { TaskCompletionSource<object> taskCompletionSource2 = (TaskCompletionSource<object>)obj; taskCompletionSource2.TrySetResult(null); }, taskCompletionSource); await taskCompletionSource.Task.ConfigureAwait(continueOnCapturedContext: false); await host.StopAsync(CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } } public static class HostingEnvironmentExtensions { public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) { if (hostingEnvironment == null) { throw new ArgumentNullException("hostingEnvironment"); } return hostingEnvironment.IsEnvironment(EnvironmentName.Development); } public static bool IsStaging(this IHostingEnvironment hostingEnvironment) { if (hostingEnvironment == null) { throw new ArgumentNullException("hostingEnvironment"); } return hostingEnvironment.IsEnvironment(EnvironmentName.Staging); } public static bool IsProduction(this IHostingEnvironment hostingEnvironment) { if (hostingEnvironment == null) { throw new ArgumentNullException("hostingEnvironment"); } return hostingEnvironment.IsEnvironment(EnvironmentName.Production); } public static bool IsEnvironment(this IHostingEnvironment hostingEnvironment, string environmentName) { if (hostingEnvironment == null) { throw new ArgumentNullException("hostingEnvironment"); } return string.Equals(hostingEnvironment.EnvironmentName, environmentName, StringComparison.OrdinalIgnoreCase); } } [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 : IDisposable { IServiceProvider Services { get; } Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)); 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); IHostBuilder UseServiceProviderFactory<TContainerBuilder>(Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory); IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate); IHost Build(); } public interface IHostedService { Task StartAsync(CancellationToken cancellationToken); 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 { Task WaitForStartAsync(CancellationToken cancellationToken); Task StopAsync(CancellationToken cancellationToken); } }
MegabonkTogether/Microsoft.Extensions.Configuration.Abstractions.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; 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.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace FxResources.Microsoft.Extensions.Configuration.Abstractions { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace Microsoft.Extensions.Configuration { public static class ConfigurationExtensions { 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 IEnumerable<KeyValuePair<string, string>> AsEnumerable(this IConfiguration configuration) { return configuration.AsEnumerable(makePathsRelative: false); } public static IEnumerable<KeyValuePair<string, string>> AsEnumerable(this IConfiguration configuration, bool makePathsRelative) { Stack<IConfiguration> stack = new Stack<IConfiguration>(); stack.Push(configuration); IConfigurationSection configurationSection = configuration as IConfigurationSection; int prefixLength = ((makePathsRelative && configurationSection != null) ? (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); } foreach (IConfigurationSection child in config.GetChildren()) { stack.Push(child); } } } public static bool Exists(this IConfigurationSection section) { if (section == null) { return false; } if (section.Value == null) { return section.GetChildren().Any(); } return true; } public static IConfigurationSection GetRequiredSection(this IConfiguration configuration, string key) { if (configuration == null) { throw new ArgumentNullException("configuration"); } IConfigurationSection section = configuration.GetSection(key); if (section.Exists()) { return section; } throw new InvalidOperationException(System.SR.Format(System.SR.InvalidSectionName, key)); } } [AttributeUsage(AttributeTargets.Property)] public sealed class ConfigurationKeyNameAttribute : Attribute { public string Name { get; } public ConfigurationKeyNameAttribute(string name) { Name = name; } } public static class ConfigurationPath { public static readonly string KeyDelimiter = ":"; public static string Combine(params string[] pathSegments) { if (pathSegments == null) { throw new ArgumentNullException("pathSegments"); } return string.Join(KeyDelimiter, pathSegments); } public static string Combine(IEnumerable<string> pathSegments) { if (pathSegments == null) { throw new ArgumentNullException("pathSegments"); } return string.Join(KeyDelimiter, pathSegments); } public static string GetSectionKey(string path) { if (string.IsNullOrEmpty(path)) { return path; } int num = path.LastIndexOf(KeyDelimiter, StringComparison.OrdinalIgnoreCase); 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.OrdinalIgnoreCase); if (num != -1) { return path.Substring(0, num); } return null; } } public static class ConfigurationRootExtensions { public static string GetDebugView(this IConfigurationRoot root) { StringBuilder stringBuilder2 = new StringBuilder(); RecurseChildren(stringBuilder2, root.GetChildren(), ""); return stringBuilder2.ToString(); void RecurseChildren(StringBuilder stringBuilder, IEnumerable<IConfigurationSection> children, string indent) { foreach (IConfigurationSection child in children) { (string, IConfigurationProvider) valueAndProvider = GetValueAndProvider(root, child.Path); if (valueAndProvider.Item2 != null) { stringBuilder.Append(indent).Append(child.Key).Append('=') .Append(valueAndProvider.Item1) .Append(" (") .Append(valueAndProvider.Item2) .AppendLine(")"); } else { stringBuilder.Append(indent).Append(child.Key).AppendLine(":"); } RecurseChildren(stringBuilder, child.GetChildren(), indent + " "); } } } private static (string Value, IConfigurationProvider Provider) GetValueAndProvider(IConfigurationRoot root, string key) { foreach (IConfigurationProvider item in root.Providers.Reverse()) { if (item.TryGet(key, out var value)) { return (value, item); } } return (null, null); } } public interface IConfiguration { string this[string key] { get; set; } IConfigurationSection GetSection(string key); IEnumerable<IConfigurationSection> GetChildren(); IChangeToken GetReloadToken(); } public interface IConfigurationBuilder { IDictionary<string, object> Properties { get; } 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(); IEnumerable<string> GetChildKeys(IEnumerable<string> earlierKeys, string parentPath); } public interface IConfigurationRoot : IConfiguration { 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); } }
MegabonkTogether/Microsoft.Extensions.Logging.Configuration.dll
Decompiled 2 hours 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.InteropServices; using System.Runtime.Versioning; using FxResources.Microsoft.Extensions.Logging.Configuration; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Configuration")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Configuration support for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Configuration")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace FxResources.Microsoft.Extensions.Logging.Configuration { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string Scope { get; set; } public string Target { get; set; } public string MessageId { get; set; } public string Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } } 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); foreach (IConfigurationSection child in _configuration.GetChildren()) { if (child.Key.Equals("LogLevel", StringComparison.OrdinalIgnoreCase)) { LoadRules(options, child, null); continue; } IConfigurationSection section = child.GetSection("LogLevel"); if (section != null) { string key = child.Key; LoadRules(options, section, key); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "IConfiguration.GetValue is safe when T is a bool.")] bool GetCaptureScopesValue(LoggerFilterOptions options) { return _configuration.GetValue("CaptureScopes", options.CaptureScopes); } } private void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger) { foreach (KeyValuePair<string, string> item2 in configurationSection.AsEnumerable(makePathsRelative: true)) { if (TryGetSwitch(item2.Value, out var level)) { string text = item2.Key; if (text.Equals("Default", StringComparison.OrdinalIgnoreCase)) { text = null; } LoggerFilterRule item = new LoggerFilterRule(logger, text, level, null); options.Rules.Add(item); } } } private static bool TryGetSwitch(string value, out LogLevel level) { if (string.IsNullOrEmpty(value)) { level = LogLevel.None; return false; } if (Enum.TryParse<LogLevel>(value, ignoreCase: true, out level)) { return true; } throw new InvalidOperationException(System.SR.Format(System.SR.ValueNotSupported, value)); } } public static class LoggingBuilderExtensions { public static ILoggingBuilder AddConfiguration(this ILoggingBuilder builder, IConfiguration configuration) { builder.AddConfiguration(); builder.Services.AddSingleton((IConfigureOptions<LoggerFilterOptions>)new LoggerFilterConfigureOptions(configuration)); builder.Services.AddSingleton((IOptionsChangeTokenSource<LoggerFilterOptions>)new ConfigurationChangeTokenSource<LoggerFilterOptions>(configuration)); builder.Services.AddSingleton(new LoggingConfiguration(configuration)); return builder; } } internal static class ProviderAliasUtilities { private const string AliasAttibuteTypeFullName = "Microsoft.Extensions.Logging.ProviderAliasAttribute"; internal static string GetAlias(Type providerType) { IList<CustomAttributeData> customAttributes = CustomAttributeData.GetCustomAttributes(providerType); for (int i = 0; i < customAttributes.Count; i++) { CustomAttributeData customAttributeData = customAttributes[i]; if (customAttributeData.AttributeType.FullName == "Microsoft.Extensions.Logging.ProviderAliasAttribute" && customAttributeData.ConstructorArguments.Count > 0) { return customAttributeData.ConstructorArguments[0].Value?.ToString(); } } return null; } } } namespace Microsoft.Extensions.Logging.Configuration { public interface ILoggerProviderConfiguration<T> { IConfiguration Configuration { get; } } public interface ILoggerProviderConfigurationFactory { IConfiguration GetConfiguration(Type providerType); } internal sealed class LoggerProviderConfiguration<T> : ILoggerProviderConfiguration<T> { public IConfiguration Configuration { get; } public LoggerProviderConfiguration(ILoggerProviderConfigurationFactory providerConfigurationFactory) { Configuration = providerConfigurationFactory.GetConfiguration(typeof(T)); } } public static class LoggerProviderOptions { internal const string TrimmingRequiresUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved."; [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static void RegisterProviderOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions, TProvider>(IServiceCollection services) where TOptions : class { services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<TOptions>, LoggerProviderConfigureOptions<TOptions, TProvider>>()); services.TryAddEnumerable(ServiceDescriptor.Singleton<IOptionsChangeTokenSource<TOptions>, LoggerProviderOptionsChangeTokenSource<TOptions, TProvider>>()); } } internal sealed class LoggerProviderConfigurationFactory : ILoggerProviderConfigurationFactory { private readonly IEnumerable<LoggingConfiguration> _configurations; public LoggerProviderConfigurationFactory(IEnumerable<LoggingConfiguration> configurations) { _configurations = configurations; } public IConfiguration GetConfiguration(Type providerType) { if (providerType == null) { throw new ArgumentNullException("providerType"); } string fullName = providerType.FullName; string alias = Microsoft.Extensions.Logging.ProviderAliasUtilities.GetAlias(providerType); ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); foreach (LoggingConfiguration configuration in _configurations) { IConfigurationSection section = configuration.Configuration.GetSection(fullName); configurationBuilder.AddConfiguration(section); if (!string.IsNullOrWhiteSpace(alias)) { IConfigurationSection section2 = configuration.Configuration.GetSection(alias); configurationBuilder.AddConfiguration(section2); } } return configurationBuilder.Build(); } } internal sealed class LoggerProviderConfigureOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions, TProvider> : ConfigureFromConfigurationOptions<TOptions> where TOptions : class { [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) { builder.Services.TryAddSingleton<ILoggerProviderConfigurationFactory, LoggerProviderConfigurationFactory>(); builder.Services.TryAddSingleton(typeof(ILoggerProviderConfiguration<>), typeof(LoggerProviderConfiguration<>)); } } internal sealed class LoggingConfiguration { public IConfiguration Configuration { get; } public LoggingConfiguration(IConfiguration configuration) { Configuration = configuration; } } }
MegabonkTogether/Microsoft.Extensions.Configuration.Json.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("JSON configuration provider implementation for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.Json")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.Json { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace 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) { if (builder == null) { throw new ArgumentNullException("builder"); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException(System.SR.Error_InvalidFilePath, "path"); } return builder.AddJsonFile(delegate(JsonConfigurationSource s) { s.FileProvider = provider; s.Path = path; s.Optional = optional; s.ReloadOnChange = reloadOnChange; s.ResolveFileProvider(); }); } public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, Action<JsonConfigurationSource> configureSource) { return builder.Add(configureSource); } public static IConfigurationBuilder AddJsonStream(this IConfigurationBuilder builder, Stream stream) { if (builder == null) { throw new ArgumentNullException("builder"); } return builder.Add(delegate(JsonStreamConfigurationSource s) { s.Stream = stream; }); } } } namespace Microsoft.Extensions.Configuration.Json { internal sealed class JsonConfigurationFileParser { private readonly Dictionary<string, string> _data = new Dictionary<string, string>(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) { JsonDocumentOptions jsonDocumentOptions = default(JsonDocumentOptions); jsonDocumentOptions.CommentHandling = JsonCommentHandling.Skip; jsonDocumentOptions.AllowTrailingCommas = true; JsonDocumentOptions options = jsonDocumentOptions; using (StreamReader streamReader = new StreamReader(input)) { using JsonDocument jsonDocument = JsonDocument.Parse(streamReader.ReadToEnd(), options); if (jsonDocument.RootElement.ValueKind != JsonValueKind.Object) { throw new FormatException(System.SR.Format(System.SR.Error_InvalidTopLevelJSONElement, jsonDocument.RootElement.ValueKind)); } VisitElement(jsonDocument.RootElement); } return _data; } private void VisitElement(JsonElement element) { bool flag = true; foreach (JsonProperty item in element.EnumerateObject()) { flag = false; EnterContext(item.Name); VisitValue(item.Value); ExitContext(); } if (flag && _paths.Count > 0) { _data[_paths.Peek()] = null; } } private void VisitValue(JsonElement value) { switch (value.ValueKind) { case JsonValueKind.Object: VisitElement(value); break; case JsonValueKind.Array: { int num = 0; { foreach (JsonElement item in value.EnumerateArray()) { EnterContext(num.ToString()); VisitValue(item); ExitContext(); num++; } break; } } case JsonValueKind.String: case JsonValueKind.Number: case JsonValueKind.True: case JsonValueKind.False: case JsonValueKind.Null: { string text = _paths.Peek(); if (_data.ContainsKey(text)) { throw new FormatException(System.SR.Format(System.SR.Error_KeyIsDuplicated, text)); } _data[text] = value.ToString(); break; } default: throw new FormatException(System.SR.Format(System.SR.Error_UnsupportedJSONToken, 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(source) { } public override void Load(Stream stream) { try { base.Data = JsonConfigurationFileParser.Parse(stream); } catch (JsonException innerException) { throw new FormatException(System.SR.Error_JSONParseError, innerException); } } } public class JsonConfigurationSource : FileConfigurationSource { public override IConfigurationProvider Build(IConfigurationBuilder builder) { EnsureDefaults(builder); return new JsonConfigurationProvider(this); } } public class JsonStreamConfigurationProvider : StreamConfigurationProvider { public JsonStreamConfigurationProvider(JsonStreamConfigurationSource source) : base(source) { } public override void Load(Stream stream) { base.Data = JsonConfigurationFileParser.Parse(stream); } } public class JsonStreamConfigurationSource : StreamConfigurationSource { public override IConfigurationProvider Build(IConfigurationBuilder builder) { return new JsonStreamConfigurationProvider(this); } } }
MegabonkTogether/Microsoft.Extensions.Configuration.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string Error_NoSources => GetResourceString("Error_NoSources"); internal static string InvalidNullArgument => GetResourceString("InvalidNullArgument"); internal static string StreamConfigurationProvidersAlreadyLoaded => GetResourceString("StreamConfigurationProvidersAlreadyLoaded"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace 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) { if (configurationBuilder == null) { throw new ArgumentNullException("configurationBuilder"); } if (config == null) { throw new ArgumentNullException("config"); } configurationBuilder.Add(new ChainedConfigurationSource { Configuration = config, ShouldDisposeConfiguration = shouldDisposeConfiguration }); return configurationBuilder; } } public class ChainedConfigurationProvider : IConfigurationProvider, IDisposable { private readonly IConfiguration _config; private readonly bool _shouldDisposeConfig; public ChainedConfigurationProvider(ChainedConfigurationSource source) { if (source == null) { throw new ArgumentNullException("source"); } if (source.Configuration == null) { throw new ArgumentException(System.SR.Format(System.SR.InvalidNullArgument, "source.Configuration"), "source"); } _config = source.Configuration; _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 IEnumerable<string> GetChildKeys(IEnumerable<string> earlierKeys, string parentPath) { IConfiguration configuration; if (parentPath != null) { IConfiguration section = _config.GetSection(parentPath); configuration = section; } else { configuration = _config; } IConfiguration configuration2 = configuration; List<string> list = new List<string>(); foreach (IConfigurationSection child in configuration2.GetChildren()) { list.Add(child.Key); } list.AddRange(earlierKeys); list.Sort(ConfigurationKeyComparer.Comparison); return list; } public void Dispose() { if (_shouldDisposeConfig) { (_config as IDisposable)?.Dispose(); } } } public class ChainedConfigurationSource : IConfigurationSource { public IConfiguration Configuration { get; set; } public bool ShouldDisposeConfiguration { get; set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return new ChainedConfigurationProvider(this); } } public class ConfigurationBuilder : IConfigurationBuilder { public IList<IConfigurationSource> Sources { get; } = new List<IConfigurationSource>(); public IDictionary<string, object> Properties { get; } = new Dictionary<string, object>(); public IConfigurationBuilder Add(IConfigurationSource source) { if (source == null) { throw new ArgumentNullException("source"); } Sources.Add(source); return this; } public IConfigurationRoot Build() { List<IConfigurationProvider> list = new List<IConfigurationProvider>(); foreach (IConfigurationSource source in Sources) { IConfigurationProvider item = source.Build(this); list.Add(item); } return new ConfigurationRoot(list); } } public class ConfigurationKeyComparer : IComparer<string> { private static readonly string[] _keyDelimiterArray = new string[1] { ConfigurationPath.KeyDelimiter }; public static ConfigurationKeyComparer Instance { get; } = new ConfigurationKeyComparer(); internal static Comparison<string> Comparison { get; } = Instance.Compare; public int Compare(string x, string y) { string[] array = x?.Split(_keyDelimiterArray, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>(); string[] array2 = y?.Split(_keyDelimiterArray, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>(); for (int i = 0; i < Math.Min(array.Length, array2.Length); i++) { x = array[i]; y = array2[i]; int result = 0; int result2 = 0; bool flag = x != null && int.TryParse(x, out result); bool flag2 = y != null && int.TryParse(y, out result2); int num = ((!flag && !flag2) ? string.Compare(x, y, StringComparison.OrdinalIgnoreCase) : ((!(flag && flag2)) ? ((!flag) ? 1 : (-1)) : (result - result2))); if (num != 0) { return num; } } return array.Length - array2.Length; } } public sealed class ConfigurationManager : IConfigurationBuilder, IConfigurationRoot, IConfiguration, IDisposable { private class ConfigurationSources : IList<IConfigurationSource>, ICollection<IConfigurationSource>, IEnumerable<IConfigurationSource>, 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 IEnumerator<IConfigurationSource> GetEnumerator() { return _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(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private class ConfigurationBuilderProperties : IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, 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 ICollection<string> Keys => _properties.Keys; public ICollection<object> Values => _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) { ((ICollection<KeyValuePair<string, object>>)_properties).Add(item); _config.ReloadSources(); } public void Clear() { _properties.Clear(); _config.ReloadSources(); } public bool Contains(KeyValuePair<string, object> item) { return _properties.Contains(item); } public bool ContainsKey(string key) { return _properties.ContainsKey(key); } public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { ((ICollection<KeyValuePair<string, object>>)_properties).CopyTo(array, arrayIndex); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return _properties.GetEnumerator(); } public bool Remove(string key) { bool result = _properties.Remove(key); _config.ReloadSources(); return result; } public bool Remove(KeyValuePair<string, object> item) { bool result = ((ICollection<KeyValuePair<string, object>>)_properties).Remove(item); _config.ReloadSources(); return result; } public bool TryGetValue(string key, out object value) { return _properties.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return _properties.GetEnumerator(); } } private readonly ConfigurationSources _sources; private readonly ConfigurationBuilderProperties _properties; private readonly object _providerLock = new object(); private readonly List<IConfigurationProvider> _providers = new List<IConfigurationProvider>(); private readonly List<IDisposable> _changeTokenRegistrations = new List<IDisposable>(); private ConfigurationReloadToken _changeToken = new ConfigurationReloadToken(); public string this[string key] { get { lock (_providerLock) { return ConfigurationRoot.GetConfiguration(_providers, key); } } set { lock (_providerLock) { ConfigurationRoot.SetConfiguration(_providers, key, value); } } } IDictionary<string, object> IConfigurationBuilder.Properties => _properties; IList<IConfigurationSource> IConfigurationBuilder.Sources => _sources; IEnumerable<IConfigurationProvider> IConfigurationRoot.Providers { get { lock (_providerLock) { return new List<IConfigurationProvider>(_providers); } } } public ConfigurationManager() { _sources = new ConfigurationSources(this); _properties = new ConfigurationBuilderProperties(this); this.AddInMemoryCollection(); AddSource(_sources[0]); } public IConfigurationSection GetSection(string key) { return new ConfigurationSection(this, key); } public IEnumerable<IConfigurationSection> GetChildren() { lock (_providerLock) { return this.GetChildrenImplementation(null).ToList(); } } public void Dispose() { lock (_providerLock) { DisposeRegistrationsAndProvidersUnsynchronized(); } } IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source) { _sources.Add(source ?? throw new ArgumentNullException("source")); return this; } IConfigurationRoot IConfigurationBuilder.Build() { return this; } IChangeToken IConfiguration.GetReloadToken() { return _changeToken; } void IConfigurationRoot.Reload() { lock (_providerLock) { foreach (IConfigurationProvider provider in _providers) { provider.Load(); } } RaiseChanged(); } private void RaiseChanged() { ConfigurationReloadToken configurationReloadToken = Interlocked.Exchange(ref _changeToken, new ConfigurationReloadToken()); configurationReloadToken.OnReload(); } private void AddSource(IConfigurationSource source) { lock (_providerLock) { IConfigurationProvider provider = source.Build(this); _providers.Add(provider); provider.Load(); _changeTokenRegistrations.Add(ChangeToken.OnChange(() => provider.GetReloadToken(), delegate { RaiseChanged(); })); } RaiseChanged(); } private void ReloadSources() { lock (_providerLock) { DisposeRegistrationsAndProvidersUnsynchronized(); _changeTokenRegistrations.Clear(); _providers.Clear(); foreach (IConfigurationSource source in _sources) { _providers.Add(source.Build(this)); } foreach (IConfigurationProvider p in _providers) { p.Load(); _changeTokenRegistrations.Add(ChangeToken.OnChange(() => p.GetReloadToken(), delegate { RaiseChanged(); })); } } RaiseChanged(); } private void DisposeRegistrationsAndProvidersUnsynchronized() { foreach (IDisposable changeTokenRegistration in _changeTokenRegistrations) { changeTokenRegistration.Dispose(); } foreach (IConfigurationProvider provider in _providers) { (provider as IDisposable)?.Dispose(); } } } public abstract class ConfigurationProvider : IConfigurationProvider { private ConfigurationReloadToken _reloadToken = new ConfigurationReloadToken(); protected IDictionary<string, string> Data { get; set; } protected ConfigurationProvider() { Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } public virtual bool TryGet(string key, out string value) { return Data.TryGetValue(key, out value); } public virtual void Set(string key, string value) { Data[key] = value; } public virtual void Load() { } public virtual IEnumerable<string> GetChildKeys(IEnumerable<string> earlierKeys, string parentPath) { List<string> list = new List<string>(); if (parentPath == null) { foreach (KeyValuePair<string, string> datum in Data) { list.Add(Segment(datum.Key, 0)); } } else { foreach (KeyValuePair<string, string> datum2 in Data) { if (datum2.Key.Length > parentPath.Length && datum2.Key.StartsWith(parentPath, StringComparison.OrdinalIgnoreCase) && datum2.Key[parentPath.Length] == ':') { list.Add(Segment(datum2.Key, parentPath.Length + 1)); } } } list.AddRange(earlierKeys); list.Sort(ConfigurationKeyComparer.Comparison); return list; } private static string Segment(string key, int prefixLength) { int num = key.IndexOf(ConfigurationPath.KeyDelimiter, prefixLength, StringComparison.OrdinalIgnoreCase); if (num >= 0) { return key.Substring(prefixLength, num - prefixLength); } return key.Substring(prefixLength); } public IChangeToken GetReloadToken() { return _reloadToken; } protected void OnReload() { ConfigurationReloadToken configurationReloadToken = Interlocked.Exchange(ref _reloadToken, new ConfigurationReloadToken()); configurationReloadToken.OnReload(); } public override string ToString() { return GetType().Name ?? ""; } } public class ConfigurationReloadToken : IChangeToken { private CancellationTokenSource _cts = new CancellationTokenSource(); public bool ActiveChangeCallbacks => true; public bool HasChanged => _cts.IsCancellationRequested; public IDisposable RegisterChangeCallback(Action<object> callback, object state) { return _cts.Token.Register(callback, state); } public void OnReload() { _cts.Cancel(); } } public class ConfigurationRoot : IConfigurationRoot, IConfiguration, IDisposable { private readonly IList<IConfigurationProvider> _providers; private readonly IList<IDisposable> _changeTokenRegistrations; private ConfigurationReloadToken _changeToken = new ConfigurationReloadToken(); public IEnumerable<IConfigurationProvider> Providers => _providers; public string this[string key] { get { return GetConfiguration(_providers, key); } set { SetConfiguration(_providers, key, value); } } public ConfigurationRoot(IList<IConfigurationProvider> providers) { if (providers == null) { throw new ArgumentNullException("providers"); } _providers = providers; _changeTokenRegistrations = new List<IDisposable>(providers.Count); foreach (IConfigurationProvider p in providers) { p.Load(); _changeTokenRegistrations.Add(ChangeToken.OnChange(() => p.GetReloadToken(), delegate { RaiseChanged(); })); } } public IEnumerable<IConfigurationSection> GetChildren() { return this.GetChildrenImplementation(null); } public IChangeToken GetReloadToken() { return _changeToken; } public IConfigurationSection GetSection(string key) { return new ConfigurationSection(this, key); } public void Reload() { foreach (IConfigurationProvider provider in _providers) { provider.Load(); } RaiseChanged(); } private void RaiseChanged() { ConfigurationReloadToken configurationReloadToken = Interlocked.Exchange(ref _changeToken, new ConfigurationReloadToken()); configurationReloadToken.OnReload(); } public void Dispose() { foreach (IDisposable changeTokenRegistration in _changeTokenRegistrations) { changeTokenRegistration.Dispose(); } foreach (IConfigurationProvider provider in _providers) { (provider as IDisposable)?.Dispose(); } } internal static string GetConfiguration(IList<IConfigurationProvider> providers, string key) { for (int num = providers.Count - 1; num >= 0; num--) { IConfigurationProvider configurationProvider = providers[num]; if (configurationProvider.TryGet(key, out var value)) { return value; } } return null; } internal static void SetConfiguration(IList<IConfigurationProvider> providers, string key, string value) { if (providers.Count == 0) { throw new InvalidOperationException(System.SR.Error_NoSources); } foreach (IConfigurationProvider provider in providers) { provider.Set(key, value); } } } public class ConfigurationSection : IConfigurationSection, IConfiguration { private readonly IConfigurationRoot _root; private readonly string _path; private string _key; public string Path => _path; public string Key { get { if (_key == null) { _key = ConfigurationPath.GetSectionKey(_path); } return _key; } } public string Value { get { return _root[Path]; } set { _root[Path] = value; } } public string this[string key] { get { return _root[ConfigurationPath.Combine(Path, key)]; } set { _root[ConfigurationPath.Combine(Path, key)] = value; } } public ConfigurationSection(IConfigurationRoot root, string path) { if (root == null) { throw new ArgumentNullException("root"); } if (path == null) { throw new ArgumentNullException("path"); } _root = root; _path = path; } public IConfigurationSection GetSection(string key) { return _root.GetSection(ConfigurationPath.Combine(Path, key)); } public IEnumerable<IConfigurationSection> GetChildren() { return _root.GetChildrenImplementation(Path); } public IChangeToken GetReloadToken() { return _root.GetReloadToken(); } } internal static class InternalConfigurationRootExtensions { internal static IEnumerable<IConfigurationSection> GetChildrenImplementation(this IConfigurationRoot root, string path) { return from key in root.Providers.Aggregate(Enumerable.Empty<string>(), (IEnumerable<string> seed, IConfigurationProvider source) => source.GetChildKeys(seed, path)).Distinct<string>(StringComparer.OrdinalIgnoreCase) select root.GetSection((path == null) ? key : ConfigurationPath.Combine(path, key)); } } public static class MemoryConfigurationBuilderExtensions { public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder) { if (configurationBuilder == null) { throw new ArgumentNullException("configurationBuilder"); } configurationBuilder.Add(new MemoryConfigurationSource()); return configurationBuilder; } public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder, IEnumerable<KeyValuePair<string, string>> initialData) { if (configurationBuilder == null) { throw new ArgumentNullException("configurationBuilder"); } configurationBuilder.Add(new MemoryConfigurationSource { InitialData = initialData }); return configurationBuilder; } } public abstract class StreamConfigurationProvider : ConfigurationProvider { private bool _loaded; public StreamConfigurationSource Source { get; } public StreamConfigurationProvider(StreamConfigurationSource source) { Source = source ?? throw new ArgumentNullException("source"); } public abstract void Load(Stream stream); public override void Load() { if (_loaded) { throw new InvalidOperationException(System.SR.StreamConfigurationProvidersAlreadyLoaded); } Load(Source.Stream); _loaded = true; } } public abstract class StreamConfigurationSource : IConfigurationSource { public Stream Stream { get; set; } public abstract IConfigurationProvider Build(IConfigurationBuilder builder); } } namespace Microsoft.Extensions.Configuration.Memory { public class MemoryConfigurationProvider : ConfigurationProvider, IEnumerable<KeyValuePair<string, string>>, IEnumerable { private readonly MemoryConfigurationSource _source; public MemoryConfigurationProvider(MemoryConfigurationSource source) { if (source == null) { throw new ArgumentNullException("source"); } _source = source; if (_source.InitialData == null) { return; } foreach (KeyValuePair<string, string> initialDatum in _source.InitialData) { base.Data.Add(initialDatum.Key, initialDatum.Value); } } public void Add(string key, string value) { base.Data.Add(key, value); } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return base.Data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class MemoryConfigurationSource : IConfigurationSource { public IEnumerable<KeyValuePair<string, string>> InitialData { get; set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return new MemoryConfigurationProvider(this); } } }
MegabonkTogether/TextCopy.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("TextCopy")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2022. All rights reserved")] [assembly: AssemblyDescription("A cross platform package to copy text to the clipboard.")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("6.2.1+409eda72dd615c1ff2cd7327d5a294553eaa9b81")] [assembly: AssemblyProduct("TextCopy")] [assembly: AssemblyTitle("TextCopy")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/CopyText/TextCopy.git")] [assembly: AssemblyVersion("1.0.0.0")] 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; } } } internal static class BashRunner { public static string Run(string commandLine) { StringBuilder errorBuilder = new StringBuilder(); StringBuilder outputBuilder = new StringBuilder(); string text = "-c \"" + commandLine + "\""; using Process process = new Process { StartInfo = new ProcessStartInfo { FileName = "bash", Arguments = text, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = false } }; process.Start(); process.OutputDataReceived += delegate(object _, DataReceivedEventArgs args) { outputBuilder.AppendLine(args.Data); }; process.BeginOutputReadLine(); process.ErrorDataReceived += delegate(object _, DataReceivedEventArgs args) { errorBuilder.AppendLine(args.Data); }; process.BeginErrorReadLine(); if (!process.DoubleWaitForExit()) { string message = $"Process timed out. Command line: bash {text}.\nOutput: {outputBuilder}\nError: {errorBuilder}"; throw new Exception(message); } if (process.ExitCode == 0) { return outputBuilder.ToString(); } string message2 = $"Could not execute process. Command line: bash {text}.\nOutput: {outputBuilder}\nError: {errorBuilder}"; throw new Exception(message2); } private static bool DoubleWaitForExit(this Process process) { bool flag = process.WaitForExit(500); if (flag) { process.WaitForExit(); } return flag; } } internal static class LinuxClipboard { private static bool isWsl; static LinuxClipboard() { isWsl = Environment.GetEnvironmentVariable("WSL_DISTRO_NAME") != null; } public static async Task SetTextAsync(string text, CancellationToken cancellation) { string tempFileName = Path.GetTempFileName(); await File.WriteAllTextAsync(tempFileName, text, cancellation); if (!cancellation.IsCancellationRequested) { InnerSetText(tempFileName); } } public static void SetText(string text) { string tempFileName = Path.GetTempFileName(); File.WriteAllText(tempFileName, text); InnerSetText(tempFileName); } private static void InnerSetText(string tempFileName) { try { if (isWsl) { BashRunner.Run("cat " + tempFileName + " | clip.exe "); } else { BashRunner.Run("cat " + tempFileName + " | xsel -i --clipboard "); } } finally { File.Delete(tempFileName); } } public static string? GetText() { string tempFileName = Path.GetTempFileName(); try { InnerGetText(tempFileName); return File.ReadAllText(tempFileName); } finally { File.Delete(tempFileName); } } public static async Task<string?> GetTextAsync(CancellationToken cancellation) { string tempFileName = Path.GetTempFileName(); try { InnerGetText(tempFileName); return await File.ReadAllTextAsync(tempFileName, cancellation); } finally { File.Delete(tempFileName); } } private static void InnerGetText(string tempFileName) { if (isWsl) { BashRunner.Run("powershell.exe -NoProfile Get-Clipboard > " + tempFileName); } else { BashRunner.Run("xsel -o --clipboard > " + tempFileName); } } } internal static class OsxClipboard { private static IntPtr nsString; private static IntPtr nsPasteboard; private static IntPtr nsStringPboardType; private static IntPtr utfTextType; private static IntPtr generalPasteboard; private static IntPtr initWithUtf8Register; private static IntPtr allocRegister; private static IntPtr setStringRegister; private static IntPtr stringForTypeRegister; private static IntPtr utf8Register; private static IntPtr generalPasteboardRegister; private static IntPtr clearContentsRegister; static OsxClipboard() { nsString = objc_getClass("NSString"); nsPasteboard = objc_getClass("NSPasteboard"); initWithUtf8Register = sel_registerName("initWithUTF8String:"); allocRegister = sel_registerName("alloc"); setStringRegister = sel_registerName("setString:forType:"); stringForTypeRegister = sel_registerName("stringForType:"); utf8Register = sel_registerName("UTF8String"); generalPasteboardRegister = sel_registerName("generalPasteboard"); clearContentsRegister = sel_registerName("clearContents"); utfTextType = objc_msgSend(objc_msgSend(nsString, allocRegister), initWithUtf8Register, "public.utf8-plain-text"); nsStringPboardType = objc_msgSend(objc_msgSend(nsString, allocRegister), initWithUtf8Register, "NSStringPboardType"); generalPasteboard = objc_msgSend(nsPasteboard, generalPasteboardRegister); } public static string? GetText() { IntPtr receiver = objc_msgSend(generalPasteboard, stringForTypeRegister, nsStringPboardType); IntPtr ptr = objc_msgSend(receiver, utf8Register); return Marshal.PtrToStringAnsi(ptr); } public static Task<string?> GetTextAsync(CancellationToken cancellation) { return Task.FromResult(GetText()); } public static void SetText(string text) { IntPtr intPtr = default(IntPtr); try { intPtr = objc_msgSend(objc_msgSend(nsString, allocRegister), initWithUtf8Register, text); objc_msgSend(generalPasteboard, clearContentsRegister); objc_msgSend(generalPasteboard, setStringRegister, intPtr, utfTextType); } finally { if (intPtr != (IntPtr)0) { objc_msgSend(intPtr, sel_registerName("release")); } } } public static Task SetTextAsync(string text, CancellationToken cancellation) { SetText(text); return Task.CompletedTask; } [DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")] private static extern IntPtr objc_getClass(string className); [DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")] private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector); [DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")] private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, string arg1); [DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")] private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, IntPtr arg1); [DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")] private static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2); [DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")] private static extern IntPtr sel_registerName(string selectorName); } internal static class WindowsClipboard { private const uint cfUnicodeText = 13u; public static async Task SetTextAsync(string text, CancellationToken cancellation) { await TryOpenClipboardAsync(cancellation); InnerSet(text); } public static void SetText(string text) { TryOpenClipboard(); InnerSet(text); } private static void InnerSet(string text) { EmptyClipboard(); IntPtr intPtr = default(IntPtr); try { int cb = (text.Length + 1) * 2; intPtr = Marshal.AllocHGlobal(cb); if (intPtr == (IntPtr)0) { ThrowWin32(); } IntPtr intPtr2 = GlobalLock(intPtr); if (intPtr2 == (IntPtr)0) { ThrowWin32(); } try { Marshal.Copy(text.ToCharArray(), 0, intPtr2, text.Length); } finally { GlobalUnlock(intPtr2); } if (SetClipboardData(13u, intPtr) == (IntPtr)0) { ThrowWin32(); } intPtr = default(IntPtr); } finally { if (intPtr != (IntPtr)0) { Marshal.FreeHGlobal(intPtr); } CloseClipboard(); } } private static async Task TryOpenClipboardAsync(CancellationToken cancellation) { int num = 10; while (!OpenClipboard((IntPtr)0)) { int num2 = num - 1; num = num2; if (num2 == 0) { ThrowWin32(); } await Task.Delay(100, cancellation); } } private static void TryOpenClipboard() { int num = 10; while (!OpenClipboard((IntPtr)0)) { if (--num == 0) { ThrowWin32(); } Thread.Sleep(100); } } public static async Task<string?> GetTextAsync(CancellationToken cancellation) { if (!IsClipboardFormatAvailable(13u)) { return null; } await TryOpenClipboardAsync(cancellation); return InnerGet(); } public static string? GetText() { if (!IsClipboardFormatAvailable(13u)) { return null; } TryOpenClipboard(); return InnerGet(); } private static string? InnerGet() { IntPtr intPtr = default(IntPtr); IntPtr intPtr2 = default(IntPtr); try { intPtr = GetClipboardData(13u); if (intPtr == (IntPtr)0) { return null; } intPtr2 = GlobalLock(intPtr); if (intPtr2 == (IntPtr)0) { return null; } int num = GlobalSize(intPtr); byte[] array = new byte[num]; Marshal.Copy(intPtr2, array, 0, num); return Encoding.Unicode.GetString(array).TrimEnd('\0'); } finally { if (intPtr2 != (IntPtr)0) { GlobalUnlock(intPtr); } CloseClipboard(); } } private static void ThrowWin32() { throw new Win32Exception(Marshal.GetLastWin32Error()); } [DllImport("User32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsClipboardFormatAvailable(uint format); [DllImport("User32.dll", SetLastError = true)] private static extern IntPtr GetClipboardData(uint uFormat); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GlobalLock(IntPtr hMem); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GlobalUnlock(IntPtr hMem); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseClipboard(); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr SetClipboardData(uint uFormat, IntPtr data); [DllImport("user32.dll")] private static extern bool EmptyClipboard(); [DllImport("Kernel32.dll", SetLastError = true)] private static extern int GlobalSize(IntPtr hMem); } namespace TextCopy { public class BlazorClipboard : IClipboard { private static Type[] types = new Type[2] { typeof(string), typeof(object[]) }; private object jsRuntime; private MethodInfo invokeAsync; public BlazorClipboard(object jsRuntime) { this.jsRuntime = jsRuntime; Type type = jsRuntime.GetType(); MethodInfo method = type.GetMethod("InvokeAsync", types); if (method == null) { IEnumerable<string> values = from x in type.GetMethods() select x.ToString(); throw new Exception($"Unable to find InvokeAsync on {type.FullName}. Methods:{Environment.NewLine}{string.Join(Environment.NewLine, values)}"); } invokeAsync = method.MakeGenericMethod(typeof(string)); } public virtual async Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken)) { object[] parameters = new object[2] { "navigator.clipboard.readText", Array.Empty<object>() }; return await (ValueTask<string>)invokeAsync.Invoke(jsRuntime, parameters); } public virtual string? GetText() { return GetTextAsync().GetAwaiter().GetResult(); } public virtual async Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken)) { object[] parameters = new object[2] { "navigator.clipboard.writeText", new object[1] { text } }; await (ValueTask<string>)invokeAsync.Invoke(jsRuntime, parameters); } public virtual void SetText(string text) { SetTextAsync(text).GetAwaiter().GetResult(); } } public class Clipboard : IClipboard { public virtual Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken)) { return ClipboardService.GetTextAsync(cancellation); } public virtual string? GetText() { return ClipboardService.GetText(); } public virtual Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken)) { return ClipboardService.SetTextAsync(text, cancellation); } public virtual void SetText(string text) { ClipboardService.SetText(text); } } public static class ClipboardService { private static Func<CancellationToken, Task<string?>> getAsyncFunc; private static Func<string?> getFunc; private static Func<string, CancellationToken, Task> setAsyncAction; private static Action<string> setAction; public static Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken)) { return getAsyncFunc(cancellation); } public static string? GetText() { return getFunc(); } static ClipboardService() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("Browser"))) { throw new Exception("The static class ClipboardService is not supported on Blazor. Instead inject an IClipboard using ServiceExtensionsInjectClipboard."); } getAsyncFunc = CreateAsyncGet(); getFunc = CreateGet(); setAsyncAction = CreateAsyncSet(); setAction = CreateSet(); } public static Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken)) { return setAsyncAction(text, cancellation); } public static void SetText(string text) { setAction(text); } private static Func<CancellationToken, Task<string?>> CreateAsyncGet() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return WindowsClipboard.GetTextAsync; } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return OsxClipboard.GetTextAsync; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return LinuxClipboard.GetTextAsync; } throw new NotSupportedException(); } private static Func<string?> CreateGet() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return WindowsClipboard.GetText; } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return OsxClipboard.GetText; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return LinuxClipboard.GetText; } throw new NotSupportedException(); } private static Func<string, CancellationToken, Task> CreateAsyncSet() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return WindowsClipboard.SetTextAsync; } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return OsxClipboard.SetTextAsync; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return LinuxClipboard.SetTextAsync; } return delegate { throw new NotSupportedException(); }; } private static Action<string> CreateSet() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return WindowsClipboard.SetText; } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return OsxClipboard.SetText; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return LinuxClipboard.SetText; } return delegate { throw new NotSupportedException(); }; } } public interface IClipboard { Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken)); string? GetText(); Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken)); void SetText(string text); } public class MockClipboard : IClipboard { public virtual Task<string?> GetTextAsync(CancellationToken cancellation = default(CancellationToken)) { return Task.FromResult<string>(null); } public virtual string? GetText() { return null; } public virtual Task SetTextAsync(string text, CancellationToken cancellation = default(CancellationToken)) { return Task.CompletedTask; } public void SetText(string text) { } } public static class ServiceExtensions { public static void InjectMockClipboard(this IServiceCollection services) { services.AddSingleton((Func<IServiceProvider, IClipboard>)((IServiceProvider _) => new MockClipboard())); } public static void InjectClipboard(this IServiceCollection services) { services.AddSingleton((Func<IServiceProvider, IClipboard>)delegate(IServiceProvider provider) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("Browser"))) { Type type = Type.GetType("Microsoft.JSInterop.IJSRuntime, Microsoft.JSInterop", throwOnError: false); if (type == null) { throw new Exception("Running in Blazor but could not resolve JSInterop type."); } object service = provider.GetService(type); if (service == null) { throw new Exception("Running in Blazor but could not get the JSInterop instance from the IServiceProvider."); } return new BlazorClipboard(service); } return new Clipboard(); }); } } } internal class TextCopy_ProcessedByFody { internal const string FodyVersion = "6.6.4.0"; internal const string Weavers = "1.0.0"; }
MegabonkTogether/ProfanityFilter.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using ProfanityFilter.Interfaces; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("Stephen Haunts")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Profanity Filter used to detect or censor text in an application. You can use the inbuilt profanity list, or load up your organizations custom list.")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("ProfanityFilter")] [assembly: AssemblyTitle("ProfanityFilter")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("1.0.0.0")] namespace ProfanityFilter { public class AllowList : IAllowList { private List<string> _allowList; public ReadOnlyCollection<string> ToList => new ReadOnlyCollection<string>(_allowList); public int Count => _allowList.Count; public AllowList() { _allowList = new List<string>(); } public void Add(string wordToAllowlist) { if (string.IsNullOrEmpty(wordToAllowlist)) { throw new ArgumentNullException("wordToAllowlist"); } if (!_allowList.Contains(wordToAllowlist.ToLower(CultureInfo.InvariantCulture))) { _allowList.Add(wordToAllowlist.ToLower(CultureInfo.InvariantCulture)); } } public bool Contains(string wordToCheck) { if (string.IsNullOrEmpty(wordToCheck)) { throw new ArgumentNullException("wordToCheck"); } return _allowList.Contains(wordToCheck.ToLower(CultureInfo.InvariantCulture)); } public void Clear() { _allowList.Clear(); } public bool Remove(string wordToRemove) { if (string.IsNullOrEmpty(wordToRemove)) { throw new ArgumentNullException("wordToRemove"); } return _allowList.Remove(wordToRemove.ToLower(CultureInfo.InvariantCulture)); } } public class ProfanityBase { protected List<string> _profanities; private readonly string[] _wordList = new string[1626] { "8===D", "8==D", "8=D", "2 girls 1 cup", "two girls one cup", "two girls 1 cup", "2 girls one cup", "2g1c", "4r5e", "5h1t", "5hit", "a$$", "a$$hole", "a_s_s", "a2m", "a55", "a55hole", "acrotomophilia", "aeolus", "ahole", "alabama hot pocket", "alaskan pipeline", "anal", "anal impaler", "anal leakage", "analprobe", "anilingus", "angrydragon", "angry dragon", "anus", "apeshit", "ar5e", "arian", "arrse", "arse", "arses", "arsehole", "aryan", "ass", "ass fuck", "ass hole", "assbag", "assbandit", "assbang", "assbanged", "assbanger", "assbangs", "assbite", "assclown", "asscock", "asscracker", "asses", "assface", "assfaces", "assfuck", "assfucker", "ass-fucker", "assfukka", "assgoblin", "assh0le", "asshat", "ass-hat", "asshead", "assho1e", "asshole", "assholes", "asshopper", "ass-jabber", "assjacker", "asslick", "asslicker", "assmaster", "assmonkey", "assmucus", "assmunch", "assmuncher", "assnigger", "asspirate", "ass-pirate", "assshit", "assshole", "asssucker", "asswad", "asswhole", "asswipe", "asswipes", "auto erotic", "autoerotic", "axwound", "axewound", "axe wound", "azazel", "azz", "b!tch", "b00bs", "b17ch", "b1tch", "babeland", "baby batter", "baby juice", "ball gag", "ball gravy", "ball kicking", "ball licking", "ball sack", "ball sucking", "ballbag", "balls", "ballsack", "bampot", "bang (one's) box", "bangbros", "bareback", "barely legal", "barenaked", "barf", "bastard", "bastardo", "bastards", "bastinado", "batty boy", "bawdy", "bbw", "bdsm", "beaner", "beaners", "beardedclam", "beastial", "beastiality", "beatch", "beaver", "beaver cleaver", "beaver lips", "beef curtain", "beef curtains", "beeyotch", "bellend", "bender", "beotch", "bescumber", "bestial", "bestiality", "bi+ch", "biatch", "big black", "big breasts", "big knockers", "big tits", "bigtits", "bimbo", "bimbos", "bint", "birdlock", "bitch", "bitch tit", "bitchass", "bitched", "bitcher", "bitchers", "bitches", "bitchin", "bitching", "bitchtits", "bitchy", "black cock", "blonde action", "blonde on blonde action", "bloodclaat", "bloody", "bloody hell", "blow job", "blow me", "blow mud", "blow your load", "blowjob", "blowjobs", "blue waffle", "blumpkin", "bod", "bodily", "boink", "boiolas", "bollock", "bollocks", "bollok", "bollox", "bondage", "boned", "boner", "boners", "bong", "boob", "boobies", "boobs", "booby", "booger", "bookie", "boong", "booobs", "boooobs", "booooobs", "booooooobs", "bootee", "bootie", "booty", "booty call", "booze", "boozer", "boozy", "bosom", "bosomy", "breasts", "breeder", "brotherfucker", "brown showers", "brunette action", "buceta", "bugger", "bukkake", "bull shit", "bulldyke", "bullet vibe", "bullshit", "bullshits", "bullshitted", "bullturds", "bum", "bum boy", "bumblefuck", "bumclat", "bummer", "buncombe", "bung", "bung hole", "bunghole", "bunny fucker", "bust a load", "busty", "butt", "butt fuck", "butt plug", "buttcheeks", "buttfuck", "buttfucka", "buttfucker", "butthole", "buttmuch", "buttmunch", "butt-pirate", "buttplug", "c.0.c.k", "c.o.c.k.", "c.u.n.t", "c0ck", "c-0-c-k", "c0cksucker", "caca", "cacafuego", "cahone", "camel toe", "cameltoe", "camgirl", "camslut", "camwhore", "carpet muncher", "carpetmuncher", "cawk", "cervix", "chesticle", "chi-chi man", "chick with a dick", "child-fucker", "chinc", "chincs", "chink", "chinky", "choad", "choade", "choc ice", "chocolate rosebuds", "chode", "chodes", "chota bags", "cipa", "circlejerk", "cl1t", "cleveland steamer", "climax", "clit", "clit licker", "clitface", "clitfuck", "clitoris", "clits", "clitty", "clitty litter", "clover clamps", "clunge", "clusterfuck", "cnut", "cocain", "cocaine", "coccydynia", "cock", "c-o-c-k", "cock pocket", "cock snot", "cock sucker", "cockass", "cockbite", "cockblock", "cockburger", "cockeye", "cockface", "cockfucker", "cockhead", "cockholster", "cockjockey", "cockknocker", "cockknoker", "cocklump", "cockmaster", "cockmongler", "cockmongruel", "cockmonkey", "cockmunch", "cockmuncher", "cocknose", "cocknugget", "cocks", "cockshit", "cocksmith", "cocksmoke", "cocksmoker", "cocksniffer", "cocksuck", "cocksucked", "cocksucker", "cock-sucker", "cocksuckers", "cocksucking", "cocksucks", "cocksuka", "cocksukka", "cockwaffle", "coffin dodger", "coital", "cok", "cokmuncher", "coksucka", "commie", "condom", "coochie", "coochy", "coon", "coonnass", "coons", "cooter", "cop some wood", "coprolagnia", "coprophilia", "corksucker", "cornhole", "corp whore", "corp whore", "corpulent", "cox", "crabs", "crack", "cracker", "crackwhore", "crap", "crappy", "creampie", "cretin", "crikey", "cripple", "crotte", "cum", "cum chugger", "cum dumpster", "cum freak", "cum guzzler", "cumbubble", "cumdump", "cumdumpster", "cumguzzler", "cumjockey", "cummer", "cummin", "cumming", "cums", "cumshot", "cumshots", "cumslut", "cumstain", "cumtart", "cunilingus", "cunillingus", "cunnie", "cunnilingus", "cunny", "cunt", "c-u-n-t", "cunt hair", "cuntass", "cuntbag", "cuntface", "cunthole", "cunthunter", "cuntlick", "cuntlicker", "cuntrag", "cunts", "cuntsicle", "cuntslut", "cunt-struck", "cus", "cut rope", "cyalis", "cyberfuc", "cyberfuck", "cyberfucked", "cyberfucker", "cyberfucking", "d0ng", "d0uch3", "d0uche", "d1ck", "d1ld0", "d1ldo", "dago", "dagos", "dammit", "damn", "damned", "damnit", "darkie", "darn", "date rape", "daterape", "dawgie-style", "deep throat", "deepthroat", "deggo", "dendrophilia", "dick", "dick head", "dick hole", "dick shy", "dickbag", "dickbeaters", "dickdipper", "dickface", "dickflipper", "dickfuck", "dickfucker", "dickhead", "dickheads", "dickhole", "dickish", "dick-ish", "dickjuice", "dickmilk", "dickmonger", "dickripper", "dicks", "dicksipper", "dickslap", "dick-sneeze", "dicksucker", "dicksucking", "dicktickler", "dickwad", "dickweasel", "dickweed", "dickwhipper", "dickwod", "dickzipper", "diddle", "dike", "dildo", "dildos", "diligaf", "dillweed", "dimwit", "dingle", "dingleberries", "dingleberry", "dink", "dinks", "dipship", "dirsa", "dirty", "dirty pillows", "dirty sanchez", "div", "dlck", "dog style", "dog-fucker", "doggie style", "doggiestyle", "doggie-style", "doggin", "dogging", "doggy style", "doggystyle", "doggy-style", "dolcett", "domination", "dominatrix", "dommes", "dong", "donkey punch", "donkeypunch", "donkeyribber", "doochbag", "doofus", "dookie", "doosh", "dopey", "double dong", "double penetration", "doublelift", "douch3", "douche", "douchebag", "douchebags", "douche-fag", "douchewaffle", "douchey", "dp action", "drunk", "dry hump", "duche", "dumass", "dumb ass", "dumbass", "dumbasses", "dumbcunt", "dumbfuck", "dumbshit", "dummy", "dumshit", "dvda", "dyke", "dykes", "eat a dick", "eat hair pie", "eat my ass", "ecchi", "ejaculate", "ejaculated", "ejaculates", "ejaculating", "ejaculating", "ejaculatings", "ejaculation", "ejakulate", "erect", "erection", "erotic", "erotism", "escort", "essohbee", "eunuch", "extacy", "extasy", "f u c k", "f u c k e r", "f.u.c.k", "f_u_c_k", "f4nny", "facial", "fack", "fag", "fagbag", "fagfucker", "fagg", "fagged", "fagging", "faggit", "faggitt", "faggot", "faggotcock", "faggots", "faggs", "fagot", "fagots", "fags", "fagtard", "faig", "faigt", "fanny", "fannybandit", "fannyflaps", "fannyfucker", "fanyy", "fart", "fartknocker", "fatass", "fcuk", "fcuker", "fcuking", "fecal", "feck", "fecker", "feist", "felch", "felcher", "felching", "fellate", "fellatio", "feltch", "feltcher", "female squirting", "femdom", "fenian", "fice", "figging", "fingerbang", "fingerfuck", "fingerfucked", "fingerfucker", "fingerfuckers", "fingerfucking", "fingerfucks", "fingering", "fist fuck", "fisted", "fistfuck", "fistfucked", "fistfucker", "fistfuckers", "fistfuckings", "fistfucks", "fisting", "fisty", "flamer", "flange", "flaps", "fleshflute", "flog the log", "floozy", "foad", "foah", "fondle", "foobar", "fook", "fooker", "foot fetish", "footjob", "foreskin", "freex", "frenchify", "frigg", "frigga", "frotting", "fubar", "fuc", "fuck", "f-u-c-k", "fuck buttons", "fuck hole", "fuck off", "fuck puppet", "fuck trophy", "fuck yo mama", "fuck you", "fucka", "fuckass", "fuck-ass", "fuckbag", "fuck bag", "fuck-bitch", "fuckboy", "fuckbrain", "fuckbutt", "fuckbutter", "fucked", "fuckedup", "fucked up", "fucker", "fuckers", "fuckersucker", "fuckface", "fuckhead", "fuckheads", "fuckhole", "fuckin", "fucking", "fuckings", "fuckme", "fuck me", "fuckmeat", "fucknugget", "fucknut", "fucknutt", "fuckoff", "fucks", "fuckstick", "fucktard", "fuck-tard", "fucktards", "fucktart", "fucktoy", "fucktwat", "fuckup", "fuckwad", "fuckwhit", "fuckwit", "fuckwitt", "fudge packer", "fudgepacker", "fudge-packer", "fuk", "fuker", "fukker", "fukkers", "fukkin", "fuks", "fukwhit", "fukwit", "fuq", "futanari", "fux", "fux0r", "fvck", "fxck", "gae", "gai", "gang bang", "gangbang", "gang-bang", "gangbanged", "gangbangs", "ganja", "gash", "gassy ass", "gay sex", "gayass", "gaybob", "gaydo", "gayfuck", "gayfuckist", "gaylord", "gays", "gaysex", "gaytard", "gaywad", "gender bender", "genitals", "gey", "gfy", "ghay", "ghey", "giant cock", "gigolo", "ginger", "gippo", "girl on", "girl on top", "girls gone wild", "glans", "goatcx", "goatse", "god", "god damn", "godamn", "godamnit", "goddam", "god-dam", "goddammit", "goddamn", "goddamned", "god-damned", "goddamnit", "godsdamn", "gokkun", "golden shower", "goldenshower", "golliwog", "gonad", "gonads", "goo girl", "gooch", "goodpoop", "gook", "gooks", "goregasm", "gringo", "grope", "group sex", "gspot", "g-spot", "gtfo", "guido", "guro", "h0m0", "h0mo", "ham flap", "hand job", "handjob", "hard core", "hard on", "hardcore", "hardcoresex", "he11", "hebe", "heeb", "hell", "hemp", "hentai", "heroin", "herp", "herpes", "herpy", "heshe", "he-she", "hircismus", "hitler", "hiv", "hoar", "hoare", "hobag", "hoe", "hoer", "holy shit", "hom0", "homey", "homo", "homodumbshit", "homoerotic", "homoey", "honkey", "honky", "hooch", "hookah", "hooker", "hoor", "hootch", "hooter", "hooters", "hore", "horniest", "horny", "hot carl", "hot chick", "hotsex", "how to kill", "how to murdep", "how to murder", "huge fat", "hump", "humped", "humping", "hun", "hussy", "hymen", "iap", "iberian slap", "inbred", "incest", "injun", "intercourse", "jack off", "jackass", "jackasses", "jackhole", "jackoff", "jack-off", "jaggi", "jagoff", "jail bait", "jailbait", "jap", "japs", "jelly donut", "jerk", "jerk off", "jerk0ff", "jerkass", "jerked", "jerkoff", "jerk-off", "jigaboo", "jiggaboo", "jiggerboo", "jism", "jiz", "jizm", "jizm", "jizz", "jizzed", "jock", "juggs", "jungle bunny", "junglebunny", "junkie", "junky", "kafir", "kawk", "kike", "kikes", "kill", "kinbaku", "kinkster", "kinky", "klan", "knob", "knob end", "knobbing", "knobead", "knobed", "knobend", "knobhead", "knobjocky", "knobjokey", "kock", "kondum", "kondums", "kooch", "kooches", "kootch", "kraut", "kum", "kummer", "kumming", "kums", "kunilingus", "kunja", "kunt", "kwif", "kyke", "l3i+ch", "l3itch", "labia", "lameass", "lardass", "leather restraint", "leather straight jacket", "lech", "lemon party", "LEN", "leper", "lesbian", "lesbians", "lesbo", "lesbos", "lez", "lezza/lesbo", "lezzie", "lmao", "lmfao", "loin", "loins", "lolita", "looney", "lovemaking", "lube", "lust", "lusting", "lusty", "m0f0", "m0fo", "m45terbate", "ma5terb8", "ma5terbate", "mafugly", "mafugly", "make me come", "male squirting", "mams", "masochist", "massa", "masterb8", "masterbat*", "masterbat3", "masterbate", "master-bate", "masterbating", "masterbation", "masterbations", "masturbate", "masturbating", "masturbation", "maxi", "mcfagget", "menage a trois", "menses", "meth", "m-fucking", "mick", "microphallus", "middle finger", "midget", "milf", "minge", "minger", "missionary position", "mof0", "mofo", "mo-fo", "molest", "mong", "moo moo foo foo", "moolie", "moron", "mothafuck", "mothafucka", "mothafuckas", "mothafuckaz", "mothafucked", "mothafucker", "mothafuckers", "mothafuckin", "mothafucking", "mothafucking", "mothafuckings", "mothafucks", "mother fucker", "motherfuck", "motherfucka", "motherfucked", "motherfucker", "motherfuckers", "motherfuckin", "motherfucking", "motherfuckings", "motherfuckka", "motherfucks", "mound of venus", "mr hands", "muff", "muff diver", "muff puff", "muffdiver", "muffdiving", "munging", "munter", "murder", "mutha", "muthafecker", "muthafuckker", "muther", "mutherfucker", "n1gga", "n1gger", "naked", "nambla", "napalm", "nappy", "nawashi", "nazi", "nazism", "need the dick", "negro", "neonazi", "nig nog", "nigaboo", "nigg3r", "nigg4h", "nigga", "niggah", "niggas", "niggaz", "nigger", "niggers", "niggle", "niglet", "nig-nog", "nimphomania", "nimrod", "ninny", "ninnyhammer", "nipple", "nipples", "nob", "nob jokey", "nobhead", "nobjocky", "nobjokey", "nonce", "nsfw images", "nude", "nudity", "numbnuts", "nut butter", "nut butter", "nut sack", "nutsack", "nutter", "nympho", "nymphomania", "octopussy", "old bag", "omg", "omorashi", "one cup two girls", "1 cup 2 girls", "one cup 2 girls", "1 cup two girls", "one guy one jar", "1 guy one jar", "one guy 1 jar", "opiate", "opium", "orally", "organ", "orgasim", "orgasims", "orgasm", "orgasmic", "orgasms", "orgies", "orgy", "ovary", "ovum", "ovums", "p.u.s.s.y.", "p.u.s.s.y", "p0rn", "paedophile", "paki", "panooch", "pansy", "pantie", "panties", "panty", "pawn", "pcp", "pecker", "peckerhead", "pedo", "pedobear", "pedophile", "pedophilia", "pedophiliac", "pee", "peepee", "pegging", "penetrate", "penetration", "penial", "penile", "penis", "penisbanger", "penisfucker", "penispuffer", "perversion", "phallic", "phone sex", "phonesex", "phuck", "phuk", "phuked", "phuking", "phukked", "phukking", "phuks", "phuq", "piece of shit", "pigfucker", "pikey", "pillowbiter", "pimp", "pimpis", "pinko", "piss", "piss off", "piss pig", "pissed", "pissed off", "pisser", "pissers", "pisses", "pissflaps", "piss flaps", "pissin", "pissin", "pissing", "pissoff", "pissoff", "piss-off", "pisspig", "playboy", "pleasure chest", "polack", "pole smoker", "polesmoker", "pollock", "ponyplay", "poof", "poon", "poonani", "poonany", "poontang", "poop", "poop chute", "poopchute", "Poopuncher", "porch monkey", "porchmonkey", "porn", "porno", "pornography", "pornos", "potty", "prick", "pricks", "prickteaser", "prig", "prince albert piercing", "prod", "pron", "prone bone", "pronebone", "prone-bone", "prostitute", "prude", "psycho", "pthc", "pube", "pubes", "pubic", "pubis", "punani", "punanny", "punany", "punkass", "punky", "punta", "puss", "pusse", "pussi", "pussies", "pussy", "pussy fart", "pussy palace", "pussylicking", "pussypounder", "pussys", "pust", "puto", "queaf", "queef", "queer", "queerbait", "queerhole", "queero", "queers", "quicky", "quim", "racy", "raghead", "raging boner", "rape", "raped", "raper", "rapey", "raping", "rapist", "raunch", "rectal", "rectum", "rectus", "reefer", "reetard", "reich", "renob", "retard", "retarded", "reverse cowgirl", "revue", "rimjaw", "rimjob", "rimming", "ritard", "rosy palm", "rosy palm and her 5 sisters", "rtard", "r-tard", "rubbish", "rum", "rump", "rumprammer", "ruski", "rusty trombone", "s&m", "s.h.i.t.", "s.o.b.", "s_h_i_t", "s0b", "sadism", "sadist", "sambo", "sand nigger", "sandbar", "sandbar", "Sandler", "sandnigger", "sanger", "santorum", "sausage queen", "scag", "scantily", "scat", "schizo", "schlong", "scissoring", "screw", "screwed", "screwing", "scroat", "scrog", "scrot", "scrote", "scrotum", "scrud", "scum", "seaman", "seduce", "seks", "semen", "sex", "sexo", "sexual", "sexy", "sh!+", "sh!t", "sh1t", "s-h-1-t", "shag", "shagger", "shaggin", "shagging", "shamedame", "shaved beaver", "shaved pussy", "shemale", "shi+", "shibari", "shirt lifter", "shit", "s-h-i-t", "shit ass", "shit fucker", "shitass", "shitbag", "shitbagger", "shitblimp", "shitbrains", "shitbreath", "shitcanned", "shitcunt", "shitdick", "shite", "shiteater", "shited", "shitey", "shitface", "shitfaced", "shitfuck", "shitfull", "shithead", "shitheads", "shithole", "shithouse", "shiting", "shitings", "shits", "shitspitter", "shitstain", "shitt", "shitted", "shitter", "shitters", "shitters", "shittier", "shittiest", "shitting", "shittings", "shitty", "shiz", "shiznit", "shota", "shrimping", "sissy", "skag", "skank", "skeet", "skullfuck", "slag", "slanteye", "slave", "sleaze", "sleazy", "slope", "slut", "slut bucket", "slutbag", "slutdumper", "slutkiss", "sluts", "smartass", "smartasses", "smeg", "smegma", "smut", "smutty", "snatch", "sniper", "snowballing", "snuff", "s-o-b", "sod off", "sodom", "sodomize", "sodomy", "son of a bitch", "son of a motherless goat", "son of a whore", "son-of-a-bitch", "souse", "soused", "spac", "spade", "sperm", "spic", "spick", "spik", "spiks", "splooge", "splooge moose", "spooge", "spook", "spread legs", "spunk", "stfu", "stiffy", "stoned", "strap on", "strapon", "strappado", "strip", "strip club", "stroke", "stupid", "style doggy", "suck", "suckass", "sucked", "sucking", "sucks", "suicide girls", "sultry women", "sumofabiatch", "swastikav", "swinger", "t1t", "t1tt1e5", "t1tties", "taff", "taig", "tainted love", "taking the piss", "tampon", "tard", "tart", "taste my", "tawdry", "tea bagging", "teabagging", "teat", "teets", "teez", "teste", "testee", "testes", "testical", "testicle", "testis", "threesome", "throating", "thrust", "thug", "thundercunt", "thunder cunt", "tied up", "tight white", "tinkle", "tit", "tit wank", "titfuck", "titi", "tities", "tits", "titt", "tittie5", "tittiefucker", "titties", "titty", "tittyfuck", "tittyfucker", "tittywank", "titwank", "toke", "tongue in a", "toots", "topless", "tosser", "towelhead", "tramp", "tranny", "trashy", "tribadism", "trumped", "tub girl", "tubgirl", "turd", "tush", "tushy", "tw4t", "twat", "twathead", "twatlips", "twats", "twatty", "twatting", "twatwaffle", "twink", "twinkie", "two fingers", "two fingers with tongue", "two girls one cup", "twunt", "twunter", "ugly", "unclefucker", "undies", "undressing", "unwed", "upskirt", "urethra play", "urinal", "urine", "urophilia", "uterus", "uzi", "v14gra", "v1gra", "vag", "vagina", "vajayjay", "va-j-j", "valium", "venus mound", "veqtable", "viagra", "vibrator", "violet wand", "virgin", "vixen", "vjayjay", "vodka", "vomit", "vorarephilia", "voyeur", "vulgar", "vulva", "w00se", "wad", "wang", "wank", "wanker", "wankjob", "wanky", "wazoo", "wedgie", "weed", "weenie", "weewee", "weiner", "weirdo", "wench", "wet dream", "wetback", "wh0re", "wh0reface", "white power", "whiz", "whoar", "whoralicious", "whore", "whorealicious", "whorebag", "whored", "whoreface", "whorehopper", "whorehouse", "whores", "whoring", "wigger", "willies", "willy", "window licker", "wiseass", "wiseasses", "wog", "womb", "wop", "wrapping men", "wrinkled starfish", "xrated", "x-rated", "xx", "xxx", "yaoi", "yeasty", "yellow showers", "yid", "yiffy", "yobbo", "zibbi", "zoophilia", "zubb" }; public int Count => _profanities.Count; public ProfanityBase() { _profanities = new List<string>(_wordList); } protected ProfanityBase(string[] profanityList) { if (profanityList == null) { throw new ArgumentNullException("profanityList"); } _profanities = new List<string>(profanityList); } protected ProfanityBase(List<string> profanityList) { if (profanityList == null) { throw new ArgumentNullException("profanityList"); } _profanities = profanityList; } public void AddProfanity(string profanity) { if (string.IsNullOrEmpty(profanity)) { throw new ArgumentNullException("profanity"); } _profanities.Add(profanity); } public void AddProfanity(string[] profanityList) { if (profanityList == null) { throw new ArgumentNullException("profanityList"); } _profanities.AddRange(profanityList); } public void AddProfanity(List<string> profanityList) { if (profanityList == null) { throw new ArgumentNullException("profanityList"); } _profanities.AddRange(profanityList); } public bool RemoveProfanity(string profanity) { if (string.IsNullOrEmpty(profanity)) { throw new ArgumentNullException("profanity"); } return _profanities.Remove(profanity.ToLower(CultureInfo.InvariantCulture)); } public bool RemoveProfanity(List<string> profanities) { if (profanities == null) { throw new ArgumentNullException("profanities"); } foreach (string profanity in profanities) { if (!RemoveProfanity(profanity)) { return false; } } return true; } public bool RemoveProfanity(string[] profanities) { if (profanities == null) { throw new ArgumentNullException("profanities"); } foreach (string profanity in profanities) { if (!RemoveProfanity(profanity)) { return false; } } return true; } public void Clear() { _profanities.Clear(); } } public class ProfanityFilter : ProfanityBase, IProfanityFilter { public IAllowList AllowList { get; } public ProfanityFilter() { AllowList = new AllowList(); } public ProfanityFilter(string[] profanityList) : base(profanityList) { AllowList = new AllowList(); } public ProfanityFilter(List<string> profanityList) : base(profanityList) { AllowList = new AllowList(); } public bool IsProfanity(string word) { if (string.IsNullOrEmpty(word)) { return false; } if (AllowList.Contains(word.ToLower(CultureInfo.InvariantCulture))) { return false; } return _profanities.Contains(word.ToLower(CultureInfo.InvariantCulture)); } public ReadOnlyCollection<string> DetectAllProfanities(string sentence) { return DetectAllProfanities(sentence, removePartialMatches: false); } public ReadOnlyCollection<string> DetectAllProfanities(string sentence, bool removePartialMatches) { if (string.IsNullOrEmpty(sentence)) { return new ReadOnlyCollection<string>(new List<string>()); } sentence = sentence.ToLower(); sentence = sentence.Replace(".", ""); sentence = sentence.Replace(",", ""); string[] words = sentence.Split(new char[1] { ' ' }); List<string> postAllowList = FilterWordListByAllowList(words); List<string> swearList = new List<string>(); AddMultiWordProfanities(swearList, ConvertWordListToSentence(postAllowList)); if (removePartialMatches) { swearList.RemoveAll((string x) => swearList.Any((string y) => x != y && y.Contains(x))); } return new ReadOnlyCollection<string>(FilterSwearListForCompleteWordsOnly(sentence, swearList).Distinct().ToList()); } public string CensorString(string sentence) { return CensorString(sentence, '*'); } public string CensorString(string sentence, char censorCharacter) { return CensorString(sentence, censorCharacter, ignoreNumbers: false); } public string CensorString(string sentence, char censorCharacter, bool ignoreNumbers) { if (string.IsNullOrEmpty(sentence)) { return string.Empty; } string text = sentence.Trim(); text = text.ToLower(); text = Regex.Replace(text, "[^\\w\\s]", ""); string[] words = text.Split(new char[1] { ' ' }); List<string> postAllowList = FilterWordListByAllowList(words); List<string> swearList = new List<string>(); AddMultiWordProfanities(swearList, ConvertWordListToSentence(postAllowList)); StringBuilder censored = new StringBuilder(sentence); StringBuilder tracker = new StringBuilder(sentence); return CensorStringByProfanityList(censorCharacter, swearList, censored, tracker, ignoreNumbers).ToString(); } public (int, int, string)? GetCompleteWord(string toCheck, string profanity) { if (string.IsNullOrEmpty(toCheck)) { return null; } string value = profanity.ToLower(CultureInfo.InvariantCulture); string text = toCheck.ToLower(CultureInfo.InvariantCulture); if (text.Contains(value)) { int num = text.IndexOf(value, StringComparison.Ordinal); int i = num; while (num > 0 && toCheck[num - 1] != ' ' && !char.IsPunctuation(toCheck[num - 1])) { num--; } for (; i < toCheck.Length && toCheck[i] != ' ' && !char.IsPunctuation(toCheck[i]); i++) { } return (num, i, text.Substring(num, i - num).ToLower(CultureInfo.InvariantCulture)); } return null; } public bool ContainsProfanity(string term) { if (string.IsNullOrWhiteSpace(term)) { return false; } List<string> list = _profanities.Where((string word) => word.Length <= term.Length).ToList(); if (list.Count == 0) { return false; } Regex regex = new Regex(string.Format("(?:{0})", string.Join("|", list).Replace("$", "\\$"), RegexOptions.IgnoreCase)); foreach (Match item in regex.Matches(term)) { if (!AllowList.Contains(item.Value.ToLower(CultureInfo.InvariantCulture))) { return true; } } return false; } private StringBuilder CensorStringByProfanityList(char censorCharacter, List<string> swearList, StringBuilder censored, StringBuilder tracker, bool ignoreNumeric) { foreach (string item in swearList.OrderByDescending((string x) => x.Length)) { (int, int, string)? tuple = (0, 0, ""); string[] array = item.Split(new char[1] { ' ' }); if (array.Length == 1) { do { tuple = GetCompleteWord(tracker.ToString(), item); if (!tuple.HasValue) { continue; } string text = tuple.Value.Item3; if (ignoreNumeric) { text = Regex.Replace(tuple.Value.Item3, "[\\d-]", string.Empty); } if (text == item) { for (int i = tuple.Value.Item1; i < tuple.Value.Item2; i++) { censored[i] = censorCharacter; tracker[i] = censorCharacter; } } else { for (int j = tuple.Value.Item1; j < tuple.Value.Item2; j++) { tracker[j] = censorCharacter; } } } while (tuple.HasValue); } else { censored = censored.Replace(item, CreateCensoredString(item, censorCharacter)); } } return censored; } private List<string> FilterSwearListForCompleteWordsOnly(string sentence, List<string> swearList) { List<string> list = new List<string>(); StringBuilder stringBuilder = new StringBuilder(sentence); foreach (string item in swearList.OrderByDescending((string x) => x.Length)) { (int, int, string)? tuple = (0, 0, ""); string[] array = item.Split(new char[1] { ' ' }); if (array.Length == 1) { do { tuple = GetCompleteWord(stringBuilder.ToString(), item); if (!tuple.HasValue) { continue; } if (tuple.Value.Item3 == item) { list.Add(item); for (int i = tuple.Value.Item1; i < tuple.Value.Item2; i++) { stringBuilder[i] = '*'; } break; } for (int j = tuple.Value.Item1; j < tuple.Value.Item2; j++) { stringBuilder[j] = '*'; } } while (tuple.HasValue); } else { list.Add(item); stringBuilder.Replace(item, " "); } } return list; } private List<string> FilterWordListByAllowList(string[] words) { List<string> list = new List<string>(); foreach (string text in words) { if (!string.IsNullOrEmpty(text) && !AllowList.Contains(text.ToLower(CultureInfo.InvariantCulture))) { list.Add(text); } } return list; } private static string ConvertWordListToSentence(List<string> postAllowList) { string text = string.Empty; foreach (string postAllow in postAllowList) { text = text + postAllow + " "; } return text; } private void AddMultiWordProfanities(List<string> swearList, string postAllowListSentence) { swearList.AddRange(from string profanity in _profanities where postAllowListSentence.ToLower(CultureInfo.InvariantCulture).Contains(profanity) select profanity); } private static string CreateCensoredString(string word, char censorCharacter) { string text = string.Empty; for (int i = 0; i < word.Length; i++) { text = ((word[i] == ' ') ? (text + " ") : (text + censorCharacter)); } return text; } } } namespace ProfanityFilter.Interfaces { public interface IAllowList { int Count { get; } ReadOnlyCollection<string> ToList { get; } void Add(string wordToAllowlist); bool Contains(string wordToCheck); bool Remove(string wordToRemove); void Clear(); } public interface IProfanityFilter { IAllowList AllowList { get; } int Count { get; } bool IsProfanity(string word); ReadOnlyCollection<string> DetectAllProfanities(string sentence); ReadOnlyCollection<string> DetectAllProfanities(string sentence, bool removePartialMatches); bool ContainsProfanity(string term); string CensorString(string sentence); string CensorString(string sentence, char censorCharacter); string CensorString(string sentence, char censorCharacter, bool ignoreNumbers); (int, int, string)? GetCompleteWord(string toCheck, string profanity); void AddProfanity(string profanity); void AddProfanity(string[] profanityList); void AddProfanity(List<string> profanityList); bool RemoveProfanity(string profanity); bool RemoveProfanity(List<string> profanities); bool RemoveProfanity(string[] profanities); void Clear(); } }
MegabonkTogether/MegabonkTogether.dll
Decompiled 2 hours 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.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Net.WebSockets; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Actors.Enemies; using Assets.Scripts.Actors; using Assets.Scripts.Actors.Enemies; using Assets.Scripts.Actors.Player; using Assets.Scripts.Camera; using Assets.Scripts.Game.Combat; using Assets.Scripts.Game.Combat.ConstantAttacks; using Assets.Scripts.Game.Combat.EnemySpecialAttacks; using Assets.Scripts.Game.Combat.EnemySpecialAttacks.Implementations; using Assets.Scripts.Game.MapGeneration; using Assets.Scripts.Game.MapGeneration.MapEvents; using Assets.Scripts.Game.Other; using Assets.Scripts.Game.Spawning; using Assets.Scripts.Game.Spawning.New; using Assets.Scripts.Game.Spawning.New.Summoners; using Assets.Scripts.Game.Spawning.New.Timelines; using Assets.Scripts.Inventory.Stats; using Assets.Scripts.Inventory__Items__Pickups; using Assets.Scripts.Inventory__Items__Pickups.AbilitiesPassive.Implementations; using Assets.Scripts.Inventory__Items__Pickups.Chests; using Assets.Scripts.Inventory__Items__Pickups.GoldAndMoney; using Assets.Scripts.Inventory__Items__Pickups.Interactables; using Assets.Scripts.Inventory__Items__Pickups.Items; using Assets.Scripts.Inventory__Items__Pickups.Items.ItemImplementations; using Assets.Scripts.Inventory__Items__Pickups.Pickups; using Assets.Scripts.Inventory__Items__Pickups.Stats; using Assets.Scripts.Inventory__Items__Pickups.Weapons; using Assets.Scripts.Inventory__Items__Pickups.Weapons.Attacks; using Assets.Scripts.Inventory__Items__Pickups.Weapons.Projectiles; using Assets.Scripts.Managers; using Assets.Scripts.MapGeneration.ProceduralTiles; using Assets.Scripts.Menu.Shop; using Assets.Scripts.Objects.Pooling; using Assets.Scripts.Saves___Serialization.Progression.Achievements; using Assets.Scripts.Steam; using Assets.Scripts.UI.InGame.Levelup; using Assets.Scripts.UI.Localization; using Assets.Scripts.Utility; using Assets.Scripts._Data.Hats; using Assets.Scripts._Data.MapsAndStages; using Assets.Scripts._Data.Tomes; using BepInEx; using BepInEx.Configuration; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.UnityEngine; using BepInEx.Unity.IL2CPP.Utils; using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LiteNetLib; using LiteNetLib.Layers; using LiteNetLib.Utils; using MegabonkTogether.Common; using MegabonkTogether.Common.Messages; using MegabonkTogether.Common.Messages.GameNetworkMessages; using MegabonkTogether.Common.Messages.WsMessages; using MegabonkTogether.Common.Models; using MegabonkTogether.Configuration; using MegabonkTogether.Extensions; using MegabonkTogether.Helpers; using MegabonkTogether.Patches; using MegabonkTogether.Scripts; using MegabonkTogether.Scripts.Button; using MegabonkTogether.Scripts.Enemies; using MegabonkTogether.Scripts.Interactables; using MegabonkTogether.Scripts.Modal; using MegabonkTogether.Scripts.NetPlayer; using MegabonkTogether.Scripts.Snapshot; using MegabonkTogether.Services; using MemoryPack; using Microsoft.CodeAnalysis; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MonoMod.Utils; using ProfanityFilter; using TMPro; using TextCopy; using Tomlyn; using Tomlyn.Model; using UnityEngine; using UnityEngine.Events; using UnityEngine.Localization; using UnityEngine.Localization.Components; using UnityEngine.Localization.Tables; using UnityEngine.Pool; using UnityEngine.UI; using Utility; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("MegabonkTogether")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0+345d21e38d0e1f40b8178e142bed88bc5edd5109")] [assembly: AssemblyProduct("MegabonkTogether")] [assembly: AssemblyTitle("MegabonkTogether")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace MegabonkTogether { [BepInPlugin("MegabonkTogether", "MegabonkTogether", "2.0.0")] public class Plugin : BasePlugin { public static Plugin Instance = null; public NetworkHandler NetworkHandler; public Dictionary<ECharacter, RawImage> CharactersIcon = new Dictionary<ECharacter, RawImage>(); public NetPlayersDisplayer NetPlayersDisplayer; public CameraSwitcher CameraSwitcher; public PlayTogetherButton PlayTogetherButton; public AchievementPopup AchievementPopup; public NotificationQueueManager NotificationQueueManager; private MainMenu MainMenu; private MapEventsManager mapEventsManager; private MapEventsDesert mapEventsDesert; private LoadingModal modal; public NetworkMode Mode = new NetworkMode(); public static IHost Host = null; internal static ManualLogSource Log; private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); private CancellationToken cancellationToken; public static float PLAYER_FEET_OFFSET_Y = 1.5f; public static bool CAN_SPAWN_PICKUPS = false; public static bool CAN_SPAWN_CHESTS = false; public static bool CAN_SEND_MESSAGES = true; public static bool CAN_ENEMY_EXPLODE = false; public static bool CAN_ENEMY_USE_SPECIAL_ATTACK = false; public bool CAN_SPAWN_TORNADOES; public bool CAN_START_STOP_STORMS; public bool CAN_DAMAGE_ENEMIES; public bool IS_HOST_READY; public bool IS_MANUAL_INVINCIBLE; public uint? CurrentReviver; private Vector3 WorldSize = Vector3.zero; public Vector3 OriginalWorldSize = Vector3.zero; public bool HasDungeonTimerStarted; private readonly ConcurrentDictionary<string, GameObject> prefabs = new ConcurrentDictionary<string, GameObject>(); private Action originalDiedAction; private Action<WeaponBase> originalWeaponAddedAction; private Action<EStat> originalStatUpdateAction; public static IServiceProvider Services => Host.Services; internal NetworkMenuTab NetworkTab { get; set; } public override void Load() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Expected O, but got Unknown //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Expected O, but got Unknown //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0252: Expected O, but got Unknown //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Expected O, but got Unknown //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Expected O, but got Unknown //IL_01d3: Unknown result type (might be due to invalid IL or missing references) Instance = this; cancellationToken = cancellationTokenSource.Token; Log = ((BasePlugin)this).Log; ManualLogSource log = Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(18, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("MegabonkTogether"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is loaded!"); } log.LogInfo(val); ModConfig.Initialize(((BasePlugin)this).Config); ManualLogSource log2 = Log; val = new BepInExInfoLogInterpolatedStringHandler(20, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Player name set to: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ModConfig.PlayerName.Value); } log2.LogInfo(val); ClassInjector.RegisterTypeInIl2Cpp<NetPlayer>(); ClassInjector.RegisterTypeInIl2Cpp<CoroutineRunner>(); ClassInjector.RegisterTypeInIl2Cpp<MainThreadDispatcher>(); ClassInjector.RegisterTypeInIl2Cpp<NetworkHandler>(); ClassInjector.RegisterTypeInIl2Cpp<PlayerInterpolator>(); ClassInjector.RegisterTypeInIl2Cpp<EnemyInterpolator>(); ClassInjector.RegisterTypeInIl2Cpp<BossOrbInterpolator>(); ClassInjector.RegisterTypeInIl2Cpp<ProjectileInterpolator>(); ClassInjector.RegisterTypeInIl2Cpp<TumbleWeedInterpolator>(); ClassInjector.RegisterTypeInIl2Cpp<NetPlayersDisplayer>(); ClassInjector.RegisterTypeInIl2Cpp<NetPlayerCard>(); ClassInjector.RegisterTypeInIl2Cpp<DisplayBar>(); ClassInjector.RegisterTypeInIl2Cpp<CustomInventoryHud>(); ClassInjector.RegisterTypeInIl2Cpp<CameraSwitcher>(); ClassInjector.RegisterTypeInIl2Cpp<PlayTogetherButton>(); ClassInjector.RegisterTypeInIl2Cpp<CustomButton>(); ClassInjector.RegisterTypeInIl2Cpp<ModalBase>(); ClassInjector.RegisterTypeInIl2Cpp<NetworkMenuTab>(); ClassInjector.RegisterTypeInIl2Cpp<LoadingModal>(); ClassInjector.RegisterTypeInIl2Cpp<UpdateAvailableModal>(); ClassInjector.RegisterTypeInIl2Cpp<ChangelogModal>(); ClassInjector.RegisterTypeInIl2Cpp<TargetSwitcher>(); ClassInjector.RegisterTypeInIl2Cpp<InteractableReviver>(); ClassInjector.RegisterTypeInIl2Cpp<NotificationQueueManager>(); HostBuilder hostBuilder = new HostBuilder(); string currentDirectory = Directory.GetCurrentDirectory(); hostBuilder.UseContentRoot(currentDirectory); hostBuilder.ConfigureServices(delegate(IServiceCollection services) { services.AddSingleton<ManualLogSource>(Log); services.AddSingleton<IWebsocketClientService, WebsocketClientService>(); services.AddSingleton<IUdpClientService, UdpClientService>(); services.AddSingleton<IPlayerManagerService, PlayerManagerService>(); services.AddSingleton<IEnemyManagerService, EnemyManagerService>(); services.AddSingleton<IProjectileManagerService, ProjectileManagerService>(); services.AddSingleton<ISynchronizationService, SynchronizationService>(); services.AddSingleton<IPickupManagerService, PickupManagerService>(); services.AddSingleton<IChestManagerService, ChestManagerService>(); services.AddSingleton<ISpawnedObjectManagerService, SpawnedObjectManagerService>(); services.AddSingleton<IFinalBossOrbManagerService, FinalBossOrbManagerService>(); services.AddSingleton<ILocalizationService, LocalizationService>(); services.AddSingleton<IGameBalanceService, GameBalanceService>(); services.AddSingleton<IAutoUpdaterService, AutoUpdaterService>(); services.AddSingleton<IChangelogService, ChangelogService>(); }); Host = hostBuilder.Build(); Services.GetRequiredService<ISynchronizationService>(); Host.StartAsync(cancellationToken); IAutoUpdaterService autoUpdaterService = Services.GetRequiredService<IAutoUpdaterService>(); if (ModConfig.CheckForUpdates.Value) { autoUpdaterService.Initialize(); Task.Run(async delegate { try { if (await autoUpdaterService.CheckAndUpdate() && !autoUpdaterService.IsThunderstoreBuild()) { Log.LogInfo((object)"An update has been downloaded and will be applied when you quit the game."); } } catch (Exception ex2) { ManualLogSource log4 = Log; bool flag2 = default(bool); BepInExErrorLogInterpolatedStringHandler val8 = new BepInExErrorLogInterpolatedStringHandler(26, 1, ref flag2); if (flag2) { ((BepInExLogInterpolatedStringHandler)val8).AppendLiteral("Auto-update check failed: "); ((BepInExLogInterpolatedStringHandler)val8).AppendFormatted<string>(ex2.Message); } log4.LogError(val8); } }); } else { Log.LogInfo((object)"Auto-update is disabled in configuration."); } try { new Harmony("MegabonkTogether").PatchAll(); } catch (Exception ex) { ManualLogSource log3 = Log; BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(25, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Harmony patching failed: "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex); } log3.LogError(val2); } GameObject val3 = new GameObject("MainThreadDispatcher"); Object.DontDestroyOnLoad((Object)val3); val3.AddComponent<MainThreadDispatcher>(); GameObject val4 = new GameObject("NetworkHandler"); Object.DontDestroyOnLoad((Object)(object)val4); NetworkHandler = val4.AddComponent<NetworkHandler>(); GameObject val5 = new GameObject("NetPlayersDisplayer"); Object.DontDestroyOnLoad((Object)(object)val5); NetPlayersDisplayer = val5.AddComponent<NetPlayersDisplayer>(); GameObject val6 = new GameObject("CameraSwitcher"); Object.DontDestroyOnLoad((Object)(object)val6); CameraSwitcher = val6.AddComponent<CameraSwitcher>(); GameObject val7 = new GameObject("NotificationQueueManager"); Object.DontDestroyOnLoad((Object)(object)val7); NotificationQueueManager = val7.AddComponent<NotificationQueueManager>(); } public void AddPrefab(GameObject prefab) { prefabs.TryAdd(((Object)prefab).name, prefab); } public GameObject GetPrefab(string name) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown if (prefabs.TryGetValue(name.Trim(), out var value)) { return value; } ManualLogSource log = Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(18, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Prefab not found: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(name); } log.LogWarning(val); return null; } public void ClearPrefabs() { prefabs.Clear(); } public void ClearCharacterIcons() { CharactersIcon.Clear(); } public void AddCharacterIcons(List<MyButtonCharacter> characterButtons) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (CharactersIcon.Count > 0) { Log.LogWarning((object)"Character icons already added"); return; } Enumerator<MyButtonCharacter> enumerator = characterButtons.GetEnumerator(); while (enumerator.MoveNext()) { MyButtonCharacter current = enumerator.Current; RawImage val = Object.Instantiate<RawImage>(current.i_icon); Object.DontDestroyOnLoad((Object)(object)val); CharactersIcon.Add(current.characterData.eCharacter, val); } } public void PreventDeath() { if ((Delegate)(object)originalDiedAction != (Delegate)null) { Log.LogWarning((object)"Death already prevented"); return; } originalDiedAction = PlayerHealth.A_Died; PlayerHealth.A_Died = Action.op_Implicit((Action)OnPlayerDied); } private void OnPlayerDied() { if (!((Object)(object)CameraSwitcher == (Object)null) && !CameraSwitcher.IsFollowingTarget) { NetPlayer randomNetPlayer = Services.GetService<IPlayerManagerService>().GetRandomNetPlayer(); if ((Object)(object)randomNetPlayer != (Object)null) { CameraSwitcher.SwitchToTarget(randomNetPlayer.ConnectionId); } } } public void RestoreDeath(bool invokeDeathEvent) { if ((Delegate)(object)originalDiedAction == (Delegate)null) { Log.LogWarning((object)"Death not prevented"); return; } CameraSwitcher.ResetToLocalPlayer(); PlayerHealth.A_Died = originalDiedAction; originalDiedAction = null; if (invokeDeathEvent) { ((Component)GameManager.Instance.player.playerRenderer).gameObject.SetActive(true); PlayerHealth.A_Died.Invoke(); } } public AchievementPopup GetAchievementPopup() { if ((Object)(object)AchievementPopup == (Object)null) { GameObject val = ((IEnumerable<GameObject>)Il2CppFindHelper.FindAllGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject go) => (Object)(object)go.GetComponent<AchievementPopup>() != (Object)null)); if ((Object)(object)val != (Object)null) { AchievementPopup = val.GetComponent<AchievementPopup>(); if ((Object)(object)AchievementPopup != (Object)null && (Object)(object)NotificationQueueManager != (Object)null) { NotificationQueueManager.Initialize(); } } } return AchievementPopup; } public MainMenu GetMainMenu() { return MainMenu; } public void SetMainMenu(MainMenu mainMenu) { MainMenu = mainMenu; } public static bool StartNotification((string tableReference, string tableEntryReference) localizedName, (string tableReference, string tableEntryReference) localizedDescription, IEnumerable<string> descriptionArgs, RandomSfx sfx = null, EItem item = 0) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance?.NotificationQueueManager == (Object)null) { Log.LogWarning((object)"NotificationQueueManager is not initialized"); return false; } Instance.NotificationQueueManager.EnqueueNotification(localizedName, localizedDescription, descriptionArgs, sfx, item); return true; } public static void GoToMainMenu() { if ((Object)(object)GameManager.Instance == (Object)null || (Object)(object)GameManager.Instance.player == (Object)null) { Window activeWindow = WindowManager.activeWindow; CharacterMenu val = (CharacterMenu)(object)((activeWindow is CharacterMenu) ? activeWindow : null); if (val != null) { ((UnityEvent)val.b_back.button.onClick).Invoke(); } if (((Object)WindowManager.activeWindow).name.Contains("Maps And Stats")) { MyButton? obj = ((IEnumerable<MyButton>)WindowManager.activeWindow.allButtons.ToArray()).FirstOrDefault((Func<MyButton, bool>)((MyButton b) => ((Object)b).name == "B_Back")); if (obj != null) { ((UnityEvent)obj.button.onClick).Invoke(); } Window activeWindow2 = WindowManager.activeWindow; Window obj2 = ((activeWindow2 is CharacterMenu) ? activeWindow2 : null); if (obj2 != null) { ((UnityEvent)((CharacterMenu)obj2).b_back.button.onClick).Invoke(); } } } else { TransitionUI.Instance.LoadMenu(); } } public void ShowModal(string message) { if ((Object)(object)modal != (Object)null) { modal.UpdateMessage(message); } else { modal = LoadingModal.Show(message); } } public void HideModal() { if ((Object)(object)modal != (Object)null) { modal.Close(); modal = null; } } public static void ShowUpdateAvailableModal() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) new GameObject("UpdateAvailableModal").AddComponent<UpdateAvailableModal>(); } public void SavePlayerInventoryActions() { originalWeaponAddedAction = WeaponInventory.A_WeaponAdded; originalStatUpdateAction = PlayerStatsNew.A_StatUpdate; WeaponInventory.A_WeaponAdded = null; PlayerStatsNew.A_StatUpdate = null; } public void RestorePlayerInventoryActions() { if ((Delegate)(object)originalWeaponAddedAction == (Delegate)null) { Log.LogWarning((object)"WeaponAdded action not saved"); return; } if ((Delegate)(object)originalStatUpdateAction == (Delegate)null) { Log.LogWarning((object)"StatUpdate action not saved"); return; } WeaponInventory.A_WeaponAdded = originalWeaponAddedAction; PlayerStatsNew.A_StatUpdate = originalStatUpdateAction; originalWeaponAddedAction = null; originalStatUpdateAction = null; } public MapEventsDesert GetMapEventsDesert() { if (mapEventsDesert == null && (Object)(object)mapEventsManager == (Object)null) { mapEventsManager = GetMapEventsManager(); mapEventsDesert = IL2CPP.PointerToValueGeneric<MapEventsDesert>(((Il2CppObjectBase)mapEventsManager.mapEvents).Pointer, false, false); } return mapEventsDesert; } private MapEventsManager GetMapEventsManager() { if ((Object)(object)mapEventsManager == (Object)null) { mapEventsManager = ((IEnumerable<GameObject>)Il2CppFindHelper.FindAllGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject go) => (Object)(object)go.GetComponent<MapEventsManager>() != (Object)null)).GetComponent<MapEventsManager>(); } return mapEventsManager; } public void ClearMapEventsManager() { mapEventsManager = null; mapEventsDesert = null; } public void SetWorldSize(Vector3 size) { //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) WorldSize = size; } public Vector3 GetWorldSize() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return WorldSize; } public void ResetWorldSize() { //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_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) WorldSize = Vector3.zero; OriginalWorldSize = Vector3.zero; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "MegabonkTogether"; public const string PLUGIN_NAME = "MegabonkTogether"; public const string PLUGIN_VERSION = "2.0.0"; } } namespace MegabonkTogether.Services { public class VersionChanges { public string Version { get; set; } public ICollection<string> Changes { get; set; } = new List<string>(); } public interface IChangelogService { Task<ICollection<VersionChanges>> LoadChangelogAsync(); ICollection<VersionChanges> GetChangesBetweenVersions(ICollection<VersionChanges> changelog, string fromVersion, string toVersion); bool ShouldShowChangelog(); void MarkChangelogAsShown(); void SetShowChangelogOnNextLaunch(string currentVersion); } public class ChangelogService : IChangelogService { [CompilerGenerated] private IAutoUpdaterService <autoUpdaterService>P; [CompilerGenerated] private ManualLogSource <logger>P; public const string CHANGELOG_FILENAME = "CHANGELOG.toml"; public ChangelogService(IAutoUpdaterService autoUpdaterService, ManualLogSource logger) { <autoUpdaterService>P = autoUpdaterService; <logger>P = logger; base..ctor(); } public async Task<ICollection<VersionChanges>> LoadChangelogAsync() { _ = 1; bool flag = default(bool); try { string location = Assembly.GetExecutingAssembly().Location; string pluginDirectory = Path.GetDirectoryName(location); await <autoUpdaterService>P.EnsureChangelogExists("2.0.0", pluginDirectory); string path = Path.Combine(pluginDirectory, "CHANGELOG.toml"); if (!File.Exists(path)) { ManualLogSource obj = <logger>P; BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(24, 0, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Changelog file not found"); } obj.LogError(val); return new List<VersionChanges>(); } ManualLogSource obj2 = <logger>P; BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(20, 0, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Loading changelog..."); } obj2.LogInfo(val2); return ParseChangelog(await File.ReadAllTextAsync(path)); } catch (Exception ex) { ManualLogSource obj3 = <logger>P; BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(25, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error loading changelog: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } obj3.LogError(val); return new List<VersionChanges>(); } } private ICollection<VersionChanges> ParseChangelog(string content) { //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Expected O, but got Unknown //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Expected O, but got Unknown List<VersionChanges> list = new List<VersionChanges>(); bool flag = default(bool); try { TomlTable val = Toml.ToModel(content, (string)null, (TomlModelOptions)null); if (!val.ContainsKey("version")) { <logger>P.LogWarning((object)"No 'version' table found in changelog"); return list; } object obj = val["version"]; TomlTable val2 = (TomlTable)((obj is TomlTable) ? obj : null); if (val2 == null) { <logger>P.LogWarning((object)"'version' is not a table"); return list; } foreach (KeyValuePair<string, object> item in val2) { string key = item.Key; object value = item.Value; TomlTable val3 = (TomlTable)((value is TomlTable) ? value : null); if (val3 == null) { ManualLogSource obj2 = <logger>P; BepInExWarningLogInterpolatedStringHandler val4 = new BepInExWarningLogInterpolatedStringHandler(28, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("Version "); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(key); ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" data is not a table"); } obj2.LogWarning(val4); continue; } if (!val3.ContainsKey("changes")) { ManualLogSource obj3 = <logger>P; BepInExWarningLogInterpolatedStringHandler val4 = new BepInExWarningLogInterpolatedStringHandler(31, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("Version "); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(key); ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" has no 'changes' array"); } obj3.LogWarning(val4); continue; } object obj4 = val3["changes"]; TomlArray val5 = (TomlArray)((obj4 is TomlArray) ? obj4 : null); if (val5 == null) { ManualLogSource obj5 = <logger>P; BepInExWarningLogInterpolatedStringHandler val4 = new BepInExWarningLogInterpolatedStringHandler(34, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("Version "); ((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(key); ((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" 'changes' is not an array"); } obj5.LogWarning(val4); continue; } List<string> list2 = new List<string>(); foreach (object item2 in val5) { if (item2 is string text && !string.IsNullOrWhiteSpace(text)) { list2.Add(text.Trim()); } } if (list2.Count > 0) { list.Add(new VersionChanges { Version = key, Changes = list2 }); } } list = list.OrderByDescending(delegate(VersionChanges v) { try { return new Version(v.Version); } catch { return new Version(0, 0, 0); } }).ToList(); } catch (Exception ex) { ManualLogSource obj6 = <logger>P; BepInExErrorLogInterpolatedStringHandler val6 = new BepInExErrorLogInterpolatedStringHandler(30, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("Error parsing changelog TOML: "); ((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<string>(ex.Message); } obj6.LogError(val6); } return list; } public ICollection<VersionChanges> GetChangesBetweenVersions(ICollection<VersionChanges> changelog, string fromVersion, string toVersion) { //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown if (changelog == null || changelog.Count == 0) { return new List<VersionChanges>(); } fromVersion = fromVersion?.TrimStart('v') ?? ""; toVersion = toVersion?.TrimStart('v') ?? ""; Version from = null; Version to = null; try { if (!string.IsNullOrEmpty(fromVersion)) { from = new Version(fromVersion); } if (!string.IsNullOrEmpty(toVersion)) { to = new Version(toVersion); } } catch { ManualLogSource obj = <logger>P; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(36, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not parse versions: from="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(fromVersion); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", to="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(toVersion); } obj.LogWarning(val); List<VersionChanges> list = new List<VersionChanges>(); list.AddRange(changelog.Take(1)); return list; } if (from == null || to == null) { List<VersionChanges> list2 = new List<VersionChanges>(); list2.AddRange(changelog.Take(1)); return list2; } List<VersionChanges> list3 = new List<VersionChanges>(); list3.AddRange(changelog.Where(delegate(VersionChanges v) { try { Version version = new Version(v.Version); return version > from && version <= to; } catch { return false; } })); return list3; } public bool ShouldShowChangelog() { return ModConfig.ShowChangelog.Value; } public void MarkChangelogAsShown() { ModConfig.ShowChangelog.Value = false; ModConfig.Save(); <logger>P.LogInfo((object)"Changelog marked as shown"); } public void SetShowChangelogOnNextLaunch(string currentVersion) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown ModConfig.PreviousVersion.Value = currentVersion; ModConfig.ShowChangelog.Value = true; ModConfig.Save(); ManualLogSource obj = <logger>P; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(65, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Changelog will be shown on next launch. Previous version set to: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(currentVersion); } obj.LogInfo(val); } } public interface IChestManagerService { uint AddChest(Object chestObject); void PushNextChestId(uint chestId); uint? SetNextChest(Object chestObject); Object? GetChest(uint chestId); void RemoveChest(uint chestId); KeyValuePair<uint, Object> GetChestByReference(OpenChest instance); void ResetForNextLevel(); } public class ChestManagerService : IChestManagerService { private readonly ConcurrentDictionary<uint, Object> chests = new ConcurrentDictionary<uint, Object>(); private readonly ConcurrentQueue<uint> nextIds = new ConcurrentQueue<uint>(); private uint nextChestId; public uint AddChest(Object chestObject) { uint num = nextChestId++; chests.TryAdd(num, chestObject); return num; } public void PushNextChestId(uint chestId) { nextIds.Enqueue(chestId); } public uint? SetNextChest(Object chestObject) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown if (nextIds.TryDequeue(out var result)) { chests.TryAdd(result, chestObject); return result; } ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(40, 0, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("No chest id available for spawned chest."); } log.LogWarning(val); return null; } public Object? GetChest(uint chestId) { chests.TryGetValue(chestId, out var value); return value; } public void RemoveChest(uint chestId) { chests.TryRemove(chestId, out var _); } public KeyValuePair<uint, Object> GetChestByReference(OpenChest instance) { foreach (KeyValuePair<uint, Object> chest in chests) { if (chest.Value == (Object)(object)((Component)instance).gameObject) { return chest; } } return new KeyValuePair<uint, Object>(0u, null); } public void ResetForNextLevel() { nextChestId = 0u; nextIds.Clear(); chests.Clear(); } } public interface IEnemyManagerService { IEnumerable<(uint, uint)> ReTargetEnemies(uint oldTargetId, IEnumerable<uint> currentPlayersExcludingOldOneId); IEnumerable<EnemyModel> GetAllEnemiesDeltaAndUpdate(); uint AddSpawnedEnemy(Enemy enemy); void SetSpawnedEnemy(uint enemyId, Enemy enemy); Enemy GetEnemyById(uint id); KeyValuePair<uint, Enemy> GetEnemyByReference(Enemy enemy); void RemoveEnemyById(uint id); void ResetForNextLevel(); void ApplyRetargetedEnemies(IEnumerable<(uint, uint)> enemy_NewTargetids, IEnumerable<(uint, Rigidbody)> playerId_rigidbody); void InitializeSwitcher(TargetSwitcher switcher, EEnemyFlag enemyFlag, EEnemy enemyName); void AddReviverEnemy_Name(Enemy enemy, string netplayName); string GetReviverEnemy_Name(Enemy enemy); void RemoveReviverEnemy_Name(Enemy enemy); } internal class EnemyManagerService : IEnemyManagerService { private readonly ConcurrentDictionary<uint, Enemy> spawnedEnemies = new ConcurrentDictionary<uint, Enemy>(); private ConcurrentBag<EnemyModel> previousSpawnedEnemiesDelta = new ConcurrentBag<EnemyModel>(); private readonly ConcurrentDictionary<Enemy, string> reviverEnemies_NetplayNames = new ConcurrentDictionary<Enemy, string>(); private uint currentEnemyId; private const float POSITION_TRESHOLD = 0.1f; private const float YAW_TRESHOLD = 5f; private const ushort HP_TRESHOLD = 1; public IEnumerable<(uint, uint)> ReTargetEnemies(uint oldTargetId, IEnumerable<uint> currentPlayersAliveExcludingOldOneId) { List<(uint, uint)> list = new List<(uint, uint)>(); foreach (Enemy item in spawnedEnemies.Values.Where(delegate(Enemy enemy) { uint? num2 = DynamicData.For((object)enemy).Get<uint?>("targetId"); return (num2.HasValue && num2.Value == oldTargetId) ? true : false; })) { int index = Random.Range(0, currentPlayersAliveExcludingOldOneId.Count()); uint num = currentPlayersAliveExcludingOldOneId.ElementAt(index); DynamicData.For((object)item).Set("targetId", (object)num); uint key = GetEnemyByReference(item).Key; list.Add((key, num)); } return list; } public void ApplyRetargetedEnemies(IEnumerable<(uint, uint)> enemy_NewTargetids, IEnumerable<(uint, Rigidbody)> playerId_rigidbody) { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown bool flag = default(bool); foreach (var enemy_NewTargetid in enemy_NewTargetids) { uint item = enemy_NewTargetid.Item1; uint newTargetId = enemy_NewTargetid.Item2; Enemy enemyById = GetEnemyById(item); if ((Object)(object)enemyById != (Object)null) { Rigidbody item2 = playerId_rigidbody.FirstOrDefault(((uint, Rigidbody) pr) => pr.Item1 == newTargetId).Item2; if ((Object)(object)item2 != (Object)null) { DynamicData.For((object)enemyById).Set("targetId", (object)newTargetId); enemyById.target = item2; } continue; } ManualLogSource log = Plugin.Log; BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(58, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to retarget enemy "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(item); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" to new target "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(newTargetId); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" - enemy not found"); } log.LogWarning(val); } } public IEnumerable<EnemyModel> GetAllEnemiesDeltaAndUpdate() { List<EnemyModel> list = spawnedEnemies.Select((KeyValuePair<uint, Enemy> kv) => kv.Value.ToModel(kv.Key)).ToList(); ConcurrentBag<EnemyModel> concurrentBag; if (previousSpawnedEnemiesDelta.Count == 0) { concurrentBag = new ConcurrentBag<EnemyModel>(); foreach (EnemyModel item in list) { concurrentBag.Add(item); } previousSpawnedEnemiesDelta = concurrentBag; return list; } List<EnemyModel> list2 = new List<EnemyModel>(); foreach (EnemyModel current in list) { EnemyModel val = ((IEnumerable<EnemyModel>)previousSpawnedEnemiesDelta).FirstOrDefault((Func<EnemyModel, bool>)((EnemyModel e) => e.Id == current.Id)); if (val == null || HasDelta(val, current)) { list2.Add(current); } } concurrentBag = new ConcurrentBag<EnemyModel>(); foreach (EnemyModel item2 in list) { concurrentBag.Add(item2); } previousSpawnedEnemiesDelta = concurrentBag; return list2; } private bool HasDelta(EnemyModel previous, EnemyModel current) { //IL_0006: 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) float num = Vector3.Distance(Quantizer.Dequantize(previous.Position), Quantizer.Dequantize(current.Position)); float num2 = Mathf.Abs(Quantizer.DequantizeYaw(previous.Yaw) - Quantizer.DequantizeYaw(current.Yaw)); float num3 = Mathf.Abs(previous.Hp - current.Hp); if (!(num > 0.1f) && !(num2 > 5f)) { return num3 > 1f; } return true; } public Enemy GetEnemyById(uint id) { if (spawnedEnemies.TryGetValue(id, out var value)) { return value; } return null; } public uint AddSpawnedEnemy(Enemy enemy) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown currentEnemyId++; if (!spawnedEnemies.TryAdd(currentEnemyId, enemy)) { ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(56, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Attempted to add an enemy that already exists. EnemyId: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(currentEnemyId); } log.LogWarning(val); return 0u; } return currentEnemyId; } public void SetSpawnedEnemy(uint enemyId, Enemy enemy) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (!spawnedEnemies.TryAdd(enemyId, enemy)) { ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(56, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Attempted to add an enemy that already exists. EnemyId: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(enemyId); } log.LogWarning(val); } } public KeyValuePair<uint, Enemy> GetEnemyByReference(Enemy enemy) { return spawnedEnemies.FirstOrDefault((KeyValuePair<uint, Enemy> kv) => (Object)(object)kv.Value == (Object)(object)enemy); } public void RemoveEnemyById(uint id) { spawnedEnemies.TryRemove(id, out var _); } public void ResetForNextLevel() { currentEnemyId = 0u; spawnedEnemies.Clear(); previousSpawnedEnemiesDelta.Clear(); } public void InitializeSwitcher(TargetSwitcher switcher, EEnemyFlag enemyFlag, EEnemy enemyName) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Invalid comparison between Unknown and I4 //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Invalid comparison between Unknown and I4 if (enemyName - 44 <= 3) { switcher.UpdateSwitchIntervalRange(7f, 12f); switcher.UpdateSwitchMaxDistance(30f); } else if ((int)enemyFlag != 4) { if ((int)enemyFlag == 32) { switcher.UpdateSwitchIntervalRange(30f, 50f); switcher.UpdateSwitchMaxDistance(300f); } else { switcher.UpdateSwitchIntervalRange(40f, 60f); switcher.UpdateSwitchMaxDistance(50f); } } else { switcher.UpdateSwitchIntervalRange(20f, 40f); switcher.UpdateSwitchMaxDistance(300f); } } public void AddReviverEnemy_Name(Enemy enemy, string netplayName) { reviverEnemies_NetplayNames.TryAdd(enemy, netplayName); } public string GetReviverEnemy_Name(Enemy enemy) { if (reviverEnemies_NetplayNames.TryGetValue(enemy, out var value)) { return value; } return null; } public void RemoveReviverEnemy_Name(Enemy enemy) { reviverEnemies_NetplayNames.TryRemove(enemy, out var _); } } public static class EventManager { private static event Action<SpawnedObject> SpawnedObjectsEvents; private static event Action<SpawnedEnemy> SpawnedEnemyEvents; private static event Action<PlayerUpdate> PlayerUpdatesEvents; private static event Action<SelectedCharacter> SelectedCharacterEvents; private static event Action<IEnumerable<EnemyModel>> EnemiesUpdateEvents; private static event Action<EnemyDied> EnemyDiedEvents; private static event Action<AbstractSpawnedProjectile> SpawnedProjectileEvents; private static event Action<ProjectileDone> ProjectileDoneEvents; private static event Action<SpawnedPickupOrb> SpawnedPickupOrbEvents; private static event Action<SpawnedPickup> SpawnedPickupEvents; private static event Action<PickupApplied> PickupAppliedEvents; private static event Action<PickupFollowingPlayer> PickupFollowingPlayerEvents; private static event Action<SpawnedChest> SpawnedChestEvents; private static event Action<ChestOpened> ChestOpenedEvents; private static event Action<WeaponAdded> WeaponAddedEvents; private static event Action<InteractableUsed> InteractableUsedEvents; private static event Action<StartingChargingShrine> StartingChargingShrineEvents; private static event Action<StoppingChargingShrine> StoppingChargingShrineEvents; private static event Action<EnemyExploder> EnemyExploderEvents; private static event Action<EnemyDamaged> EnemyDamagedEvents; private static event Action<SpawnedEnemySpecialAttack> SpawnedEnemySpecialAttackEvents; private static event Action<StartingChargingPylon> StartingChargingPylonEvents; private static event Action<StoppingChargingPylon> StoppingChargingPylonEvents; private static event Action<FinalBossOrbSpawned> FinalBossOrbSpawnedEvents; private static event Action<IEnumerable<BossOrbModel>> FinalBossOrbsUpdateEvents; private static event Action<FinalBossOrbDestroyed> FinalBossOrbDestroyedEvents; private static event Action<StartedSwarmEvent> StartedSwarmEventEvents; private static event Action<GameOver> GameOverEvents; private static event Action<PlayerDied> PlayerDiedEvents; private static event Action<RetargetedEnemies> RetargetedEnemiesEvents; private static event Action<RunStarted> RunStartedEvents; private static event Action<PlayerDisconnected> PlayerDisconnectedEvents; private static event Action<IEnumerable<Projectile>> ProjectilesUpdateEvents; private static event Action<TomeAdded> TomeAddedEvents; private static event Action<LightningStrike> LightningStrikeEvents; private static event Action<TornadoesSpawned> TornadoesSpawnedEvents; private static event Action<StormStarted> StormStartedEvents; private static event Action<StormStopped> StormStoppedEvents; private static event Action<TumbleWeedSpawned> TumbleWeedSpawnedEvents; private static event Action<IEnumerable<TumbleWeedModel>> TumbleWeedsUpdateEvents; private static event Action<TumbleWeedDespawned> TumbleWeedDespawnedEvents; private static event Action<InteractableCharacterFightEnemySpawned> InteractableCharacterFightEnemySpawnedEvents; private static event Action<WantToStartFollowingPickup> WantToStartFollowingPickupEvents; private static event Action<ItemAdded> ItemAddedEvents; private static event Action<ItemRemoved> ItemRemovedEvents; private static event Action<WeaponToggled> WeaponToggledEvents; private static event Action GameStartedEvents; private static event Action PortalOpenedEvents; private static event Action<SpawnedObjectInCrypt> SpawnedObjectInCryptEvents; private static event Action<StartingChargingLamp> StartingChargingLampEvents; private static event Action<StoppingChargingLamp> StoppingChargingLampEvents; private static event Action<TimerStarted> TimerStartedEvents; private static event Action<HatChanged> HatChangedEvents; private static event Action<SpawnedReviver> SpawnedReviverEvents; private static event Action<PlayerRespawned> PlayerRespawnedEvents; public static void OnSpawnedObject(SpawnedObject spawnedObject) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedObjectsEvents?.Invoke(spawnedObject); }); } public static void SubscribeSpawnedObjectsEvents(Action<SpawnedObject> action) { SpawnedObjectsEvents += action; } public static void OnPlayerUpdate(PlayerUpdate playerUpdate) { MainThreadDispatcher.Enqueue(delegate { EventManager.PlayerUpdatesEvents?.Invoke(playerUpdate); }); } public static void SubscribePlayerUpdatesEvents(Action<PlayerUpdate> action) { PlayerUpdatesEvents += action; } public static void OnSpawnedEnemy(SpawnedEnemy spawnedEnemy) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedEnemyEvents?.Invoke(spawnedEnemy); }); } public static void SubscribeSpawnedEnemyEvents(Action<SpawnedEnemy> action) { SpawnedEnemyEvents += action; } public static void SubscribeSelectedCharacterEvents(Action<SelectedCharacter> action) { SelectedCharacterEvents += action; } public static void OnSelectedCharacter(SelectedCharacter selectedCharacter) { MainThreadDispatcher.Enqueue(delegate { EventManager.SelectedCharacterEvents?.Invoke(selectedCharacter); }); } public static void SubscribeEnemiesUpdateEvents(Action<IEnumerable<EnemyModel>> action) { EnemiesUpdateEvents += action; } public static void OnEnemiesUpdate(IEnumerable<EnemyModel> enemies) { MainThreadDispatcher.Enqueue(delegate { EventManager.EnemiesUpdateEvents?.Invoke(enemies); }); } public static void SubscribeEnemyDiedEvents(Action<EnemyDied> action) { EnemyDiedEvents += action; } public static void OnEnemyDied(EnemyDied enemyDied) { MainThreadDispatcher.Enqueue(delegate { EventManager.EnemyDiedEvents?.Invoke(enemyDied); }); } public static void SubscribeSpawnedProjectileEvents(Action<AbstractSpawnedProjectile> action) { SpawnedProjectileEvents += action; } public static void OnSpawnedProjectile(AbstractSpawnedProjectile spawnedProjectile) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedProjectileEvents?.Invoke(spawnedProjectile); }); } public static void SubscribeProjectileDoneEvents(Action<ProjectileDone> action) { ProjectileDoneEvents += action; } public static void OnProjectileDone(ProjectileDone projectileDone) { MainThreadDispatcher.Enqueue(delegate { EventManager.ProjectileDoneEvents?.Invoke(projectileDone); }); } public static void SubscribeSpawnedPickupOrbEvents(Action<SpawnedPickupOrb> action) { SpawnedPickupOrbEvents += action; } public static void OnSpawnedPickupOrb(SpawnedPickupOrb spawnedPickup) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedPickupOrbEvents?.Invoke(spawnedPickup); }); } public static void SubscribeSpawnedPickupEvents(Action<SpawnedPickup> action) { SpawnedPickupEvents += action; } public static void OnSpawnedPickup(SpawnedPickup spawnedPickup) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedPickupEvents?.Invoke(spawnedPickup); }); } public static void SubscribePickupAppliedEvents(Action<PickupApplied> action) { PickupAppliedEvents += action; } public static void OnPickupApplied(PickupApplied pickupApplied) { MainThreadDispatcher.Enqueue(delegate { EventManager.PickupAppliedEvents?.Invoke(pickupApplied); }); } public static void SubscribePickupFollowingPlayerEvents(Action<PickupFollowingPlayer> action) { PickupFollowingPlayerEvents += action; } public static void OnPickupFollowingPlayer(PickupFollowingPlayer pickupFollowingPlayer) { MainThreadDispatcher.Enqueue(delegate { EventManager.PickupFollowingPlayerEvents?.Invoke(pickupFollowingPlayer); }); } public static void SubscribeSpawnedChestEvents(Action<SpawnedChest> action) { SpawnedChestEvents += action; } public static void OnSpawnedChest(SpawnedChest spawnedChest) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedChestEvents?.Invoke(spawnedChest); }); } public static void SubscribeChestOpenedEvents(Action<ChestOpened> action) { ChestOpenedEvents += action; } public static void OnChestOpened(ChestOpened chestOpened) { MainThreadDispatcher.Enqueue(delegate { EventManager.ChestOpenedEvents?.Invoke(chestOpened); }); } public static void SubscribeWeaponAddedEvents(Action<WeaponAdded> action) { WeaponAddedEvents += action; } public static void OnWeaponAdded(WeaponAdded weaponAdded) { MainThreadDispatcher.Enqueue(delegate { EventManager.WeaponAddedEvents?.Invoke(weaponAdded); }); } public static void SubscribeInteractableUsedEvents(Action<InteractableUsed> action) { InteractableUsedEvents += action; } public static void OnInteractableUsed(InteractableUsed interactableUsed) { MainThreadDispatcher.Enqueue(delegate { EventManager.InteractableUsedEvents?.Invoke(interactableUsed); }); } public static void SubscribeStartingChargingShrineEvents(Action<StartingChargingShrine> action) { StartingChargingShrineEvents += action; } public static void OnStartingChargingShrine(StartingChargingShrine startingChargingShrine) { MainThreadDispatcher.Enqueue(delegate { EventManager.StartingChargingShrineEvents?.Invoke(startingChargingShrine); }); } public static void SubscribeStoppingChargingShrineEvents(Action<StoppingChargingShrine> action) { StoppingChargingShrineEvents += action; } public static void OnStoppingChargingShrine(StoppingChargingShrine stoppingChargingShrine) { MainThreadDispatcher.Enqueue(delegate { EventManager.StoppingChargingShrineEvents?.Invoke(stoppingChargingShrine); }); } public static void SubscribeEnemyExploderEvents(Action<EnemyExploder> action) { EnemyExploderEvents += action; } public static void OnEnemyExploder(EnemyExploder enemyExploder) { MainThreadDispatcher.Enqueue(delegate { EventManager.EnemyExploderEvents?.Invoke(enemyExploder); }); } public static void SubscribeEnemyDamagedEvents(Action<EnemyDamaged> action) { EnemyDamagedEvents += action; } public static void OnEnemyDamaged(EnemyDamaged enemyDamaged) { MainThreadDispatcher.Enqueue(delegate { EventManager.EnemyDamagedEvents?.Invoke(enemyDamaged); }); } public static void SubscribeSpawnedEnemySpecialAttackEvents(Action<SpawnedEnemySpecialAttack> action) { SpawnedEnemySpecialAttackEvents += action; } public static void OnSpawnedEnemySpecialAttack(SpawnedEnemySpecialAttack spawnedEnemySpecialAttack) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedEnemySpecialAttackEvents?.Invoke(spawnedEnemySpecialAttack); }); } public static void SubscribeStartingChargingPylonEvents(Action<StartingChargingPylon> action) { StartingChargingPylonEvents += action; } public static void OnStartingChargingPylon(StartingChargingPylon startingChargingPylon) { MainThreadDispatcher.Enqueue(delegate { EventManager.StartingChargingPylonEvents?.Invoke(startingChargingPylon); }); } public static void SubscribeStoppingChargingPylonEvents(Action<StoppingChargingPylon> action) { StoppingChargingPylonEvents += action; } public static void OnStoppingChargingPylon(StoppingChargingPylon stoppingChargingPylon) { MainThreadDispatcher.Enqueue(delegate { EventManager.StoppingChargingPylonEvents?.Invoke(stoppingChargingPylon); }); } public static void SubscribeFinalBossOrbSpawnedEvents(Action<FinalBossOrbSpawned> action) { FinalBossOrbSpawnedEvents += action; } public static void OnFinalBossOrbSpawned(FinalBossOrbSpawned finalBossOrbSpawned) { MainThreadDispatcher.Enqueue(delegate { EventManager.FinalBossOrbSpawnedEvents?.Invoke(finalBossOrbSpawned); }); } public static void SubscribeFinalBossOrbsUpdateEvents(Action<IEnumerable<BossOrbModel>> action) { FinalBossOrbsUpdateEvents += action; } public static void OnFinalBossOrbsUpdate(IEnumerable<BossOrbModel> bossOrbs) { MainThreadDispatcher.Enqueue(delegate { EventManager.FinalBossOrbsUpdateEvents?.Invoke(bossOrbs); }); } public static void SubscribeFinalBossOrbDestroyedEvents(Action<FinalBossOrbDestroyed> action) { FinalBossOrbDestroyedEvents += action; } public static void OnFinalBossOrbDestroyed(FinalBossOrbDestroyed finalBossOrbDestroyed) { MainThreadDispatcher.Enqueue(delegate { EventManager.FinalBossOrbDestroyedEvents?.Invoke(finalBossOrbDestroyed); }); } public static void SubscribeStartedSwarmEventEvents(Action<StartedSwarmEvent> action) { StartedSwarmEventEvents += action; } public static void OnStartedSwarmEvent(StartedSwarmEvent startedSwarmEvent) { MainThreadDispatcher.Enqueue(delegate { EventManager.StartedSwarmEventEvents?.Invoke(startedSwarmEvent); }); } public static void SubscribeGameOverEvents(Action<GameOver> action) { GameOverEvents += action; } public static void OnGameOver(GameOver gameOver) { MainThreadDispatcher.Enqueue(delegate { EventManager.GameOverEvents?.Invoke(gameOver); }); } public static void SubscribePlayerDiedEvents(Action<PlayerDied> action) { PlayerDiedEvents += action; } public static void OnPlayerDied(PlayerDied playerDied) { MainThreadDispatcher.Enqueue(delegate { EventManager.PlayerDiedEvents?.Invoke(playerDied); }); } public static void SubscribeRetargetedEnemiesEvents(Action<RetargetedEnemies> action) { RetargetedEnemiesEvents += action; } public static void OnRetargetedEnemies(RetargetedEnemies retargetedEnemies) { MainThreadDispatcher.Enqueue(delegate { EventManager.RetargetedEnemiesEvents?.Invoke(retargetedEnemies); }); } public static void SubscribeRunStartedEvents(Action<RunStarted> action) { RunStartedEvents += action; } public static void OnRunStarted(RunStarted runStarted) { MainThreadDispatcher.Enqueue(delegate { EventManager.RunStartedEvents?.Invoke(runStarted); }); } public static void SubscribePlayerDisconnectedEvents(Action<PlayerDisconnected> action) { PlayerDisconnectedEvents += action; } public static void OnPlayerDisconnected(PlayerDisconnected playerDisconnected) { MainThreadDispatcher.Enqueue(delegate { EventManager.PlayerDisconnectedEvents?.Invoke(playerDisconnected); }); } public static void SubscribeProjectilesUpdateEvents(Action<IEnumerable<Projectile>> action) { ProjectilesUpdateEvents += action; } public static void OnProjectilesUpdate(IEnumerable<Projectile> projectiles) { MainThreadDispatcher.Enqueue(delegate { EventManager.ProjectilesUpdateEvents?.Invoke(projectiles); }); } public static void SubscribeTomeAddedEvents(Action<TomeAdded> action) { TomeAddedEvents += action; } public static void OnTomeAdded(TomeAdded tomeAdded) { MainThreadDispatcher.Enqueue(delegate { EventManager.TomeAddedEvents?.Invoke(tomeAdded); }); } public static void SubscribeLightningStrikeEvents(Action<LightningStrike> action) { LightningStrikeEvents += action; } public static void OnLightningStrike(LightningStrike lightningStrike) { MainThreadDispatcher.Enqueue(delegate { EventManager.LightningStrikeEvents?.Invoke(lightningStrike); }); } public static void SubscribeTornadoesSpawnedEvents(Action<TornadoesSpawned> action) { TornadoesSpawnedEvents += action; } public static void OnTornadoesSpawned(TornadoesSpawned tornadoesSpawned) { MainThreadDispatcher.Enqueue(delegate { EventManager.TornadoesSpawnedEvents?.Invoke(tornadoesSpawned); }); } public static void SubscribeStormStartedEvents(Action<StormStarted> action) { StormStartedEvents += action; } public static void OnStormStarted(StormStarted stormStarted) { MainThreadDispatcher.Enqueue(delegate { EventManager.StormStartedEvents?.Invoke(stormStarted); }); } public static void SubscribeStormStoppedEvents(Action<StormStopped> action) { StormStoppedEvents += action; } public static void OnStormStopped(StormStopped stormStopped) { MainThreadDispatcher.Enqueue(delegate { EventManager.StormStoppedEvents?.Invoke(stormStopped); }); } public static void SubscribeTumbleWeedSpawnedEvents(Action<TumbleWeedSpawned> action) { TumbleWeedSpawnedEvents += action; } public static void OnTumbleWeedSpawned(TumbleWeedSpawned tumbleWeedSpawned) { MainThreadDispatcher.Enqueue(delegate { EventManager.TumbleWeedSpawnedEvents?.Invoke(tumbleWeedSpawned); }); } public static void SubscribeTumbleWeedsUpdateEvents(Action<IEnumerable<TumbleWeedModel>> action) { TumbleWeedsUpdateEvents += action; } public static void OnTumbleWeedsUpdate(IEnumerable<TumbleWeedModel> tumbleWeeds) { MainThreadDispatcher.Enqueue(delegate { EventManager.TumbleWeedsUpdateEvents?.Invoke(tumbleWeeds); }); } public static void SubscribeTumbleWeedDespawnedEvents(Action<TumbleWeedDespawned> action) { TumbleWeedDespawnedEvents += action; } public static void OnTumbleWeedDespawned(TumbleWeedDespawned tumbleWeedDespawned) { MainThreadDispatcher.Enqueue(delegate { EventManager.TumbleWeedDespawnedEvents?.Invoke(tumbleWeedDespawned); }); } public static void SubscribeInteractableCharacterFightEnemySpawnedEvents(Action<InteractableCharacterFightEnemySpawned> action) { InteractableCharacterFightEnemySpawnedEvents += action; } public static void OnInteractableCharacterFightEnemySpawned(InteractableCharacterFightEnemySpawned interactableCharacterFightEnemySpawned) { MainThreadDispatcher.Enqueue(delegate { EventManager.InteractableCharacterFightEnemySpawnedEvents?.Invoke(interactableCharacterFightEnemySpawned); }); } public static void SubscribeWantToStartFollowingPickupEvents(Action<WantToStartFollowingPickup> action) { WantToStartFollowingPickupEvents += action; } public static void OnWantToStartFollowingPickup(WantToStartFollowingPickup wantToStartFollowingPickup) { MainThreadDispatcher.Enqueue(delegate { EventManager.WantToStartFollowingPickupEvents?.Invoke(wantToStartFollowingPickup); }); } public static void SubscribeItemAddedEvents(Action<ItemAdded> action) { ItemAddedEvents += action; } public static void OnItemAdded(ItemAdded itemAdded) { MainThreadDispatcher.Enqueue(delegate { EventManager.ItemAddedEvents?.Invoke(itemAdded); }); } public static void SubscribeItemRemovedEvents(Action<ItemRemoved> action) { ItemRemovedEvents += action; } public static void OnItemRemoved(ItemRemoved itemRemoved) { MainThreadDispatcher.Enqueue(delegate { EventManager.ItemRemovedEvents?.Invoke(itemRemoved); }); } public static void SubscribeWeaponToggledEvents(Action<WeaponToggled> action) { WeaponToggledEvents += action; } public static void OnWeaponToggled(WeaponToggled weaponToggled) { MainThreadDispatcher.Enqueue(delegate { EventManager.WeaponToggledEvents?.Invoke(weaponToggled); }); } public static void SubscribeGameStartedEvents(Action action) { GameStartedEvents += action; } public static void OnGameStarted() { MainThreadDispatcher.Enqueue(delegate { EventManager.GameStartedEvents?.Invoke(); }); } public static void SubscribePortalOpenedEvents(Action action) { PortalOpenedEvents += action; } public static void OnPortalOpened() { MainThreadDispatcher.Enqueue(delegate { EventManager.PortalOpenedEvents?.Invoke(); }); } public static void SubscribeSpawnedObjectInCryptEvents(Action<SpawnedObjectInCrypt> action) { SpawnedObjectInCryptEvents += action; } public static void OnSpawnedObjectInCrypt(SpawnedObjectInCrypt spawnedObjectInCrypt) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedObjectInCryptEvents?.Invoke(spawnedObjectInCrypt); }); } public static void SubscribeStartingChargingLampEvents(Action<StartingChargingLamp> action) { StartingChargingLampEvents += action; } public static void OnStartingChargingLamp(StartingChargingLamp startingChargingLamp) { MainThreadDispatcher.Enqueue(delegate { EventManager.StartingChargingLampEvents?.Invoke(startingChargingLamp); }); } public static void SubscribeStoppingChargingLampEvents(Action<StoppingChargingLamp> action) { StoppingChargingLampEvents += action; } public static void OnStoppingChargingLamp(StoppingChargingLamp stoppingChargingLamp) { MainThreadDispatcher.Enqueue(delegate { EventManager.StoppingChargingLampEvents?.Invoke(stoppingChargingLamp); }); } public static void SubscribeTimerStartedEvents(Action<TimerStarted> action) { TimerStartedEvents += action; } public static void OnTimerStarted(TimerStarted timerStarted) { MainThreadDispatcher.Enqueue(delegate { EventManager.TimerStartedEvents?.Invoke(timerStarted); }); } public static void SubscribeHatChangedEvents(Action<HatChanged> action) { HatChangedEvents += action; } public static void OnHatChanged(HatChanged hatChanged) { MainThreadDispatcher.Enqueue(delegate { EventManager.HatChangedEvents?.Invoke(hatChanged); }); } public static void SubscribeSpawnedReviverEvents(Action<SpawnedReviver> action) { SpawnedReviverEvents += action; } public static void OnSpawnedReviver(SpawnedReviver spawnedReviver) { MainThreadDispatcher.Enqueue(delegate { EventManager.SpawnedReviverEvents?.Invoke(spawnedReviver); }); } public static void SubscribePlayerRespawnedEvents(Action<PlayerRespawned> action) { PlayerRespawnedEvents += action; } internal static void OnPlayerRespawned(PlayerRespawned playerRespawned) { MainThreadDispatcher.Enqueue(delegate { EventManager.PlayerRespawnedEvents?.Invoke(playerRespawned); }); } } public interface IFinalBossOrbManagerService { void QueueNextTarget(uint targetId); Tuple<uint, uint> PeakNextTarget(); Tuple<uint, uint> GetNextTargetAndOrbId(); void SetOrbTarget(uint targetId, GameObject target, uint orbId); uint? RemoveOrbTarget(GameObject go); bool ContainsOrbTarget(GameObject go); void Reset(); IEnumerable<BossOrbModel> GetAllOrbs(); GameObject GetOrbById(uint id); uint? GetTargetIdByReference(GameObject go); void ClearQueueNextTarget(); } internal class FinalBossOrbManagerService : IFinalBossOrbManagerService { private class OrbInfo { public uint OrbId { get; set; } public uint TargetId { get; set; } public GameObject GameObject { get; set; } } private readonly ConcurrentDictionary<uint, OrbInfo> _orbsById = new ConcurrentDictionary<uint, OrbInfo>(); private readonly ConcurrentQueue<uint> _queuedTargetIds = new ConcurrentQueue<uint>(); private readonly ConcurrentQueue<(uint targetId, uint orbId)> _pendingOrbCreation = new ConcurrentQueue<(uint, uint)>(); private uint _nextOrbId; public void QueueNextTarget(uint targetId) { _queuedTargetIds.Enqueue(targetId); } public void ClearQueueNextTarget() { _queuedTargetIds.Clear(); } public Tuple<uint, uint> PeakNextTarget() { if (!_queuedTargetIds.TryPeek(out var result)) { return null; } uint item = ++_nextOrbId; _pendingOrbCreation.Enqueue((result, item)); return Tuple.Create(result, item); } public Tuple<uint, uint> GetNextTargetAndOrbId() { if (_pendingOrbCreation.TryDequeue(out (uint, uint) result)) { return Tuple.Create(result.Item1, result.Item2); } return null; } public void SetOrbTarget(uint targetId, GameObject target, uint orbId) { _orbsById[orbId] = new OrbInfo { OrbId = orbId, TargetId = targetId, GameObject = target }; } public void Reset() { _orbsById.Clear(); _queuedTargetIds.Clear(); _pendingOrbCreation.Clear(); _nextOrbId = 0u; } public bool ContainsOrbTarget(GameObject go) { return _orbsById.Values.Any((OrbInfo orb) => (Object)(object)orb.GameObject == (Object)(object)go); } public IEnumerable<BossOrbModel> GetAllOrbs() { return _orbsById.Values.Where((OrbInfo orb) => (Object)(object)orb.GameObject != (Object)null).Select((Func<OrbInfo, BossOrbModel>)((OrbInfo orb) => new BossOrbModel { Id = orb.OrbId, Position = Quantizer.Quantize(orb.GameObject.transform.position) })); } public GameObject GetOrbById(uint id) { if (!_orbsById.TryGetValue(id, out var value)) { return null; } return value.GameObject; } public uint? RemoveOrbTarget(GameObject go) { KeyValuePair<uint, OrbInfo> keyValuePair = _orbsById.FirstOrDefault((KeyValuePair<uint, OrbInfo> kv) => (Object)(object)kv.Value.GameObject == (Object)(object)go); if (keyValuePair.Value == null) { return null; } _orbsById.TryRemove(keyValuePair.Key, out var _); return keyValuePair.Key; } public uint? GetTargetIdByReference(GameObject go) { return _orbsById.Values.FirstOrDefault((OrbInfo o) => (Object)(object)o.GameObject == (Object)(object)go)?.TargetId; } } public interface IGameBalanceService { float GetCreditsTimerMultiplier(); float GetEnemyHpMultiplier(EEnemyFlag enemyFlag); float GetFreeChestSpawnRateMultiplier(); int GetPickupXpValue(); void Initialize(); int GetMaxEnemiesSpawnable(); float GetBossLampRequiredCharge(); } public enum DifficultyLevel { None, Duo, Trio, Quad, Five, Six } internal class GameBalanceService : IGameBalanceService { [CompilerGenerated] private IPlayerManagerService <playerManagerService>P; private const float hpScalingPerAdditionalPlayer = 0.1f; private const float baseBossLampInitialChargeTimeSeconds = 3f; private int PlayersCount => <playerManagerService>P.GetAllPlayersAlive().Count(); private static int StageIndex { get { RunConfig runConfig = MapController.runConfig; if (runConfig == null) { return 0; } return ((Il2CppArrayBase<StageData>)(object)runConfig.mapData.stages).IndexOf(MapController.currentStage); } } public GameBalanceService(IPlayerManagerService playerManagerService) { <playerManagerService>P = playerManagerService; base..ctor(); } public int GetMaxEnemiesSpawnable() { if (GameManager.Instance.IsFinalSwarm()) { return 400; } DifficultyLevel difficultyLevelByPlayers = GetDifficultyLevelByPlayers(); if ((uint)(difficultyLevelByPlayers - 3) <= 2u) { return 600; } return 500; } public float GetCreditsTimerMultiplier() { return GetDifficultyLevelByPlayers() switch { DifficultyLevel.Duo => 1.02f, DifficultyLevel.Trio => 1.05f, DifficultyLevel.Quad => 1.1f, DifficultyLevel.Five => 1.15f, DifficultyLevel.Six => 1.3f, _ => 1f, } * StageIndex switch { 0 => 1f, 1 => 1.1f, 2 => 1.2f, _ => 1f, }; } public float GetEnemyHpMultiplier(EEnemyFlag enemyFlag) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 float num; if ((int)enemyFlag <= 8) { if ((int)enemyFlag != 1) { if ((int)enemyFlag != 2) { if ((int)enemyFlag != 8) { goto IL_0053; } num = 1.15f; } else { num = 1.2f; } } else { num = 1.05f; } } else if ((int)enemyFlag != 16) { if ((int)enemyFlag != 32) { if ((int)enemyFlag != 54) { goto IL_0053; } num = 1.1f; } else { num = 1.25f; } } else { num = 1.1f; } goto IL_0059; IL_0059: float num2 = num; float num3 = 1f + (float)(PlayersCount - 1) * 0.1f; return num2 * num3 * StageIndex switch { 0 => 1f, 1 => 1.1f, 2 => 1.2f, _ => 1f, }; IL_0053: num = 1f; goto IL_0059; } public float GetFreeChestSpawnRateMultiplier() { return GetDifficultyLevelByPlayers() switch { DifficultyLevel.Duo => 1.5f, DifficultyLevel.Trio => 1.8f, DifficultyLevel.Quad => 2f, DifficultyLevel.Five => 2.2f, DifficultyLevel.Six => 2.4f, _ => 1f, } * StageIndex switch { 0 => 1f, 1 => 1.1f, 2 => 1.15f, _ => 1f, }; } public int GetPickupXpValue() { switch (PlayersCount) { case 1: return 1; case 2: case 3: case 4: return 2; case 5: return 3; default: return 1; } } public void Initialize() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Expected O, but got Unknown float creditsTimerMultiplier = GetCreditsTimerMultiplier(); float enemyHpMultiplier = GetEnemyHpMultiplier((EEnemyFlag)0); float freeChestSpawnRateMultiplier = GetFreeChestSpawnRateMultiplier(); int pickupXpValue = GetPickupXpValue(); ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(60, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[GameBalance] Initialized for "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(PlayersCount); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" players, Stage "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(StageIndex + 1); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", Difficulty: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<DifficultyLevel>(GetDifficultyLevelByPlayers()); } log.LogInfo(val); ManualLogSource log2 = Plugin.Log; val = new BepInExInfoLogInterpolatedStringHandler(41, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[GameBalance] Credits Timer Multiplier: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(creditsTimerMultiplier, "F2"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("x"); } log2.LogInfo(val); ManualLogSource log3 = Plugin.Log; val = new BepInExInfoLogInterpolatedStringHandler(47, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[GameBalance] Basic Enemy HP Base Multiplier: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(enemyHpMultiplier, "F2"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("x"); } log3.LogInfo(val); ManualLogSource log4 = Plugin.Log; val = new BepInExInfoLogInterpolatedStringHandler(49, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[GameBalance] Free Chest Spawn Rate Multiplier: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(freeChestSpawnRateMultiplier, "F2"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("x"); } log4.LogInfo(val); ManualLogSource log5 = Plugin.Log; val = new BepInExInfoLogInterpolatedStringHandler(24, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[GameBalance] XP Value: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(pickupXpValue); } log5.LogInfo(val); } private DifficultyLevel GetDifficultyLevelByPlayers() { return PlayersCount switch { 2 => DifficultyLevel.Duo, 3 => DifficultyLevel.Trio, 4 => DifficultyLevel.Quad, 5 => DifficultyLevel.Five, 6 => DifficultyLevel.Six, _ => DifficultyLevel.None, }; } public float GetBossLampRequiredCharge() { return GetDifficultyLevelByPlayers() switch { DifficultyLevel.Duo => 6f, DifficultyLevel.Trio => 7.5f, DifficultyLevel.Quad => 9f, DifficultyLevel.Five => 10.5f, DifficultyLevel.Six => 12f, _ => 3f, }; } } public interface ILocalizationService { string GetCustomLocalizedString(string category, string key); void EnqueueNextLocalizedDescription(IEnumerable<string> descriptionArgs); string GetNextCustomLocalizedDescription(string category, string key); } public class LocalizationService : ILocalizationService { public readonly Dictionary<(string, string), string> LocalizationOverrides = new Dictionary<(string, string), string> { { ("MegabonkTogether", "MatchSuccess"), "Match" }, { ("MegabonkTogether", "MatchSuccessDesc"), "Joined as {0} a lobby of {1} players successfully!" }, { ("MegabonkTogether", "PlayerDisconnected"), "Disconnected" }, { ("MegabonkTogether", "PlayerDisconnected_Description"), "Player {0} disconnected" }, { ("MegabonkTogether", "AllPlayerDisconnected"), "Disconnected" }, { ("MegabonkTogether", "AllPlayerDisconnected_Description"), "All players left!" }, { ("MegabonkTogether", "HostDisconnected"), "Disconnected" }, { ("MegabonkTogether", "HostDisconnected_Description"), "Host left!" }, { ("MegabonkTogether", "ClientDisconnected"), "Disconnected" }, { ("MegabonkTogether", "ClientDisconnected_Description"), "Client disconnected" }, { ("MegabonkTogether", "FriendliesHostSuccess"), "Friendlies" }, { ("MegabonkTogether", "FriendliesHostSuccessDesc"), "Hosting a friendly lobby" }, { ("MegabonkTogether", "FriendliesClientSuccess"), "Friendlies" }, { ("MegabonkTogether", "FriendliesClientSuccessDesc"), "Joined {0} lobby" }, { ("MegabonkTogether", "FriendliesClientJoinSuccess"), "Friendlies" }, { ("MegabonkTogether", "FriendliesClientJoinSuccessDesc"), "{0} joined " } }; private readonly Queue<IEnumerable<string>> NextLocalizedDescription = new Queue<IEnumerable<string>>(); public string GetCustomLocalizedString(string category, string key) { if (LocalizationOverrides.TryGetValue((category, key), out var value)) { return value; } return string.Empty; } public void EnqueueNextLocalizedDescription(IEnumerable<string> descriptionArgs) { NextLocalizedDescription.Enqueue(descriptionArgs); } public string GetNextCustomLocalizedDescription(string category, string key) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown string customLocalizedString = GetCustomLocalizedString(category, key); if (string.IsNullOrEmpty(customLocalizedString)) { return ""; } if (NextLocalizedDescription.Count > 0) { IEnumerable<string> source = NextLocalizedDescription.Dequeue(); try { object[] args = source.ToArray(); return string.Format(customLocalizedString, args); } catch (Exception ex) { ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(35, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error formatting localized string: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } log.LogError(val); return customLocalizedString; } } return customLocalizedString; } } public interface IPickupManagerService { IEnumerable<PickupModel> GetAllPickups(); IEnumerable<(uint, Pickup)> GetAllPickupXp(); uint AddSpawnedPickup(Pickup pickup); void SetSpawnedPickup(uint pickupId, Pickup pickup); Pickup GetPickupById(uint id); KeyValuePair<uint, Pickup> GetPickupByReference(Pickup pickup); Pickup GetSpawnedPickupById(uint id); void RemoveSpawnedPickupById(uint id); void ResetForNextLevel(); } internal class PickupManagerService : IPickupManagerService { private readonly ConcurrentDictionary<uint, Pickup> spawnedPickups = new ConcurrentDictionary<uint, Pickup>(); private uint currentPickupId; public IEnumerable<PickupModel> GetAllPickups() { return spawnedPickups.Select((KeyValuePair<uint, Pickup> kv) => kv.Value.ToModel(kv.Key)).ToList(); } public Pickup GetPickupById(uint id) { if (spawnedPickups.TryGetValue(id, out var value)) { return value; } return null; } public uint AddSpawnedPickup(Pickup pickup) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown currentPickupId++; if (!spawnedPickups.TryAdd(currentPickupId, pickup)) { ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(58, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Attempted to add an pickup that already exists. PickupId: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(currentPickupId); } log.LogWarning(val); return 0u; } return currentPickupId; } public void SetSpawnedPickup(uint pickupId, Pickup pickup) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (!spawnedPickups.TryAdd(pickupId, pickup)) { ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(58, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Attempted to add an pickup that already exists. PickupId: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(pickupId); } log.LogWarning(val); } } public KeyValuePair<uint, Pickup> GetPickupByReference(Pickup pickup) { return spawnedPickups.FirstOrDefault((KeyValuePair<uint, Pickup> kv) => (Object)(object)kv.Value == (Object)(object)pickup); } public Pickup GetSpawnedPickupById(uint id) { if (spawnedPickups.TryGetValue(id, out var value)) { return value; } return null; } public void RemoveSpawnedPickupById(uint id) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (spawnedPickups.TryRemove(id, out var value) && (int)value.ePickup == 0) { PickupManager.Instance.xpList.RemovePickup(value); } } public IEnumerable<(uint, Pickup)> GetAllPickupXp() { return from p in spawnedPickups.ToList() where (int)p.Value.ePickup == 0 select (p.Key, p.Value); } public void ResetForNextLevel() { currentPickupId = 0u; spawnedPickups.Clear(); } } public interface IPlayerManagerService { PlayerUpdate? GetLocalPlayerUpdate(); IEnumerable<Player> GetAllNonHostPlayers(); IEnumerable<Player> GetAllPlayers(); IEnumerable<Player> GetAllPlayersAlive(); IEnumerable<Player> GetAllPlayersExceptLocal(); IEnumerable<NetPlayer> GetAllSpawnedNetPlayers(); bool AddPlayer(uint connectionId, bool isHost, bool isSelf, string name = "Player"); Player GetPlayer(uint connectionId); void UpdatePlayer(Player player); Player? GetHost(); Player? GetLocalPlayer(); void SpawnPlayers(); NetPlayer GetRandomNetPlayer(); void AddProjectileToSpawn(uint connectionId); void AddGetNetplayerPosition(uint connectionId); void AddGetNetplayerPositionRequest(uint connectionId); bool TryGetProjectileToSpawn(out uint connectionId); bool TryGetGetNetplayerPosition(out uint connectionId); uint? PeakNetplayerPosition(); uint? PeakNetplayerPositionRequest(); void UnqueueNetplayerPositionRequest(); NetPlayer GetNetPlayerByNetplayId(uint connectionId); NetPlayer GetNetPlayerByWeapon(WeaponBase weapon); void ResetForNextLevel(); void AddPlayerInventory(uint connectionId, PlayerInventory inventory); PlayerInventory GetPlayerInventory(uint connectionId); bool IsGameOver(); uint? GetRandomPlayerAliveConnectionId(); IEnumerable<(uint, Rigidbody)> GetConnectionIdsAndRigidBodies(); void Disconnect(uint connectionId); void Reset(); void OnSelectedCharacterSet(); bool HasSelectedCharacter(); bool IsLocalConnectionId(uint ownerId); bool IsRemoteConnectionId(uint value); void SetSeed(int seed); int GetSeed(); bool IsRemotePlayerHealth(PlayerHealth instance); bool IsANetPlayerAbility(PassiveAbilityBullseye instance); bool IsRemoteItem(ItemGhost instance); void RemovePlayer(uint clientConnectionId); } public class PlayerManagerService : IPlayerManagerService { private readonly ConcurrentDictionary<uint, Player> players = new ConcurrentDictionary<uint, Player>(); private readonly ManualLogSource logger; private ConcurrentDictionary<uint, GameObject> spawnedPlayers = new ConcurrentDictionary<uint, GameObject>(); private uint localConnectionId; private bool isLocalPlayerSet; private bool hasSelectedCharacter; private int seed; private ConcurrentQueue<uint> projectileToSpawnQueue = new ConcurrentQueue<uint>(); private ConcurrentQueue<uint> getNetplayerPositionQueue = new ConcurrentQueue<uint>(); private ConcurrentQueue<uint> getNetplayerPositionRequestQueue = new ConcurrentQueue<uint>(); private ConcurrentDictionary<uint, PlayerInventory> playerInventories = new ConcurrentDictionary<uint, PlayerInventory>(); public PlayerManagerService(ManualLogSource logger) { this.logger = logger; } public bool IsLocalConnectionId(uint ownerId) { return ownerId == localConnectionId; } public bool IsRemoteConnectionId(uint value) { return value != localConnectionId; } public bool IsRemotePlayerHealth(PlayerHealth instance) { MyPlayer player = GameManager.Instance.player; if ((Object)(object)player == (Object)null || player.inventory == null) { logger.LogWarning((object)"Local player or inventory is null when checking remote PlayerHealth."); return false; } return instance != player.inventory.playerHealth; } public IEnumerable<Player> GetAllNonHostPlayers() { return (from p in players where !p.Value.IsHost select p.Value).ToList(); } public IEnumerable<Player> GetAllPlayers() { return new <>z__ReadOnlyArray<Player>(players.Values.ToArray()); } public IEnumerable<Player> GetAllPlayersAlive() { List<Player> list = new List<Player>(); list.AddRange(from p in players where p.Value.Hp != 0 select p.Value); return new <>z__ReadOnlyList<Player>(list); } public uint? GetRandomPlayerAliveConnectionId() { List<KeyValuePair<uint, Player>> list = players.Where((KeyValuePair<uint, Player> p) => p.Value.Hp != 0).ToList(); if (list.Count == 0) { logger.LogWarning((object)"No alive players available to select."); return null; } int index = Random.Range(0, list.Count); return list.ElementAt(index).Value.ConnectionId; } public IEnumerable<(uint, Rigidbody)> GetConnectionIdsAndRigidBodies() { List<(uint, Rigidbody)> list = new List<(uint, Rigidbody)>(); foreach (KeyValuePair<uint, GameObject> spawnedPlayer in spawnedPlayers) { NetPlayer component = spawnedPlayer.Value.GetComponent<NetPlayer>(); if ((Object)(object)component != (Object)null) { Rigidbody rigidbody = component.Rigidbody; list.Add((component.ConnectionId, rigidbody)); } } Player localPlayer = GetLocalPlayer(); if (localPlayer != null) { Rigidbody component2 = ((Component)GameManager.Instance.player).gameObject.GetComponent<Rigidbody>(); if ((Object)(object)component2 != (Object)null) { list.Add((localPlayer.ConnectionId, component2)); } } return list; } public void OnSelectedCharacterSet() { hasSelectedCharacter = true; } public bool HasSelectedCharacter() { return hasSelectedCharacter; } public bool AddPlayer(uint connectionId, bool isHost, bool isSelf, string name = "Player") { //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_0013: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown Player value = new Player { ConnectionId = connectionId, IsHost = isHost, Name = (isSelf ? ModConfig.PlayerName.Value : name) }; if (!players.TryAdd(connectionId, value)) { return false; } ManualLogSource obj = logger; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(29, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Player added. Total players: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(players.Count); } obj.LogInfo(val); if (isSelf) { localConnectionId = connectionId; isLocalPlayerSet = true; } return true; } public void RemovePlayer(uint connectionId) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown if (!players.Remove(connectionId, out var _)) { logger.LogWarning((object)"Attempted to remove a player that does not exist."); return; } GameManager instance = GameManager.Instance; if ((Object)(object)((instance != null) ? instance.player : null) == (Object)null) { return; } if ((Object)(object)GetNetPlayerByNetplayId(connectionId) == (Object)null) { ManualLogSource obj = logger; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(56, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("No NetPlayer found for ConnectionId: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(connectionId); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" during disconnect."); } obj.LogWarning(val); } else { spawnedPlayers.TryRemove(connectionId, out var value2); Object.Destroy((Object)(object)value2); CleanQueue(projectileToSpawnQueue, connectionId); CleanQueue(getNetplayerPositionQueue, connectionId); CleanQueue(getNetplayerPositionRequestQueue, connectionId); } } private static void CleanQueue(ConcurrentQueue<uint> queue, uint connectionId) { List<uint> list = queue.Where((uint id) => id != connectionId).ToList(); queue.Clear(); foreach (uint item in list) { queue.Enqueue(item); } } public Player GetPlayer(uint connectionId) { if (players.TryGetValue(connectionId, out var value)) { return value; } logger.LogWarning((object)("Player not found for ConnectionId: " + connectionId)); return null; } public void UpdatePlayer(Player player) { if (!players.Remove(player.ConnectionId, out var _)) { logger.LogWarning((object)"Attempted to update a player that does not exist."); } else { players.TryAdd(player.ConnectionId, player); } } public Player GetHost() { return players.FirstOrDefault((KeyValuePair<uint, Player> p) => p.Value.IsHost).Value; } public void SpawnPlayers() { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown if (spawnedPlayers.Count > 0) { logger.LogWarning((object)"Players have already been spawned."); return; } foreach (Player item in GetAllPlayersExceptLocal()) { GameObject val = new GameObject($"NetPlayer-{item.ConnectionId}"); NetPlayer netPlayer = val.AddComponent<NetPlayer>(); spawnedPlayers.TryAdd(item.ConnectionId, val); netPlayer.Initialize((ECharacter)item.Character, item.ConnectionId, item.Skin); } } public IEnumerable<NetPlayer> GetAllSpawnedNetPlayers() { return spawnedPlayers.Select((KeyValuePair<uint, GameObject> p) => p.Value.GetComponent<NetPlayer>()).ToList(); } public NetPlayer GetRandomNetPlayer() { if (spawnedPlayers.Count == 0) { logger.LogWarning((object)"No spawned players available to select."); return null; } int index = Random.Range(0, spawnedPlayers.Count); return spawnedPlayers.ElementAt(index).Value.GetComponent<NetPlayer>(); } public void AddProjectileToSpawn(uint connectionId) { projectileToSpawnQueue.Enqueue(connectionId); } public bool TryGetProjectileToSpawn(out uint connectionId) { return projectileToSpawnQueue.TryDequeue(out connectionId); } public NetPlayer GetNetPlayerByNetplayId(uint connectionId) { return (from p in spawnedPlayers where (Object)(object)p.Value != (Object)null && (Object)(object)p.Value.GetComponent<NetPlayer>() != (Object)null select p.Value.GetComponent<NetPlayer>()).FirstOrDefault((NetPlayer np) => np.ConnectionId == connectionId); } public void AddGetNetplayerPosition(uint connectionId) { getNetplayerPositionQueue.Enqueue(connectionId); } public uint? PeakNetplayerPosition() { if (getNetplayerPositionQueue.TryPeek(out var result)) { return result; } return null; } public bool TryGetGetNetplayerPosition(out uint connectionId) { return getNetplayerPositionQueue.TryDequeue(out connectionId); } public PlayerUpdate? GetLocalPlayerUpdate() { //IL_003a: 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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Invalid comparison between Unknown and I4 //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: 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_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: 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_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Expected O, but got Unknown //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_011b: 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_0143: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected O, but got Unknown //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) MyPlayer player = GameManager.Instance.player; PlayerCamera playerCamera = GameManager.Instance.playerCamera; if ((Object)(object)player == (Object)null || (Object)(object)playerCamera == (Object)null || player.inventory == null) { return null; } Vector3 defaultPos = default(Vector3); ((Vector3)(ref defaultPos))..ctor(((Component)player).transform.position.x, ((Component)player).transform.position.y - Plugin.PLAYER_FEET_OFFSET_Y, ((Component)player).transform.position.z); if ((int)player.character == 13) { HoverAnimations component = ((Component)player).GetComponent<HoverAnimations>(); if ((Object)(object)component != (Object)null) { defaultPos = component.defaultPos; } } AnimatorState animatorState = player.GetAnimatorState(); Vector2 position = default(Vector2); ((Vector2)(ref position))..ctor(MyInputManager.GetPlayer().GetAxis("Move Horizontal"), MyInputManager.GetPlayer().GetAxis("Move Vertical")); return new PlayerUpdate { Position = defaultPos.ToNumericsVector3(), MovementState = new MovementState { AxisInput = Quantizer.Quantize(position), CameraForward = Quantizer.Quantize(((Component)playerCamera).transform.forward), CameraRight = Quantizer.Quantize(((Component)playerCamera).transform.right) }, AnimatorState = animatorState, ConnectionId = localConnectionId, Hp = (uint)Math.Max(0, player.inventory.playerHealth.hp), MaxHp = (uint)Math.Max(0, player.inventory.playerHealth.maxHp), Shield = (uint)Math.Max(0f, player.inventory.playerHealth.shield), MaxShield = (uint)Math.Max(0f, player.inventory.playerHealth.maxShield), Inventory = player.inventory.ToInventoryInfos(), Name = ModConfig.PlayerName.Value }; } public Player? GetLocalPlayer() { if (!isLocalPlayerSet) { logger.LogWarning((object)"Local connection ID is not set."); return null; } return GetPlayer(localConnectionId); } public IEnumerable<Player> GetAllPlayersExceptLocal() { return (from p in players where p.Key != localConnectionId select p.Value).ToList(); } public NetPlayer GetNetPlayerByWeapon(WeaponBase weapon) { return spawnedPlayers.Select((KeyValuePair<uint, GameObject> p) => p.Value.GetComponent<NetPlayer>()).FirstOrDefault((NetPlayer np) => np.Inventory.weaponInventory.weapons.ContainsValue(weapon)); } public void UnqueueNetplayerPositionRequest() { getNetplayerPositionRequestQueue.TryDequeue(out var _); } public void AddGetNetplayerPositionRequest(uint connectionId) { getNetplayerPositionRequestQueue.Enqueue(connectionId); } public uint? PeakNetplayerPositionRequest() { if (getNetplayerPositionRequestQueue.TryPeek(out var result)) { return result; } return null; } public void ResetForNextLevel() { players.Values.ToList().ForEach(delegate(Player p) { p.IsReady = false; }); spawnedPlayers.ToList().ForEach(delegate(KeyValuePair<uint, GameObject> p) { p.Value.gameObject.SetActive(false); }); spawnedPlayers.Clear(); projectileToSpawnQueue.Clear(); getNetplayerPositionQueue.Clear(); getNetplayerPositionRequestQueue.Clear(); } public void AddPlayerInventory(uint connectionId, PlayerInventory inventory) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown if (!playerInventories.TryAdd(connectionId, inventory)) { ManualLogSource obj = logger; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(48, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to add PlayerInventory for ConnectionId: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(connectionId);
MegabonkTogether/System.Diagnostics.EventLog.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Security.Principal; using FxResources.System.Diagnostics.EventLog; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: SupportedOSPlatform("windows")] [assembly: AssemblyDefaultAlias("System.Diagnostics.EventLog")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("NotSupported", "True")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides the System.Diagnostics.EventLog class, which allows the applications to use the windows event log service.\r\n\r\nCommonly Used Types:\r\nSystem.Diagnostics.EventLog")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Diagnostics.EventLog")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] namespace FxResources.System.Diagnostics.EventLog { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string BadLogName => GetResourceString("BadLogName"); internal static string CannotDeleteEqualSource => GetResourceString("CannotDeleteEqualSource"); internal static string CantMonitorEventLog => GetResourceString("CantMonitorEventLog"); internal static string CantOpenLog => GetResourceString("CantOpenLog"); internal static string CantOpenLogAccess => GetResourceString("CantOpenLogAccess"); internal static string CantReadLogEntryAt => GetResourceString("CantReadLogEntryAt"); internal static string CantRetrieveEntries => GetResourceString("CantRetrieveEntries"); internal static string DuplicateLogName => GetResourceString("DuplicateLogName"); internal static string EventID => GetResourceString("EventID"); internal static string IndexOutOfBounds => GetResourceString("IndexOutOfBounds"); internal static string InitTwice => GetResourceString("InitTwice"); internal static string InvalidCustomerLogName => GetResourceString("InvalidCustomerLogName"); internal static string InvalidParameter => GetResourceString("InvalidParameter"); internal static string InvalidParameterFormat => GetResourceString("InvalidParameterFormat"); internal static string LocalLogAlreadyExistsAsSource => GetResourceString("LocalLogAlreadyExistsAsSource"); internal static string LocalRegKeyMissing => GetResourceString("LocalRegKeyMissing"); internal static string LocalSourceAlreadyExists => GetResourceString("LocalSourceAlreadyExists"); internal static string LocalSourceNotRegistered => GetResourceString("LocalSourceNotRegistered"); internal static string LogDoesNotExists => GetResourceString("LogDoesNotExists"); internal static string LogEntryTooLong => GetResourceString("LogEntryTooLong"); internal static string LogSourceMismatch => GetResourceString("LogSourceMismatch"); internal static string MaximumKilobytesOutOfRange => GetResourceString("MaximumKilobytesOutOfRange"); internal static string MessageNotFormatted => GetResourceString("MessageNotFormatted"); internal static string MissingLog => GetResourceString("MissingLog"); internal static string MissingLogProperty => GetResourceString("MissingLogProperty"); internal static string MissingParameter => GetResourceString("MissingParameter"); internal static string NeedSourceToOpen => GetResourceString("NeedSourceToOpen"); internal static string NeedSourceToWrite => GetResourceString("NeedSourceToWrite"); internal static string NoCurrentEntry => GetResourceString("NoCurrentEntry"); internal static string NoLogName => GetResourceString("NoLogName"); internal static string ParameterTooLong => GetResourceString("ParameterTooLong"); internal static string PlatformNotSupported_EventLog => GetResourceString("PlatformNotSupported_EventLog"); internal static string RegKeyMissing => GetResourceString("RegKeyMissing"); internal static string RegKeyMissingShort => GetResourceString("RegKeyMissingShort"); internal static string RegKeyNoAccess => GetResourceString("RegKeyNoAccess"); internal static string RentionDaysOutOfRange => GetResourceString("RentionDaysOutOfRange"); internal static string SomeLogsInaccessible => GetResourceString("SomeLogsInaccessible"); internal static string SomeLogsInaccessibleToCreate => GetResourceString("SomeLogsInaccessibleToCreate"); internal static string SourceAlreadyExists => GetResourceString("SourceAlreadyExists"); internal static string SourceNotRegistered => GetResourceString("SourceNotRegistered"); internal static string TooManyReplacementStrings => GetResourceString("TooManyReplacementStrings"); internal static string LogAlreadyExistsAsSource => GetResourceString("LogAlreadyExistsAsSource"); internal static string NotSupported_IONonFileDevices => GetResourceString("NotSupported_IONonFileDevices"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics { public class EntryWrittenEventArgs : EventArgs { public EventLogEntry Entry { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EntryWrittenEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EntryWrittenEventArgs(EventLogEntry entry) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public delegate void EntryWrittenEventHandler(object sender, EntryWrittenEventArgs e); public class EventInstance { public int CategoryId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogEntryType EntryType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long InstanceId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventInstance(long instanceId, int categoryId) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventInstance(long instanceId, int categoryId, EventLogEntryType entryType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [DefaultEvent("EntryWritten")] public class EventLog : Component, ISupportInitialize { [Browsable(false)] [DefaultValue(false)] public bool EnableRaisingEvents { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public EventLogEntryCollection Entries { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [DefaultValue("")] [ReadOnly(true)] [SettingsBindable(true)] public string Log { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [Browsable(false)] public string LogDisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [DefaultValue(".")] [ReadOnly(true)] [SettingsBindable(true)] public string MachineName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public long MaximumKilobytes { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [Browsable(false)] public int MinimumRetentionDays { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [Browsable(false)] public OverflowAction OverflowAction { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [DefaultValue("")] [ReadOnly(true)] [SettingsBindable(true)] public string Source { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [Browsable(false)] [DefaultValue(null)] public ISynchronizeInvoke SynchronizingObject { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public event EntryWrittenEventHandler EntryWritten { add { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } remove { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLog() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLog(string logName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLog(string logName, string machineName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLog(string logName, string machineName, string source) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void BeginInit() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Clear() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Close() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void CreateEventSource(EventSourceCreationData sourceData) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void CreateEventSource(string source, string logName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } [Obsolete("EventLog.CreateEventSource has been deprecated. Use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead.")] public static void CreateEventSource(string source, string logName, string machineName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void Delete(string logName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void Delete(string logName, string machineName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void DeleteEventSource(string source) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void DeleteEventSource(string source, string machineName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected override void Dispose(bool disposing) { } public void EndInit() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static bool Exists(string logName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static bool Exists(string logName, string machineName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static EventLog[] GetEventLogs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static EventLog[] GetEventLogs(string machineName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static string LogNameFromSourceName(string source, string machineName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void ModifyOverflowPolicy(OverflowAction action, int retentionDays) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void RegisterDisplayName(string resourceFile, long resourceId) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static bool SourceExists(string source) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static bool SourceExists(string source, string machineName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void WriteEntry(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void WriteEntry(string message, EventLogEntryType type) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void WriteEntry(string message, EventLogEntryType type, int eventID) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void WriteEntry(string source, string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void WriteEntry(string source, string message, EventLogEntryType type) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void WriteEvent(EventInstance instance, byte[] data, params object[] values) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void WriteEvent(EventInstance instance, params object[] values) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void WriteEvent(string source, EventInstance instance, byte[] data, params object[] values) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public static void WriteEvent(string source, EventInstance instance, params object[] values) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [DesignTimeVisible(false)] [ToolboxItem(false)] public sealed class EventLogEntry : Component, ISerializable { public string Category { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public short CategoryNumber { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public byte[] Data { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogEntryType EntryType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [Obsolete("EventLogEntry.EventID has been deprecated. Use System.Diagnostics.EventLogEntry.InstanceId instead.")] public int EventID { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int Index { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long InstanceId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string MachineName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } [Editor("System.ComponentModel.Design.BinaryEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public string Message { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string[] ReplacementStrings { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string Source { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public DateTime TimeGenerated { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public DateTime TimeWritten { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string UserName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventLogEntry() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public bool Equals(EventLogEntry otherEntry) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogEntryCollection : ICollection, IEnumerable { public int Count { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public virtual EventLogEntry this[int index] { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } bool ICollection.IsSynchronized { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } object ICollection.SyncRoot { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventLogEntryCollection() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void CopyTo(EventLogEntry[] entries, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public IEnumerator GetEnumerator() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } void ICollection.CopyTo(Array array, int index) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public enum EventLogEntryType { Error = 1, Warning = 2, Information = 4, SuccessAudit = 8, FailureAudit = 0x10 } public sealed class EventLogTraceListener : TraceListener { public EventLog EventLog { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogTraceListener() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogTraceListener(EventLog eventLog) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogTraceListener(string source) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public override void Close() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected override void Dispose(bool disposing) { } [ComVisible(false)] public override void TraceData(TraceEventCache eventCache, string source, TraceEventType severity, int id, object data) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } [ComVisible(false)] public override void TraceData(TraceEventCache eventCache, string source, TraceEventType severity, int id, params object[] data) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } [ComVisible(false)] public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } [ComVisible(false)] public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType severity, int id, string format, params object[] args) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public override void Write(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public override void WriteLine(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventSourceCreationData { public int CategoryCount { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string CategoryResourceFile { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string LogName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string MachineName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string MessageResourceFile { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string ParameterResourceFile { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string Source { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventSourceCreationData(string source, string logName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public enum OverflowAction { DoNotOverwrite = -1, OverwriteAsNeeded, OverwriteOlder } } namespace System.Diagnostics.Eventing.Reader { public class EventBookmark { internal EventBookmark() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public sealed class EventKeyword { public string DisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventKeyword() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public sealed class EventLevel { public string DisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventLevel() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogConfiguration : IDisposable { public bool IsClassicLog { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public bool IsEnabled { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string LogFilePath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogIsolation LogIsolation { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogMode LogMode { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string LogName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogType LogType { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long MaximumSizeInBytes { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string OwningProviderName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int? ProviderBufferSize { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public Guid? ProviderControlGuid { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long? ProviderKeywords { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int? ProviderLatency { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int? ProviderLevel { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int? ProviderMaximumNumberOfBuffers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int? ProviderMinimumNumberOfBuffers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IEnumerable<string> ProviderNames { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string SecurityDescriptor { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogConfiguration(string logName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogConfiguration(string logName, EventLogSession session) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void SaveChanges() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogException : Exception { public override string Message { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogException() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected EventLogException(int errorCode) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected EventLogException(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogException(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogException(string message, Exception innerException) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public sealed class EventLogInformation { public int? Attributes { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public DateTime? CreationTime { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long? FileSize { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public bool? IsLogFull { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public DateTime? LastAccessTime { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public DateTime? LastWriteTime { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long? OldestRecordNumber { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long? RecordCount { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventLogInformation() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogInvalidDataException : EventLogException { public EventLogInvalidDataException() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected EventLogInvalidDataException(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogInvalidDataException(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogInvalidDataException(string message, Exception innerException) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public enum EventLogIsolation { Application, System, Custom } public sealed class EventLogLink { public string DisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public bool IsImported { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string LogName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventLogLink() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public enum EventLogMode { Circular, AutoBackup, Retain } public class EventLogNotFoundException : EventLogException { public EventLogNotFoundException() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected EventLogNotFoundException(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogNotFoundException(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogNotFoundException(string message, Exception innerException) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogPropertySelector : IDisposable { public EventLogPropertySelector(IEnumerable<string> propertyQueries) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public class EventLogProviderDisabledException : EventLogException { public EventLogProviderDisabledException() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected EventLogProviderDisabledException(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogProviderDisabledException(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogProviderDisabledException(string message, Exception innerException) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogQuery { public bool ReverseDirection { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogSession Session { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public bool TolerateQueryErrors { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogQuery(string path, PathType pathType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogQuery(string path, PathType pathType, string query) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogReader : IDisposable { public int BatchSize { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IList<EventLogStatus> LogStatus { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogReader(EventLogQuery eventQuery) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogReader(string path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogReader(string path, PathType pathType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void CancelReading() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public EventRecord ReadEvent() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventRecord ReadEvent(TimeSpan timeout) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Seek(EventBookmark bookmark) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Seek(EventBookmark bookmark, long offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Seek(SeekOrigin origin, long offset) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogReadingException : EventLogException { public EventLogReadingException() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected EventLogReadingException(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogReadingException(string message) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogReadingException(string message, Exception innerException) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogRecord : EventRecord { public override Guid? ActivityId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override EventBookmark Bookmark { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string ContainerLog { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override int Id { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override long? Keywords { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override IEnumerable<string> KeywordsDisplayNames { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override byte? Level { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override string LevelDisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override string LogName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override string MachineName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IEnumerable<int> MatchedQueryIds { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override short? Opcode { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override string OpcodeDisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override int? ProcessId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override IList<EventProperty> Properties { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override Guid? ProviderId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override string ProviderName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override int? Qualifiers { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override long? RecordId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override Guid? RelatedActivityId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override int? Task { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override string TaskDisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override int? ThreadId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override DateTime? TimeCreated { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override SecurityIdentifier UserId { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public override byte? Version { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventLogRecord() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } protected override void Dispose(bool disposing) { } public override string FormatDescription() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public override string FormatDescription(IEnumerable<object> values) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public IList<object> GetPropertyValues(EventLogPropertySelector propertySelector) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public override string ToXml() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public class EventLogSession : IDisposable { public static EventLogSession GlobalSession { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogSession() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogSession(string server) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void CancelCurrentOperations() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void ClearLog(string logName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void ClearLog(string logName, string backupPath) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void ExportLog(string path, PathType pathType, string query, string targetFilePath) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void ExportLog(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors, CultureInfo targetCultureInfo) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogInformation GetLogInformation(string logName, PathType pathType) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public IEnumerable<string> GetLogNames() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public IEnumerable<string> GetProviderNames() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public sealed class EventLogStatus { public string LogName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int StatusCode { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventLogStatus() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public enum EventLogType { Administrative, Operational, Analytical, Debug } public class EventLogWatcher : IDisposable { public bool Enabled { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } set { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public event EventHandler<EventRecordWrittenEventArgs> EventRecordWritten { add { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } remove { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogWatcher(EventLogQuery eventQuery) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark, bool readExistingEvents) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public EventLogWatcher(string path) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public sealed class EventMetadata { public string Description { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public long Id { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IEnumerable<EventKeyword> Keywords { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLevel Level { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventLogLink LogLink { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventOpcode Opcode { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventTask Task { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string Template { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public byte Version { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventMetadata() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public sealed class EventOpcode { public string DisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventOpcode() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public sealed class EventProperty { public object Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventProperty() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public abstract class EventRecord : IDisposable { public abstract Guid? ActivityId { get; } public abstract EventBookmark Bookmark { get; } public abstract int Id { get; } public abstract long? Keywords { get; } public abstract IEnumerable<string> KeywordsDisplayNames { get; } public abstract byte? Level { get; } public abstract string LevelDisplayName { get; } public abstract string LogName { get; } public abstract string MachineName { get; } public abstract short? Opcode { get; } public abstract string OpcodeDisplayName { get; } public abstract int? ProcessId { get; } public abstract IList<EventProperty> Properties { get; } public abstract Guid? ProviderId { get; } public abstract string ProviderName { get; } public abstract int? Qualifiers { get; } public abstract long? RecordId { get; } public abstract Guid? RelatedActivityId { get; } public abstract int? Task { get; } public abstract string TaskDisplayName { get; } public abstract int? ThreadId { get; } public abstract DateTime? TimeCreated { get; } public abstract SecurityIdentifier UserId { get; } public abstract byte? Version { get; } protected EventRecord() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract string FormatDescription(); public abstract string FormatDescription(IEnumerable<object> values); public abstract string ToXml(); } public sealed class EventRecordWrittenEventArgs : EventArgs { public Exception EventException { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public EventRecord EventRecord { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventRecordWrittenEventArgs() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public sealed class EventTask { public string DisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public Guid EventGuid { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public int Value { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } internal EventTask() { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public enum PathType { LogName = 1, FilePath } public class ProviderMetadata : IDisposable { public string DisplayName { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IEnumerable<EventMetadata> Events { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public Uri HelpLink { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public Guid Id { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IList<EventKeyword> Keywords { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IList<EventLevel> Levels { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IList<EventLogLink> LogLinks { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string MessageFilePath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string Name { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IList<EventOpcode> Opcodes { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string ParameterFilePath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public string ResourceFilePath { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public IList<EventTask> Tasks { get { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } } public ProviderMetadata(string providerName) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo) { throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_EventLog); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public enum SessionAuthentication { Default, Negotiate, Kerberos, Ntlm } [Flags] public enum StandardEventKeywords : long { None = 0L, ResponseTime = 0x1000000000000L, WdiContext = 0x2000000000000L, WdiDiagnostic = 0x4000000000000L, Sqm = 0x8000000000000L, AuditFailure = 0x10000000000000L, [Obsolete("StandardEventKeywords.CorrelationHint has an incorrect value and has been deprecated. Use CorrelationHint2 instead.")] CorrelationHint = 0x10000000000000L, AuditSuccess = 0x20000000000000L, CorrelationHint2 = 0x40000000000000L, EventLogClassic = 0x80000000000000L } public enum StandardEventLevel { LogAlways, Critical, Error, Warning, Informational, Verbose } public enum StandardEventOpcode { Info = 0, Start = 1, Stop = 2, DataCollectionStart = 3, DataCollectionStop = 4, Extension = 5, Reply = 6, Resume = 7, Suspend = 8, Send = 9, Receive = 240 } public enum StandardEventTask { None } }
MegabonkTogether/Microsoft.Extensions.Logging.Abstractions.dll
Decompiled 2 hours 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.322.12309")] [assembly: AssemblyInformationalVersion("6.0.3+c24d9a9c91c5d04b7b4de71f1a9f33ac35e09663")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.Logging.Abstractions { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Text { internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => ref _chars[index]; public Span<char> RawChars => _chars; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public void EnsureCapacity(int capacity) { if ((uint)capacity > (uint)_chars.Length) { Grow(capacity - _pos); } } public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public override string ToString() { string result = _chars.Slice(0, _pos).ToString(); Dispose(); return result; } public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan<char> AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } charsWritten = 0; Dispose(); return false; } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int length = _pos - index; _chars.Slice(index, length).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string? s) { if (s != null) { int length = s.Length; if (_pos > _chars.Length - length) { Grow(length); } int length2 = _pos - index; _chars.Slice(index, length2).CopyTo(_chars.Slice(index + length)); s.CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; if ((uint)pos < (uint)_chars.Length) { _chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string? s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> span = _chars.Slice(_pos, count); for (int i = 0; i < span.Length; i++) { span[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } Span<char> span = _chars.Slice(_pos, length); for (int i = 0; i < span.Length; i++) { span[i] = *(value++); } _pos += length; } public void Append(ReadOnlySpan<char> value) { int pos = _pos; if (pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<char> AppendSpan(int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } _pos = pos + length; return _chars.Slice(pos, length); } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowAndAppend(char c) { Grow(1); Append(c); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalCapacityBeyondPos) { char[] array = ArrayPool<char>.Shared.Rent((int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), (uint)(_chars.Length * 2))); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(System.Text.ValueStringBuilder); if (arrayToReturnToPool != null) { ArrayPool<char>.Shared.Return(arrayToReturnToPool); } } } } namespace Microsoft.Extensions.Internal { internal static class TypeNameHelper { private readonly struct DisplayNameOptions { public bool FullName { get; } public bool IncludeGenericParameters { get; } public bool IncludeGenericParameterNames { get; } public char NestedTypeDelimiter { get; } public DisplayNameOptions(bool fullName, bool includeGenericParameterNames, bool includeGenericParameters, char nestedTypeDelimiter) { FullName = fullName; IncludeGenericParameters = includeGenericParameters; IncludeGenericParameterNames = includeGenericParameterNames; NestedTypeDelimiter = nestedTypeDelimiter; } } private const char DefaultNestedTypeDelimiter = '+'; private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string> { { typeof(void), "void" }, { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(char), "char" }, { typeof(decimal), "decimal" }, { typeof(double), "double" }, { typeof(float), "float" }, { typeof(int), "int" }, { typeof(long), "long" }, { typeof(object), "object" }, { typeof(sbyte), "sbyte" }, { typeof(short), "short" }, { typeof(string), "string" }, { typeof(uint), "uint" }, { typeof(ulong), "ulong" }, { typeof(ushort), "ushort" } }; [return: NotNullIfNotNull("item")] public static string? GetTypeDisplayName(object? item, bool fullName = true) { if (item != null) { return GetTypeDisplayName(item.GetType(), fullName); } return null; } public static string GetTypeDisplayName(Type type, bool fullName = true, bool includeGenericParameterNames = false, bool includeGenericParameters = true, char nestedTypeDelimiter = '+') { StringBuilder stringBuilder = new StringBuilder(); DisplayNameOptions options = new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter); ProcessType(stringBuilder, type, in options); return stringBuilder.ToString(); } private static void ProcessType(StringBuilder builder, Type type, in DisplayNameOptions options) { if (type.IsGenericType) { Type[] genericArguments = type.GetGenericArguments(); ProcessGenericType(builder, type, genericArguments, genericArguments.Length, in options); return; } if (type.IsArray) { ProcessArrayType(builder, type, in options); return; } if (_builtInTypeNames.TryGetValue(type, out var value)) { builder.Append(value); return; } if (type.IsGenericParameter) { if (options.IncludeGenericParameterNames) { builder.Append(type.Name); } return; } string text = (options.FullName ? type.FullName : type.Name); builder.Append(text); if (options.NestedTypeDelimiter != '+') { builder.Replace('+', options.NestedTypeDelimiter, builder.Length - text.Length, text.Length); } } private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options) { 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, Type type, Type[] genericArguments, int length, in DisplayNameOptions options) { int num = 0; if (type.IsNested) { num = type.DeclaringType.GetGenericArguments().Length; } if (options.FullName) { if (type.IsNested) { ProcessGenericType(builder, type.DeclaringType, genericArguments, num, in options); builder.Append(options.NestedTypeDelimiter); } else if (!string.IsNullOrEmpty(type.Namespace)) { builder.Append(type.Namespace); builder.Append('.'); } } int num2 = type.Name.IndexOf('`'); if (num2 <= 0) { builder.Append(type.Name); return; } builder.Append(type.Name, 0, num2); if (!options.IncludeGenericParameters) { return; } builder.Append('<'); for (int i = num; i < length; i++) { ProcessType(builder, genericArguments[i], in options); if (i + 1 != length) { builder.Append(','); if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter) { builder.Append(' '); } } } builder.Append('>'); } } } namespace Microsoft.Extensions.Logging { public readonly struct EventId { public int Id { get; } public string? Name { get; } public static implicit operator EventId(int i) { return new EventId(i); } public static bool operator ==(EventId left, EventId right) { return left.Equals(right); } public static bool operator !=(EventId left, EventId right) { return !left.Equals(right); } public EventId(int id, string? name = null) { Id = id; Name = name; } public override string ToString() { return Name ?? Id.ToString(); } public bool Equals(EventId other) { return Id == other.Id; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) { return false; } if (obj is EventId other) { return Equals(other); } return false; } public override int GetHashCode() { return Id; } } internal readonly struct FormattedLogValues : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>> { internal const int MaxCachedFormatters = 1024; private const string NullFormat = "[null]"; private static int _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 { if (index < 0 || index >= Count) { throw new IndexOutOfRangeException("index"); } if (index == Count - 1) { return new KeyValuePair<string, object>("{OriginalFormat}", _originalMessage); } return _formatter.GetValue(_values, index); } } public int Count { get { if (_formatter == null) { return 1; } return _formatter.ValueNames.Count + 1; } } public FormattedLogValues(string? format, params object?[]? values) { if (values != null && values.Length != 0 && format != null) { if (_count >= 1024) { if (!_formatters.TryGetValue(format, out _formatter)) { _formatter = new LogValuesFormatter(format); } } else { _formatter = _formatters.GetOrAdd(format, delegate(string f) { Interlocked.Increment(ref _count); return new LogValuesFormatter(f); }); } } else { _formatter = null; } _originalMessage = format ?? "[null]"; _values = values; } public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { if (_formatter == null) { return _originalMessage; } return _formatter.Format(_values); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public interface IExternalScopeProvider { void ForEachScope<TState>(Action<object?, TState> callback, TState state); IDisposable Push(object? state); } public interface ILogger { void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter); bool IsEnabled(LogLevel logLevel); IDisposable BeginScope<TState>(TState state); } public interface ILoggerFactory : IDisposable { ILogger CreateLogger(string categoryName); void AddProvider(ILoggerProvider provider); } public interface ILoggerProvider : IDisposable { ILogger CreateLogger(string categoryName); } public interface ILogger<out TCategoryName> : ILogger { } public interface ISupportExternalScope { void SetScopeProvider(IExternalScopeProvider scopeProvider); } public class LogDefineOptions { public bool SkipEnabledCheck { get; set; } } public static class LoggerExtensions { private static readonly Func<FormattedLogValues, Exception, string> _messageFormatter = MessageFormatter; public static void LogDebug(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Debug, eventId, exception, message, args); } public static void LogDebug(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Debug, eventId, message, args); } public static void LogDebug(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Debug, exception, message, args); } public static void LogDebug(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Debug, message, args); } public static void LogTrace(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Trace, eventId, exception, message, args); } public static void LogTrace(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Trace, eventId, message, args); } public static void LogTrace(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Trace, exception, message, args); } public static void LogTrace(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Trace, message, args); } public static void LogInformation(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Information, eventId, exception, message, args); } public static void LogInformation(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Information, eventId, message, args); } public static void LogInformation(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Information, exception, message, args); } public static void LogInformation(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Information, message, args); } public static void LogWarning(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Warning, eventId, exception, message, args); } public static void LogWarning(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Warning, eventId, message, args); } public static void LogWarning(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Warning, exception, message, args); } public static void LogWarning(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Warning, message, args); } public static void LogError(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Error, eventId, exception, message, args); } public static void LogError(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Error, eventId, message, args); } public static void LogError(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Error, exception, message, args); } public static void LogError(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Error, message, args); } public static void LogCritical(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Critical, eventId, exception, message, args); } public static void LogCritical(this ILogger logger, EventId eventId, string? message, params object?[] args) { logger.Log(LogLevel.Critical, eventId, message, args); } public static void LogCritical(this ILogger logger, Exception? exception, string? message, params object?[] args) { logger.Log(LogLevel.Critical, exception, message, args); } public static void LogCritical(this ILogger logger, string? message, params object?[] args) { logger.Log(LogLevel.Critical, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, string? message, params object?[] args) { logger.Log(logLevel, 0, null, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string? message, params object?[] args) { logger.Log(logLevel, eventId, null, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, Exception? exception, string? message, params object?[] args) { logger.Log(logLevel, 0, exception, message, args); } public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, string? message, params object?[] args) { if (logger == null) { throw new ArgumentNullException("logger"); } logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); } public static IDisposable BeginScope(this ILogger logger, string messageFormat, params object?[] args) { if (logger == null) { throw new ArgumentNullException("logger"); } return logger.BeginScope(new FormattedLogValues(messageFormat, args)); } private static string MessageFormatter(FormattedLogValues state, Exception error) { return state.ToString(); } } public class LoggerExternalScopeProvider : IExternalScopeProvider { private sealed class Scope : IDisposable { private readonly LoggerExternalScopeProvider _provider; private bool _isDisposed; public Scope Parent { get; } public object State { get; } internal Scope(LoggerExternalScopeProvider provider, object state, Scope parent) { _provider = provider; State = state; Parent = parent; } public override string ToString() { return State?.ToString(); } public void Dispose() { if (!_isDisposed) { _provider._currentScope.Value = Parent; _isDisposed = true; } } } private readonly AsyncLocal<Scope> _currentScope = new AsyncLocal<Scope>(); public void ForEachScope<TState>(Action<object?, TState> callback, TState state) { Action<object, TState> callback2 = callback; TState state2 = state; Report(_currentScope.Value); void Report(Scope? current) { if (current != null) { Report(current.Parent); callback2(current.State, state2); } } } public IDisposable Push(object? state) { Scope value = _currentScope.Value; Scope scope = new Scope(this, state, value); _currentScope.Value = scope; return scope; } } public static class LoggerFactoryExtensions { public static ILogger<T> CreateLogger<T>(this ILoggerFactory factory) { if (factory == null) { throw new ArgumentNullException("factory"); } return new Logger<T>(factory); } public static ILogger CreateLogger(this ILoggerFactory factory, Type type) { if (factory == null) { throw new ArgumentNullException("factory"); } if (type == null) { throw new ArgumentNullException("type"); } return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.')); } } public static class LoggerMessage { private readonly struct LogValues : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues, Exception, string> Callback = (LogValues state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; public KeyValuePair<string, object> this[int index] { get { if (index == 0) { return new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat); } throw new IndexOutOfRangeException("index"); } } public int Count => 1; public LogValues(LogValuesFormatter formatter) { _formatter = formatter; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { yield return this[0]; } public override string ToString() { return _formatter.Format(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0>, Exception, string> Callback = (LogValues<T0> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public int Count => 2; public LogValues(LogValuesFormatter formatter, T0 value0) { _formatter = formatter; _value0 = value0; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { return _formatter.Format(_value0); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1>, Exception, string> Callback = (LogValues<T0, T1> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public int Count => 3; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1) { _formatter = formatter; _value0 = value0; _value1 = value1; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } public override string ToString() { return _formatter.Format(_value0, _value1); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2>, Exception, string> Callback = (LogValues<T0, T1, T2> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; public int Count => 4; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; } public override string ToString() { return _formatter.Format(_value0, _value1, _value2); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3>, Exception, string> Callback = (LogValues<T0, T1, T2, T3> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; public int Count => 5; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; } private object[] ToArray() { return new object[4] { _value0, _value1, _value2, _value3 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3, T4> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3, T4>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; private readonly T4 _value4; public int Count => 6; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 5 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; _value4 = value4; } private object[] ToArray() { return new object[5] { _value0, _value1, _value2, _value3, _value4 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private readonly struct LogValues<T0, T1, T2, T3, T4, T5> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { public static readonly Func<LogValues<T0, T1, T2, T3, T4, T5>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4, T5> state, Exception exception) => state.ToString(); private readonly LogValuesFormatter _formatter; private readonly T0 _value0; private readonly T1 _value1; private readonly T2 _value2; private readonly T3 _value3; private readonly T4 _value4; private readonly T5 _value5; public int Count => 7; public KeyValuePair<string, object> this[int index] => index switch { 0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 5 => new KeyValuePair<string, object>(_formatter.ValueNames[5], _value5), 6 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), _ => throw new IndexOutOfRangeException("index"), }; public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) { _formatter = formatter; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; _value4 = value4; _value5 = value5; } private object[] ToArray() { return new object[6] { _value0, _value1, _value2, _value3, _value4, _value5 }; } public override string ToString() { return _formatter.FormatWithOverwrite(ToArray()); } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static Func<ILogger, IDisposable> DefineScope(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0); LogValues logValues = new LogValues(formatter); return (ILogger logger) => logger.BeginScope(logValues); } public static Func<ILogger, T1, IDisposable> DefineScope<T1>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1); return (ILogger logger, T1 arg1) => logger.BeginScope(new LogValues<T1>(formatter, arg1)); } public static Func<ILogger, T1, T2, IDisposable> DefineScope<T1, T2>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2); return (ILogger logger, T1 arg1, T2 arg2) => logger.BeginScope(new LogValues<T1, T2>(formatter, arg1, arg2)); } public static Func<ILogger, T1, T2, T3, IDisposable> DefineScope<T1, T2, T3>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3) => logger.BeginScope(new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3)); } public static Func<ILogger, T1, T2, T3, T4, IDisposable> DefineScope<T1, T2, T3, T4>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4) => logger.BeginScope(new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4)); } public static Func<ILogger, T1, T2, T3, T4, T5, IDisposable> DefineScope<T1, T2, T3, T4, T5>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5)); } public static Func<ILogger, T1, T2, T3, T4, T5, T6, IDisposable> DefineScope<T1, T2, T3, T4, T5, T6>(string formatString) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6); return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6)); } public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString) { return Define(logLevel, eventId, formatString, null); } public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, exception); } }; void Log(ILogger logger, Exception exception) { logger.Log(logLevel, eventId, new LogValues(formatter), exception, LogValues.Callback); } } public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, exception); } }; void Log(ILogger logger, T1 arg1, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1>(formatter, arg1), exception, LogValues<T1>.Callback); } } public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2>(formatter, arg1, arg2), exception, LogValues<T1, T2>.Callback); } } public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3), exception, LogValues<T1, T2, T3>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4), exception, LogValues<T1, T2, T3, T4>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4, T5>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, arg5, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5), exception, LogValues<T1, T2, T3, T4, T5>.Callback); } } public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString) { return Define<T1, T2, T3, T4, T5, T6>(logLevel, eventId, formatString, null); } public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options) { LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6); if (options != null && options.SkipEnabledCheck) { return Log; } return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception) { if (logger.IsEnabled(logLevel)) { Log(logger, arg1, arg2, arg3, arg4, arg5, arg6, exception); } }; void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception) { logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6), exception, LogValues<T1, T2, T3, T4, T5, T6>.Callback); } } private static LogValuesFormatter CreateLogValuesFormatter(string formatString, int expectedNamedParameterCount) { LogValuesFormatter logValuesFormatter = new LogValuesFormatter(formatString); int count = logValuesFormatter.ValueNames.Count; if (count != expectedNamedParameterCount) { throw new ArgumentException(System.SR.Format(System.SR.UnexpectedNumberOfNamedParameters, formatString, expectedNamedParameterCount, count)); } return logValuesFormatter; } } [AttributeUsage(AttributeTargets.Method)] public sealed class LoggerMessageAttribute : Attribute { public int EventId { get; set; } = -1; public string? EventName { get; set; } public LogLevel Level { get; set; } = LogLevel.None; public string Message { get; set; } = ""; public bool SkipEnabledCheck { get; set; } public LoggerMessageAttribute() { } public LoggerMessageAttribute(int eventId, LogLevel level, string message) { EventId = eventId; Level = level; Message = message; } } public class Logger<T> : ILogger<T>, ILogger { private readonly ILogger _logger; public Logger(ILoggerFactory factory) { if (factory == null) { throw new ArgumentNullException("factory"); } _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T), fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.')); } IDisposable ILogger.BeginScope<TState>(TState state) { return _logger.BeginScope(state); } bool ILogger.IsEnabled(LogLevel logLevel) { return _logger.IsEnabled(logLevel); } void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { _logger.Log(logLevel, eventId, state, exception, formatter); } } 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>(); public string OriginalFormat { get; private set; } public List<string> ValueNames => _valueNames; public LogValuesFormatter(string format) { if (format == null) { throw new ArgumentNullException("format"); } OriginalFormat = format; Span<char> initialBuffer = stackalloc char[256]; System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer); int num = 0; int length = format.Length; while (num < length) { int num2 = FindBraceIndex(format, '{', num, length); if (num == 0 && num2 == length) { _format = format; return; } int num3 = FindBraceIndex(format, '}', num2, length); if (num3 == length) { valueStringBuilder.Append(format.AsSpan(num, length - num)); num = length; continue; } int num4 = FindIndexOfAny(format, FormatDelimiters, num2, num3); valueStringBuilder.Append(format.AsSpan(num, num2 - num + 1)); valueStringBuilder.Append(_valueNames.Count.ToString()); _valueNames.Add(format.Substring(num2 + 1, num4 - num2 - 1)); valueStringBuilder.Append(format.AsSpan(num4, num3 - num4 + 1)); num = num3 + 1; } _format = valueStringBuilder.ToString(); } private static int FindBraceIndex(string format, char brace, int startIndex, int endIndex) { int result = endIndex; int i = startIndex; int num = 0; for (; i < endIndex; i++) { if (num > 0 && format[i] != brace) { if (num % 2 != 0) { break; } num = 0; result = endIndex; } else { if (format[i] != brace) { continue; } if (brace == '}') { if (num == 0) { result = i; } } else { result = i; } num++; } } return result; } private static int FindIndexOfAny(string format, char[] chars, int startIndex, int endIndex) { int num = format.IndexOfAny(chars, startIndex, endIndex - startIndex); if (num != -1) { return num; } return endIndex; } public string Format(object?[]? values) { object[] array = values; if (values != null) { for (int i = 0; i < values.Length; i++) { object obj = FormatArgument(values[i]); if (obj != values[i]) { array = new object[values.Length]; Array.Copy(values, array, i); array[i++] = obj; for (; i < values.Length; i++) { array[i] = FormatArgument(values[i]); } break; } } } return string.Format(CultureInfo.InvariantCulture, _format, array ?? Array.Empty<object>()); } internal string FormatWithOverwrite(object?[]? values) { if (values != null) { for (int i = 0; i < values.Length; i++) { values[i] = FormatArgument(values[i]); } } return string.Format(CultureInfo.InvariantCulture, _format, values ?? Array.Empty<object>()); } internal string Format() { return _format; } internal string Format(object? arg0) { return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0)); } internal string Format(object? arg0, object? arg1) { return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1)); } internal string Format(object? arg0, object? arg1, object? arg2) { return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1), FormatArgument(arg2)); } public KeyValuePair<string, object?> GetValue(object?[] values, int index) { if (index < 0 || index > _valueNames.Count) { throw new IndexOutOfRangeException("index"); } if (_valueNames.Count > index) { return new KeyValuePair<string, object>(_valueNames[index], values[index]); } return new KeyValuePair<string, object>("{OriginalFormat}", OriginalFormat); } public IEnumerable<KeyValuePair<string, object?>> GetValues(object[] values) { KeyValuePair<string, object>[] array = new KeyValuePair<string, object>[values.Length + 1]; for (int i = 0; i != _valueNames.Count; i++) { array[i] = new KeyValuePair<string, object>(_valueNames[i], values[i]); } array[^1] = new KeyValuePair<string, object>("{OriginalFormat}", OriginalFormat); return array; } private object FormatArgument(object value) { if (value == null) { return "(null)"; } if (value is string) { return value; } if (value is IEnumerable enumerable) { Span<char> initialBuffer = stackalloc char[256]; System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer); bool flag = true; foreach (object item in enumerable) { if (!flag) { valueStringBuilder.Append(", "); } valueStringBuilder.Append((item != null) ? item.ToString() : "(null)"); flag = false; } return valueStringBuilder.ToString(); } return value; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { public static IExternalScopeProvider Instance { get; } = new NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } IDisposable IExternalScopeProvider.Push(object state) { return NullScope.Instance; } } internal sealed class NullScope : IDisposable { public static NullScope Instance { get; } = new NullScope(); private NullScope() { } public void Dispose() { } } } namespace Microsoft.Extensions.Logging.Abstractions { public readonly struct LogEntry<TState> { public LogLevel LogLevel { get; } public string Category { get; } public EventId EventId { get; } public TState State { get; } public Exception? Exception { get; } public Func<TState, Exception?, string>? Formatter { get; } public LogEntry(LogLevel logLevel, string category, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { LogLevel = logLevel; Category = category; EventId = eventId; State = state; Exception = exception; Formatter = formatter; } } public class NullLogger : ILogger { public static NullLogger Instance { get; } = new NullLogger(); private NullLogger() { } public IDisposable BeginScope<TState>(TState state) { return NullScope.Instance; } public bool IsEnabled(LogLevel logLevel) { return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { } } public class NullLoggerFactory : ILoggerFactory, IDisposable { public static readonly NullLoggerFactory Instance = new NullLoggerFactory(); public ILogger CreateLogger(string name) { return NullLogger.Instance; } public void AddProvider(ILoggerProvider provider) { } public void Dispose() { } } public class NullLoggerProvider : ILoggerProvider, IDisposable { public static NullLoggerProvider Instance { get; } = new NullLoggerProvider(); private NullLoggerProvider() { } public ILogger CreateLogger(string categoryName) { return NullLogger.Instance; } public void Dispose() { } } public class NullLogger<T> : ILogger<T>, ILogger { public static readonly NullLogger<T> Instance = new NullLogger<T>(); public IDisposable BeginScope<TState>(TState state) { return NullScope.Instance; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { } public bool IsEnabled(LogLevel logLevel) { return false; } } }
MegabonkTogether/Microsoft.Extensions.Logging.EventLog.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.EventLog")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.EventLog")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace System.Runtime.Versioning { internal abstract class OSPlatformAttribute : Attribute { public string PlatformName { get; } private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute { public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute { public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } } namespace Microsoft.Extensions.Logging { public static class EventLoggerFactoryExtensions { public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder) { if (builder == null) { throw new ArgumentNullException("builder"); } builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, EventLogLoggerProvider>()); return builder; } public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, EventLogSettings settings) { if (builder == null) { throw new ArgumentNullException("builder"); } if (settings == null) { throw new ArgumentNullException("settings"); } builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton((ILoggerProvider)new EventLogLoggerProvider(settings))); return builder; } public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, Action<EventLogSettings> configure) { if (configure == null) { throw new ArgumentNullException("configure"); } builder.AddEventLog(); builder.Services.Configure(configure); return builder; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { public static IExternalScopeProvider Instance { get; } = new Microsoft.Extensions.Logging.NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } IDisposable IExternalScopeProvider.Push(object state) { return Microsoft.Extensions.Logging.NullScope.Instance; } } internal sealed class NullScope : IDisposable { public static Microsoft.Extensions.Logging.NullScope Instance { get; } = new Microsoft.Extensions.Logging.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; public IEventLog EventLog { get; } public EventLogLogger(string name, EventLogSettings settings, IExternalScopeProvider externalScopeProvider) { _name = name ?? throw new ArgumentNullException("name"); _settings = settings ?? throw new ArgumentNullException("settings"); _externalScopeProvider = externalScopeProvider; EventLog = settings.EventLog; _beginOrEndMessageSegmentSize = EventLog.MaxMessageSize - "...".Length; _intermediateMessageSegmentSize = EventLog.MaxMessageSize - 2 * "...".Length; } public IDisposable BeginScope<TState>(TState state) { return _externalScopeProvider?.Push(state); } public bool IsEnabled(LogLevel logLevel) { if (logLevel != LogLevel.None) { if (_settings.Filter != null) { return _settings.Filter(_name, logLevel); } return true; } return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } if (formatter == null) { throw new ArgumentNullException("formatter"); } string value = formatter(state, exception); if (string.IsNullOrEmpty(value)) { return; } StringBuilder stringBuilder = new StringBuilder().Append("Category: ").AppendLine(_name).Append("EventId: ") .Append(eventId.Id) .AppendLine(); _externalScopeProvider?.ForEachScope(delegate(object scope, StringBuilder sb) { if (scope is IEnumerable<KeyValuePair<string, object>> enumerable) { { foreach (KeyValuePair<string, object> item in enumerable) { sb.Append(item.Key).Append(": ").AppendLine(item.Value?.ToString()); } return; } } if (scope != null) { sb.AppendLine(scope.ToString()); } }, stringBuilder); stringBuilder.AppendLine().AppendLine(value); if (exception != null) { stringBuilder.AppendLine().AppendLine("Exception: ").Append(exception) .AppendLine(); } WriteMessage(stringBuilder.ToString(), GetEventLogEntryType(logLevel), EventLog.DefaultEventId ?? eventId.Id); } private void WriteMessage(string message, EventLogEntryType eventLogEntryType, int eventId) { if (message.Length <= EventLog.MaxMessageSize) { EventLog.WriteEntry(message, eventLogEntryType, eventId, 0); return; } int num = 0; string text = null; while (true) { if (num == 0) { text = message.Substring(num, _beginOrEndMessageSegmentSize) + "..."; num += _beginOrEndMessageSegmentSize; } else { if (message.Length - (num + 1) <= _beginOrEndMessageSegmentSize) { break; } text = "..." + message.Substring(num, _intermediateMessageSegmentSize) + "..."; num += _intermediateMessageSegmentSize; } EventLog.WriteEntry(text, eventLogEntryType, eventId, 0); } text = "..." + message.Substring(num); EventLog.WriteEntry(text, eventLogEntryType, eventId, 0); } private EventLogEntryType GetEventLogEntryType(LogLevel level) { switch (level) { case LogLevel.Trace: case LogLevel.Debug: case LogLevel.Information: return EventLogEntryType.Information; case LogLevel.Warning: return EventLogEntryType.Warning; case LogLevel.Error: case LogLevel.Critical: return EventLogEntryType.Error; default: return EventLogEntryType.Information; } } } [ProviderAlias("EventLog")] public class EventLogLoggerProvider : ILoggerProvider, 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 new EventLogLogger(name, _settings, _scopeProvider); } public void Dispose() { if (_settings.EventLog is WindowsEventLog windowsEventLog) { windowsEventLog.DiagnosticsEventLog.Dispose(); } } public void SetScopeProvider(IExternalScopeProvider scopeProvider) { _scopeProvider = scopeProvider; } } public class EventLogSettings { private IEventLog _eventLog; public string LogName { get; set; } public string SourceName { get; set; } public string MachineName { get; set; } public Func<string, LogLevel, bool> Filter { get; 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; public System.Diagnostics.EventLog DiagnosticsEventLog { get; } public int MaxMessageSize => 31839; public int? DefaultEventId { get; set; } public WindowsEventLog(string logName, string machineName, string sourceName) { DiagnosticsEventLog = new System.Diagnostics.EventLog(logName, machineName, sourceName); } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) { try { if (_enabled) { DiagnosticsEventLog.WriteEvent(new EventInstance(eventID, category, type), message); } } catch (SecurityException ex) { _enabled = false; try { using System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application", ".", "Application"); eventLog.WriteEvent(new EventInstance(0L, 0, EventLogEntryType.Error), "Unable to log .NET application events. " + ex.Message); } catch (Exception) { } } } } }
MegabonkTogether/LiteNetLib.dll
Decompiled 2 hours 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.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using LiteNetLib.Layers; using LiteNetLib.Utils; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Ruslan Pyrch")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2024 Ruslan Pyrch")] [assembly: AssemblyDescription("Lite reliable UDP library for .NET, Mono, and .NET Core")] [assembly: AssemblyFileVersion("1.3.5")] [assembly: AssemblyInformationalVersion("1.0.0+cf54c7d7a15a45bd2460cd4a460807329ee7026a")] [assembly: AssemblyProduct("LiteNetLib")] [assembly: AssemblyTitle("LiteNetLib")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/RevenantX/LiteNetLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.3.5.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } } namespace LiteNetLib { internal abstract class BaseChannel { protected readonly NetPeer Peer; protected readonly Queue<NetPacket> OutgoingQueue = new Queue<NetPacket>(64); private int _isAddedToPeerChannelSendQueue; public int PacketsInQueue => OutgoingQueue.Count; protected BaseChannel(NetPeer peer) { Peer = peer; } public void AddToQueue(NetPacket packet) { lock (OutgoingQueue) { OutgoingQueue.Enqueue(packet); } AddToPeerChannelSendQueue(); } protected void AddToPeerChannelSendQueue() { if (Interlocked.CompareExchange(ref _isAddedToPeerChannelSendQueue, 1, 0) == 0) { Peer.AddToReliableChannelSendQueue(this); } } public bool SendAndCheckQueue() { bool num = SendNextPackets(); if (!num) { Interlocked.Exchange(ref _isAddedToPeerChannelSendQueue, 0); } return num; } protected abstract bool SendNextPackets(); public abstract bool ProcessPacket(NetPacket packet); } internal enum ConnectionRequestResult { None, Accept, Reject, RejectForce } public class ConnectionRequest { private readonly NetManager _listener; private int _used; internal NetConnectRequestPacket InternalPacket; public readonly IPEndPoint RemoteEndPoint; public NetDataReader Data => InternalPacket.Data; internal ConnectionRequestResult Result { get; private set; } internal void UpdateRequest(NetConnectRequestPacket connectRequest) { if (connectRequest.ConnectionTime >= InternalPacket.ConnectionTime && (connectRequest.ConnectionTime != InternalPacket.ConnectionTime || connectRequest.ConnectionNumber != InternalPacket.ConnectionNumber)) { InternalPacket = connectRequest; } } private bool TryActivate() { return Interlocked.CompareExchange(ref _used, 1, 0) == 0; } internal ConnectionRequest(IPEndPoint remoteEndPoint, NetConnectRequestPacket requestPacket, NetManager listener) { InternalPacket = requestPacket; RemoteEndPoint = remoteEndPoint; _listener = listener; } public NetPeer AcceptIfKey(string key) { if (!TryActivate()) { return null; } try { if (Data.GetString() == key) { Result = ConnectionRequestResult.Accept; } } catch { NetDebug.WriteError("[AC] Invalid incoming data"); } if (Result == ConnectionRequestResult.Accept) { return _listener.OnConnectionSolved(this, null, 0, 0); } Result = ConnectionRequestResult.Reject; _listener.OnConnectionSolved(this, null, 0, 0); return null; } public NetPeer Accept() { if (!TryActivate()) { return null; } Result = ConnectionRequestResult.Accept; return _listener.OnConnectionSolved(this, null, 0, 0); } public void Reject(byte[] rejectData, int start, int length, bool force) { if (TryActivate()) { Result = (force ? ConnectionRequestResult.RejectForce : ConnectionRequestResult.Reject); _listener.OnConnectionSolved(this, rejectData, start, length); } } public void Reject(byte[] rejectData, int start, int length) { Reject(rejectData, start, length, force: false); } public void RejectForce(byte[] rejectData, int start, int length) { Reject(rejectData, start, length, force: true); } public void RejectForce() { Reject(null, 0, 0, force: true); } public void RejectForce(byte[] rejectData) { Reject(rejectData, 0, rejectData.Length, force: true); } public void RejectForce(NetDataWriter rejectData) { Reject(rejectData.Data, 0, rejectData.Length, force: true); } public void Reject() { Reject(null, 0, 0, force: false); } public void Reject(byte[] rejectData) { Reject(rejectData, 0, rejectData.Length, force: false); } public void Reject(NetDataWriter rejectData) { Reject(rejectData.Data, 0, rejectData.Length, force: false); } } public enum UnconnectedMessageType { BasicMessage, Broadcast } public enum DisconnectReason { ConnectionFailed, Timeout, HostUnreachable, NetworkUnreachable, RemoteConnectionClose, DisconnectPeerCalled, ConnectionRejected, InvalidProtocol, UnknownHost, Reconnect, PeerToPeerConnection, PeerNotFound } public struct DisconnectInfo { public DisconnectReason Reason; public SocketError SocketErrorCode; public NetPacketReader AdditionalData; } public interface INetEventListener { void OnPeerConnected(NetPeer peer); void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo); void OnNetworkError(IPEndPoint endPoint, SocketError socketError); void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod); void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType); void OnNetworkLatencyUpdate(NetPeer peer, int latency); void OnConnectionRequest(ConnectionRequest request); } public interface IDeliveryEventListener { void OnMessageDelivered(NetPeer peer, object userData); } public interface INtpEventListener { void OnNtpResponse(NtpPacket packet); } public interface IPeerAddressChangedListener { void OnPeerAddressChanged(NetPeer peer, IPEndPoint previousAddress); } public class EventBasedNetListener : INetEventListener, IDeliveryEventListener, INtpEventListener, IPeerAddressChangedListener { public delegate void OnPeerConnected(NetPeer peer); public delegate void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo); public delegate void OnNetworkError(IPEndPoint endPoint, SocketError socketError); public delegate void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod deliveryMethod); public delegate void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType); public delegate void OnNetworkLatencyUpdate(NetPeer peer, int latency); public delegate void OnConnectionRequest(ConnectionRequest request); public delegate void OnDeliveryEvent(NetPeer peer, object userData); public delegate void OnNtpResponseEvent(NtpPacket packet); public delegate void OnPeerAddressChangedEvent(NetPeer peer, IPEndPoint previousAddress); public event OnPeerConnected PeerConnectedEvent; public event OnPeerDisconnected PeerDisconnectedEvent; public event OnNetworkError NetworkErrorEvent; public event OnNetworkReceive NetworkReceiveEvent; public event OnNetworkReceiveUnconnected NetworkReceiveUnconnectedEvent; public event OnNetworkLatencyUpdate NetworkLatencyUpdateEvent; public event OnConnectionRequest ConnectionRequestEvent; public event OnDeliveryEvent DeliveryEvent; public event OnNtpResponseEvent NtpResponseEvent; public event OnPeerAddressChangedEvent PeerAddressChangedEvent; public void ClearPeerConnectedEvent() { this.PeerConnectedEvent = null; } public void ClearPeerDisconnectedEvent() { this.PeerDisconnectedEvent = null; } public void ClearNetworkErrorEvent() { this.NetworkErrorEvent = null; } public void ClearNetworkReceiveEvent() { this.NetworkReceiveEvent = null; } public void ClearNetworkReceiveUnconnectedEvent() { this.NetworkReceiveUnconnectedEvent = null; } public void ClearNetworkLatencyUpdateEvent() { this.NetworkLatencyUpdateEvent = null; } public void ClearConnectionRequestEvent() { this.ConnectionRequestEvent = null; } public void ClearDeliveryEvent() { this.DeliveryEvent = null; } public void ClearNtpResponseEvent() { this.NtpResponseEvent = null; } public void ClearPeerAddressChangedEvent() { this.PeerAddressChangedEvent = null; } void INetEventListener.OnPeerConnected(NetPeer peer) { if (this.PeerConnectedEvent != null) { this.PeerConnectedEvent(peer); } } void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) { if (this.PeerDisconnectedEvent != null) { this.PeerDisconnectedEvent(peer, disconnectInfo); } } void INetEventListener.OnNetworkError(IPEndPoint endPoint, SocketError socketErrorCode) { if (this.NetworkErrorEvent != null) { this.NetworkErrorEvent(endPoint, socketErrorCode); } } void INetEventListener.OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod) { if (this.NetworkReceiveEvent != null) { this.NetworkReceiveEvent(peer, reader, channelNumber, deliveryMethod); } } void INetEventListener.OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType) { if (this.NetworkReceiveUnconnectedEvent != null) { this.NetworkReceiveUnconnectedEvent(remoteEndPoint, reader, messageType); } } void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency) { if (this.NetworkLatencyUpdateEvent != null) { this.NetworkLatencyUpdateEvent(peer, latency); } } void INetEventListener.OnConnectionRequest(ConnectionRequest request) { if (this.ConnectionRequestEvent != null) { this.ConnectionRequestEvent(request); } } void IDeliveryEventListener.OnMessageDelivered(NetPeer peer, object userData) { if (this.DeliveryEvent != null) { this.DeliveryEvent(peer, userData); } } void INtpEventListener.OnNtpResponse(NtpPacket packet) { if (this.NtpResponseEvent != null) { this.NtpResponseEvent(packet); } } void IPeerAddressChangedListener.OnPeerAddressChanged(NetPeer peer, IPEndPoint previousAddress) { if (this.PeerAddressChangedEvent != null) { this.PeerAddressChangedEvent(peer, previousAddress); } } } internal sealed class NetConnectRequestPacket { public const int HeaderSize = 18; public readonly long ConnectionTime; public byte ConnectionNumber; public readonly byte[] TargetAddress; public readonly NetDataReader Data; public readonly int PeerId; private NetConnectRequestPacket(long connectionTime, byte connectionNumber, int localId, byte[] targetAddress, NetDataReader data) { ConnectionTime = connectionTime; ConnectionNumber = connectionNumber; TargetAddress = targetAddress; Data = data; PeerId = localId; } public static int GetProtocolId(NetPacket packet) { return BitConverter.ToInt32(packet.RawData, 1); } public static NetConnectRequestPacket FromData(NetPacket packet) { if (packet.ConnectionNumber >= 4) { return null; } long connectionTime = BitConverter.ToInt64(packet.RawData, 5); int localId = BitConverter.ToInt32(packet.RawData, 13); int num = packet.RawData[17]; if (num != 16 && num != 28) { return null; } byte[] array = new byte[num]; Buffer.BlockCopy(packet.RawData, 18, array, 0, num); NetDataReader netDataReader = new NetDataReader(null, 0, 0); if (packet.Size > 18 + num) { netDataReader.SetSource(packet.RawData, 18 + num, packet.Size); } return new NetConnectRequestPacket(connectionTime, packet.ConnectionNumber, localId, array, netDataReader); } public static NetPacket Make(NetDataWriter connectData, SocketAddress addressBytes, long connectTime, int localId) { NetPacket netPacket = new NetPacket(PacketProperty.ConnectRequest, connectData.Length + addressBytes.Size); FastBitConverter.GetBytes(netPacket.RawData, 1, 13); FastBitConverter.GetBytes(netPacket.RawData, 5, connectTime); FastBitConverter.GetBytes(netPacket.RawData, 13, localId); netPacket.RawData[17] = (byte)addressBytes.Size; for (int i = 0; i < addressBytes.Size; i++) { netPacket.RawData[18 + i] = addressBytes[i]; } Buffer.BlockCopy(connectData.Data, 0, netPacket.RawData, 18 + addressBytes.Size, connectData.Length); return netPacket; } public static NetPacket Make(ReadOnlySpan<byte> connectData, SocketAddress addressBytes, long connectTime, int localId) { NetPacket netPacket = new NetPacket(PacketProperty.ConnectRequest, connectData.Length + addressBytes.Size); FastBitConverter.GetBytes(netPacket.RawData, 1, 13); FastBitConverter.GetBytes(netPacket.RawData, 5, connectTime); FastBitConverter.GetBytes(netPacket.RawData, 13, localId); netPacket.RawData[17] = (byte)addressBytes.Size; for (int i = 0; i < addressBytes.Size; i++) { netPacket.RawData[18 + i] = addressBytes[i]; } connectData.CopyTo(netPacket.RawData.AsSpan(18 + addressBytes.Size)); return netPacket; } } internal sealed class NetConnectAcceptPacket { public const int Size = 15; public readonly long ConnectionTime; public readonly byte ConnectionNumber; public readonly int PeerId; public readonly bool PeerNetworkChanged; private NetConnectAcceptPacket(long connectionTime, byte connectionNumber, int peerId, bool peerNetworkChanged) { ConnectionTime = connectionTime; ConnectionNumber = connectionNumber; PeerId = peerId; PeerNetworkChanged = peerNetworkChanged; } public static NetConnectAcceptPacket FromData(NetPacket packet) { if (packet.Size != 15) { return null; } long connectionTime = BitConverter.ToInt64(packet.RawData, 1); byte b = packet.RawData[9]; if (b >= 4) { return null; } byte b2 = packet.RawData[10]; if (b2 > 1) { return null; } int num = BitConverter.ToInt32(packet.RawData, 11); if (num < 0) { return null; } return new NetConnectAcceptPacket(connectionTime, b, num, b2 == 1); } public static NetPacket Make(long connectTime, byte connectNum, int localPeerId) { NetPacket netPacket = new NetPacket(PacketProperty.ConnectAccept, 0); FastBitConverter.GetBytes(netPacket.RawData, 1, connectTime); netPacket.RawData[9] = connectNum; FastBitConverter.GetBytes(netPacket.RawData, 11, localPeerId); return netPacket; } public static NetPacket MakeNetworkChanged(NetPeer peer) { NetPacket netPacket = new NetPacket(PacketProperty.PeerNotFound, 14); FastBitConverter.GetBytes(netPacket.RawData, 1, peer.ConnectTime); netPacket.RawData[9] = peer.ConnectionNum; netPacket.RawData[10] = 1; FastBitConverter.GetBytes(netPacket.RawData, 11, peer.RemoteId); return netPacket; } } internal static class NativeSocket { private static class WinSock { private const string LibName = "ws2_32.dll"; [DllImport("ws2_32.dll", SetLastError = true)] public static extern int recvfrom(IntPtr socketHandle, [In][Out] byte[] pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [Out] byte[] socketAddress, [In][Out] ref int socketAddressSize); [DllImport("ws2_32.dll", SetLastError = true)] internal unsafe static extern int sendto(IntPtr socketHandle, byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [In] byte[] socketAddress, [In] int socketAddressSize); } private static class UnixSock { private const string LibName = "libc"; [DllImport("libc", SetLastError = true)] public static extern int recvfrom(IntPtr socketHandle, [In][Out] byte[] pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [Out] byte[] socketAddress, [In][Out] ref int socketAddressSize); [DllImport("libc", SetLastError = true)] internal unsafe static extern int sendto(IntPtr socketHandle, byte* pinnedBuffer, [In] int len, [In] SocketFlags socketFlags, [In] byte[] socketAddress, [In] int socketAddressSize); } public static readonly bool IsSupported; public static readonly bool UnixMode; public const int IPv4AddrSize = 16; public const int IPv6AddrSize = 28; public const int AF_INET = 2; public const int AF_INET6 = 10; private static readonly Dictionary<int, SocketError> NativeErrorToSocketError; static NativeSocket() { IsSupported = false; UnixMode = false; NativeErrorToSocketError = new Dictionary<int, SocketError> { { 13, SocketError.AccessDenied }, { 98, SocketError.AddressAlreadyInUse }, { 99, SocketError.AddressNotAvailable }, { 97, SocketError.AddressFamilyNotSupported }, { 11, SocketError.WouldBlock }, { 114, SocketError.AlreadyInProgress }, { 9, SocketError.OperationAborted }, { 125, SocketError.OperationAborted }, { 103, SocketError.ConnectionAborted }, { 111, SocketError.ConnectionRefused }, { 104, SocketError.ConnectionReset }, { 89, SocketError.DestinationAddressRequired }, { 14, SocketError.Fault }, { 112, SocketError.HostDown }, { 6, SocketError.HostNotFound }, { 113, SocketError.HostUnreachable }, { 115, SocketError.InProgress }, { 4, SocketError.Interrupted }, { 22, SocketError.InvalidArgument }, { 106, SocketError.IsConnected }, { 24, SocketError.TooManyOpenSockets }, { 90, SocketError.MessageSize }, { 100, SocketError.NetworkDown }, { 102, SocketError.NetworkReset }, { 101, SocketError.NetworkUnreachable }, { 23, SocketError.TooManyOpenSockets }, { 105, SocketError.NoBufferSpaceAvailable }, { 61, SocketError.NoData }, { 2, SocketError.AddressNotAvailable }, { 92, SocketError.ProtocolOption }, { 107, SocketError.NotConnected }, { 88, SocketError.NotSocket }, { 3440, SocketError.OperationNotSupported }, { 1, SocketError.AccessDenied }, { 32, SocketError.Shutdown }, { 96, SocketError.ProtocolFamilyNotSupported }, { 93, SocketError.ProtocolNotSupported }, { 91, SocketError.ProtocolType }, { 94, SocketError.SocketNotSupported }, { 108, SocketError.Disconnecting }, { 110, SocketError.TimedOut }, { 0, SocketError.Success } }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { IsSupported = true; UnixMode = true; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { IsSupported = true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int RecvFrom(IntPtr socketHandle, byte[] pinnedBuffer, int len, byte[] socketAddress, ref int socketAddressSize) { if (!UnixMode) { return WinSock.recvfrom(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, ref socketAddressSize); } return UnixSock.recvfrom(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, ref socketAddressSize); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int SendTo(IntPtr socketHandle, byte* pinnedBuffer, int len, byte[] socketAddress, int socketAddressSize) { if (!UnixMode) { return WinSock.sendto(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, socketAddressSize); } return UnixSock.sendto(socketHandle, pinnedBuffer, len, SocketFlags.None, socketAddress, socketAddressSize); } public static SocketError GetSocketError() { int lastWin32Error = Marshal.GetLastWin32Error(); if (UnixMode) { if (!NativeErrorToSocketError.TryGetValue(lastWin32Error, out var value)) { return SocketError.SocketError; } return value; } return (SocketError)lastWin32Error; } public static SocketException GetSocketException() { int lastWin32Error = Marshal.GetLastWin32Error(); if (UnixMode) { if (!NativeErrorToSocketError.TryGetValue(lastWin32Error, out var value)) { return new SocketException(-1); } return new SocketException((int)value); } return new SocketException(lastWin32Error); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short GetNativeAddressFamily(IPEndPoint remoteEndPoint) { if (!UnixMode) { return (short)remoteEndPoint.AddressFamily; } return (short)((remoteEndPoint.AddressFamily == AddressFamily.InterNetwork) ? 2 : 10); } } public enum NatAddressType { Internal, External } public interface INatPunchListener { void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token); void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token); } public class EventBasedNatPunchListener : INatPunchListener { public delegate void OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token); public delegate void OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token); public event OnNatIntroductionRequest NatIntroductionRequest; public event OnNatIntroductionSuccess NatIntroductionSuccess; void INatPunchListener.OnNatIntroductionRequest(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, string token) { if (this.NatIntroductionRequest != null) { this.NatIntroductionRequest(localEndPoint, remoteEndPoint, token); } } void INatPunchListener.OnNatIntroductionSuccess(IPEndPoint targetEndPoint, NatAddressType type, string token) { if (this.NatIntroductionSuccess != null) { this.NatIntroductionSuccess(targetEndPoint, type, token); } } } public sealed class NatPunchModule { private struct RequestEventData { public IPEndPoint LocalEndPoint; public IPEndPoint RemoteEndPoint; public string Token; } private struct SuccessEventData { public IPEndPoint TargetEndPoint; public NatAddressType Type; public string Token; } private class NatIntroduceRequestPacket { public IPEndPoint Internal { [Preserve] get; [Preserve] set; } public string Token { [Preserve] get; [Preserve] set; } } private class NatIntroduceResponsePacket { public IPEndPoint Internal { [Preserve] get; [Preserve] set; } public IPEndPoint External { [Preserve] get; [Preserve] set; } public string Token { [Preserve] get; [Preserve] set; } } private class NatPunchPacket { public string Token { [Preserve] get; [Preserve] set; } public bool IsExternal { [Preserve] get; [Preserve] set; } } private readonly NetManager _socket; private readonly ConcurrentQueue<RequestEventData> _requestEvents = new ConcurrentQueue<RequestEventData>(); private readonly ConcurrentQueue<SuccessEventData> _successEvents = new ConcurrentQueue<SuccessEventData>(); private readonly NetDataReader _cacheReader = new NetDataReader(); private readonly NetDataWriter _cacheWriter = new NetDataWriter(); private readonly NetPacketProcessor _netPacketProcessor = new NetPacketProcessor(256); private INatPunchListener _natPunchListener; public const int MaxTokenLength = 256; public bool UnsyncedEvents; internal NatPunchModule(NetManager socket) { _socket = socket; _netPacketProcessor.SubscribeReusable<NatIntroduceResponsePacket>(OnNatIntroductionResponse); _netPacketProcessor.SubscribeReusable<NatIntroduceRequestPacket, IPEndPoint>(OnNatIntroductionRequest); _netPacketProcessor.SubscribeReusable<NatPunchPacket, IPEndPoint>(OnNatPunch); } internal void ProcessMessage(IPEndPoint senderEndPoint, NetPacket packet) { lock (_cacheReader) { _cacheReader.SetSource(packet.RawData, 1, packet.Size); _netPacketProcessor.ReadAllPackets(_cacheReader, senderEndPoint); } } public void Init(INatPunchListener listener) { _natPunchListener = listener; } private void Send<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T packet, IPEndPoint target) where T : class, new() { _cacheWriter.Reset(); _cacheWriter.Put((byte)16); _netPacketProcessor.Write(_cacheWriter, packet); _socket.SendRaw(_cacheWriter.Data, 0, _cacheWriter.Length, target); } public void NatIntroduce(IPEndPoint hostInternal, IPEndPoint hostExternal, IPEndPoint clientInternal, IPEndPoint clientExternal, string additionalInfo) { NatIntroduceResponsePacket natIntroduceResponsePacket = new NatIntroduceResponsePacket { Token = additionalInfo }; natIntroduceResponsePacket.Internal = hostInternal; natIntroduceResponsePacket.External = hostExternal; Send(natIntroduceResponsePacket, clientExternal); natIntroduceResponsePacket.Internal = clientInternal; natIntroduceResponsePacket.External = clientExternal; Send(natIntroduceResponsePacket, hostExternal); } public void PollEvents() { if (!UnsyncedEvents && _natPunchListener != null && (!_successEvents.IsEmpty || !_requestEvents.IsEmpty)) { SuccessEventData result; while (_successEvents.TryDequeue(out result)) { _natPunchListener.OnNatIntroductionSuccess(result.TargetEndPoint, result.Type, result.Token); } RequestEventData result2; while (_requestEvents.TryDequeue(out result2)) { _natPunchListener.OnNatIntroductionRequest(result2.LocalEndPoint, result2.RemoteEndPoint, result2.Token); } } } public void SendNatIntroduceRequest(string host, int port, string additionalInfo) { SendNatIntroduceRequest(NetUtils.MakeEndPoint(host, port), additionalInfo); } public void SendNatIntroduceRequest(IPEndPoint masterServerEndPoint, string additionalInfo) { string localIp = NetUtils.GetLocalIp(LocalAddrType.IPv4); if (string.IsNullOrEmpty(localIp) || masterServerEndPoint.AddressFamily == AddressFamily.InterNetworkV6) { localIp = NetUtils.GetLocalIp(LocalAddrType.IPv6); } Send(new NatIntroduceRequestPacket { Internal = NetUtils.MakeEndPoint(localIp, _socket.LocalPort), Token = additionalInfo }, masterServerEndPoint); } private void OnNatIntroductionRequest(NatIntroduceRequestPacket req, IPEndPoint senderEndPoint) { if (UnsyncedEvents) { _natPunchListener.OnNatIntroductionRequest(req.Internal, senderEndPoint, req.Token); return; } _requestEvents.Enqueue(new RequestEventData { LocalEndPoint = req.Internal, RemoteEndPoint = senderEndPoint, Token = req.Token }); } private void OnNatIntroductionResponse(NatIntroduceResponsePacket req) { NatPunchPacket natPunchPacket = new NatPunchPacket { Token = req.Token }; Send(natPunchPacket, req.Internal); _socket.Ttl = 2; _socket.SendRaw(new byte[1] { 17 }, 0, 1, req.External); _socket.Ttl = 255; natPunchPacket.IsExternal = true; Send(natPunchPacket, req.External); } private void OnNatPunch(NatPunchPacket req, IPEndPoint senderEndPoint) { if (UnsyncedEvents) { _natPunchListener.OnNatIntroductionSuccess(senderEndPoint, req.IsExternal ? NatAddressType.External : NatAddressType.Internal, req.Token); return; } _successEvents.Enqueue(new SuccessEventData { TargetEndPoint = senderEndPoint, Type = (req.IsExternal ? NatAddressType.External : NatAddressType.Internal), Token = req.Token }); } } public enum DeliveryMethod : byte { Unreliable = 4, ReliableUnordered = 0, Sequenced = 1, ReliableOrdered = 2, ReliableSequenced = 3 } public static class NetConstants { public const int DefaultWindowSize = 64; public const int SocketBufferSize = 1048576; public const int SocketTTL = 255; public const int HeaderSize = 1; public const int ChanneledHeaderSize = 4; public const int FragmentHeaderSize = 6; public const int FragmentedHeaderTotalSize = 10; public const ushort MaxSequence = 32768; public const ushort HalfMaxSequence = 16384; internal const int ProtocolId = 13; internal const int MaxUdpHeaderSize = 68; internal const int ChannelTypeCount = 4; internal const int FragmentedChannelsCount = 2; internal const int MaxFragmentsInWindow = 32; internal static readonly int[] PossibleMtu = new int[6] { 1024, 1164, 1392, 1404, 1424, 1432 }; public static readonly int InitialMtu = PossibleMtu[0]; public static readonly int MaxPacketSize = PossibleMtu[PossibleMtu.Length - 1]; public static readonly int MaxUnreliableDataSize = MaxPacketSize - 1; public const byte MaxConnectionNumber = 4; } public class InvalidPacketException : ArgumentException { public InvalidPacketException(string message) : base(message) { } } public class TooBigPacketException : InvalidPacketException { public TooBigPacketException(string message) : base(message) { } } public enum NetLogLevel { Warning, Error, Trace, Info } public interface INetLogger { void WriteNet(NetLogLevel level, string str, params object[] args); } public static class NetDebug { public static INetLogger Logger = null; private static readonly object DebugLogLock = new object(); private static void WriteLogic(NetLogLevel logLevel, string str, params object[] args) { lock (DebugLogLock) { if (Logger == null) { Console.WriteLine(str, args); } else { Logger.WriteNet(logLevel, str, args); } } } [Conditional("DEBUG_MESSAGES")] internal static void Write(string str) { WriteLogic(NetLogLevel.Trace, str); } [Conditional("DEBUG_MESSAGES")] internal static void Write(NetLogLevel level, string str) { WriteLogic(level, str); } [Conditional("DEBUG_MESSAGES")] [Conditional("DEBUG")] internal static void WriteForce(string str) { WriteLogic(NetLogLevel.Trace, str); } [Conditional("DEBUG_MESSAGES")] [Conditional("DEBUG")] internal static void WriteForce(NetLogLevel level, string str) { WriteLogic(level, str); } internal static void WriteError(string str) { WriteLogic(NetLogLevel.Error, str); } } public sealed class NetPacketReader : NetDataReader { private NetPacket _packet; private readonly NetManager _manager; private readonly NetEvent _evt; internal NetPacketReader(NetManager manager, NetEvent evt) { _manager = manager; _evt = evt; } internal void SetSource(NetPacket packet, int headerSize) { if (packet != null) { _packet = packet; SetSource(packet.RawData, headerSize, packet.Size); } } internal void RecycleInternal() { Clear(); if (_packet != null) { _manager.PoolRecycle(_packet); } _packet = null; _manager.RecycleEvent(_evt); } public void Recycle() { if (!_manager.AutoRecycle) { RecycleInternal(); } } } internal sealed class NetEvent { public enum EType { Connect, Disconnect, Receive, ReceiveUnconnected, Error, ConnectionLatencyUpdated, Broadcast, ConnectionRequest, MessageDelivered, PeerAddressChanged } public NetEvent Next; public EType Type; public NetPeer Peer; public IPEndPoint RemoteEndPoint; public object UserData; public int Latency; public SocketError ErrorCode; public DisconnectReason DisconnectReason; public ConnectionRequest ConnectionRequest; public DeliveryMethod DeliveryMethod; public byte ChannelNumber; public readonly NetPacketReader DataReader; public NetEvent(NetManager manager) { DataReader = new NetPacketReader(manager, this); } } public class NetManager : IEnumerable<NetPeer>, IEnumerable { public struct NetPeerEnumerator : IEnumerator<NetPeer>, IEnumerator, IDisposable { private readonly NetPeer _initialPeer; private NetPeer _p; public NetPeer Current => _p; object IEnumerator.Current => _p; public NetPeerEnumerator(NetPeer p) { _initialPeer = p; _p = null; } public void Dispose() { } public bool MoveNext() { _p = ((_p == null) ? _initialPeer : _p.NextPeer); return _p != null; } public void Reset() { throw new NotSupportedException(); } } private struct IncomingData { public NetPacket Data; public IPEndPoint EndPoint; public DateTime TimeWhenGet; } private struct OutboundDelayedPacket { public byte[] Data; public int Start; public int Length; public IPEndPoint EndPoint; public DateTime TimeWhenSend; } private struct Slot { internal int HashCode; internal int Next; internal NetPeer Value; } private readonly List<IncomingData> _pingSimulationList = new List<IncomingData>(); private readonly List<OutboundDelayedPacket> _outboundSimulationList = new List<OutboundDelayedPacket>(); private readonly Random _randomGenerator = new Random(); private const int MinLatencyThreshold = 5; private Thread _logicThread; private bool _manualMode; private readonly AutoResetEvent _updateTriggerEvent = new AutoResetEvent(initialState: true); private NetEvent _pendingEventHead; private NetEvent _pendingEventTail; private NetEvent _netEventPoolHead; private readonly INetEventListener _netEventListener; private readonly IDeliveryEventListener _deliveryEventListener; private readonly INtpEventListener _ntpEventListener; private readonly IPeerAddressChangedListener _peerAddressChangedListener; private readonly Dictionary<IPEndPoint, ConnectionRequest> _requestsDict = new Dictionary<IPEndPoint, ConnectionRequest>(); private readonly ConcurrentDictionary<IPEndPoint, NtpRequest> _ntpRequests = new ConcurrentDictionary<IPEndPoint, NtpRequest>(); private long _connectedPeersCount; private readonly List<NetPeer> _connectedPeerListCache = new List<NetPeer>(); private readonly PacketLayerBase _extraPacketLayer; private int _lastPeerId; private ConcurrentQueue<int> _peerIds = new ConcurrentQueue<int>(); private byte _channelsCount = 1; private readonly object _eventLock = new object(); private volatile bool _isRunning; private bool _dropPacket; public bool UnconnectedMessagesEnabled; public bool NatPunchEnabled; public int UpdateTime = 15; public int PingInterval = 1000; public int DisconnectTimeout = 5000; public bool SimulatePacketLoss; public bool SimulateLatency; public int SimulationPacketLossChance = 10; public int SimulationMinLatency = 30; public int SimulationMaxLatency = 100; public bool UnsyncedEvents; public bool UnsyncedReceiveEvent; public bool UnsyncedDeliveryEvent; public bool BroadcastReceiveEnabled; public int ReconnectDelay = 500; public int MaxConnectAttempts = 10; public bool ReuseAddress; public bool DontRoute; public readonly NetStatistics Statistics = new NetStatistics(); public bool EnableStatistics; public readonly NatPunchModule NatPunchModule; public bool AutoRecycle; public bool IPv6Enabled = true; public int MtuOverride; public bool MtuDiscovery; public bool UseNativeSockets; public bool DisconnectOnUnreachable; public bool AllowPeerAddressChange; private const int MaxPrimeArrayLength = 2147483587; private const int HashPrime = 101; private const int Lower31BitMask = int.MaxValue; private static readonly int[] Primes; private int[] _buckets; private Slot[] _slots; private int _count; private int _lastIndex; private int _freeList = -1; private NetPeer[] _peersArray = new NetPeer[32]; private readonly ReaderWriterLockSlim _peersLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); private volatile NetPeer _headPeer; private NetPacket _poolHead; private int _poolCount; private readonly object _poolLock = new object(); public int PacketPoolSize = 1000; private Socket _udpSocketv4; private Socket _udpSocketv6; private Thread _receiveThread; private IPEndPoint _bufferEndPointv4; private IPEndPoint _bufferEndPointv6; private const int SioUdpConnreset = -1744830452; private static readonly IPAddress MulticastAddressV6; public static readonly bool IPv6Support; internal bool NotConnected; public int ReceivePollingTime = 50000; public bool IsRunning => _isRunning; public int LocalPort { get; private set; } public NetPeer FirstPeer => _headPeer; public byte ChannelsCount { get { return _channelsCount; } set { if (value < 1 || value > 64) { throw new ArgumentException("Channels count must be between 1 and 64"); } _channelsCount = value; } } public List<NetPeer> ConnectedPeerList { get { GetPeersNonAlloc(_connectedPeerListCache, ConnectionState.Connected); return _connectedPeerListCache; } } public int ConnectedPeersCount => (int)Interlocked.Read(ref _connectedPeersCount); public int ExtraPacketSizeForLayer => _extraPacketLayer?.ExtraPacketSizeForLayer ?? 0; public int PoolCount => _poolCount; public short Ttl { get { return _udpSocketv4.Ttl; } internal set { _udpSocketv4.Ttl = value; } } public NetManager(INetEventListener listener, PacketLayerBase extraPacketLayer = null) { _netEventListener = listener; _deliveryEventListener = listener as IDeliveryEventListener; _ntpEventListener = listener as INtpEventListener; _peerAddressChangedListener = listener as IPeerAddressChangedListener; NatPunchModule = new NatPunchModule(this); _extraPacketLayer = extraPacketLayer; } internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency) { CreateEvent(NetEvent.EType.ConnectionLatencyUpdated, fromPeer, null, SocketError.Success, latency, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); } internal void MessageDelivered(NetPeer fromPeer, object userData) { if (_deliveryEventListener != null) { CreateEvent(NetEvent.EType.MessageDelivered, fromPeer, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, null, userData); } } internal void DisconnectPeerForce(NetPeer peer, DisconnectReason reason, SocketError socketErrorCode, NetPacket eventData) { DisconnectPeer(peer, reason, socketErrorCode, force: true, null, 0, 0, eventData); } private void DisconnectPeer(NetPeer peer, DisconnectReason reason, SocketError socketErrorCode, bool force, byte[] data, int start, int count, NetPacket eventData) { switch (peer.Shutdown(data, start, count, force)) { case ShutdownResult.None: return; case ShutdownResult.WasConnected: Interlocked.Decrement(ref _connectedPeersCount); break; } CreateEvent(NetEvent.EType.Disconnect, peer, null, socketErrorCode, 0, reason, null, DeliveryMethod.Unreliable, 0, eventData); } private void CreateEvent(NetEvent.EType type, NetPeer peer = null, IPEndPoint remoteEndPoint = null, SocketError errorCode = SocketError.Success, int latency = 0, DisconnectReason disconnectReason = DisconnectReason.ConnectionFailed, ConnectionRequest connectionRequest = null, DeliveryMethod deliveryMethod = DeliveryMethod.Unreliable, byte channelNumber = 0, NetPacket readerSource = null, object userData = null) { bool flag = UnsyncedEvents; switch (type) { case NetEvent.EType.Connect: Interlocked.Increment(ref _connectedPeersCount); break; case NetEvent.EType.MessageDelivered: flag = UnsyncedDeliveryEvent; break; } NetEvent netEvent; lock (_eventLock) { netEvent = _netEventPoolHead; if (netEvent == null) { netEvent = new NetEvent(this); } else { _netEventPoolHead = netEvent.Next; } } netEvent.Next = null; netEvent.Type = type; netEvent.DataReader.SetSource(readerSource, readerSource?.GetHeaderSize() ?? 0); netEvent.Peer = peer; netEvent.RemoteEndPoint = remoteEndPoint; netEvent.Latency = latency; netEvent.ErrorCode = errorCode; netEvent.DisconnectReason = disconnectReason; netEvent.ConnectionRequest = connectionRequest; netEvent.DeliveryMethod = deliveryMethod; netEvent.ChannelNumber = channelNumber; netEvent.UserData = userData; if (flag || _manualMode) { ProcessEvent(netEvent); return; } lock (_eventLock) { if (_pendingEventTail == null) { _pendingEventHead = netEvent; } else { _pendingEventTail.Next = netEvent; } _pendingEventTail = netEvent; } } private void ProcessEvent(NetEvent evt) { bool isNull = evt.DataReader.IsNull; switch (evt.Type) { case NetEvent.EType.Connect: _netEventListener.OnPeerConnected(evt.Peer); break; case NetEvent.EType.Disconnect: { DisconnectInfo disconnectInfo = default(DisconnectInfo); disconnectInfo.Reason = evt.DisconnectReason; disconnectInfo.AdditionalData = evt.DataReader; disconnectInfo.SocketErrorCode = evt.ErrorCode; DisconnectInfo disconnectInfo2 = disconnectInfo; _netEventListener.OnPeerDisconnected(evt.Peer, disconnectInfo2); break; } case NetEvent.EType.Receive: _netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader, evt.ChannelNumber, evt.DeliveryMethod); break; case NetEvent.EType.ReceiveUnconnected: _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.BasicMessage); break; case NetEvent.EType.Broadcast: _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.Broadcast); break; case NetEvent.EType.Error: _netEventListener.OnNetworkError(evt.RemoteEndPoint, evt.ErrorCode); break; case NetEvent.EType.ConnectionLatencyUpdated: _netEventListener.OnNetworkLatencyUpdate(evt.Peer, evt.Latency); break; case NetEvent.EType.ConnectionRequest: _netEventListener.OnConnectionRequest(evt.ConnectionRequest); break; case NetEvent.EType.MessageDelivered: _deliveryEventListener.OnMessageDelivered(evt.Peer, evt.UserData); break; case NetEvent.EType.PeerAddressChanged: { _peersLock.EnterUpgradeableReadLock(); IPEndPoint iPEndPoint = null; if (ContainsPeer(evt.Peer)) { _peersLock.EnterWriteLock(); RemovePeerFromSet(evt.Peer); iPEndPoint = new IPEndPoint(evt.Peer.Address, evt.Peer.Port); evt.Peer.FinishEndPointChange(evt.RemoteEndPoint); AddPeerToSet(evt.Peer); _peersLock.ExitWriteLock(); } _peersLock.ExitUpgradeableReadLock(); if (iPEndPoint != null && _peerAddressChangedListener != null) { _peerAddressChangedListener.OnPeerAddressChanged(evt.Peer, iPEndPoint); } break; } } if (isNull) { RecycleEvent(evt); } else if (AutoRecycle) { evt.DataReader.RecycleInternal(); } } internal void RecycleEvent(NetEvent evt) { evt.Peer = null; evt.ErrorCode = SocketError.Success; evt.RemoteEndPoint = null; evt.ConnectionRequest = null; lock (_eventLock) { evt.Next = _netEventPoolHead; _netEventPoolHead = evt; } } private void UpdateLogic() { List<NetPeer> list = new List<NetPeer>(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (_isRunning) { try { float num = (float)((double)stopwatch.ElapsedTicks / (double)Stopwatch.Frequency * 1000.0); num = ((num <= 0f) ? 0.001f : num); stopwatch.Restart(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if (netPeer.ConnectionState == ConnectionState.Disconnected && netPeer.TimeSinceLastPacket > (float)DisconnectTimeout) { list.Add(netPeer); } else { netPeer.Update(num); } } if (list.Count > 0) { _peersLock.EnterWriteLock(); for (int i = 0; i < list.Count; i++) { RemovePeer(list[i], enableWriteLock: false); } _peersLock.ExitWriteLock(); list.Clear(); } ProcessNtpRequests(num); int num2 = UpdateTime - (int)stopwatch.ElapsedMilliseconds; if (num2 > 0) { _updateTriggerEvent.WaitOne(num2); } } catch (ThreadAbortException) { return; } catch (Exception ex2) { NetDebug.WriteError("[NM] LogicThread error: " + ex2); } } stopwatch.Stop(); } [Conditional("DEBUG")] [Conditional("SIMULATE_NETWORK")] private void ProcessDelayedPackets() { if (!SimulateLatency) { return; } DateTime utcNow = DateTime.UtcNow; lock (_pingSimulationList) { for (int i = 0; i < _pingSimulationList.Count; i++) { IncomingData incomingData = _pingSimulationList[i]; if (incomingData.TimeWhenGet <= utcNow) { HandleMessageReceived(incomingData.Data, incomingData.EndPoint); _pingSimulationList.RemoveAt(i); i--; } } } lock (_outboundSimulationList) { for (int j = 0; j < _outboundSimulationList.Count; j++) { OutboundDelayedPacket outboundDelayedPacket = _outboundSimulationList[j]; if (outboundDelayedPacket.TimeWhenSend <= utcNow) { SendRawCore(outboundDelayedPacket.Data, outboundDelayedPacket.Start, outboundDelayedPacket.Length, outboundDelayedPacket.EndPoint); _outboundSimulationList.RemoveAt(j); j--; } } } } private void ProcessNtpRequests(float elapsedMilliseconds) { if (_ntpRequests.IsEmpty) { return; } List<IPEndPoint> list = null; foreach (KeyValuePair<IPEndPoint, NtpRequest> ntpRequest in _ntpRequests) { ntpRequest.Value.Send(_udpSocketv4, elapsedMilliseconds); if (ntpRequest.Value.NeedToKill) { if (list == null) { list = new List<IPEndPoint>(); } list.Add(ntpRequest.Key); } } if (list == null) { return; } foreach (IPEndPoint item in list) { _ntpRequests.TryRemove(item, out var _); } } public void ManualUpdate(float elapsedMilliseconds) { if (!_manualMode) { return; } for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if (netPeer.ConnectionState == ConnectionState.Disconnected && netPeer.TimeSinceLastPacket > (float)DisconnectTimeout) { RemovePeer(netPeer, enableWriteLock: false); } else { netPeer.Update(elapsedMilliseconds); } } ProcessNtpRequests(elapsedMilliseconds); } internal NetPeer OnConnectionSolved(ConnectionRequest request, byte[] rejectData, int start, int length) { NetPeer actualValue = null; if (request.Result == ConnectionRequestResult.RejectForce) { if (rejectData != null && length > 0) { NetPacket netPacket = PoolGetWithProperty(PacketProperty.Disconnect, length); netPacket.ConnectionNumber = request.InternalPacket.ConnectionNumber; FastBitConverter.GetBytes(netPacket.RawData, 1, request.InternalPacket.ConnectionTime); if (netPacket.Size >= NetConstants.PossibleMtu[0]) { NetDebug.WriteError("[Peer] Disconnect additional data size more than MTU!"); } else { Buffer.BlockCopy(rejectData, start, netPacket.RawData, 9, length); } SendRawAndRecycle(netPacket, request.RemoteEndPoint); } lock (_requestsDict) { _requestsDict.Remove(request.RemoteEndPoint); } } else { lock (_requestsDict) { if (!TryGetPeer(request.RemoteEndPoint, out actualValue)) { if (request.Result == ConnectionRequestResult.Reject) { actualValue = new NetPeer(this, request.RemoteEndPoint, GetNextPeerId()); actualValue.Reject(request.InternalPacket, rejectData, start, length); AddPeer(actualValue); } else { actualValue = new NetPeer(this, request, GetNextPeerId()); AddPeer(actualValue); CreateEvent(NetEvent.EType.Connect, actualValue, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); } } _requestsDict.Remove(request.RemoteEndPoint); } } return actualValue; } private int GetNextPeerId() { if (!_peerIds.TryDequeue(out var result)) { return _lastPeerId++; } return result; } private void ProcessConnectRequest(IPEndPoint remoteEndPoint, NetPeer netPeer, NetConnectRequestPacket connRequest) { if (netPeer != null) { ConnectRequestResult connectRequestResult = netPeer.ProcessConnectRequest(connRequest); switch (connectRequestResult) { default: return; case ConnectRequestResult.Reconnection: DisconnectPeerForce(netPeer, DisconnectReason.Reconnect, SocketError.Success, null); RemovePeer(netPeer, enableWriteLock: true); break; case ConnectRequestResult.NewConnection: RemovePeer(netPeer, enableWriteLock: true); break; case ConnectRequestResult.P2PLose: DisconnectPeerForce(netPeer, DisconnectReason.PeerToPeerConnection, SocketError.Success, null); RemovePeer(netPeer, enableWriteLock: true); break; } if (connectRequestResult != ConnectRequestResult.P2PLose) { connRequest.ConnectionNumber = (byte)((netPeer.ConnectionNum + 1) % 4); } } ConnectionRequest value; lock (_requestsDict) { if (_requestsDict.TryGetValue(remoteEndPoint, out value)) { value.UpdateRequest(connRequest); return; } value = new ConnectionRequest(remoteEndPoint, connRequest, this); _requestsDict.Add(remoteEndPoint, value); } CreateEvent(NetEvent.EType.ConnectionRequest, null, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, value, DeliveryMethod.Unreliable, 0); } private void OnMessageReceived(NetPacket packet, IPEndPoint remoteEndPoint) { if (packet.Size == 0) { PoolRecycle(packet); return; } _dropPacket = false; if (!_dropPacket) { HandleMessageReceived(packet, remoteEndPoint); } } [Conditional("DEBUG")] [Conditional("SIMULATE_NETWORK")] private void HandleSimulateLatency(NetPacket packet, IPEndPoint remoteEndPoint) { if (!SimulateLatency) { return; } int num = _randomGenerator.Next(SimulationMinLatency, SimulationMaxLatency) / 2; if (num > 5) { lock (_pingSimulationList) { _pingSimulationList.Add(new IncomingData { Data = packet, EndPoint = remoteEndPoint, TimeWhenGet = DateTime.UtcNow.AddMilliseconds(num) }); } _dropPacket = true; } } [Conditional("DEBUG")] [Conditional("SIMULATE_NETWORK")] private void HandleSimulatePacketLoss() { if (SimulatePacketLoss && _randomGenerator.NextDouble() * 100.0 < (double)SimulationPacketLossChance) { _dropPacket = true; } } private void HandleMessageReceived(NetPacket packet, IPEndPoint remoteEndPoint) { int size = packet.Size; if (EnableStatistics) { Statistics.IncrementPacketsReceived(); Statistics.AddBytesReceived(size); } if (_ntpRequests.Count > 0 && _ntpRequests.TryGetValue(remoteEndPoint, out var _)) { if (packet.Size >= 48) { byte[] array = new byte[packet.Size]; Buffer.BlockCopy(packet.RawData, 0, array, 0, packet.Size); NtpPacket ntpPacket = NtpPacket.FromServerResponse(array, DateTime.UtcNow); try { ntpPacket.ValidateReply(); } catch (InvalidOperationException) { ntpPacket = null; } if (ntpPacket != null) { _ntpRequests.TryRemove(remoteEndPoint, out var _); _ntpEventListener?.OnNtpResponse(ntpPacket); } } return; } if (_extraPacketLayer != null) { _extraPacketLayer.ProcessInboundPacket(ref remoteEndPoint, ref packet.RawData, ref packet.Size); if (packet.Size == 0) { return; } } if (!packet.Verify()) { NetDebug.WriteError("[NM] DataReceived: bad!"); PoolRecycle(packet); return; } switch (packet.Property) { case PacketProperty.ConnectRequest: if (NetConnectRequestPacket.GetProtocolId(packet) != 13) { SendRawAndRecycle(PoolGetWithProperty(PacketProperty.InvalidProtocol), remoteEndPoint); return; } break; case PacketProperty.Broadcast: if (BroadcastReceiveEnabled) { CreateEvent(NetEvent.EType.Broadcast, null, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, packet); } return; case PacketProperty.UnconnectedMessage: if (UnconnectedMessagesEnabled) { CreateEvent(NetEvent.EType.ReceiveUnconnected, null, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0, packet); } return; case PacketProperty.NatMessage: if (NatPunchEnabled) { NatPunchModule.ProcessMessage(remoteEndPoint, packet); } return; } NetPeer actualValue = remoteEndPoint as NetPeer; bool flag = actualValue != null || TryGetPeer(remoteEndPoint, out actualValue); if (flag && EnableStatistics) { actualValue.Statistics.IncrementPacketsReceived(); actualValue.Statistics.AddBytesReceived(size); } switch (packet.Property) { case PacketProperty.ConnectRequest: { NetConnectRequestPacket netConnectRequestPacket = NetConnectRequestPacket.FromData(packet); if (netConnectRequestPacket != null) { ProcessConnectRequest(remoteEndPoint, actualValue, netConnectRequestPacket); } break; } case PacketProperty.PeerNotFound: if (flag) { if (actualValue.ConnectionState == ConnectionState.Connected) { if (packet.Size == 1) { actualValue.ResetMtu(); SendRaw(NetConnectAcceptPacket.MakeNetworkChanged(actualValue), remoteEndPoint); } else if (packet.Size == 2 && packet.RawData[1] == 1) { DisconnectPeerForce(actualValue, DisconnectReason.PeerNotFound, SocketError.Success, null); } } } else { if (packet.Size <= 1) { break; } bool flag2 = false; if (AllowPeerAddressChange) { NetConnectAcceptPacket netConnectAcceptPacket = NetConnectAcceptPacket.FromData(packet); if (netConnectAcceptPacket != null && netConnectAcceptPacket.PeerNetworkChanged && netConnectAcceptPacket.PeerId < _peersArray.Length) { _peersLock.EnterUpgradeableReadLock(); NetPeer netPeer = _peersArray[netConnectAcceptPacket.PeerId]; _peersLock.ExitUpgradeableReadLock(); if (netPeer != null && netPeer.ConnectTime == netConnectAcceptPacket.ConnectionTime && netPeer.ConnectionNum == netConnectAcceptPacket.ConnectionNumber) { if (netPeer.ConnectionState == ConnectionState.Connected) { netPeer.InitiateEndPointChange(); CreateEvent(NetEvent.EType.PeerAddressChanged, netPeer, remoteEndPoint, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); } flag2 = true; } } } PoolRecycle(packet); if (!flag2) { NetPacket netPacket = PoolGetWithProperty(PacketProperty.PeerNotFound, 1); netPacket.RawData[1] = 1; SendRawAndRecycle(netPacket, remoteEndPoint); } } break; case PacketProperty.InvalidProtocol: if (flag && actualValue.ConnectionState == ConnectionState.Outgoing) { DisconnectPeerForce(actualValue, DisconnectReason.InvalidProtocol, SocketError.Success, null); } break; case PacketProperty.Disconnect: if (flag) { DisconnectResult disconnectResult = actualValue.ProcessDisconnect(packet); if (disconnectResult == DisconnectResult.None) { PoolRecycle(packet); break; } DisconnectPeerForce(actualValue, (disconnectResult == DisconnectResult.Disconnect) ? DisconnectReason.RemoteConnectionClose : DisconnectReason.ConnectionRejected, SocketError.Success, packet); } else { PoolRecycle(packet); } SendRawAndRecycle(PoolGetWithProperty(PacketProperty.ShutdownOk), remoteEndPoint); break; case PacketProperty.ConnectAccept: if (flag) { NetConnectAcceptPacket netConnectAcceptPacket2 = NetConnectAcceptPacket.FromData(packet); if (netConnectAcceptPacket2 != null && actualValue.ProcessConnectAccept(netConnectAcceptPacket2)) { CreateEvent(NetEvent.EType.Connect, actualValue, null, SocketError.Success, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); } } break; default: if (flag) { actualValue.ProcessPacket(packet); } else { SendRawAndRecycle(PoolGetWithProperty(PacketProperty.PeerNotFound), remoteEndPoint); } break; } } internal void CreateReceiveEvent(NetPacket packet, DeliveryMethod method, byte channelNumber, int headerSize, NetPeer fromPeer) { if (UnsyncedEvents || UnsyncedReceiveEvent || _manualMode) { NetEvent netEvent; lock (_eventLock) { netEvent = _netEventPoolHead; if (netEvent == null) { netEvent = new NetEvent(this); } else { _netEventPoolHead = netEvent.Next; } } netEvent.Next = null; netEvent.Type = NetEvent.EType.Receive; netEvent.DataReader.SetSource(packet, headerSize); netEvent.Peer = fromPeer; netEvent.DeliveryMethod = method; netEvent.ChannelNumber = channelNumber; ProcessEvent(netEvent); return; } lock (_eventLock) { NetEvent netEvent = _netEventPoolHead; if (netEvent == null) { netEvent = new NetEvent(this); } else { _netEventPoolHead = netEvent.Next; } netEvent.Next = null; netEvent.Type = NetEvent.EType.Receive; netEvent.DataReader.SetSource(packet, headerSize); netEvent.Peer = fromPeer; netEvent.DeliveryMethod = method; netEvent.ChannelNumber = channelNumber; if (_pendingEventTail == null) { _pendingEventHead = netEvent; } else { _pendingEventTail.Next = netEvent; } _pendingEventTail = netEvent; } } public void SendToAll(NetDataWriter writer, DeliveryMethod options) { SendToAll(writer.Data, 0, writer.Length, options); } public void SendToAll(byte[] data, DeliveryMethod options) { SendToAll(data, 0, data.Length, options); } public void SendToAll(byte[] data, int start, int length, DeliveryMethod options) { SendToAll(data, start, length, 0, options); } public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options) { SendToAll(writer.Data, 0, writer.Length, channelNumber, options); } public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options) { SendToAll(data, 0, data.Length, channelNumber, options); } public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options) { try { _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { netPeer.Send(data, start, length, channelNumber, options); } } finally { _peersLock.ExitReadLock(); } } public void SendToAll(NetDataWriter writer, DeliveryMethod options, NetPeer excludePeer) { SendToAll(writer.Data, 0, writer.Length, 0, options, excludePeer); } public void SendToAll(byte[] data, DeliveryMethod options, NetPeer excludePeer) { SendToAll(data, 0, data.Length, 0, options, excludePeer); } public void SendToAll(byte[] data, int start, int length, DeliveryMethod options, NetPeer excludePeer) { SendToAll(data, start, length, 0, options, excludePeer); } public void SendToAll(NetDataWriter writer, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) { SendToAll(writer.Data, 0, writer.Length, channelNumber, options, excludePeer); } public void SendToAll(byte[] data, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) { SendToAll(data, 0, data.Length, channelNumber, options, excludePeer); } public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) { try { _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if (netPeer != excludePeer) { netPeer.Send(data, start, length, channelNumber, options); } } } finally { _peersLock.ExitReadLock(); } } public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options) { SendToAll(data, 0, options, null); } public void SendToAll(ReadOnlySpan<byte> data, DeliveryMethod options, NetPeer excludePeer) { SendToAll(data, 0, options, excludePeer); } public void SendToAll(ReadOnlySpan<byte> data, byte channelNumber, DeliveryMethod options, NetPeer excludePeer) { try { _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if (netPeer != excludePeer) { netPeer.Send(data, channelNumber, options); } } } finally { _peersLock.ExitReadLock(); } } public bool SendUnconnectedMessage(ReadOnlySpan<byte> message, IPEndPoint remoteEndPoint) { int headerSize = NetPacket.GetHeaderSize(PacketProperty.UnconnectedMessage); NetPacket netPacket = PoolGetPacket(message.Length + headerSize); netPacket.Property = PacketProperty.UnconnectedMessage; message.CopyTo(new Span<byte>(netPacket.RawData, headerSize, message.Length)); return SendRawAndRecycle(netPacket, remoteEndPoint) > 0; } public bool Start() { return Start(0); } public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port) { return Start(addressIPv4, addressIPv6, port, manualMode: false); } public bool Start(string addressIPv4, string addressIPv6, int port) { IPAddress addressIPv7 = NetUtils.ResolveAddress(addressIPv4); IPAddress addressIPv8 = NetUtils.ResolveAddress(addressIPv6); return Start(addressIPv7, addressIPv8, port); } public bool Start(int port) { return Start(IPAddress.Any, IPAddress.IPv6Any, port); } public bool StartInManualMode(IPAddress addressIPv4, IPAddress addressIPv6, int port) { return Start(addressIPv4, addressIPv6, port, manualMode: true); } public bool StartInManualMode(string addressIPv4, string addressIPv6, int port) { IPAddress addressIPv7 = NetUtils.ResolveAddress(addressIPv4); IPAddress addressIPv8 = NetUtils.ResolveAddress(addressIPv6); return StartInManualMode(addressIPv7, addressIPv8, port); } public bool StartInManualMode(int port) { return StartInManualMode(IPAddress.Any, IPAddress.IPv6Any, port); } public bool SendUnconnectedMessage(byte[] message, IPEndPoint remoteEndPoint) { return SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint); } public bool SendUnconnectedMessage(NetDataWriter writer, string address, int port) { IPEndPoint remoteEndPoint = NetUtils.MakeEndPoint(address, port); return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint); } public bool SendUnconnectedMessage(NetDataWriter writer, IPEndPoint remoteEndPoint) { return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint); } public bool SendUnconnectedMessage(byte[] message, int start, int length, IPEndPoint remoteEndPoint) { NetPacket packet = PoolGetWithData(PacketProperty.UnconnectedMessage, message, start, length); return SendRawAndRecycle(packet, remoteEndPoint) > 0; } public void TriggerUpdate() { _updateTriggerEvent.Set(); } public void PollEvents(int maxProcessedEvents = 0) { if (_manualMode) { if (_udpSocketv4 != null) { ManualReceive(_udpSocketv4, _bufferEndPointv4, maxProcessedEvents); } if (_udpSocketv6 != null && _udpSocketv6 != _udpSocketv4) { ManualReceive(_udpSocketv6, _bufferEndPointv6, maxProcessedEvents); } } else { if (UnsyncedEvents) { return; } NetEvent netEvent; lock (_eventLock) { netEvent = _pendingEventHead; _pendingEventHead = null; _pendingEventTail = null; } int num = 0; while (netEvent != null) { NetEvent next = netEvent.Next; ProcessEvent(netEvent); netEvent = next; num++; if (num == maxProcessedEvents) { break; } } } } public NetPeer Connect(string address, int port, string key) { return Connect(address, port, NetDataWriter.FromString(key)); } public NetPeer Connect(string address, int port, NetDataWriter connectionData) { IPEndPoint target; try { target = NetUtils.MakeEndPoint(address, port); } catch { CreateEvent(NetEvent.EType.Disconnect, null, null, SocketError.Success, 0, DisconnectReason.UnknownHost, null, DeliveryMethod.Unreliable, 0); return null; } return Connect(target, connectionData); } public NetPeer Connect(IPEndPoint target, string key) { return Connect(target, NetDataWriter.FromString(key)); } public NetPeer Connect(IPEndPoint target, NetDataWriter connectionData) { if (!_isRunning) { throw new InvalidOperationException("Client is not running"); } lock (_requestsDict) { if (_requestsDict.ContainsKey(target)) { return null; } byte connectNum = 0; if (TryGetPeer(target, out var actualValue)) { ConnectionState connectionState = actualValue.ConnectionState; if (connectionState == ConnectionState.Outgoing || connectionState == ConnectionState.Connected) { return actualValue; } connectNum = (byte)((actualValue.ConnectionNum + 1) % 4); RemovePeer(actualValue, enableWriteLock: true); } actualValue = new NetPeer(this, target, GetNextPeerId(), connectNum, connectionData); AddPeer(actualValue); return actualValue; } } public NetPeer Connect(IPEndPoint target, ReadOnlySpan<byte> connectionData) { if (!_isRunning) { throw new InvalidOperationException("Client is not running"); } lock (_requestsDict) { if (_requestsDict.ContainsKey(target)) { return null; } byte connectNum = 0; if (TryGetPeer(target, out var actualValue)) { ConnectionState connectionState = actualValue.ConnectionState; if (connectionState == ConnectionState.Outgoing || connectionState == ConnectionState.Connected) { return actualValue; } connectNum = (byte)((actualValue.ConnectionNum + 1) % 4); RemovePeer(actualValue, enableWriteLock: true); } actualValue = new NetPeer(this, target, GetNextPeerId(), connectNum, connectionData); AddPeer(actualValue); return actualValue; } } public void Stop() { Stop(sendDisconnectMessages: true); } public void Stop(bool sendDisconnectMessages) { if (_isRunning) { for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { netPeer.Shutdown(null, 0, 0, !sendDisconnectMessages); } CloseSocket(); _updateTriggerEvent.Set(); if (!_manualMode) { _logicThread.Join(); _logicThread = null; } ClearPeerSet(); _peerIds = new ConcurrentQueue<int>(); _lastPeerId = 0; _connectedPeersCount = 0L; _pendingEventHead = null; _pendingEventTail = null; } } [Conditional("DEBUG")] [Conditional("SIMULATE_NETWORK")] private void ClearPingSimulationList() { lock (_pingSimulationList) { _pingSimulationList.Clear(); } } [Conditional("DEBUG")] [Conditional("SIMULATE_NETWORK")] private void ClearOutboundSimulationList() { lock (_outboundSimulationList) { _outboundSimulationList.Clear(); } } public int GetPeersCount(ConnectionState peerState) { int num = 0; _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if ((netPeer.ConnectionState & peerState) != 0) { num++; } } _peersLock.ExitReadLock(); return num; } public void GetPeersNonAlloc(List<NetPeer> peers, ConnectionState peerState) { peers.Clear(); _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { if ((netPeer.ConnectionState & peerState) != 0) { peers.Add(netPeer); } } _peersLock.ExitReadLock(); } public void DisconnectAll() { DisconnectAll(null, 0, 0); } public void DisconnectAll(byte[] data, int start, int count) { _peersLock.EnterReadLock(); for (NetPeer netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer) { DisconnectPeer(netPeer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, force: false, data, start, count, null); } _peersLock.ExitReadLock(); } public void DisconnectPeerForce(NetPeer peer) { DisconnectPeerForce(peer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, null); } public void DisconnectPeer(NetPeer peer) { DisconnectPeer(peer, null, 0, 0); } public void DisconnectPeer(NetPeer peer, byte[] data) { DisconnectPeer(peer, data, 0, data.Length); } public void DisconnectPeer(NetPeer peer, NetDataWriter writer) { DisconnectPeer(peer, writer.Data, 0, writer.Length); } public void DisconnectPeer(NetPeer peer, byte[] data, int start, int count) { DisconnectPeer(peer, DisconnectReason.DisconnectPeerCalled, SocketError.Success, force: false, data, start, count, null); } public void CreateNtpRequest(IPEndPoint endPoint) { _ntpRequests.TryAdd(endPoint, new NtpRequest(endPoint)); } public void CreateNtpRequest(string ntpServerAddress, int port) { IPEndPoint iPEndPoint = NetUtils.MakeEndPoint(ntpServerAddress, port); _ntpRequests.TryAdd(iPEndPoint, new NtpRequest(iPEndPoint)); } public void CreateNtpRequest(string ntpServerAddress) { IPEndPoint iPEndPoint = NetUtils.MakeEndPoint(ntpServerAddress, 123); _ntpRequests.TryAdd(iPEndPoint, new NtpRequest(iPEndPoint)); } public NetPeerEnumerator GetEnumerator() { return new NetPeerEnumerator(_headPeer); } IEnumerator<NetPeer> IEnumerable<NetPeer>.GetEnumerator() { return new NetPeerEnumerator(_headPeer); } IEnumerator IEnumerable.GetEnumerator() { return new NetPeerEnumerator(_headPeer); } private static int HashSetGetPrime(int min) { int[] primes = Primes; foreach (int num in primes) { 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; static bool IsPrime(int candidate) { if (((uint)candidate & (true ? 1u : 0u)) != 0) { int num2 = (int)Math.Sqrt(candidate); for (int k = 3; k <= num2; k += 2) { if (candidate % k == 0) { return false; } } return true; } return candidate == 2; } } private void ClearPeerSet() { _peersLock.EnterWriteLock(); _headPeer = null; if (_lastIndex > 0) { Array.Clear(_slots, 0, _lastIndex); Array.Clear(_buckets, 0, _buckets.Length); _lastIndex = 0; _count = 0; _freeList = -1; } _peersArray = new NetPeer[32]; _peersLock.ExitWriteLock(); } private bool ContainsPeer(NetPeer item) { if (item == null) { NetDebug.WriteError($"Contains peer null: {item}"); return false; } if (_buckets != null) { int num = item.GetHashCode() & 0x7FFFFFFF; for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next) { if (_slots[num2].HashCode == num && _slots[num2].Value.Equals(item)) { return true; } } } return false; } public NetPeer GetPeerById(int id) { if (id < 0 || id >= _peersArray.Length) { return null; } return _peersArray[id]; } public bool TryGetPeerById(int id, out NetPeer peer) { peer = GetPeerById(id); return peer != null; } private void AddPeer(NetPeer peer) { if (peer == null) { NetDebug.WriteError($"Add peer null: {peer}"); return; } _peersLock.EnterWriteLock(); if (_headPeer != null) { peer.NextPeer = _headPeer; _headPeer.PrevPeer = peer; } _headPeer = peer; AddPeerToSet(peer); if (peer.Id >= _peersArray.Length) { int num = _peersArray.Length * 2; while (peer.Id >= num) { num *= 2; } Array.Resize(ref _peersArray, num); } _peersArray[peer.Id] = peer; _peersLock.ExitWriteLock(); } private void RemovePeer(NetPeer peer, bool enableWriteLock) { if (enableWriteLock) { _peersLock.EnterWriteLock(); } if (!RemovePeerFromSet(peer)) { if (enableWriteLock) { _peersLock.ExitWriteLock(); } return; } if (peer == _headPeer) { _headPeer = peer.NextPeer; } if (peer.PrevPeer != null) { peer.PrevPeer.NextPeer = peer.NextPeer; } if (peer.NextPeer != null) { peer.NextPeer.PrevPeer = peer.PrevPeer; } peer.PrevPeer = null; _peersArray[peer.Id] = null; _peerIds.Enqueue(peer.Id); if (enableWriteLock) { _peersLock.ExitWriteLock(); } } private bool RemovePeerFromSet(NetPeer peer) { if (_buckets == null || peer == null) { return false; } int num = peer.GetHashCode() & 0x7FFFFFFF; int num2 = num % _buckets.Length; int num3 = -1; for (int num4 = _buckets[num2] - 1; num4 >= 0; num4 = _slots[num4].Next) { if (_slots[num4].HashCode == num && _slots[num4].Value.Equals(peer)) { if (num3 < 0) { _buckets[num2] = _slots[num4].Next + 1; } else { _slots[num3].Next = _slots[num4].Next; } _slots[num4].HashCode = -1; _slots[num4].Value = null; _slots[num4].Next = _freeList; _count--; if (_count == 0) { _lastIndex = 0; _freeList = -1; } else { _freeList = num4; } return true; } num3 = num4; } return false; } private bool TryGetPeer(IPEndPoint endPoint, out NetPeer actualValue) { if (_buckets != null) { int num = endPoint.GetHashCode() & 0x7FFFFFFF; _peersLock.EnterReadLock(); for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next) { if (_slots[num2].HashCode == num && _slots[num2].Value.Equals(endPoint)) { actualValue = _slots[num2].Value; _peersLock.ExitReadLock(); return true; } } _peersLock.ExitReadLock(); } actualValue = null; return false; } private bool TryGetPeer(SocketAddress saddr, out NetPeer actualValue) { if (_buckets != null) { int num = saddr.GetHashCode() & 0x7FFFFFFF; _peersLock.EnterReadLock(); for (int num2 = _buckets[num % _buckets.Length] - 1; num2 >= 0; num2 = _slots[num2].Next) { if (_slots[num2].HashCode == num && _slots[num2].Value.Serialize().Equals(saddr)) { actualValue = _slots[num2].Value; _peersLock.ExitReadLock(); return true; } } _peersLock.ExitReadLock(); } actualValue = null; return false; } private bool AddPeerToSet(NetPeer value) { if (_buckets == null) { int num = HashSetGetPrime(0); _buckets = new int[num]; _slots = new Slot[num]; } int num2 = value.GetHashCode() & 0x7FFFFFFF; int num3 = num2 % _buckets.Length; for (int num4 = _buckets[num2 % _buckets.Length] - 1; num4 >= 0; num4 = _slots[num4].Next) { if (_slots[num4].HashCode == num2 && _slots[num4].Value.Equals(value)) { return false; } } int num5; if (_freeList >= 0) { num5 = _freeList; _freeList = _slots[num5].Next; } else { if (_lastIndex == _slots.Length) { int num6 = 2 * _count; num6 = (((uint)num6 > 2147483587u && 2147483587 > _count) ? 2147483587 : HashSetGetPrime(num6)); Slot[] array = new Slot[num6]; Array.Copy(_slots, 0, array, 0, _lastIndex); _buckets = new int[num6]; for (int i = 0; i < _lastIndex; i++) { int num7 = array[i].HashCode % num6; array[i].Next = _buckets[num7] - 1; _buckets[num7] = i + 1; } _slots = array; num3 = num2 % _buckets.Length; } num5 = _lastIndex; _lastIndex++; } _slots[num5].HashCode = num2; _slots[num5].Value = value; _slots[num5].Next = _buckets[num3] - 1; _buckets[num3] = num5 + 1; _count++; return true; } private NetPacket PoolGetWithData(PacketProperty property, byte[] data, int start, int length) { int headerSize = NetPacket.GetHeaderSize(property); NetPacket netPacket = PoolGetPacket(length + headerSize); netPacket.Property = property; Buffer.BlockCopy(data, start, netPacket.RawData, headerSize, length); return netPacket; } private NetPacket PoolGetWithProperty(PacketProperty property, int size) { NetPacket netPacket = PoolGetPacket(size + NetPacket.GetHeaderSize(property)); netPacket.Property = property; return netPacket; } private NetPacket PoolGetWithProperty(PacketProperty property) { NetPacket netPacket = PoolGetPacket(NetPacket.GetHeaderSize(property)); netPacket.Property = property; return netPacket; } internal NetPacket PoolGetPacket(int size) { if (size > NetConstants.MaxPacketSize) { return new NetPacket(size); } NetPacket poolHead; lock (_poolLock) { poolHead = _poolHead; if (poolHead == null) { return new NetPacket(size); } _poolHead = _poolHead.Next; _poolCount--; } poolHead.Size = size; if (poolHead.RawData.Length < size) { poolHead.RawData = new byte[size]; } return poolHead; } internal void PoolRecycle(NetPacket packet) { if (packet.RawData.Length > NetConstants.MaxPacketSize || _poolCount >= PacketPoolSize) { return; } packet.RawData[0] = 0; lock (_poolLock) { packet.Next = _poolHead; _poolHead = packet; _poolCount++; } } static NetManager() { 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 }; MulticastAddressV6 = IPAddress.Parse("ff02::1"); IPv6Support = Socket.OSSupportsIPv6; } private bool ProcessError(SocketException ex) { switch (ex.SocketErrorCode) { case SocketError.NotConnected: NotConnected = true; return true; case SocketError.OperationAborted: case SocketError.Interrupted: case SocketError.NotSocket: return true; default: NetDebug.WriteError($"[R]Error code: {ex.SocketErrorCode} - {ex}"); CreateEvent(NetEvent.EType.Error, null, null, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); break; case SocketError.WouldBlock: case SocketError.MessageSize: case SocketError.NetworkReset: case SocketError.ConnectionReset: case SocketError.TimedOut: break; } return false; } private void ManualReceive(Socket socket, EndPoint bufferEndPoint, int maxReceive) { try { int num = 0; while (socket.Available > 0) { ReceiveFrom(socket, ref bufferEndPoint); num++; if (num == maxReceive) { break; } } } catch (SocketException ex) { ProcessError(ex); } catch (ObjectDisposedException) { } catch (Exception ex3) { NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex3); } } private void NativeReceiveLogic() { IntPtr handle = _udpSocketv4.Handle; IntPtr s2 = _udpSocketv6?.Handle ?? IntPtr.Zero; byte[] address2 = new byte[16]; byte[] address3 = new byte[28]; IPEndPoint tempEndPoint = new IPEndPoint(IPAddress.Any, 0); List<Socket> list = new List<Socket>(2); Socket udpSocketv = _udpSocketv4; Socket udpSocketv2 = _udpSocketv6; NetPacket packet = PoolGetPacket(NetConstants.MaxPacketSize); while (_isRunning) { try { if (udpSocketv2 == null) { if (!NativeReceiveFrom(handle, address2)) { break; } continue; } bool flag = false; if (udpSocketv.Available != 0 || list.Contains(udpSocketv)) { if (!NativeReceiveFrom(handle, address2)) { break; } flag = true; } if (udpSocketv2.Available != 0 || list.Contains(udpSocketv2)) { if (!NativeReceiveFrom(s2, address3)) { break; } flag = true; } list.Clear(); if (!flag) { list.Add(udpSocketv); list.Add(udpSocketv2); Socket.Select(list, null, null, ReceivePollingTime); } } catch (SocketException ex) { if (ProcessError(ex)) { break; } } catch (ObjectDisposedException) { break; } catch (ThreadAbortException) { break; } catch (Exception ex4) { NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex4); } } bool NativeReceiveFrom(IntPtr s, byte[] address) { int socketAddressSize = address.Length; packet.Size = NativeSocket.RecvFrom(s, packet.RawData, NetConstants.MaxPacketSize, address, ref socketAddressSize); if (packet.Size == 0) { return true; } if (packet.Size == -1) { return !ProcessError(new SocketException((int)NativeSocket.GetSocketError())); } short num = (short)((address[1] << 8) | address[0]); tempEndPoint.Port = (ushort)((address[2] << 8) | address[3]); if ((NativeSocket.UnixMode && num == 10) || (!NativeSocket.UnixMode && num == 23)) { uint num2 = (uint)((address[27] << 24) + (address[26] << 16) + (address[25] << 8) + address[24]); tempEndPoint.Address = new IPAddress(new ReadOnlySpan<byte>(address, 8, 16), num2); } else { long newAddress = (uint)((address[4] & 0xFF) | ((address[5] << 8) & 0xFF00) | ((address[6] << 16) & 0xFF0000) | (address[7] << 24)); tempEndPoint.Address = new IPAddress(newAddress); } if (TryGetPeer(tempEndPoint, out var actualValue)) { OnMessageReceived(packet, actualValue); } else { OnMessageReceived(packet, tempEndPoint); tempEndPoint = new IPEndPoint(IPAddress.Any, 0); } packet = PoolGetPacket(NetConstants.MaxPacketSize); return true; } } private void ReceiveFrom(Socket s, ref EndPoint bufferEndPoint) { NetPacket netPacket = PoolGetPacket(NetConstants.MaxPacketSize); netPacket.Size = s.ReceiveFrom(netPacket.RawData, 0, NetConstants.MaxPacketSize, SocketFlags.None, ref bufferEndPoint); OnMessageReceived(netPacket, (IPEndPoint)bufferEndPoint); } private void ReceiveLogic() { EndPoint bufferEndPoint = new IPEndPoint(IPAddress.Any, 0); EndPoint bufferEndPoint2 = new IPEndPoint(IPAddress.IPv6Any, 0); List<Socket> list = new List<Socket>(2); Socket udpSocketv = _udpSocketv4; Socket udpSocketv2 = _udpSocketv6; while (_isRunning) { try { if (udpSocketv2 == null) { if (udpSocketv.Available != 0 || udpSocketv.Poll(ReceivePollingTime, SelectMode.SelectRead)) { ReceiveFrom(udpSocketv, ref bufferEndPoint); } continue; } bool flag = false; if (udpSocketv.Available != 0 || list.Contains(udpSocketv)) { ReceiveFrom(udpSocketv, ref bufferEndPoint); flag = true; } if (udpSocketv2.Available != 0 || list.Contains(udpSocketv2)) { ReceiveFrom(udpSocketv2, ref bufferEndPoint2); flag = true; } list.Clear(); if (!flag) { list.Add(udpSocketv); list.Add(udpSocketv2); Socket.Select(list, null, null, ReceivePollingTime); } } catch (SocketException ex) { if (ProcessError(ex)) { break; } } catch (ObjectDisposedException) { break; } catch (ThreadAbortException) { break; } catch (Exception ex4) { NetDebug.WriteError("[NM] SocketReceiveThread error: " + ex4); } } } public bool Start(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool manualMode) { if (IsRunning && !NotConnected) { return false; } NotConnected = false; _manualMode = manualMode; UseNativeSockets = UseNativeSockets && NativeSocket.IsSupported; _udpSocketv4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); if (!BindSocket(_udpSocketv4, new IPEndPoint(addressIPv4, port))) { return false; } LocalPort = ((IPEndPoint)_udpSocketv4.LocalEndPoint).Port; _isRunning = true; if (_manualMode) { _bufferEndPointv4 = new IPEndPoint(IPAddress.Any, 0); } if (IPv6Support && IPv6Enabled) { _udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); if (BindSocket(_udpSocketv6, new IPEndPoint(addressIPv6, LocalPort))) { if (_manualMode) { _bufferEndPointv6 = new IPEndPoint(IPAddress.IPv6Any, 0); } } else { _udpSocketv6 = null; } } if (!manualMode) { ThreadStart start = ReceiveLogic; if (UseNativeSockets) { start = NativeReceiveLogic; } _receiveThread = new Thread(start) { Name = $"ReceiveThread({LocalPort})", IsBackground = true }; _receiveThread.Start(); if (_logicThread == null) { _logicThread = new Thread(UpdateLogic) { Name = "LogicThread", IsBackground = true }; _logicThread.Start(); } } return true; } private bool BindSocket(Socket socket, IPEndPoint ep) { socket.ReceiveTimeout = 500; socket.SendTimeout = 500; socket.ReceiveBufferSize = 1048576; socket.SendBufferSize = 1048576; socket.Blocking = true; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { socket.IOControl(-1744830452, new byte[1], null); } catch { } } try { socket.ExclusiveAddressUse = !ReuseAddress; socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, ReuseAddress); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, DontRoute); } catch { } if (ep.AddressFamily == AddressFamily.InterNetwork) { Ttl = 255; try { socket.EnableBroadcast = true; } catch (SocketException ex) { NetDebug.WriteError($"[B]Broadcast error: {ex.SocketErrorCode}"); } if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { try { socket.DontFragment = true; } catch (SocketException ex2) { NetDebug.WriteError($"[B]DontFragment error: {ex2.SocketErrorCode}"); } } } try { socket.Bind(ep); if (ep.AddressFamily == AddressFamily.InterNetworkV6) { try { socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(MulticastAddressV6)); } catch (Exception) { } } } catch (SocketException ex4) { switch (ex4.SocketErrorCode) { case SocketError.AddressAlreadyInUse: if (socket.AddressFamily == AddressFamily.InterNetworkV6) { try { socket.DualMode = false; socket.Bind(ep); } catch (SocketException ex5) { NetDebug.WriteError($"[B]Bind exception: {ex5}, errorCode: {ex5.SocketErrorCode}"); return false; } return true; } break; case SocketError.AddressFamilyNotSupported: return true; } NetDebug.WriteError($"[B]Bind exception: {ex4}, errorCode: {ex4.SocketErrorCode}"); return false; } return true; } internal int SendRawAndRecycle(NetPacket packet, IPEndPoint remoteEndPoint) { int result = SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint); PoolRecycle(packet); return result; } internal int SendRaw(NetPacket packet, IPEndPoint remoteEndPoint) { return SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint); } internal int SendRaw(byte[] message, int start, int length, IPEndPoint remoteEndPoint) { if (!_isRunning) { return 0; } NetPacket netPacket = null; if (_extraPacketLayer != null) { netPacket = PoolGetPacket(length + _extraPacketLayer.ExtraPacketSizeForLayer); Buffer.BlockCopy(message, start, netPacket.RawData, 0, length); start = 0; _extraPacketLayer.ProcessOutBoundPacket(ref remoteEndPoint, ref netPacket.RawData, ref start, ref length); message = netPacket.RawData; } return SendRawCoreWithCleanup(message, start, length, remoteEndPoint, netPacket); } private int SendRawCoreWithCleanup(byte[] message, int start, int length, IPEndPoint remoteEndPoint, NetPacket expandedPacket) { try { return SendRawCore(message, start, length, remoteEndPoint); } finally { if (expandedPacket != null) { PoolRecycle(expandedPacket); } } } internal unsafe int SendRawCore(byte[] message, int start, int length, IPEndPoint remoteEndPoint) { if (!_isRunning) { return 0; } Socket socket = _udpSocketv4; if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support) { socket = _udpSocketv6; if (socket == null) { return 0; } } int num; try { if (UseNativeSockets && remoteEndPoint is NetPeer netPeer) { fixed (byte* pinnedBuffer = &message[start]) { num = NativeSocket.SendTo(socket.Handle, pinnedBuffer, length, netPeer.NativeAddress, netPeer.NativeAddress.Length); } if (num == -1) { throw NativeSocket.GetSocketException(); } } else { num = socket.SendTo(message, start, length, SocketFlags.None, remoteEndPoint); } } catch (SocketException ex) { switch (ex.SocketErrorCode) { case SocketError.Interrupted: case SocketError.NoBufferSpaceAvailable: return 0; case SocketError.MessageSize: return 0; case SocketError.NetworkUnreachable: case SocketError.HostUnreachable: if (DisconnectOnUnreachable && remoteEndPoint is NetPeer peer) { DisconnectPeerForce(peer, (ex.SocketErrorCode == SocketError.HostUnreachable) ? DisconnectReason.HostUnreachable : DisconnectReason.NetworkUnreachable, ex.SocketErrorCode, null); } CreateEvent(NetEvent.EType.Error, null, remoteEndPoint, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); return -1; case SocketError.Shutdown: CreateEvent(NetEvent.EType.Error, null, remoteEndPoint, ex.SocketErrorCode, 0, DisconnectReason.ConnectionFailed, null, DeliveryMethod.Unreliable, 0); return -1; default: NetDebug.WriteError($"[S] {ex}"); return -1; } } catch (Exception value) { NetDebug.WriteError($"[S] {value}"); return 0; } if (num <= 0) { return 0; } if (EnableStatistics) { Statistics.IncrementPacketsSent(); Statistics.AddBytesSent(length); } return num; } public bool SendBroadcast(NetDataWriter writer, int port) { return SendBroadcast(writer.Data, 0, writer.Length, port); } public bool SendBroadcast(byte[] data, int port) { return SendBroadcast(data, 0, data.Length, port); } public bool SendBroadcast(byte[] data, int start, int length, int port) { if (!IsRunning) { return false; } NetPacket netPacket; if (_extraPacketLayer != null) { int headerSize = NetPacket.GetHeaderSize(PacketProperty.Broadcast); netPacket = PoolGetPacket(headerSize + length + _extraPacketLayer.ExtraPacketSizeForLayer); netPacket.Property = PacketProperty.Broadcast; Buffer.BlockCopy(data, start, netPacket.RawData, headerSize, length); int offset = 0; int length2 = length + headerSize; IPEndPoint endPoint = null; _extraPacketLayer.ProcessOutBoundPacket(ref endPoint, ref netPacket.RawData, ref offset, ref length2); } else { netPacket = PoolGetWithData(PacketProperty.Broadcast, data, start, length); } bool flag = false; bool flag2 = false; try { flag = _udpSocketv4.SendTo(netPacket.RawData, 0, netPacket.Size, SocketFlags.None, new IPEndPoint(IPAddress.Broadcast, port)) > 0; if (_udpSocketv6 != null) { flag2 = _udpSocketv6.SendTo(netPacket.RawData, 0, netPacket.Size, SocketFlags.None, new IPEndPoint(MulticastAddressV6, port)) > 0; } } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.HostUnreachable) { return flag; } NetDebug.WriteError($"[S][MCAST] {ex}"); return flag; } catch (Exception value) { NetDebug.WriteError($"[S][MCAST] {value}"); return flag; } finally { PoolRecycle(netPacket); } return flag || flag2; } private void CloseSocket() { _isRunning = false; if (_receiveThread != null && _receiveThread != Thread.CurrentThread) { _receiveThread.Join(); } _receiveThread = null; _udpSocketv4?.Close(); _udpSocketv6?.Close(); _udpSocketv4 = null; _udpSocketv6 = null; } } internal enum PacketProperty : byte { Unreliable, Channeled, Ack, Ping, Pong, ConnectRequest, ConnectAccept, Disconnect, UnconnectedMessage, MtuCheck, MtuOk, Broadcast, Merged, ShutdownOk, PeerNotFound, InvalidProtocol, NatMessage, Empty } internal sealed class NetPacket { private static readonly int PropertiesCount; private static readonly int[] HeaderSizes; public byte[] RawData; public int Size; public object UserData; public NetPacket Next; public PacketProperty Property { get { return (PacketProperty)(RawData[0] & 0x1Fu); } set { RawData[0] = (byte)((RawData[0] & 0xE0u) | (uint)value); } } public byte ConnectionNumber { get { return (byte)((RawData[0] & 0x60) >> 5); } set { RawData[0] = (byte)((RawData[0] & 0x9Fu) | (uint)(value << 5)); } } public ushort Sequence { get { return BitConverter.ToUInt16(RawData, 1); } set { FastBitConverter.GetBytes(RawData, 1, value); } } public bool IsFragmented => (RawData[0] & 0x80) != 0; public byte ChannelId { get { return RawData[3]; } set { RawData[3] = value; } } public ushort FragmentId { get { return BitConverter.ToUInt16(RawData, 4); } set { FastBitConverter.GetBytes(RawData, 4, value); } } public ushort FragmentPart { get { return BitConverter.ToUInt16(RawData, 6); } set { FastBitConverter.GetBytes(RawData, 6, value); } } public ushort FragmentsTotal { get { return BitConverter.ToUInt16(RawData, 8); } set { FastBitConverter.GetBytes(RawData, 8, value); } } static NetPacket() { PropertiesCount = Enum.GetValues(typeof(PacketProperty)).Length; HeaderSizes = NetUtils.AllocatePinnedUninitializedArray<int>(PropertiesCount); for (int i = 0; i < HeaderSizes.Length; i++) { switch ((PacketProperty)(byte)i) { case PacketProperty.Channeled: case PacketProperty.Ack: HeaderSizes[i] = 4; break; case PacketProperty.Ping: HeaderSizes[i] = 3; break; case PacketProperty.ConnectRequest: HeaderSizes[i] = 18; break; case PacketProperty.ConnectAccept: HeaderSizes[i] = 15; break; case PacketProperty.Disconnect: HeaderSizes[i] = 9; break; case PacketProperty.Pong: HeaderSizes[i] = 11; break; default: HeaderSizes[i] = 1; break; } } } public void MarkFragmented() { RawData[0] |= 128; } public NetPacket(int size) { RawData = new byte[size]; Size = size; } public NetPacket(PacketProperty property, int size) { size += GetHeaderSize(property); RawData = new byte[size]; Property = property; Size = size; } public static int GetHeaderSize(PacketProperty property) { return HeaderSizes[(uint)property]; } public int GetHeaderSize() { return HeaderSizes[RawData[0] & 0x1F]; } public bool Verify() { byte b = (byte)(RawData[0] & 0x1Fu); if (b >= PropertiesCount) { return false; } int num = HeaderSizes[b]; bool flag = (RawData[0] & 0x80) != 0; if (Size >= num) { if (flag) { return Size >= num + 6; } return true; } return false; } public static implicit operator Span<byte>(NetPacket p) { return new Span<byte>(p.RawData, 0, p.Size); } } [Flags] public enum ConnectionState : byte { Outgoing = 2, Connected = 4, ShutdownRequested = 8, Disconnected = 0x10, EndPointChange = 0x20, Any = 0x2E } internal enum ConnectRequestResult { None, P2PLose, Reconnection, NewConnection } internal enum DisconnectResult { None, Reject, Disconnect } internal enum ShutdownResult { None, Success, WasConnected } public class NetPeer : IPEndPoint { private class IncomingFragments { public NetPacket[] Fragments; public int ReceivedCount; public int TotalSize; public byte ChannelId; } private int _rtt; private int _avgRtt; private int _rttCount; private double _resendDelay = 27.0; private float _pingSendTimer; private float _rttResetTimer; private readonly Stopwatch _pingTimer = new Stopwatch(); private volatile float _timeSinceLastPacket; private long _remoteDelta; private readonly object _shutdownLock = new object(); internal volatile NetPeer NextPeer; internal NetPeer PrevPeer; private NetPacket[] _unreliableSecondQueue; private NetPacket[] _unreliableChannel; private int _unreliablePendingCount; private readonly object _unreliableChannelLock = new object(); private readonly ConcurrentQueue<BaseChannel> _channelSendQueue; private readonly BaseChannel[] _channels; private int _mtu; private int _mtuIdx; private bool _finishMtu; private float _mtuCheckTimer; private int _mtuCheckAttempts; private const int MtuCheckDelay = 1000; private const int MaxMtuCheckAttempts = 4; private readonly object _mtuMutex = new object(); private int _fragmentId; private readonly Dictionary<ushort, IncomingFragments> _holdedFragments; private readonly Dictionary<ushort, ushort> _deliveredFragments; private readonly NetPacket _mergeData; private int _mergePos; private int _mergeCount; private int _connectAttempts; private float _connectTimer; private long _connectTime; private byte _connectNum; private ConnectionState _connectionState; private NetPacket _shutdownPacket; private const int ShutdownDelay = 300; private float _shutdownTimer; private readonly NetPacket _pingPacket; private readonly NetPacket _pongPacket; private readonly NetPacket _connectRequestPacket; private readonly NetPacket _connectAcceptPacket; public readonly NetManager NetManager; public readonly int Id; public object Tag; public readonly NetStatistics Statistics; private SocketAddress _cachedSocketAddr; private int _cachedHashCode; internal byte[] NativeAddress; internal byte ConnectionNum { get { return _connectNum; } private set { _connectNum = value; _mergeData.ConnectionNumber = value; _pingPacket.ConnectionNumber = value; _pongPacket.ConnectionNumber = value; } } public ConnectionState ConnectionState => _connectionState; internal long ConnectTime => _connectTime; public int RemoteId { get; private set; } public int Ping => _avgRtt / 2; public int RoundTripTime => _avgRtt; public int Mtu => _mtu; public long RemoteTimeDelta => _remoteDelta; public DateTime RemoteUtcTime => new DateTime(DateTime.UtcNow.Ticks +
MegabonkTogether/Microsoft.Extensions.DependencyInjection.Abstractions.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.DependencyInjection.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.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(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Abstractions for dependency injection.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.DependencyInjection.IServiceCollection")] [assembly: AssemblyFileVersion("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: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.Microsoft.Extensions.DependencyInjection.Abstractions { internal static class SR { } } namespace System { internal static class ThrowHelper { internal static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { throw new ArgumentNullException(paramName); } } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string AmbiguousConstructorMatch => GetResourceString("AmbiguousConstructorMatch"); internal static string CannotResolveService => GetResourceString("CannotResolveService"); internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch"); internal static string NoServiceRegistered => GetResourceString("NoServiceRegistered"); internal static string ServiceCollectionReadOnly => GetResourceString("ServiceCollectionReadOnly"); internal static string TryAddIndistinguishableTypeToEnumerable => GetResourceString("TryAddIndistinguishableTypeToEnumerable"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } } namespace Microsoft.Extensions.Internal { internal static class ParameterDefaultValue { public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue) { bool tryToGetDefaultValue; bool flag = CheckHasDefaultValue(parameter, out tryToGetDefaultValue); defaultValue = null; if (flag) { if (tryToGetDefaultValue) { defaultValue = parameter.DefaultValue; } bool flag2 = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>); if (defaultValue == null && parameter.ParameterType.IsValueType && !flag2) { defaultValue = CreateValueType(parameter.ParameterType); } if (defaultValue != null && flag2) { Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType != null && underlyingType.IsEnum) { defaultValue = Enum.ToObject(underlyingType, defaultValue); } } } return flag; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")] static object? CreateValueType(Type t) { return RuntimeHelpers.GetUninitializedObject(t); } } public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue) { tryToGetDefaultValue = true; 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 = _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++) { Type c = givenParameters[i]?.GetType(); bool flag = false; int num2 = num; while (!flag && num2 != _parameters.Length) { if (_parameterValues[num2] == null && _parameters[num2].ParameterType.IsAssignableFrom(c)) { 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) { 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 '{_constructor.DeclaringType}'."); } _parameterValues[i] = defaultValue; } else { _parameterValues[i] = service; } } return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, _parameterValues, null); } } private static readonly MethodInfo GetServiceInfo = GetMethodInfo<Func<IServiceProvider, Type, Type, bool, object>>((IServiceProvider sp, Type t, Type r, bool c) => GetService(sp, t, r, c)); public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters) { int num = -1; bool flag = false; ConstructorMatcher constructorMatcher = default(ConstructorMatcher); if (!instanceType.IsAbstract) { ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo constructorInfo in constructors) { ConstructorMatcher constructorMatcher2 = new ConstructorMatcher(constructorInfo); bool flag2 = constructorInfo.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: 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 message = $"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(message); } return constructorMatcher.CreateInstance(provider); } public static ObjectFactory CreateFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes) { FindApplicableConstructor(instanceType, argumentTypes, out var matchingConstructor, out var matchingParameterMap); ParameterExpression parameterExpression = Expression.Parameter(typeof(IServiceProvider), "provider"); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(object[]), "argumentArray"); Expression body = BuildFactoryExpression(matchingConstructor, matchingParameterMap, parameterExpression, parameterExpression2); Expression<Func<IServiceProvider, object[], object>> expression = Expression.Lambda<Func<IServiceProvider, object[], object>>(body, new ParameterExpression[2] { parameterExpression, parameterExpression2 }); Func<IServiceProvider, object[], object> @object = expression.Compile(); return @object.Invoke; } public static T CreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider, params object[] parameters) { return (T)CreateInstance(provider, typeof(T), parameters); } public static T GetServiceOrCreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider) { return (T)GetServiceOrCreateInstance(provider, typeof(T)); } public static object GetServiceOrCreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { return provider.GetService(type) ?? CreateInstance(provider, type); } private static MethodInfo GetMethodInfo<T>(Expression<T> expr) { MethodCallExpression methodCallExpression = (MethodCallExpression)expr.Body; return methodCallExpression.Method; } private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) { object service = sp.GetService(type); if (service == null && !isDefaultParameterRequired) { string message = $"Unable to resolve service for type '{type}' while attempting to activate '{requiredBy}'."; throw new InvalidOperationException(message); } return service; } private static Expression BuildFactoryExpression(ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray) { ParameterInfo[] parameters = constructor.GetParameters(); Expression[] array = new Expression[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameterInfo = parameters[i]; Type parameterType = parameterInfo.ParameterType; object defaultValue; bool flag = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue); if (parameterMap[i].HasValue) { array[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i])); } else { Expression[] arguments = new Expression[4] { serviceProvider, Expression.Constant(parameterType, typeof(Type)), Expression.Constant(constructor.DeclaringType, typeof(Type)), Expression.Constant(flag) }; array[i] = Expression.Call(GetServiceInfo, arguments); } if (flag) { ConstantExpression right = Expression.Constant(defaultValue); array[i] = Expression.Coalesce(array[i], right); } array[i] = Expression.Convert(array[i], parameterType); } return Expression.New(constructor, array); } private static void FindApplicableConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap) { ConstructorInfo matchingConstructor2 = null; int?[] parameterMap = null; if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref matchingConstructor2, ref parameterMap) && !TryFindMatchingConstructor(instanceType, argumentTypes, ref matchingConstructor2, ref parameterMap)) { string message = $"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(message); } matchingConstructor = matchingConstructor2; matchingParameterMap = parameterMap; } private static bool TryFindMatchingConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] ref ConstructorInfo matchingConstructor, [NotNullWhen(true)] ref int?[] parameterMap) { ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo constructorInfo in constructors) { if (TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2)) { if (matchingConstructor != 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 = constructorInfo; parameterMap = parameterMap2; } } if (matchingConstructor != null) { return true; } return false; } private static bool TryFindPreferredConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] ref ConstructorInfo matchingConstructor, [NotNullWhen(true)] ref int?[] parameterMap) { bool flag = false; ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo constructorInfo in constructors) { if (constructorInfo.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false)) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (!TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2)) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } matchingConstructor = constructorInfo; parameterMap = parameterMap2; flag = true; } } if (matchingConstructor != null) { return true; } return false; } private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap) { parameterMap = new int?[constructorParameters.Length]; for (int i = 0; i < argumentTypes.Length; i++) { bool flag = false; Type c = argumentTypes[i]; for (int j = 0; j < constructorParameters.Length; j++) { if (!parameterMap[j].HasValue && constructorParameters[j].ParameterType.IsAssignableFrom(c)) { flag = true; parameterMap[j] = i; break; } } if (!flag) { return false; } } return true; } private static void ThrowMultipleCtorsMarkedWithAttributeException() { throw new InvalidOperationException("Multiple constructors were marked with ActivatorUtilitiesConstructorAttribute."); } private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments() { throw new InvalidOperationException("Constructor marked with ActivatorUtilitiesConstructorAttribute does not accept all given argument types."); } } [AttributeUsage(AttributeTargets.All)] public class ActivatorUtilitiesConstructorAttribute : Attribute { } public readonly struct AsyncServiceScope : IServiceScope, IDisposable, IAsyncDisposable { private readonly IServiceScope _serviceScope; public IServiceProvider ServiceProvider => _serviceScope.ServiceProvider; public AsyncServiceScope(IServiceScope serviceScope) { System.ThrowHelper.ThrowIfNull(serviceScope, "serviceScope"); _serviceScope = serviceScope; } public void Dispose() { _serviceScope.Dispose(); } public ValueTask DisposeAsync() { if (_serviceScope is IAsyncDisposable asyncDisposable) { return asyncDisposable.DisposeAsync(); } _serviceScope.Dispose(); return default(ValueTask); } } public interface IServiceCollection : IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable { } public interface IServiceProviderFactory<TContainerBuilder> where TContainerBuilder : notnull { TContainerBuilder CreateBuilder(IServiceCollection services); IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder); } public interface IServiceProviderIsService { bool IsService(Type serviceType); } public interface IServiceScope : IDisposable { IServiceProvider ServiceProvider { get; } } public interface IServiceScopeFactory { IServiceScope CreateScope(); } public interface ISupportRequiredService { object GetRequiredService(Type serviceType); } public delegate object ObjectFactory(IServiceProvider serviceProvider, object?[]? arguments); public class ServiceCollection : IServiceCollection, IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, 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 IEnumerator<ServiceDescriptor> GetEnumerator() { return _descriptors.GetEnumerator(); } void ICollection<ServiceDescriptor>.Add(ServiceDescriptor item) { CheckReadOnly(); _descriptors.Add(item); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int IndexOf(ServiceDescriptor item) { return _descriptors.IndexOf(item); } public void Insert(int index, ServiceDescriptor item) { CheckReadOnly(); _descriptors.Insert(index, item); } public void RemoveAt(int index) { CheckReadOnly(); _descriptors.RemoveAt(index); } public void MakeReadOnly() { _isReadOnly = true; } private void CheckReadOnly() { if (_isReadOnly) { ThrowReadOnlyException(); } } private static void ThrowReadOnlyException() { throw new InvalidOperationException(System.SR.ServiceCollectionReadOnly); } } public static class ServiceCollectionServiceExtensions { public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); } public static IServiceCollection AddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddTransient(serviceType, serviceType); } public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService)); } public static IServiceCollection AddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddScoped(serviceType, serviceType); } public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService)); } public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); return services.AddSingleton(serviceType, serviceType); } public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService)); } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, object implementationInstance) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationInstance); services.Add(item); return services; } public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return services.AddSingleton(typeof(TService), implementationInstance); } private static IServiceCollection Add(IServiceCollection collection, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationType, lifetime); collection.Add(item); return collection; } private static IServiceCollection Add(IServiceCollection collection, Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationFactory, lifetime); collection.Add(item); return collection; } } [DebuggerDisplay("Lifetime = {Lifetime}, ServiceType = {ServiceType}, ImplementationType = {ImplementationType}")] public class ServiceDescriptor { public ServiceLifetime Lifetime { get; } public Type ServiceType { get; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public Type? ImplementationType { get; } public object? ImplementationInstance { get; } public Func<IServiceProvider, object>? ImplementationFactory { get; } public ServiceDescriptor(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) : this(serviceType, lifetime) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ImplementationType = implementationType; } public ServiceDescriptor(Type serviceType, object instance) : this(serviceType, ServiceLifetime.Singleton) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(instance, "instance"); ImplementationInstance = instance; } public ServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime) : this(serviceType, lifetime) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(factory, "factory"); ImplementationFactory = factory; } private ServiceDescriptor(Type serviceType, ServiceLifetime lifetime) { Lifetime = lifetime; ServiceType = serviceType; } public override string ToString() { string text = $"{"ServiceType"}: {ServiceType} {"Lifetime"}: {Lifetime} "; if (ImplementationType != null) { return text + $"{"ImplementationType"}: {ImplementationType}"; } if (ImplementationFactory != null) { return text + $"{"ImplementationFactory"}: {ImplementationFactory.Method}"; } return text + $"{"ImplementationInstance"}: {ImplementationInstance}"; } internal Type GetImplementationType() { if (ImplementationType != null) { return ImplementationType; } if (ImplementationInstance != null) { return ImplementationInstance.GetType(); } if (ImplementationFactory != null) { Type[] genericTypeArguments = ImplementationFactory.GetType().GenericTypeArguments; return genericTypeArguments[1]; } return null; } public static ServiceDescriptor Transient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Scoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] 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 { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Singleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService { return Describe<TService, TImplementation>(ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class { System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type serviceType, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton<TService>(TService implementationInstance) where TService : class { System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return Singleton(typeof(TService), implementationInstance); } public static ServiceDescriptor Singleton(Type serviceType, object implementationInstance) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); System.ThrowHelper.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, implementationInstance); } private static ServiceDescriptor Describe<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(ServiceLifetime lifetime) where TService : class where TImplementation : class, TService { return Describe(typeof(TService), typeof(TImplementation), lifetime); } public static ServiceDescriptor Describe(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationType, lifetime); } public static ServiceDescriptor Describe(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) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetService(typeof(T)); } public static object GetRequiredService(this IServiceProvider provider, Type serviceType) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); if (provider is ISupportRequiredService supportRequiredService) { return supportRequiredService.GetRequiredService(serviceType); } object service = provider.GetService(serviceType); if (service == null) { throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType)); } return service; } public static T GetRequiredService<T>(this IServiceProvider provider) where T : notnull { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredService(typeof(T)); } public static IEnumerable<T> GetServices<T>(this IServiceProvider provider) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return provider.GetRequiredService<IEnumerable<T>>(); } [RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")] public static IEnumerable<object?> GetServices(this IServiceProvider provider, Type serviceType) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable<object>)provider.GetRequiredService(serviceType2); } public static IServiceScope CreateScope(this IServiceProvider provider) { return provider.GetRequiredService<IServiceScopeFactory>().CreateScope(); } public static AsyncServiceScope CreateAsyncScope(this IServiceProvider provider) { return new AsyncServiceScope(provider.CreateScope()); } public static AsyncServiceScope CreateAsyncScope(this IServiceScopeFactory serviceScopeFactory) { return new AsyncServiceScope(serviceScopeFactory.CreateScope()); } } } namespace Microsoft.Extensions.DependencyInjection.Extensions { public static class ServiceCollectionDescriptorExtensions { public static IServiceCollection Add(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); collection.Add(descriptor); return collection; } public static IServiceCollection Add(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.Add(descriptor); } return collection; } public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); int count = collection.Count; for (int i = 0; i < count; i++) { if (collection[i].ServiceType == descriptor.ServiceType) { return; } } collection.Add(descriptor); } public static void TryAdd(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.TryAdd(descriptor); } } public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, service); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TService)); } public static void TryAddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TImplementation)); } public static void TryAddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Transient(implementationFactory)); } public static void TryAddScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, service); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TService)); } public static void TryAddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TImplementation)); } public static void TryAddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Scoped(implementationFactory)); } public static void TryAddSingleton(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, service); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(service, "service"); System.ThrowHelper.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TService)); } public static void TryAddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService { System.ThrowHelper.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TImplementation)); } public static void TryAddSingleton<TService>(this IServiceCollection collection, TService instance) where TService : class { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(instance, "instance"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(typeof(TService), instance); collection.TryAdd(descriptor); } public static void TryAddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Singleton(implementationFactory)); } public static void TryAddEnumerable(this IServiceCollection services, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); Type implementationType = descriptor.GetImplementationType(); if (implementationType == typeof(object) || implementationType == descriptor.ServiceType) { throw new ArgumentException(System.SR.Format(System.SR.TryAddIndistinguishableTypeToEnumerable, implementationType, descriptor.ServiceType), "descriptor"); } int count = services.Count; for (int i = 0; i < count; i++) { ServiceDescriptor serviceDescriptor = services[i]; if (serviceDescriptor.ServiceType == descriptor.ServiceType && serviceDescriptor.GetImplementationType() == implementationType) { return; } } services.Add(descriptor); } public static void TryAddEnumerable(this IServiceCollection services, IEnumerable<ServiceDescriptor> descriptors) { System.ThrowHelper.ThrowIfNull(services, "services"); System.ThrowHelper.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { services.TryAddEnumerable(descriptor); } } public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor) { System.ThrowHelper.ThrowIfNull(collection, "collection"); System.ThrowHelper.ThrowIfNull(descriptor, "descriptor"); int count = collection.Count; for (int i = 0; i < count; i++) { if (collection[i].ServiceType == descriptor.ServiceType) { collection.RemoveAt(i); break; } } collection.Add(descriptor); return collection; } public static IServiceCollection RemoveAll<T>(this IServiceCollection collection) { return collection.RemoveAll(typeof(T)); } public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType) { System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); for (int num = collection.Count - 1; num >= 0; num--) { ServiceDescriptor serviceDescriptor = collection[num]; if (serviceDescriptor.ServiceType == serviceType) { collection.RemoveAt(num); } } return collection; } } }
MegabonkTogether/Microsoft.Extensions.Options.dll
Decompiled 2 hours agousing System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Options.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Options")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Options")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.Options { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string? Scope { get; set; } public string? Target { get; set; } public string? MessageId { get; set; } public string? Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } } namespace Microsoft.Extensions.DependencyInjection { public static class OptionsServiceCollectionExtensions { public static IServiceCollection AddOptions(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException("services"); } services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(UnnamedOptionsManager<>))); services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>))); services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>))); services.TryAdd(ServiceDescriptor.Transient(typeof(IOptionsFactory<>), typeof(OptionsFactory<>))); services.TryAdd(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(Microsoft.Extensions.Options.Options.DefaultName, configureOptions); } public static IServiceCollection Configure<TOptions>(this IServiceCollection services, string name, Action<TOptions> configureOptions) where TOptions : class { if (services == null) { throw new ArgumentNullException("services"); } if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } services.AddOptions(); services.AddSingleton((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(null, configureOptions); } public static IServiceCollection PostConfigure<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class { return services.PostConfigure(Microsoft.Extensions.Options.Options.DefaultName, configureOptions); } public static IServiceCollection PostConfigure<TOptions>(this IServiceCollection services, string name, Action<TOptions> configureOptions) where TOptions : class { if (services == null) { throw new ArgumentNullException("services"); } if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } services.AddOptions(); services.AddSingleton((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(null, configureOptions); } public static IServiceCollection ConfigureOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TConfigureOptions>(this IServiceCollection services) where TConfigureOptions : class { return services.ConfigureOptions(typeof(TConfigureOptions)); } private static IEnumerable<Type> FindConfigurationServices(Type type) { Type[] array = GetInterfacesOnType(type); foreach (Type type2 in array) { if (type2.IsGenericType) { Type genericTypeDefinition = type2.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(IConfigureOptions<>) || genericTypeDefinition == typeof(IPostConfigureOptions<>) || genericTypeDefinition == typeof(IValidateOptions<>)) { yield return type2; } } } [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 Type[] GetInterfacesOnType(Type t) { return t.GetInterfaces(); } } private static void ThrowNoConfigServices(Type type) { 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(DynamicallyAccessedMemberTypes.PublicConstructors)] Type configureType) { services.AddOptions(); bool flag = false; foreach (Type item in FindConfigurationServices(configureType)) { services.AddTransient(item, configureType); flag = true; } if (!flag) { ThrowNoConfigServices(configureType); } return services; } public static IServiceCollection ConfigureOptions(this IServiceCollection services, object configureInstance) { services.AddOptions(); Type type = configureInstance.GetType(); bool flag = false; foreach (Type item in FindConfigurationServices(type)) { services.AddSingleton(item, configureInstance); flag = true; } 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 { if (services == null) { throw new ArgumentNullException("services"); } services.AddOptions(); return new OptionsBuilder<TOptions>(services, name); } } } namespace Microsoft.Extensions.Options { public class ConfigureNamedOptions<TOptions> : IConfigureNamedOptions<TOptions>, IConfigureOptions<TOptions> where TOptions : class { public string Name { get; } public Action<TOptions> Action { get; } public ConfigureNamedOptions(string name, Action<TOptions> action) { Name = name; Action = action; } public virtual void Configure(string name, TOptions options) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep> Action { get; } public TDep Dependency { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep1, TDep2> Action { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep1, TDep2, TDep3> Action { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep1, TDep2, TDep3, TDep4> Action { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { get; } public TDep4 Dependency4 { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> Action { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { get; } public TDep4 Dependency4 { get; } public TDep5 Dependency5 { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public ConfigureOptions(Action<TOptions> action) { Action = action; } public virtual void Configure(TOptions options) { if (options == null) { throw new ArgumentNullException("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(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] out TOptions> where TOptions : class { TOptions Value { get; } } public interface IOptionsChangeTokenSource<out TOptions> { string Name { get; } IChangeToken GetChangeToken(); } public interface IOptionsFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> where TOptions : class { TOptions Create(string name); } public interface IOptionsMonitor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] out TOptions> { TOptions CurrentValue { get; } TOptions Get(string name); IDisposable OnChange(Action<TOptions, string> listener); } public interface IOptionsMonitorCache<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] 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(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] 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 = DynamicallyAccessedMemberTypes.PublicParameterlessConstructor; public static readonly string DefaultName = string.Empty; public static IOptions<TOptions> Create<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] 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 { get; } public IServiceCollection Services { get; } public OptionsBuilder(IServiceCollection services, string name) { if (services == null) { throw new ArgumentNullException("services"); } Services = services; Name = name ?? Options.DefaultName; } public virtual OptionsBuilder<TOptions> Configure(Action<TOptions> configureOptions) { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddSingleton((IConfigureOptions<TOptions>)new ConfigureNamedOptions<TOptions>(Name, configureOptions)); return this; } public virtual OptionsBuilder<TOptions> Configure<TDep>(Action<TOptions, TDep> configureOptions) where TDep : class { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), configureOptions))); return this; } public virtual OptionsBuilder<TOptions> Configure<TDep1, TDep2>(Action<TOptions, TDep1, TDep2> configureOptions) where TDep1 : class where TDep2 : class { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), configureOptions))); 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 { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), configureOptions))); 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 { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), configureOptions))); 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 { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IConfigureOptions<TOptions>>)((IServiceProvider sp) => new ConfigureNamedOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), sp.GetRequiredService<TDep5>(), configureOptions))); return this; } public virtual OptionsBuilder<TOptions> PostConfigure(Action<TOptions> configureOptions) { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddSingleton((IPostConfigureOptions<TOptions>)new PostConfigureOptions<TOptions>(Name, configureOptions)); return this; } public virtual OptionsBuilder<TOptions> PostConfigure<TDep>(Action<TOptions, TDep> configureOptions) where TDep : class { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), configureOptions))); return this; } public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2>(Action<TOptions, TDep1, TDep2> configureOptions) where TDep1 : class where TDep2 : class { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), configureOptions))); 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 { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), configureOptions))); 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 { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), configureOptions))); 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 { if (configureOptions == null) { throw new ArgumentNullException("configureOptions"); } Services.AddTransient((Func<IServiceProvider, IPostConfigureOptions<TOptions>>)((IServiceProvider sp) => new PostConfigureOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), sp.GetRequiredService<TDep5>(), configureOptions))); 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) { if (validation == null) { throw new ArgumentNullException("validation"); } Services.AddSingleton((IValidateOptions<TOptions>)new ValidateOptions<TOptions>(Name, validation, failureMessage)); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep>(Func<TOptions, TDep, bool> validation) { return Validate(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate<TDep>(Func<TOptions, TDep, bool> validation, string failureMessage) { if (validation == null) { throw new ArgumentNullException("validation"); } Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep>(Name, sp.GetRequiredService<TDep>(), validation, failureMessage))); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2>(Func<TOptions, TDep1, TDep2, bool> validation) { return Validate(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2>(Func<TOptions, TDep1, TDep2, bool> validation, string failureMessage) { if (validation == null) { throw new ArgumentNullException("validation"); } Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), validation, failureMessage))); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3>(Func<TOptions, TDep1, TDep2, TDep3, bool> validation) { return Validate(validation, "A validation error has occurred."); } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3>(Func<TOptions, TDep1, TDep2, TDep3, bool> validation, string failureMessage) { if (validation == null) { throw new ArgumentNullException("validation"); } Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), validation, failureMessage))); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation) { return Validate(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) { if (validation == null) { throw new ArgumentNullException("validation"); } Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), validation, failureMessage))); return this; } public virtual OptionsBuilder<TOptions> Validate<TDep1, TDep2, TDep3, TDep4, TDep5>(Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> validation) { return Validate(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) { if (validation == null) { throw new ArgumentNullException("validation"); } Services.AddTransient((Func<IServiceProvider, IValidateOptions<TOptions>>)((IServiceProvider sp) => new ValidateOptions<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5>(Name, sp.GetRequiredService<TDep1>(), sp.GetRequiredService<TDep2>(), sp.GetRequiredService<TDep3>(), sp.GetRequiredService<TDep4>(), sp.GetRequiredService<TDep5>(), validation, failureMessage))); return this; } } public class OptionsCache<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptionsMonitorCache<TOptions> where TOptions : class { private readonly ConcurrentDictionary<string, Lazy<TOptions>> _cache = new ConcurrentDictionary<string, Lazy<TOptions>>(1, 31, StringComparer.Ordinal); public void Clear() { _cache.Clear(); } public virtual TOptions GetOrAdd(string name, Func<TOptions> createOptions) { if (createOptions == null) { throw new ArgumentNullException("createOptions"); } name = name ?? Options.DefaultName; Lazy<TOptions> orAdd = _cache.GetOrAdd(name, (string name, Func<TOptions> createOptions) => new Lazy<TOptions>(createOptions), createOptions); return orAdd.Value; } internal bool TryGetValue(string name, out TOptions options) { if (_cache.TryGetValue(name ?? Options.DefaultName, out var value)) { options = value.Value; return true; } options = null; return false; } public virtual bool TryAdd(string name, TOptions options) { if (options == null) { throw new ArgumentNullException("options"); } return _cache.TryAdd(name ?? Options.DefaultName, new Lazy<TOptions>(options)); } public virtual bool TryRemove(string name) { Lazy<TOptions> value; return _cache.TryRemove(name ?? Options.DefaultName, out value); } } public class OptionsFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptionsFactory<TOptions> where TOptions : class { private readonly IConfigureOptions<TOptions>[] _setups; private readonly IPostConfigureOptions<TOptions>[] _postConfigures; private readonly IValidateOptions<TOptions>[] _validations; public OptionsFactory(IEnumerable<IConfigureOptions<TOptions>> setups, IEnumerable<IPostConfigureOptions<TOptions>> postConfigures) : this(setups, postConfigures, (IEnumerable<IValidateOptions<TOptions>>)Array.Empty<IValidateOptions<TOptions>>()) { } public OptionsFactory(IEnumerable<IConfigureOptions<TOptions>> setups, IEnumerable<IPostConfigureOptions<TOptions>> postConfigures, IEnumerable<IValidateOptions<TOptions>> validations) { _setups = (setups as IConfigureOptions<TOptions>[]) ?? new List<IConfigureOptions<TOptions>>(setups).ToArray(); _postConfigures = (postConfigures as IPostConfigureOptions<TOptions>[]) ?? new List<IPostConfigureOptions<TOptions>>(postConfigures).ToArray(); _validations = (validations as IValidateOptions<TOptions>[]) ?? new List<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 != null) { List<string> list = new List<string>(); IValidateOptions<TOptions>[] validations = _validations; foreach (IValidateOptions<TOptions> validateOptions in validations) { ValidateOptionsResult validateOptionsResult = validateOptions.Validate(name, val); if (validateOptionsResult != null && validateOptionsResult.Failed) { list.AddRange(validateOptionsResult.Failures); } } if (list.Count > 0) { throw new OptionsValidationException(name, typeof(TOptions), list); } } return val; } protected virtual TOptions CreateInstance(string name) { return Activator.CreateInstance<TOptions>(); } } public class OptionsManager<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] 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) { name = 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(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptionsMonitor<TOptions>, IDisposable where TOptions : class { internal sealed class ChangeTrackerDisposable : 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(options, name); } public void Dispose() { _monitor._onChange -= OnChange; } } private readonly IOptionsMonitorCache<TOptions> _cache; private readonly IOptionsFactory<TOptions> _factory; private readonly List<IDisposable> _registrations = new List<IDisposable>(); public TOptions CurrentValue => Get(Options.DefaultName); internal event Action<TOptions, string> _onChange; public OptionsMonitor(IOptionsFactory<TOptions> factory, 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); void RegisterSource(IOptionsChangeTokenSource<TOptions> source) { IDisposable item = ChangeToken.OnChange(() => source.GetChangeToken(), delegate(string name) { InvokeChanged(name); }, source.Name); _registrations.Add(item); } } return; } foreach (IOptionsChangeTokenSource<TOptions> source3 in sources) { RegisterSource(source3); } } private void InvokeChanged(string name) { name = name ?? Options.DefaultName; _cache.TryRemove(name); TOptions arg = Get(name); if (this._onChange != null) { this._onChange(arg, name); } } public virtual TOptions Get(string name) { name = name ?? Options.DefaultName; return _cache.GetOrAdd(name, () => _factory.Create(name)); } public IDisposable OnChange(Action<TOptions, string> listener) { ChangeTrackerDisposable changeTrackerDisposable = new ChangeTrackerDisposable(this, listener); _onChange += changeTrackerDisposable.OnChange; return changeTrackerDisposable; } public void Dispose() { foreach (IDisposable registration in _registrations) { registration.Dispose(); } _registrations.Clear(); } } public static class OptionsMonitorExtensions { public static IDisposable OnChange<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(this IOptionsMonitor<TOptions> monitor, Action<TOptions> listener) { return monitor.OnChange(delegate(TOptions o, string _) { listener(o); }); } } public class OptionsValidationException : Exception { public string OptionsName { get; } public Type OptionsType { get; } public IEnumerable<string> Failures { get; } public override string Message => string.Join("; ", Failures); public OptionsValidationException(string optionsName, Type optionsType, IEnumerable<string> failureMessages) { Failures = failureMessages ?? new List<string>(); OptionsType = optionsType ?? throw new ArgumentNullException("optionsType"); OptionsName = optionsName ?? throw new ArgumentNullException("optionsName"); } } public class OptionsWrapper<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions> : IOptions<TOptions> where TOptions : class { public TOptions Value { get; } public OptionsWrapper(TOptions options) { Value = options; } } public class PostConfigureOptions<TOptions> : IPostConfigureOptions<TOptions> where TOptions : class { public string Name { get; } public Action<TOptions> Action { get; } public PostConfigureOptions(string name, Action<TOptions> action) { Name = name; Action = action; } public virtual void PostConfigure(string name, TOptions options) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep> Action { get; } public TDep Dependency { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep1, TDep2> Action { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep1, TDep2, TDep3> Action { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep1, TDep2, TDep3, TDep4> Action { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { get; } public TDep4 Dependency4 { 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) { if (options == null) { throw new ArgumentNullException("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 { get; } public Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> Action { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { get; } public TDep4 Dependency4 { get; } public TDep5 Dependency5 { 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) { if (options == null) { throw new ArgumentNullException("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(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] 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(), 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 { get; } public Func<TOptions, bool> Validation { get; } public string FailureMessage { get; } public ValidateOptions(string name, Func<TOptions, bool> validation, string failureMessage) { Name = name; Validation = validation; FailureMessage = failureMessage; } public ValidateOptionsResult Validate(string name, TOptions options) { if (Name == null || name == Name) { if ((Validation?.Invoke(options)).Value) { return ValidateOptionsResult.Success; } return ValidateOptionsResult.Fail(FailureMessage); } return ValidateOptionsResult.Skip; } } public class ValidateOptions<TOptions, TDep> : IValidateOptions<TOptions> where TOptions : class { public string Name { get; } public Func<TOptions, TDep, bool> Validation { get; } public string FailureMessage { get; } public TDep Dependency { get; } public ValidateOptions(string name, TDep dependency, Func<TOptions, TDep, bool> validation, string failureMessage) { 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)).Value) { return ValidateOptionsResult.Success; } return ValidateOptionsResult.Fail(FailureMessage); } return ValidateOptionsResult.Skip; } } public class ValidateOptions<TOptions, TDep1, TDep2> : IValidateOptions<TOptions> where TOptions : class { public string Name { get; } public Func<TOptions, TDep1, TDep2, bool> Validation { get; } public string FailureMessage { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public ValidateOptions(string name, TDep1 dependency1, TDep2 dependency2, Func<TOptions, TDep1, TDep2, bool> validation, string failureMessage) { 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)).Value) { 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 { get; } public Func<TOptions, TDep1, TDep2, TDep3, bool> Validation { get; } public string FailureMessage { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { get; } public ValidateOptions(string name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, Func<TOptions, TDep1, TDep2, TDep3, bool> validation, string failureMessage) { 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)).Value) { 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 { get; } public Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> Validation { get; } public string FailureMessage { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { get; } public TDep4 Dependency4 { get; } public ValidateOptions(string name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Func<TOptions, TDep1, TDep2, TDep3, TDep4, bool> validation, string failureMessage) { 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)).Value) { 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 { get; } public Func<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5, bool> Validation { get; } public string FailureMessage { get; } public TDep1 Dependency1 { get; } public TDep2 Dependency2 { get; } public TDep3 Dependency3 { get; } public TDep4 Dependency4 { get; } public TDep5 Dependency5 { 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) { 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)).Value) { 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 }; public bool Succeeded { get; protected set; } public bool Skipped { get; protected set; } public bool Failed { get; protected set; } public string FailureMessage { get; protected set; } public IEnumerable<string> Failures { get; 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(IEnumerable<string> failures) { return new ValidateOptionsResult { Failed = true, FailureMessage = string.Join("; ", failures), Failures = failures }; } } }
MegabonkTogether/Microsoft.Extensions.Configuration.CommandLine.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.CommandLine.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.CommandLine")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Command line configuration provider implementation for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.CommandLine")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.CommandLine { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace 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(new CommandLineConfigurationSource { Args = args, SwitchMappings = switchMappings }); return configurationBuilder; } public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action<CommandLineConfigurationSource> configureSource) { return builder.Add(configureSource); } } } namespace Microsoft.Extensions.Configuration.CommandLine { public class CommandLineConfigurationProvider : ConfigurationProvider { private readonly Dictionary<string, string> _switchMappings; protected IEnumerable<string> Args { get; private set; } public CommandLineConfigurationProvider(IEnumerable<string> args, IDictionary<string, string> switchMappings = null) { Args = args ?? throw new ArgumentNullException("args"); if (switchMappings != null) { _switchMappings = GetValidatedSwitchMappingsCopy(switchMappings); } } public override void Load() { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (IEnumerator<string> enumerator = Args.GetEnumerator()) { while (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 key; string value2; if (num2 < 0) { if (num == 0) { continue; } if (_switchMappings != null && _switchMappings.TryGetValue(text, out var value)) { key = value; } else { if (num == 1) { continue; } key = text.Substring(num); } string current = enumerator.Current; if (!enumerator.MoveNext()) { continue; } value2 = enumerator.Current; } else { string key2 = text.Substring(0, num2); if (_switchMappings != null && _switchMappings.TryGetValue(key2, out var value3)) { key = value3; } else { if (num == 1) { throw new FormatException(System.SR.Format(System.SR.Error_ShortSwitchNotDefined, text)); } key = text.Substring(num, num2 - num); } value2 = text.Substring(num2 + 1); } dictionary[key] = value2; } } base.Data = dictionary; } private Dictionary<string, string> GetValidatedSwitchMappingsCopy(IDictionary<string, string> switchMappings) { Dictionary<string, string> dictionary = new Dictionary<string, string>(switchMappings.Count, StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, string> switchMapping in switchMappings) { if (!switchMapping.Key.StartsWith("-") && !switchMapping.Key.StartsWith("--")) { throw new ArgumentException(System.SR.Format(System.SR.Error_InvalidSwitchMapping, switchMapping.Key), "switchMappings"); } if (dictionary.ContainsKey(switchMapping.Key)) { throw new ArgumentException(System.SR.Format(System.SR.Error_DuplicatedKeyInSwitchMappings, switchMapping.Key), "switchMappings"); } dictionary.Add(switchMapping.Key, switchMapping.Value); } return dictionary; } } public class CommandLineConfigurationSource : IConfigurationSource { public IDictionary<string, string> SwitchMappings { get; set; } public IEnumerable<string> Args { get; set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return new CommandLineConfigurationProvider(Args, SwitchMappings); } } }
MegabonkTogether/Microsoft.Extensions.Options.ConfigurationExtensions.dll
Decompiled 2 hours 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.Extensions.Configuration; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Options.ConfigurationExtensions")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Provides additional configuration specific functionality related to Options.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Options.ConfigurationExtensions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string Scope { get; set; } public string Target { get; set; } public string MessageId { get; set; } public string Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } } namespace Microsoft.Extensions.DependencyInjection { public static class OptionsBuilderConfigurationExtensions { internal const string TrimmingRequiredUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved."; [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static OptionsBuilder<TOptions> Bind<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, IConfiguration config) where TOptions : class { return optionsBuilder.Bind(config, delegate { }); } [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static OptionsBuilder<TOptions> Bind<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, IConfiguration config, Action<BinderOptions> configureBinder) where TOptions : class { if (optionsBuilder == null) { throw new ArgumentNullException("optionsBuilder"); } optionsBuilder.Services.Configure<TOptions>(optionsBuilder.Name, config, configureBinder); return optionsBuilder; } [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static OptionsBuilder<TOptions> BindConfiguration<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder, string configSectionPath, Action<BinderOptions> configureBinder = null) where TOptions : class { if (optionsBuilder == null) { throw new ArgumentNullException("optionsBuilder"); } if (configSectionPath == null) { throw new ArgumentNullException("configSectionPath"); } optionsBuilder.Configure(delegate(TOptions opts, IConfiguration config) { BindFromOptions(opts, config, configSectionPath, configureBinder); }); optionsBuilder.Services.AddSingleton<IOptionsChangeTokenSource<TOptions>, ConfigurationChangeTokenSource<TOptions>>(); return optionsBuilder; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The only call to this method is in BindConfiguration method which is already annotated as RequiresUnreferencedCode.")] private static void BindFromOptions<TOptions>(TOptions opts, IConfiguration config, string configSectionPath, Action<BinderOptions> configureBinder) where TOptions : class { IConfiguration configuration; if (!string.Equals("", configSectionPath, StringComparison.OrdinalIgnoreCase)) { IConfiguration section = config.GetSection(configSectionPath); configuration = section; } else { configuration = config; } IConfiguration configuration2 = configuration; configuration2.Bind(opts, configureBinder); } } public static class OptionsConfigurationServiceCollectionExtensions { [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, IConfiguration config) where TOptions : class { return services.Configure<TOptions>(Microsoft.Extensions.Options.Options.DefaultName, config); } [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, string name, IConfiguration config) where TOptions : class { return services.Configure<TOptions>(name, config, delegate { }); } [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, IConfiguration config, Action<BinderOptions> configureBinder) where TOptions : class { return services.Configure<TOptions>(Microsoft.Extensions.Options.Options.DefaultName, config, configureBinder); } [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, string name, IConfiguration config, Action<BinderOptions> configureBinder) where TOptions : class { if (services == null) { throw new ArgumentNullException("services"); } if (config == null) { throw new ArgumentNullException("config"); } services.AddOptions(); services.AddSingleton((IOptionsChangeTokenSource<TOptions>)new ConfigurationChangeTokenSource<TOptions>(name, config)); return services.AddSingleton((IConfigureOptions<TOptions>)new NamedConfigureFromConfigurationOptions<TOptions>(name, config, configureBinder)); } } } namespace Microsoft.Extensions.Options { public class ConfigurationChangeTokenSource<TOptions> : IOptionsChangeTokenSource<TOptions> { private IConfiguration _config; public string Name { get; } public ConfigurationChangeTokenSource(IConfiguration config) : this(Options.DefaultName, config) { } public ConfigurationChangeTokenSource(string name, IConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _config = config; Name = name ?? Options.DefaultName; } public IChangeToken GetChangeToken() { return _config.GetReloadToken(); } } public class ConfigureFromConfigurationOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions> : ConfigureOptions<TOptions> where TOptions : class { [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public ConfigureFromConfigurationOptions(IConfiguration config) : base((Action<TOptions>)delegate(TOptions options) { BindFromOptions(options, config); }) { if (config == null) { throw new ArgumentNullException("config"); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The only call to this method is the constructor which is already annotated as RequiresUnreferencedCode.")] private static void BindFromOptions(TOptions options, IConfiguration config) { config.Bind(options); } } public class NamedConfigureFromConfigurationOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions> : ConfigureNamedOptions<TOptions> where TOptions : class { [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 { }) { } [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) : base(name, (Action<TOptions>)delegate(TOptions options) { BindFromOptions(options, config, configureBinder); }) { if (config == null) { throw new ArgumentNullException("config"); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The only call to this method is the constructor which is already annotated as RequiresUnreferencedCode.")] private static void BindFromOptions(TOptions options, IConfiguration config, Action<BinderOptions> configureBinder) { config.Bind(options, configureBinder); } } }
MegabonkTogether/Microsoft.Extensions.Configuration.EnvironmentVariables.dll
Decompiled 2 hours 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.Extensions.Configuration.EnvironmentVariables; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.EnvironmentVariables.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.EnvironmentVariables")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Environment variables configuration provider implementation for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("6.0.222.6406")] [assembly: AssemblyInformationalVersion("6.0.2+839cdfb0ecca5e0be3dbccd926e7651ef50fdf10")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.EnvironmentVariables")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace Microsoft.Extensions.Configuration { public static class EnvironmentVariablesExtensions { public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder configurationBuilder) { configurationBuilder.Add(new EnvironmentVariablesConfigurationSource()); return configurationBuilder; } public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder configurationBuilder, string prefix) { configurationBuilder.Add(new EnvironmentVariablesConfigurationSource { Prefix = prefix }); return configurationBuilder; } public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action<EnvironmentVariablesConfigurationSource> configureSource) { return builder.Add(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 CustomPrefix = "CUSTOMCONNSTR_"; private readonly string _prefix; public EnvironmentVariablesConfigurationProvider() { _prefix = string.Empty; } public EnvironmentVariablesConfigurationProvider(string prefix) { _prefix = prefix ?? string.Empty; } public override void Load() { Load(Environment.GetEnvironmentVariables()); } public override string ToString() { return GetType().Name + " Prefix: '" + _prefix + "'"; } internal void Load(IDictionary envVariables) { Dictionary<string, string> data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (DictionaryEntry envVariable in envVariables) { string text = (string)envVariable.Key; string text2 = null; string text3; if (text.StartsWith("MYSQLCONNSTR_", StringComparison.OrdinalIgnoreCase)) { text3 = "MYSQLCONNSTR_"; text2 = "MySql.Data.MySqlClient"; } else if (text.StartsWith("SQLAZURECONNSTR_", StringComparison.OrdinalIgnoreCase)) { text3 = "SQLAZURECONNSTR_"; text2 = "System.Data.SqlClient"; } else if (text.StartsWith("SQLCONNSTR_", StringComparison.OrdinalIgnoreCase)) { text3 = "SQLCONNSTR_"; text2 = "System.Data.SqlClient"; } else { if (!text.StartsWith("CUSTOMCONNSTR_", StringComparison.OrdinalIgnoreCase)) { AddIfPrefixed(data, NormalizeKey(text), (string)envVariable.Value); continue; } text3 = "CUSTOMCONNSTR_"; } text = NormalizeKey(text.Substring(text3.Length)); AddIfPrefixed(data, "ConnectionStrings:" + text, (string)envVariable.Value); if (text2 != null) { AddIfPrefixed(data, "ConnectionStrings:" + text + "_ProviderName", text2); } } base.Data = data; } private void AddIfPrefixed(Dictionary<string, string> data, string key, string value) { if (key.StartsWith(_prefix, StringComparison.OrdinalIgnoreCase)) { key = key.Substring(_prefix.Length); data[key] = value; } } private static string NormalizeKey(string key) { return key.Replace("__", ConfigurationPath.KeyDelimiter); } } public class EnvironmentVariablesConfigurationSource : IConfigurationSource { public string Prefix { get; set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return new EnvironmentVariablesConfigurationProvider(Prefix); } } }
MegabonkTogether/Microsoft.Extensions.Logging.Debug.dll
Decompiled 2 hours ago#define DEBUG using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging.Debug; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Debug")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Debug")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace Microsoft.Extensions.Logging { public static class DebugLoggerFactoryExtensions { public static ILoggingBuilder AddDebug(this ILoggingBuilder builder) { builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, DebugLoggerProvider>()); return builder; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { public static IExternalScopeProvider Instance { get; } = new Microsoft.Extensions.Logging.NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } IDisposable IExternalScopeProvider.Push(object state) { return Microsoft.Extensions.Logging.NullScope.Instance; } } internal sealed class NullScope : IDisposable { public static Microsoft.Extensions.Logging.NullScope Instance { get; } = new Microsoft.Extensions.Logging.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 IDisposable BeginScope<TState>(TState state) { return Microsoft.Extensions.Logging.NullScope.Instance; } public bool IsEnabled(LogLevel logLevel) { if (Debugger.IsAttached) { return logLevel != LogLevel.None; } return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } if (formatter == null) { throw new ArgumentNullException("formatter"); } string text = formatter(state, exception); if (!string.IsNullOrEmpty(text)) { text = $"{logLevel}: {text}"; if (exception != null) { text = text + Environment.NewLine + Environment.NewLine + exception; } DebugWriteLine(text, _name); } } private void DebugWriteLine(string message, string name) { System.Diagnostics.Debug.WriteLine(message, name); } } [ProviderAlias("Debug")] public class DebugLoggerProvider : ILoggerProvider, IDisposable { public ILogger CreateLogger(string name) { return new DebugLogger(name); } public void Dispose() { } } }
MegabonkTogether/MegabonkTogether.Common.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.WebSockets; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using System.Threading.Tasks; using MegabonkTogether.Common.Messages; using MegabonkTogether.Common.Messages.GameNetworkMessages; using MegabonkTogether.Common.Messages.WsMessages; using MegabonkTogether.Common.Models; using MemoryPack; using MemoryPack.Formatters; using MemoryPack.Internal; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("MegabonkTogether.Common")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0+345d21e38d0e1f40b8178e142bed88bc5edd5109")] [assembly: AssemblyProduct("MegabonkTogether.Common")] [assembly: AssemblyTitle("MegabonkTogether.Common")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace MegabonkTogether.Common.Models { [MemoryPackable(/*Could not decode attribute arguments.*/)] public class BossOrbModel : IMemoryPackable<BossOrbModel>, IMemoryPackFormatterRegister { [Preserve] private sealed class BossOrbModelFormatter : MemoryPackFormatter<BossOrbModel> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref BossOrbModel value) { BossOrbModel.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref BossOrbModel value) { BossOrbModel.Deserialize(ref reader, ref value); } } public QuantizedVector3 Position = new QuantizedVector3(); public uint Id { get; set; } static BossOrbModel() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<BossOrbModel>()) { MemoryPackFormatterProvider.Register<BossOrbModel>((MemoryPackFormatter<BossOrbModel>)(object)new BossOrbModelFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<BossOrbModel[]>()) { MemoryPackFormatterProvider.Register<BossOrbModel[]>((MemoryPackFormatter<BossOrbModel[]>)(object)new ArrayFormatter<BossOrbModel>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref BossOrbModel? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint id = value.Id; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint>((byte)2, ref id); Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<QuantizedVector3>>(ref writer).WritePackable<QuantizedVector3>(ref value.Position); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref BossOrbModel? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint id = default(uint); QuantizedVector3 position; if (b == 2) { if (value != null) { id = value.Id; position = value.Position; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); goto IL_009b; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); position = ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(BossOrbModel), (byte)2, b); return; } if (value == null) { id = 0u; position = null; } else { id = value.Id; position = value.Position; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); _ = 2; } } if (value != null) { goto IL_009b; } } value = new BossOrbModel { Id = id, Position = position }; return; IL_009b: value.Id = id; value.Position = position; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class EnemyModel : IMemoryPackable<EnemyModel>, IMemoryPackFormatterRegister { [Preserve] private sealed class EnemyModelFormatter : MemoryPackFormatter<EnemyModel> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref EnemyModel value) { EnemyModel.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref EnemyModel value) { EnemyModel.Deserialize(ref reader, ref value); } } public uint Id { get; set; } public float Hp { get; set; } public QuantizedVector3 Position { get; set; } = new QuantizedVector3(); public QuantizedRotation Yaw { get; set; } = new QuantizedRotation(); static EnemyModel() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<EnemyModel>()) { MemoryPackFormatterProvider.Register<EnemyModel>((MemoryPackFormatter<EnemyModel>)(object)new EnemyModelFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<EnemyModel[]>()) { MemoryPackFormatterProvider.Register<EnemyModel[]>((MemoryPackFormatter<EnemyModel[]>)(object)new ArrayFormatter<EnemyModel>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref EnemyModel? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint id = value.Id; float hp = value.Hp; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, float>((byte)4, ref id, ref hp); QuantizedVector3 position = value.Position; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<QuantizedVector3>>(ref writer).WritePackable<QuantizedVector3>(ref position); QuantizedRotation yaw = value.Yaw; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<QuantizedRotation>>(ref writer).WritePackable<QuantizedRotation>(ref yaw); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref EnemyModel? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint id = default(uint); float hp = default(float); QuantizedVector3 position; QuantizedRotation yaw; if (b == 4) { if (value != null) { id = value.Id; hp = value.Hp; position = value.Position; yaw = value.Yaw; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); ((MemoryPackReader)(ref reader)).ReadUnmanaged<float>(ref hp); ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedRotation>(ref yaw); goto IL_00fb; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, float>(ref id, ref hp); position = ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(); yaw = ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedRotation>(); } else { if (b > 4) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(EnemyModel), (byte)4, b); return; } if (value == null) { id = 0u; hp = 0f; position = null; yaw = null; } else { id = value.Id; hp = value.Hp; position = value.Position; yaw = value.Yaw; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<float>(ref hp); if (b != 2) { ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); if (b != 3) { ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedRotation>(ref yaw); _ = 4; } } } } if (value != null) { goto IL_00fb; } } value = new EnemyModel { Id = id, Hp = hp, Position = position, Yaw = yaw }; return; IL_00fb: value.Id = id; value.Hp = hp; value.Position = position; value.Yaw = yaw; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class InventoryInfo : IMemoryPackable<InventoryInfo>, IMemoryPackFormatterRegister { [Preserve] private sealed class InventoryInfoFormatter : MemoryPackFormatter<InventoryInfo> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref InventoryInfo value) { InventoryInfo.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref InventoryInfo value) { InventoryInfo.Deserialize(ref reader, ref value); } } public ICollection<WeaponInfo> WeaponInfos { get; set; } = new List<WeaponInfo>(); public ICollection<TomeInfo> TomeInfos { get; set; } = new List<TomeInfo>(); static InventoryInfo() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<InventoryInfo>()) { MemoryPackFormatterProvider.Register<InventoryInfo>((MemoryPackFormatter<InventoryInfo>)(object)new InventoryInfoFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<InventoryInfo[]>()) { MemoryPackFormatterProvider.Register<InventoryInfo[]>((MemoryPackFormatter<InventoryInfo[]>)(object)new ArrayFormatter<InventoryInfo>()); } if (!MemoryPackFormatterProvider.IsRegistered<ICollection<WeaponInfo>>()) { MemoryPackFormatterProvider.Register<ICollection<WeaponInfo>>((MemoryPackFormatter<ICollection<WeaponInfo>>)(object)new InterfaceCollectionFormatter<WeaponInfo>()); } if (!MemoryPackFormatterProvider.IsRegistered<ICollection<TomeInfo>>()) { MemoryPackFormatterProvider.Register<ICollection<TomeInfo>>((MemoryPackFormatter<ICollection<TomeInfo>>)(object)new InterfaceCollectionFormatter<TomeInfo>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref InventoryInfo? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } writer.WriteObjectHeader((byte)2); ICollection<WeaponInfo> weaponInfos = value.WeaponInfos; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<ICollection<WeaponInfo>>>(ref writer).WriteValue<ICollection<WeaponInfo>>(ref weaponInfos); ICollection<TomeInfo> tomeInfos = value.TomeInfos; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<ICollection<TomeInfo>>>(ref writer).WriteValue<ICollection<TomeInfo>>(ref tomeInfos); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref InventoryInfo? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } ICollection<WeaponInfo> weaponInfos; ICollection<TomeInfo> tomeInfos; if (b == 2) { if (value != null) { weaponInfos = value.WeaponInfos; tomeInfos = value.TomeInfos; ((MemoryPackReader)(ref reader)).ReadValue<ICollection<WeaponInfo>>(ref weaponInfos); ((MemoryPackReader)(ref reader)).ReadValue<ICollection<TomeInfo>>(ref tomeInfos); goto IL_009a; } weaponInfos = ((MemoryPackReader)(ref reader)).ReadValue<ICollection<WeaponInfo>>(); tomeInfos = ((MemoryPackReader)(ref reader)).ReadValue<ICollection<TomeInfo>>(); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(InventoryInfo), (byte)2, b); return; } if (value == null) { weaponInfos = null; tomeInfos = null; } else { weaponInfos = value.WeaponInfos; tomeInfos = value.TomeInfos; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadValue<ICollection<WeaponInfo>>(ref weaponInfos); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadValue<ICollection<TomeInfo>>(ref tomeInfos); _ = 2; } } if (value != null) { goto IL_009a; } } value = new InventoryInfo { WeaponInfos = weaponInfos, TomeInfos = tomeInfos }; return; IL_009a: value.WeaponInfos = weaponInfos; value.TomeInfos = tomeInfos; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class WeaponInfo : IMemoryPackable<WeaponInfo>, IMemoryPackFormatterRegister { [Preserve] private sealed class WeaponInfoFormatter : MemoryPackFormatter<WeaponInfo> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref WeaponInfo value) { WeaponInfo.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref WeaponInfo value) { WeaponInfo.Deserialize(ref reader, ref value); } } public uint EWeapon; public uint Level; static WeaponInfo() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<WeaponInfo>()) { MemoryPackFormatterProvider.Register<WeaponInfo>((MemoryPackFormatter<WeaponInfo>)(object)new WeaponInfoFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<WeaponInfo[]>()) { MemoryPackFormatterProvider.Register<WeaponInfo[]>((MemoryPackFormatter<WeaponInfo[]>)(object)new ArrayFormatter<WeaponInfo>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref WeaponInfo? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); } else { Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, uint>((byte)2, ref value.EWeapon, ref value.Level); } } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref WeaponInfo? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint eWeapon = default(uint); uint level = default(uint); if (b == 2) { if (value != null) { eWeapon = value.EWeapon; level = value.Level; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref eWeapon); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref level); goto IL_0096; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, uint>(ref eWeapon, ref level); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(WeaponInfo), (byte)2, b); return; } if (value == null) { eWeapon = 0u; level = 0u; } else { eWeapon = value.EWeapon; level = value.Level; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref eWeapon); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref level); _ = 2; } } if (value != null) { goto IL_0096; } } value = new WeaponInfo { EWeapon = eWeapon, Level = level }; return; IL_0096: value.EWeapon = eWeapon; value.Level = level; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class TomeInfo : IMemoryPackable<TomeInfo>, IMemoryPackFormatterRegister { [Preserve] private sealed class TomeInfoFormatter : MemoryPackFormatter<TomeInfo> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref TomeInfo value) { TomeInfo.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref TomeInfo value) { TomeInfo.Deserialize(ref reader, ref value); } } public uint ETome; public uint Level; static TomeInfo() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<TomeInfo>()) { MemoryPackFormatterProvider.Register<TomeInfo>((MemoryPackFormatter<TomeInfo>)(object)new TomeInfoFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<TomeInfo[]>()) { MemoryPackFormatterProvider.Register<TomeInfo[]>((MemoryPackFormatter<TomeInfo[]>)(object)new ArrayFormatter<TomeInfo>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref TomeInfo? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); } else { Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, uint>((byte)2, ref value.ETome, ref value.Level); } } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref TomeInfo? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint eTome = default(uint); uint level = default(uint); if (b == 2) { if (value != null) { eTome = value.ETome; level = value.Level; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref eTome); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref level); goto IL_0096; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, uint>(ref eTome, ref level); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(TomeInfo), (byte)2, b); return; } if (value == null) { eTome = 0u; level = 0u; } else { eTome = value.ETome; level = value.Level; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref eTome); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref level); _ = 2; } } if (value != null) { goto IL_0096; } } value = new TomeInfo { ETome = eTome, Level = level }; return; IL_0096: value.ETome = eTome; value.Level = level; } } public enum NetworkModeType { Random, Friendlies } public enum Role { Host, Client } public class NetworkMode { public NetworkModeType Mode { get; set; } public Role Role { get; set; } public string RoomCode { get; set; } = ""; } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class PickupModel : IMemoryPackable<PickupModel>, IMemoryPackFormatterRegister { [Preserve] private sealed class PickupModelFormatter : MemoryPackFormatter<PickupModel> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref PickupModel value) { PickupModel.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref PickupModel value) { PickupModel.Deserialize(ref reader, ref value); } } public Vector3 Position = Vector3.Zero; public uint Id { get; set; } static PickupModel() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<PickupModel>()) { MemoryPackFormatterProvider.Register<PickupModel>((MemoryPackFormatter<PickupModel>)(object)new PickupModelFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<PickupModel[]>()) { MemoryPackFormatterProvider.Register<PickupModel[]>((MemoryPackFormatter<PickupModel[]>)(object)new ArrayFormatter<PickupModel>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref PickupModel? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint id = value.Id; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, Vector3>((byte)2, ref id, ref value.Position); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref PickupModel? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint id = default(uint); Vector3 position = default(Vector3); if (b == 2) { if (value != null) { id = value.Id; position = value.Position; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); ((MemoryPackReader)(ref reader)).ReadUnmanaged<Vector3>(ref position); goto IL_009c; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, Vector3>(ref id, ref position); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(PickupModel), (byte)2, b); return; } if (value == null) { id = 0u; position = default(Vector3); } else { id = value.Id; position = value.Position; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<Vector3>(ref position); _ = 2; } } if (value != null) { goto IL_009c; } } value = new PickupModel { Id = id, Position = position }; return; IL_009c: value.Id = id; value.Position = position; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class Player : IMemoryPackable<Player>, IMemoryPackFormatterRegister { [Preserve] private sealed class PlayerFormatter : MemoryPackFormatter<Player> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref Player value) { Player.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref Player value) { Player.Deserialize(ref reader, ref value); } } public uint ConnectionId; public bool IsHost; public uint Character; public string Skin = ""; public bool IsReady; public string Name = "Player"; public QuantizedVector3 Position = new QuantizedVector3(); public uint Hp = 100u; public uint MaxHp = 100u; public uint Shield; public uint MaxShield; public AnimatorState AnimatorState { get; set; } = new AnimatorState(); public MovementState MovementState { get; set; } = new MovementState(); public InventoryInfo Inventory { get; set; } = new InventoryInfo(); static Player() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<Player>()) { MemoryPackFormatterProvider.Register<Player>((MemoryPackFormatter<Player>)(object)new PlayerFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<Player[]>()) { MemoryPackFormatterProvider.Register<Player[]>((MemoryPackFormatter<Player[]>)(object)new ArrayFormatter<Player>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref Player? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, bool, uint>((byte)14, ref value.ConnectionId, ref value.IsHost, ref value.Character); writer.WriteString(value.Skin); Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<bool>>(ref writer).WriteUnmanaged<bool>(ref value.IsReady); writer.WriteString(value.Name); Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<QuantizedVector3>>(ref writer).WritePackable<QuantizedVector3>(ref value.Position); AnimatorState animatorState = value.AnimatorState; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<AnimatorState>>(ref writer).WritePackable<AnimatorState>(ref animatorState); MovementState movementState = value.MovementState; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<MovementState>>(ref writer).WritePackable<MovementState>(ref movementState); InventoryInfo inventory = value.Inventory; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<InventoryInfo>>(ref writer).WritePackable<InventoryInfo>(ref inventory); Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanaged<uint, uint, uint, uint>(ref value.Hp, ref value.MaxHp, ref value.Shield, ref value.MaxShield); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref Player? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint connectionId = default(uint); bool isHost = default(bool); uint character = default(uint); bool isReady = default(bool); QuantizedVector3 position; AnimatorState animatorState; MovementState movementState; InventoryInfo inventory; uint hp = default(uint); uint maxHp = default(uint); uint shield = default(uint); uint maxShield = default(uint); string skin; string name; if (b == 14) { if (value != null) { connectionId = value.ConnectionId; isHost = value.IsHost; character = value.Character; skin = value.Skin; isReady = value.IsReady; name = value.Name; position = value.Position; animatorState = value.AnimatorState; movementState = value.MovementState; inventory = value.Inventory; hp = value.Hp; maxHp = value.MaxHp; shield = value.Shield; maxShield = value.MaxShield; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref connectionId); ((MemoryPackReader)(ref reader)).ReadUnmanaged<bool>(ref isHost); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref character); skin = ((MemoryPackReader)(ref reader)).ReadString(); ((MemoryPackReader)(ref reader)).ReadUnmanaged<bool>(ref isReady); name = ((MemoryPackReader)(ref reader)).ReadString(); ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); ((MemoryPackReader)(ref reader)).ReadPackable<AnimatorState>(ref animatorState); ((MemoryPackReader)(ref reader)).ReadPackable<MovementState>(ref movementState); ((MemoryPackReader)(ref reader)).ReadPackable<InventoryInfo>(ref inventory); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref hp); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref maxHp); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref shield); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref maxShield); goto IL_02e2; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, bool, uint>(ref connectionId, ref isHost, ref character); skin = ((MemoryPackReader)(ref reader)).ReadString(); ((MemoryPackReader)(ref reader)).ReadUnmanaged<bool>(ref isReady); name = ((MemoryPackReader)(ref reader)).ReadString(); position = ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(); animatorState = ((MemoryPackReader)(ref reader)).ReadPackable<AnimatorState>(); movementState = ((MemoryPackReader)(ref reader)).ReadPackable<MovementState>(); inventory = ((MemoryPackReader)(ref reader)).ReadPackable<InventoryInfo>(); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, uint, uint, uint>(ref hp, ref maxHp, ref shield, ref maxShield); } else { if (b > 14) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(Player), (byte)14, b); return; } if (value == null) { connectionId = 0u; isHost = false; character = 0u; skin = null; isReady = false; name = null; position = null; animatorState = null; movementState = null; inventory = null; hp = 0u; maxHp = 0u; shield = 0u; maxShield = 0u; } else { connectionId = value.ConnectionId; isHost = value.IsHost; character = value.Character; skin = value.Skin; isReady = value.IsReady; name = value.Name; position = value.Position; animatorState = value.AnimatorState; movementState = value.MovementState; inventory = value.Inventory; hp = value.Hp; maxHp = value.MaxHp; shield = value.Shield; maxShield = value.MaxShield; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref connectionId); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<bool>(ref isHost); if (b != 2) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref character); if (b != 3) { skin = ((MemoryPackReader)(ref reader)).ReadString(); if (b != 4) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<bool>(ref isReady); if (b != 5) { name = ((MemoryPackReader)(ref reader)).ReadString(); if (b != 6) { ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); if (b != 7) { ((MemoryPackReader)(ref reader)).ReadPackable<AnimatorState>(ref animatorState); if (b != 8) { ((MemoryPackReader)(ref reader)).ReadPackable<MovementState>(ref movementState); if (b != 9) { ((MemoryPackReader)(ref reader)).ReadPackable<InventoryInfo>(ref inventory); if (b != 10) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref hp); if (b != 11) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref maxHp); if (b != 12) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref shield); if (b != 13) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref maxShield); _ = 14; } } } } } } } } } } } } } } if (value != null) { goto IL_02e2; } } value = new Player { ConnectionId = connectionId, IsHost = isHost, Character = character, Skin = skin, IsReady = isReady, Name = name, Position = position, AnimatorState = animatorState, MovementState = movementState, Inventory = inventory, Hp = hp, MaxHp = maxHp, Shield = shield, MaxShield = maxShield }; return; IL_02e2: value.ConnectionId = connectionId; value.IsHost = isHost; value.Character = character; value.Skin = skin; value.IsReady = isReady; value.Name = name; value.Position = position; value.AnimatorState = animatorState; value.MovementState = movementState; value.Inventory = inventory; value.Hp = hp; value.MaxHp = maxHp; value.Shield = shield; value.MaxShield = maxShield; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class Projectile : IMemoryPackable<Projectile>, IMemoryPackFormatterRegister { [Preserve] private sealed class ProjectileFormatter : MemoryPackFormatter<Projectile> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref Projectile value) { Projectile.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref Projectile value) { Projectile.Deserialize(ref reader, ref value); } } public QuantizedVector3 Position = new QuantizedVector3(); public QuantizedVector3 FordwardVector = new QuantizedVector3(); public uint Id { get; set; } static Projectile() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<Projectile>()) { MemoryPackFormatterProvider.Register<Projectile>((MemoryPackFormatter<Projectile>)(object)new ProjectileFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<Projectile[]>()) { MemoryPackFormatterProvider.Register<Projectile[]>((MemoryPackFormatter<Projectile[]>)(object)new ArrayFormatter<Projectile>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref Projectile? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint id = value.Id; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint>((byte)3, ref id); Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<QuantizedVector3>>(ref writer).WritePackable<QuantizedVector3>(ref value.Position); Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<QuantizedVector3>>(ref writer).WritePackable<QuantizedVector3>(ref value.FordwardVector); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref Projectile? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint id = default(uint); QuantizedVector3 position; QuantizedVector3 fordwardVector; if (b == 3) { if (value != null) { id = value.Id; position = value.Position; fordwardVector = value.FordwardVector; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref fordwardVector); goto IL_00c8; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); position = ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(); fordwardVector = ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(); } else { if (b > 3) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(Projectile), (byte)3, b); return; } if (value == null) { id = 0u; position = null; fordwardVector = null; } else { id = value.Id; position = value.Position; fordwardVector = value.FordwardVector; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref id); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); if (b != 2) { ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref fordwardVector); _ = 3; } } } if (value != null) { goto IL_00c8; } } value = new Projectile { Id = id, Position = position, FordwardVector = fordwardVector }; return; IL_00c8: value.Id = id; value.Position = position; value.FordwardVector = fordwardVector; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class QuantizedRotation : IMemoryPackable<QuantizedRotation>, IMemoryPackFormatterRegister { [Preserve] private sealed class QuantizedRotationFormatter : MemoryPackFormatter<QuantizedRotation> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref QuantizedRotation value) { QuantizedRotation.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref QuantizedRotation value) { QuantizedRotation.Deserialize(ref reader, ref value); } } public ushort QuantizedYaw { get; set; } static QuantizedRotation() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<QuantizedRotation>()) { MemoryPackFormatterProvider.Register<QuantizedRotation>((MemoryPackFormatter<QuantizedRotation>)(object)new QuantizedRotationFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<QuantizedRotation[]>()) { MemoryPackFormatterProvider.Register<QuantizedRotation[]>((MemoryPackFormatter<QuantizedRotation[]>)(object)new ArrayFormatter<QuantizedRotation>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref QuantizedRotation? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } ushort quantizedYaw = value.QuantizedYaw; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<ushort>>(ref writer).WriteUnmanagedWithObjectHeader<ushort>((byte)1, ref quantizedYaw); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref QuantizedRotation? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } ushort quantizedYaw = default(ushort); if (b == 1) { if (value != null) { quantizedYaw = value.QuantizedYaw; ((MemoryPackReader)(ref reader)).ReadUnmanaged<ushort>(ref quantizedYaw); goto IL_006b; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<ushort>(ref quantizedYaw); } else { if (b > 1) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(QuantizedRotation), (byte)1, b); return; } quantizedYaw = (ushort)((value != null) ? value.QuantizedYaw : 0); if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<ushort>(ref quantizedYaw); _ = 1; } if (value != null) { goto IL_006b; } } value = new QuantizedRotation { QuantizedYaw = quantizedYaw }; return; IL_006b: value.QuantizedYaw = quantizedYaw; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class QuantizedVector2 : IMemoryPackable<QuantizedVector2>, IMemoryPackFormatterRegister { [Preserve] private sealed class QuantizedVector2Formatter : MemoryPackFormatter<QuantizedVector2> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref QuantizedVector2 value) { QuantizedVector2.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref QuantizedVector2 value) { QuantizedVector2.Deserialize(ref reader, ref value); } } public short QuantizedX { get; set; } public short QuantizedY { get; set; } static QuantizedVector2() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<QuantizedVector2>()) { MemoryPackFormatterProvider.Register<QuantizedVector2>((MemoryPackFormatter<QuantizedVector2>)(object)new QuantizedVector2Formatter()); } if (!MemoryPackFormatterProvider.IsRegistered<QuantizedVector2[]>()) { MemoryPackFormatterProvider.Register<QuantizedVector2[]>((MemoryPackFormatter<QuantizedVector2[]>)(object)new ArrayFormatter<QuantizedVector2>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref QuantizedVector2? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } short quantizedX = value.QuantizedX; short quantizedY = value.QuantizedY; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<short>>(ref writer).WriteUnmanagedWithObjectHeader<short, short>((byte)2, ref quantizedX, ref quantizedY); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref QuantizedVector2? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } short quantizedX = default(short); short quantizedY = default(short); if (b == 2) { if (value != null) { quantizedX = value.QuantizedX; quantizedY = value.QuantizedY; ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedX); ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedY); goto IL_0096; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<short, short>(ref quantizedX, ref quantizedY); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(QuantizedVector2), (byte)2, b); return; } if (value == null) { quantizedX = 0; quantizedY = 0; } else { quantizedX = value.QuantizedX; quantizedY = value.QuantizedY; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedX); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedY); _ = 2; } } if (value != null) { goto IL_0096; } } value = new QuantizedVector2 { QuantizedX = quantizedX, QuantizedY = quantizedY }; return; IL_0096: value.QuantizedX = quantizedX; value.QuantizedY = quantizedY; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class QuantizedVector3 : IMemoryPackable<QuantizedVector3>, IMemoryPackFormatterRegister { [Preserve] private sealed class QuantizedVector3Formatter : MemoryPackFormatter<QuantizedVector3> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref QuantizedVector3 value) { QuantizedVector3.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref QuantizedVector3 value) { QuantizedVector3.Deserialize(ref reader, ref value); } } public short QuantizedX { get; set; } public short QuantizedY { get; set; } public short QuantizedZ { get; set; } static QuantizedVector3() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<QuantizedVector3>()) { MemoryPackFormatterProvider.Register<QuantizedVector3>((MemoryPackFormatter<QuantizedVector3>)(object)new QuantizedVector3Formatter()); } if (!MemoryPackFormatterProvider.IsRegistered<QuantizedVector3[]>()) { MemoryPackFormatterProvider.Register<QuantizedVector3[]>((MemoryPackFormatter<QuantizedVector3[]>)(object)new ArrayFormatter<QuantizedVector3>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref QuantizedVector3? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } short quantizedX = value.QuantizedX; short quantizedY = value.QuantizedY; short quantizedZ = value.QuantizedZ; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<short>>(ref writer).WriteUnmanagedWithObjectHeader<short, short, short>((byte)3, ref quantizedX, ref quantizedY, ref quantizedZ); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref QuantizedVector3? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } short quantizedX = default(short); short quantizedY = default(short); short quantizedZ = default(short); if (b == 3) { if (value != null) { quantizedX = value.QuantizedX; quantizedY = value.QuantizedY; quantizedZ = value.QuantizedZ; ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedX); ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedY); ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedZ); goto IL_00be; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<short, short, short>(ref quantizedX, ref quantizedY, ref quantizedZ); } else { if (b > 3) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(QuantizedVector3), (byte)3, b); return; } if (value == null) { quantizedX = 0; quantizedY = 0; quantizedZ = 0; } else { quantizedX = value.QuantizedX; quantizedY = value.QuantizedY; quantizedZ = value.QuantizedZ; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedX); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedY); if (b != 2) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedZ); _ = 3; } } } if (value != null) { goto IL_00be; } } value = new QuantizedVector3 { QuantizedX = quantizedX, QuantizedY = quantizedY, QuantizedZ = quantizedZ }; return; IL_00be: value.QuantizedX = quantizedX; value.QuantizedY = quantizedY; value.QuantizedZ = quantizedZ; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class QuantizedVector4 : IMemoryPackable<QuantizedVector4>, IMemoryPackFormatterRegister { [Preserve] private sealed class QuantizedVector4Formatter : MemoryPackFormatter<QuantizedVector4> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref QuantizedVector4 value) { QuantizedVector4.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref QuantizedVector4 value) { QuantizedVector4.Deserialize(ref reader, ref value); } } public short QuantizedX { get; set; } public short QuantizedY { get; set; } public short QuantizedZ { get; set; } public short QuantizedW { get; set; } static QuantizedVector4() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<QuantizedVector4>()) { MemoryPackFormatterProvider.Register<QuantizedVector4>((MemoryPackFormatter<QuantizedVector4>)(object)new QuantizedVector4Formatter()); } if (!MemoryPackFormatterProvider.IsRegistered<QuantizedVector4[]>()) { MemoryPackFormatterProvider.Register<QuantizedVector4[]>((MemoryPackFormatter<QuantizedVector4[]>)(object)new ArrayFormatter<QuantizedVector4>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref QuantizedVector4? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } short quantizedX = value.QuantizedX; short quantizedY = value.QuantizedY; short quantizedZ = value.QuantizedZ; short quantizedW = value.QuantizedW; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<short>>(ref writer).WriteUnmanagedWithObjectHeader<short, short, short, short>((byte)4, ref quantizedX, ref quantizedY, ref quantizedZ, ref quantizedW); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref QuantizedVector4? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } short quantizedX = default(short); short quantizedY = default(short); short quantizedZ = default(short); short quantizedW = default(short); if (b == 4) { if (value != null) { quantizedX = value.QuantizedX; quantizedY = value.QuantizedY; quantizedZ = value.QuantizedZ; quantizedW = value.QuantizedW; ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedX); ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedY); ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedZ); ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedW); goto IL_00e9; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<short, short, short, short>(ref quantizedX, ref quantizedY, ref quantizedZ, ref quantizedW); } else { if (b > 4) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(QuantizedVector4), (byte)4, b); return; } if (value == null) { quantizedX = 0; quantizedY = 0; quantizedZ = 0; quantizedW = 0; } else { quantizedX = value.QuantizedX; quantizedY = value.QuantizedY; quantizedZ = value.QuantizedZ; quantizedW = value.QuantizedW; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedX); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedY); if (b != 2) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedZ); if (b != 3) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<short>(ref quantizedW); _ = 4; } } } } if (value != null) { goto IL_00e9; } } value = new QuantizedVector4 { QuantizedX = quantizedX, QuantizedY = quantizedY, QuantizedZ = quantizedZ, QuantizedW = quantizedW }; return; IL_00e9: value.QuantizedX = quantizedX; value.QuantizedY = quantizedY; value.QuantizedZ = quantizedZ; value.QuantizedW = quantizedW; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class TumbleWeedModel : IMemoryPackable<TumbleWeedModel>, IMemoryPackFormatterRegister { [Preserve] private sealed class TumbleWeedModelFormatter : MemoryPackFormatter<TumbleWeedModel> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref TumbleWeedModel value) { TumbleWeedModel.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref TumbleWeedModel value) { TumbleWeedModel.Deserialize(ref reader, ref value); } } public uint NetplayId { get; set; } public QuantizedVector3 Position { get; set; } static TumbleWeedModel() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<TumbleWeedModel>()) { MemoryPackFormatterProvider.Register<TumbleWeedModel>((MemoryPackFormatter<TumbleWeedModel>)(object)new TumbleWeedModelFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<TumbleWeedModel[]>()) { MemoryPackFormatterProvider.Register<TumbleWeedModel[]>((MemoryPackFormatter<TumbleWeedModel[]>)(object)new ArrayFormatter<TumbleWeedModel>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref TumbleWeedModel? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint netplayId = value.NetplayId; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint>((byte)2, ref netplayId); QuantizedVector3 position = value.Position; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<QuantizedVector3>>(ref writer).WritePackable<QuantizedVector3>(ref position); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref TumbleWeedModel? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint netplayId = default(uint); QuantizedVector3 position; if (b == 2) { if (value != null) { netplayId = value.NetplayId; position = value.Position; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref netplayId); ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); goto IL_009b; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref netplayId); position = ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(TumbleWeedModel), (byte)2, b); return; } if (value == null) { netplayId = 0u; position = null; } else { netplayId = value.NetplayId; position = value.Position; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref netplayId); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadPackable<QuantizedVector3>(ref position); _ = 2; } } if (value != null) { goto IL_009b; } } value = new TumbleWeedModel { NetplayId = netplayId, Position = position }; return; IL_009b: value.NetplayId = netplayId; value.Position = position; } } } namespace MegabonkTogether.Common.Messages { [MemoryPackable(/*Could not decode attribute arguments.*/)] public class ChestOpened : IGameNetworkMessage, IMemoryPackFormatterRegister, IMemoryPackable<ChestOpened> { [Preserve] private sealed class ChestOpenedFormatter : MemoryPackFormatter<ChestOpened> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref ChestOpened value) { ChestOpened.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref ChestOpened value) { ChestOpened.Deserialize(ref reader, ref value); } } public uint ChestId { get; set; } public uint OwnerId { get; set; } static ChestOpened() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<ChestOpened>()) { MemoryPackFormatterProvider.Register<ChestOpened>((MemoryPackFormatter<ChestOpened>)(object)new ChestOpenedFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<ChestOpened[]>()) { MemoryPackFormatterProvider.Register<ChestOpened[]>((MemoryPackFormatter<ChestOpened[]>)(object)new ArrayFormatter<ChestOpened>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref ChestOpened? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint chestId = value.ChestId; uint ownerId = value.OwnerId; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, uint>((byte)2, ref chestId, ref ownerId); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref ChestOpened? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint chestId = default(uint); uint ownerId = default(uint); if (b == 2) { if (value != null) { chestId = value.ChestId; ownerId = value.OwnerId; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref chestId); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref ownerId); goto IL_0096; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, uint>(ref chestId, ref ownerId); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(ChestOpened), (byte)2, b); return; } if (value == null) { chestId = 0u; ownerId = 0u; } else { chestId = value.ChestId; ownerId = value.OwnerId; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref chestId); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref ownerId); _ = 2; } } if (value != null) { goto IL_0096; } } value = new ChestOpened { ChestId = chestId, OwnerId = ownerId }; return; IL_0096: value.ChestId = chestId; value.OwnerId = ownerId; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class ClientInGameReady : IGameNetworkMessage, IMemoryPackFormatterRegister, IMemoryPackable<ClientInGameReady> { [Preserve] private sealed class ClientInGameReadyFormatter : MemoryPackFormatter<ClientInGameReady> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref ClientInGameReady value) { ClientInGameReady.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref ClientInGameReady value) { ClientInGameReady.Deserialize(ref reader, ref value); } } public uint ConnectionId { get; set; } static ClientInGameReady() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<ClientInGameReady>()) { MemoryPackFormatterProvider.Register<ClientInGameReady>((MemoryPackFormatter<ClientInGameReady>)(object)new ClientInGameReadyFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<ClientInGameReady[]>()) { MemoryPackFormatterProvider.Register<ClientInGameReady[]>((MemoryPackFormatter<ClientInGameReady[]>)(object)new ArrayFormatter<ClientInGameReady>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref ClientInGameReady? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint connectionId = value.ConnectionId; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint>((byte)1, ref connectionId); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref ClientInGameReady? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint connectionId = default(uint); if (b == 1) { if (value != null) { connectionId = value.ConnectionId; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref connectionId); goto IL_006b; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref connectionId); } else { if (b > 1) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(ClientInGameReady), (byte)1, b); return; } connectionId = ((value != null) ? value.ConnectionId : 0u); if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref connectionId); _ = 1; } if (value != null) { goto IL_006b; } } value = new ClientInGameReady { ConnectionId = connectionId }; return; IL_006b: value.ConnectionId = connectionId; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class ClientReadyMessage : IWsMessage, IMemoryPackFormatterRegister, IMemoryPackable<ClientReadyMessage> { [Preserve] private sealed class ClientReadyMessageFormatter : MemoryPackFormatter<ClientReadyMessage> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref ClientReadyMessage value) { ClientReadyMessage.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref ClientReadyMessage value) { ClientReadyMessage.Deserialize(ref reader, ref value); } } static ClientReadyMessage() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<ClientReadyMessage>()) { MemoryPackFormatterProvider.Register<ClientReadyMessage>((MemoryPackFormatter<ClientReadyMessage>)(object)new ClientReadyMessageFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<ClientReadyMessage[]>()) { MemoryPackFormatterProvider.Register<ClientReadyMessage[]>((MemoryPackFormatter<ClientReadyMessage[]>)(object)new ArrayFormatter<ClientReadyMessage>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref ClientReadyMessage? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); } else { writer.WriteObjectHeader((byte)0); } } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref ClientReadyMessage? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } if (b == 0) { if (value != null) { return; } } else { if (b > 0) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(ClientReadyMessage), (byte)0, b); return; } _ = value; if (value != null) { return; } } value = new ClientReadyMessage(); } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class EnemyDamaged : IGameNetworkMessage, IMemoryPackFormatterRegister, IMemoryPackable<EnemyDamaged> { [Preserve] private sealed class EnemyDamagedFormatter : MemoryPackFormatter<EnemyDamaged> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref EnemyDamaged value) { EnemyDamaged.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref EnemyDamaged value) { EnemyDamaged.Deserialize(ref reader, ref value); } } public uint EnemyId { get; set; } public float Damage { get; set; } public int DamageEffect { get; set; } public int DamageBlockedByArmor { get; set; } public string DamageSource { get; set; } public float DamageProcCoefficient { get; set; } public int DamageElement { get; set; } public int DamageFlags { get; set; } public float DamageKnockback { get; set; } public bool DamageIsCrit { get; set; } public uint AttackerId { get; set; } static EnemyDamaged() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<EnemyDamaged>()) { MemoryPackFormatterProvider.Register<EnemyDamaged>((MemoryPackFormatter<EnemyDamaged>)(object)new EnemyDamagedFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<EnemyDamaged[]>()) { MemoryPackFormatterProvider.Register<EnemyDamaged[]>((MemoryPackFormatter<EnemyDamaged[]>)(object)new ArrayFormatter<EnemyDamaged>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref EnemyDamaged? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint enemyId = value.EnemyId; float damage = value.Damage; int damageEffect = value.DamageEffect; int damageBlockedByArmor = value.DamageBlockedByArmor; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, float, int, int>((byte)11, ref enemyId, ref damage, ref damageEffect, ref damageBlockedByArmor); writer.WriteString(value.DamageSource); float damageProcCoefficient = value.DamageProcCoefficient; int damageElement = value.DamageElement; int damageFlags = value.DamageFlags; float damageKnockback = value.DamageKnockback; bool damageIsCrit = value.DamageIsCrit; uint attackerId = value.AttackerId; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<float>>(ref writer).WriteUnmanaged<float, int, int, float, bool, uint>(ref damageProcCoefficient, ref damageElement, ref damageFlags, ref damageKnockback, ref damageIsCrit, ref attackerId); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref EnemyDamaged? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint enemyId = default(uint); float damage = default(float); int damageEffect = default(int); int damageBlockedByArmor = default(int); float damageProcCoefficient = default(float); int damageElement = default(int); int damageFlags = default(int); float damageKnockback = default(float); bool damageIsCrit = default(bool); uint attackerId = default(uint); string damageSource; if (b == 11) { if (value != null) { enemyId = value.EnemyId; damage = value.Damage; damageEffect = value.DamageEffect; damageBlockedByArmor = value.DamageBlockedByArmor; damageSource = value.DamageSource; damageProcCoefficient = value.DamageProcCoefficient; damageElement = value.DamageElement; damageFlags = value.DamageFlags; damageKnockback = value.DamageKnockback; damageIsCrit = value.DamageIsCrit; attackerId = value.AttackerId; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref enemyId); ((MemoryPackReader)(ref reader)).ReadUnmanaged<float>(ref damage); ((MemoryPackReader)(ref reader)).ReadUnmanaged<int>(ref damageEffect); ((MemoryPackReader)(ref reader)).ReadUnmanaged<int>(ref damageBlockedByArmor); damageSource = ((MemoryPackReader)(ref reader)).ReadString(); ((MemoryPackReader)(ref reader)).ReadUnmanaged<float>(ref damageProcCoefficient); ((MemoryPackReader)(ref reader)).ReadUnmanaged<int>(ref damageElement); ((MemoryPackReader)(ref reader)).ReadUnmanaged<int>(ref damageFlags); ((MemoryPackReader)(ref reader)).ReadUnmanaged<float>(ref damageKnockback); ((MemoryPackReader)(ref reader)).ReadUnmanaged<bool>(ref damageIsCrit); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref attackerId); goto IL_023d; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, float, int, int>(ref enemyId, ref damage, ref damageEffect, ref damageBlockedByArmor); damageSource = ((MemoryPackReader)(ref reader)).ReadString(); ((MemoryPackReader)(ref reader)).ReadUnmanaged<float, int, int, float, bool, uint>(ref damageProcCoefficient, ref damageElement, ref damageFlags, ref damageKnockback, ref damageIsCrit, ref attackerId); } else { if (b > 11) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(EnemyDamaged), (byte)11, b); return; } if (value == null) { enemyId = 0u; damage = 0f; damageEffect = 0; damageBlockedByArmor = 0; damageSource = null; damageProcCoefficient = 0f; damageElement = 0; damageFlags = 0; damageKnockback = 0f; damageIsCrit = false; attackerId = 0u; } else { enemyId = value.EnemyId; damage = value.Damage; damageEffect = value.DamageEffect; damageBlockedByArmor = value.DamageBlockedByArmor; damageSource = value.DamageSource; damageProcCoefficient = value.DamageProcCoefficient; damageElement = value.DamageElement; damageFlags = value.DamageFlags; damageKnockback = value.DamageKnockback; damageIsCrit = value.DamageIsCrit; attackerId = value.AttackerId; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref enemyId); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<float>(ref damage); if (b != 2) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<int>(ref damageEffect); if (b != 3) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<int>(ref damageBlockedByArmor); if (b != 4) { damageSource = ((MemoryPackReader)(ref reader)).ReadString(); if (b != 5) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<float>(ref damageProcCoefficient); if (b != 6) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<int>(ref damageElement); if (b != 7) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<int>(ref damageFlags); if (b != 8) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<float>(ref damageKnockback); if (b != 9) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<bool>(ref damageIsCrit); if (b != 10) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref attackerId); _ = 11; } } } } } } } } } } } if (value != null) { goto IL_023d; } } value = new EnemyDamaged { EnemyId = enemyId, Damage = damage, DamageEffect = damageEffect, DamageBlockedByArmor = damageBlockedByArmor, DamageSource = damageSource, DamageProcCoefficient = damageProcCoefficient, DamageElement = damageElement, DamageFlags = damageFlags, DamageKnockback = damageKnockback, DamageIsCrit = damageIsCrit, AttackerId = attackerId }; return; IL_023d: value.EnemyId = enemyId; value.Damage = damage; value.DamageEffect = damageEffect; value.DamageBlockedByArmor = damageBlockedByArmor; value.DamageSource = damageSource; value.DamageProcCoefficient = damageProcCoefficient; value.DamageElement = damageElement; value.DamageFlags = damageFlags; value.DamageKnockback = damageKnockback; value.DamageIsCrit = damageIsCrit; value.AttackerId = attackerId; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class EnemyDied : IGameNetworkMessage, IMemoryPackFormatterRegister, IMemoryPackable<EnemyDied> { [Preserve] private sealed class EnemyDiedFormatter : MemoryPackFormatter<EnemyDied> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref EnemyDied value) { EnemyDied.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref EnemyDied value) { EnemyDied.Deserialize(ref reader, ref value); } } public uint EnemyId { get; set; } public uint DiedByOwnerId { get; set; } static EnemyDied() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<EnemyDied>()) { MemoryPackFormatterProvider.Register<EnemyDied>((MemoryPackFormatter<EnemyDied>)(object)new EnemyDiedFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<EnemyDied[]>()) { MemoryPackFormatterProvider.Register<EnemyDied[]>((MemoryPackFormatter<EnemyDied[]>)(object)new ArrayFormatter<EnemyDied>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref EnemyDied? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint enemyId = value.EnemyId; uint diedByOwnerId = value.DiedByOwnerId; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, uint>((byte)2, ref enemyId, ref diedByOwnerId); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref EnemyDied? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint enemyId = default(uint); uint diedByOwnerId = default(uint); if (b == 2) { if (value != null) { enemyId = value.EnemyId; diedByOwnerId = value.DiedByOwnerId; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref enemyId); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref diedByOwnerId); goto IL_0096; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, uint>(ref enemyId, ref diedByOwnerId); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(EnemyDied), (byte)2, b); return; } if (value == null) { enemyId = 0u; diedByOwnerId = 0u; } else { enemyId = value.EnemyId; diedByOwnerId = value.DiedByOwnerId; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref enemyId); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref diedByOwnerId); _ = 2; } } if (value != null) { goto IL_0096; } } value = new EnemyDied { EnemyId = enemyId, DiedByOwnerId = diedByOwnerId }; return; IL_0096: value.EnemyId = enemyId; value.DiedByOwnerId = diedByOwnerId; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class EnemyExploder : IGameNetworkMessage, IMemoryPackFormatterRegister, IMemoryPackable<EnemyExploder> { [Preserve] private sealed class EnemyExploderFormatter : MemoryPackFormatter<EnemyExploder> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref EnemyExploder value) { EnemyExploder.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref EnemyExploder value) { EnemyExploder.Deserialize(ref reader, ref value); } } public uint EnemyId { get; set; } public uint SenderId { get; set; } static EnemyExploder() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<EnemyExploder>()) { MemoryPackFormatterProvider.Register<EnemyExploder>((MemoryPackFormatter<EnemyExploder>)(object)new EnemyExploderFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<EnemyExploder[]>()) { MemoryPackFormatterProvider.Register<EnemyExploder[]>((MemoryPackFormatter<EnemyExploder[]>)(object)new ArrayFormatter<EnemyExploder>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref EnemyExploder? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint enemyId = value.EnemyId; uint senderId = value.SenderId; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, uint>((byte)2, ref enemyId, ref senderId); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref EnemyExploder? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint enemyId = default(uint); uint senderId = default(uint); if (b == 2) { if (value != null) { enemyId = value.EnemyId; senderId = value.SenderId; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref enemyId); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref senderId); goto IL_0096; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, uint>(ref enemyId, ref senderId); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(EnemyExploder), (byte)2, b); return; } if (value == null) { enemyId = 0u; senderId = 0u; } else { enemyId = value.EnemyId; senderId = value.SenderId; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref enemyId); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref senderId); _ = 2; } } if (value != null) { goto IL_0096; } } value = new EnemyExploder { EnemyId = enemyId, SenderId = senderId }; return; IL_0096: value.EnemyId = enemyId; value.SenderId = senderId; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class FinalBossOrbDestroyed : IGameNetworkMessage, IMemoryPackFormatterRegister, IMemoryPackable<FinalBossOrbDestroyed> { [Preserve] private sealed class FinalBossOrbDestroyedFormatter : MemoryPackFormatter<FinalBossOrbDestroyed> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref FinalBossOrbDestroyed value) { FinalBossOrbDestroyed.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref FinalBossOrbDestroyed value) { FinalBossOrbDestroyed.Deserialize(ref reader, ref value); } } public uint OrbId { get; set; } public uint SenderId { get; set; } static FinalBossOrbDestroyed() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<FinalBossOrbDestroyed>()) { MemoryPackFormatterProvider.Register<FinalBossOrbDestroyed>((MemoryPackFormatter<FinalBossOrbDestroyed>)(object)new FinalBossOrbDestroyedFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<FinalBossOrbDestroyed[]>()) { MemoryPackFormatterProvider.Register<FinalBossOrbDestroyed[]>((MemoryPackFormatter<FinalBossOrbDestroyed[]>)(object)new ArrayFormatter<FinalBossOrbDestroyed>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref FinalBossOrbDestroyed? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } uint orbId = value.OrbId; uint senderId = value.SenderId; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<uint>>(ref writer).WriteUnmanagedWithObjectHeader<uint, uint>((byte)2, ref orbId, ref senderId); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref FinalBossOrbDestroyed? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } uint orbId = default(uint); uint senderId = default(uint); if (b == 2) { if (value != null) { orbId = value.OrbId; senderId = value.SenderId; ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref orbId); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref senderId); goto IL_0096; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint, uint>(ref orbId, ref senderId); } else { if (b > 2) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(FinalBossOrbDestroyed), (byte)2, b); return; } if (value == null) { orbId = 0u; senderId = 0u; } else { orbId = value.OrbId; senderId = value.SenderId; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref orbId); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref senderId); _ = 2; } } if (value != null) { goto IL_0096; } } value = new FinalBossOrbDestroyed { OrbId = orbId, SenderId = senderId }; return; IL_0096: value.OrbId = orbId; value.SenderId = senderId; } } [MemoryPackable(/*Could not decode attribute arguments.*/)] public class FinalBossOrbSpawned : IGameNetworkMessage, IMemoryPackFormatterRegister, IMemoryPackable<FinalBossOrbSpawned> { [Preserve] private sealed class FinalBossOrbSpawnedFormatter : MemoryPackFormatter<FinalBossOrbSpawned> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref FinalBossOrbSpawned value) { FinalBossOrbSpawned.Serialize(ref writer, ref value); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, ref FinalBossOrbSpawned value) { FinalBossOrbSpawned.Deserialize(ref reader, ref value); } } public Orb OrbType { get; set; } public uint Target { get; set; } public uint OrbId { get; set; } static FinalBossOrbSpawned() { RegisterFormatter(); } [Preserve] public static void RegisterFormatter() { if (!MemoryPackFormatterProvider.IsRegistered<FinalBossOrbSpawned>()) { MemoryPackFormatterProvider.Register<FinalBossOrbSpawned>((MemoryPackFormatter<FinalBossOrbSpawned>)(object)new FinalBossOrbSpawnedFormatter()); } if (!MemoryPackFormatterProvider.IsRegistered<FinalBossOrbSpawned[]>()) { MemoryPackFormatterProvider.Register<FinalBossOrbSpawned[]>((MemoryPackFormatter<FinalBossOrbSpawned[]>)(object)new ArrayFormatter<FinalBossOrbSpawned>()); } if (!MemoryPackFormatterProvider.IsRegistered<Orb>()) { MemoryPackFormatterProvider.Register<Orb>((MemoryPackFormatter<Orb>)(object)new UnmanagedFormatter<Orb>()); } } [Preserve] public static void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref FinalBossOrbSpawned? value) where TBufferWriter : class, IBufferWriter<byte> { if (value == null) { writer.WriteNullObjectHeader(); return; } Orb orbType = value.OrbType; uint target = value.Target; uint orbId = value.OrbId; Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<Orb>>(ref writer).WriteUnmanagedWithObjectHeader<Orb, uint, uint>((byte)3, ref orbType, ref target, ref orbId); } [Preserve] public static void Deserialize(ref MemoryPackReader reader, ref FinalBossOrbSpawned? value) { byte b = default(byte); if (!((MemoryPackReader)(ref reader)).TryReadObjectHeader(ref b)) { value = null; return; } Orb orbType = default(Orb); uint target = default(uint); uint orbId = default(uint); if (b == 3) { if (value != null) { orbType = value.OrbType; target = value.Target; orbId = value.OrbId; ((MemoryPackReader)(ref reader)).ReadUnmanaged<Orb>(ref orbType); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref target); ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref orbId); goto IL_00be; } ((MemoryPackReader)(ref reader)).ReadUnmanaged<Orb, uint, uint>(ref orbType, ref target, ref orbId); } else { if (b > 3) { MemoryPackSerializationException.ThrowInvalidPropertyCount(typeof(FinalBossOrbSpawned), (byte)3, b); return; } if (value == null) { orbType = Orb.Bleed; target = 0u; orbId = 0u; } else { orbType = value.OrbType; target = value.Target; orbId = value.OrbId; } if (b != 0) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<Orb>(ref orbType); if (b != 1) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref target); if (b != 2) { ((MemoryPackReader)(ref reader)).ReadUnmanaged<uint>(ref orbId); _ = 3; } } } if (value != null) { goto IL_00be; } } value = new FinalBossOrbSpawned { OrbType = orbType, Target = target, OrbId = orbId }; return; IL_00be: value.OrbType = orbType; value.Target = target; value.OrbId = orbId; } } public enum Orb { Bleed, Following, Shooty } [MemoryPackable(/*Could not decode attribute arguments.*/)] [MemoryPackUnion(0, typeof(LobbyUpdates))] [MemoryPackUnion(1, typeof(ClientInGameReady))] [MemoryPackUnion(2, typeof(SpawnedObject))] [MemoryPackUnion(3, typeof(PlayerUpdate))] [MemoryPackUnion(4, typeof(SpawnedEnemy))] [MemoryPackUnion(5, typeof(SelectedCharacter))] [MemoryPackUnion(6, typeof(EnemyDied))] [MemoryPackUnion(7, typeof(SpawnedProjectile))] [MemoryPackUnion(8, typeof(ProjectileDone))] [MemoryPackUnion(9, typeof(SpawnedPickupOrb))] [MemoryPackUnion(10, typeof(SpawnedPickup))] [MemoryPackUnion(11, typeof(PickupApplied))] [MemoryPackUnion(12, typeof(PickupFollowingPlayer))] [MemoryPackUnion(13, typeof(SpawnedChest))] [MemoryPackUnion(14, typeof(ChestOpened))] [MemoryPackUnion(15, typeof(WeaponAdded))] [MemoryPackUnion(16, typeof(InteractableUsed))] [MemoryPackUnion(17, typeof(StartingChargingShrine))] [MemoryPackUnion(18, typeof(StoppingChargingShrine))] [MemoryPackUnion(19, typeof(EnemyExploder))] [MemoryPackUnion(20, typeof(EnemyDamaged))] [MemoryPackUnion(21, typeof(SpawnedEnemySpecialAttack))] [MemoryPackUnion(22, typeof(StartingChargingPylon))] [MemoryPackUnion(23, typeof(StoppingChargingPylon))] [MemoryPackUnion(24, typeof(FinalBossOrbSpawned))] [MemoryPackUnion(25, typeof(FinalBossOrbDestroyed))] [MemoryPackUnion(26, typeof(StartedSwarmEvent))] [MemoryPackUnion(27, typeof(GameOver))] [MemoryPackUnion(28, typeof(PlayerDied))] [MemoryPackUnion(29, typeof(RetargetedEnemies))] [MemoryPackUnion(30, typeof(Introduced))] [MemoryPackUnion(31, typeof(PlayerDisconnected))] [MemoryPackUnion(32, typeof(RunStarted))] [MemoryPackUnion(33, typeof(SpawnedAxeProjectile))] [MemoryPackUnion(34, typeof(SpawnedBlackHoleProjectile))] [MemoryPackUnion(35, typeof(SpawnedCringeSwordProjectile))] [MemoryPackUnion(36, typeof(SpawnedFireFieldProjectile))] [MemoryPackUnion(37, typeof(SpawnedHeroSwordProjectile))] [MemoryPackUnion(38, typeof(SpawnedRocketProjectile))] [MemoryPackUnion(39, typeof(ProjectilesUpdate))] [MemoryPackUnion(40, typeof(TomeAdded))] [MemoryPackUnion(41, typeof(LightningStrike))] [MemoryPackUnion(42, typeof(TornadoesSpawned))] [MemoryPackUnion(43, typeof(StormStarted))] [MemoryPackUnion(44, typeof(StormStopped))] [MemoryPackUnion(45, typeof(TumbleWeedSpawned))] [MemoryPackUnion(46, typeof(TumbleWeedsUpdate))] [MemoryPackUnion(47, typeof(TumbleWeedDespawned))] [MemoryPackUnion(48, typeof(InteractableCharacterFightEnemySpawned))] [MemoryPackUnion(49, typeof(WantToStartFollowingPickup))] [MemoryPackUnion(50, typeof(SpawnedShotgunProjectile))] [MemoryPackUnion(51, typeof(SpawnedDexecutionerProjectile))] [MemoryPackUnion(52, typeof(ItemAdded))] [MemoryPackUnion(53, typeof(ItemRemoved))] [MemoryPackUnion(54, typeof(WeaponToggled))] [MemoryPackUnion(55, typeof(SpawnedObjectInCrypt))] [MemoryPackUnion(56, typeof(StartingChargingLamp))] [MemoryPackUnion(57, typeof(StoppingChargingLamp))] [MemoryPackUnion(58, typeof(TimerStarted))] [MemoryPackUnion(59, typeof(HatChanged))] [MemoryPackUnion(60, typeof(SpawnedRevolverProjectile))] [MemoryPackUnion(61, typeof(SpawnedSniperProjectile))] [MemoryPackUnion(62, typeof(SpawnedReviver))] [MemoryPackUnion(63, typeof(PlayerRespawned))] public interface IGameNetworkMessage : IMemoryPackFormatterRegister { [Preserve] public sealed class IGameNetworkMessageFormatter : MemoryPackFormatter<IGameNetworkMessage> { private static readonly Dictionary<Type, ushort> __typeToTag = new Dictionary<Type, ushort>(64) { { typeof(LobbyUpdates), 0 }, { typeof(ClientInGameReady), 1 }, { typeof(SpawnedObject), 2 }, { typeof(PlayerUpdate), 3 }, { typeof(SpawnedEnemy), 4 }, { typeof(SelectedCharacter), 5 }, { typeof(EnemyDied), 6 }, { typeof(SpawnedProjectile), 7 }, { typeof(ProjectileDone), 8 }, { typeof(SpawnedPickupOrb), 9 }, { typeof(SpawnedPickup), 10 }, { typeof(PickupApplied), 11 }, { typeof(PickupFollowingPlayer), 12 }, { typeof(SpawnedChest), 13 }, { typeof(ChestOpened), 14 }, { typeof(WeaponAdded), 15 }, { typeof(InteractableUsed), 16 }, { typeof(StartingChargingShrine), 17 }, { typeof(StoppingChargingShrine), 18 }, { typeof(EnemyExploder), 19 }, { typeof(EnemyDamaged), 20 }, { typeof(SpawnedEnemySpecialAttack), 21 }, { typeof(StartingChargingPylon), 22 }, { typeof(StoppingChargingPylon), 23 }, { typeof(FinalBossOrbSpawned), 24 }, { typeof(FinalBossOrbDestroyed), 25 }, { typeof(StartedSwarmEvent), 26 }, { typeof(GameOver), 27 }, { typeof(PlayerDied), 28 }, { typeof(RetargetedEnemies), 29 }, { typeof(Introduced), 30 }, { typeof(PlayerDisconnected), 31 }, { typeof(RunStarted), 32 }, { typeof(SpawnedAxeProjectile), 33 }, { typeof(SpawnedBlackHoleProjectile), 34 }, { typeof(SpawnedCringeSwordProjectile), 35 }, { typeof(SpawnedFireFieldProjectile), 36 }, { typeof(SpawnedHeroSwordProjectile), 37 }, { typeof(SpawnedRocketProjectile), 38 }, { typeof(ProjectilesUpdate), 39 }, { typeof(TomeAdded), 40 }, { typeof(LightningStrike), 41 }, { typeof(TornadoesSpawned), 42 }, { typeof(StormStarted), 43 }, { typeof(StormStopped), 44 }, { typeof(TumbleWeedSpawned), 45 }, { typeof(TumbleWeedsUpdate), 46 }, { typeof(TumbleWeedDespawned), 47 }, { typeof(InteractableCharacterFightEnemySpawned), 48 }, { typeof(WantToStartFollowingPickup), 49 }, { typeof(SpawnedShotgunProjectile), 50 }, { typeof(SpawnedDexecutionerProjectile), 51 }, { typeof(ItemAdded), 52 }, { typeof(ItemRemoved), 53 }, { typeof(WeaponToggled), 54 }, { typeof(SpawnedObjectInCrypt), 55 }, { typeof(StartingChargingLamp), 56 }, { typeof(StoppingChargingLamp), 57 }, { typeof(TimerStarted), 58 }, { typeof(HatChanged), 59 }, { typeof(SpawnedRevolverProjectile), 60 }, { typeof(SpawnedSniperProjectile), 61 }, { typeof(SpawnedReviver), 62 }, { typeof(PlayerRespawned), 63 } }; [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, ref IGameNetworkMessage? value) { ushort value2; if (value == null) { writer.WriteNullUnionHeader(); } else if (__typeToTag.TryGetValue(value.GetType(), out value2)) { writer.WriteUnionHeader(value2); switch (value2) { case 0: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<LobbyUpdates>>(ref writer).WritePackable<LobbyUpdates>(ref Unsafe.As<IGameNetworkMessage, LobbyUpdates>(ref value)); break; case 1: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<ClientInGameReady>>(ref writer).WritePackable<ClientInGameReady>(ref Unsafe.As<IGameNetworkMessage, ClientInGameReady>(ref value)); break; case 2: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedObject>>(ref writer).WritePackable<SpawnedObject>(ref Unsafe.As<IGameNetworkMessage, SpawnedObject>(ref value)); break; case 3: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<PlayerUpdate>>(ref writer).WritePackable<PlayerUpdate>(ref Unsafe.As<IGameNetworkMessage, PlayerUpdate>(ref value)); break; case 4: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedEnemy>>(ref writer).WritePackable<SpawnedEnemy>(ref Unsafe.As<IGameNetworkMessage, SpawnedEnemy>(ref value)); break; case 5: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SelectedCharacter>>(ref writer).WritePackable<SelectedCharacter>(ref Unsafe.As<IGameNetworkMessage, SelectedCharacter>(ref value)); break; case 6: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<EnemyDied>>(ref writer).WritePackable<EnemyDied>(ref Unsafe.As<IGameNetworkMessage, EnemyDied>(ref value)); break; case 7: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedProjectile>>(ref writer).WritePackable<SpawnedProjectile>(ref Unsafe.As<IGameNetworkMessage, SpawnedProjectile>(ref value)); break; case 8: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<ProjectileDone>>(ref writer).WritePackable<ProjectileDone>(ref Unsafe.As<IGameNetworkMessage, ProjectileDone>(ref value)); break; case 9: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedPickupOrb>>(ref writer).WritePackable<SpawnedPickupOrb>(ref Unsafe.As<IGameNetworkMessage, SpawnedPickupOrb>(ref value)); break; case 10: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedPickup>>(ref writer).WritePackable<SpawnedPickup>(ref Unsafe.As<IGameNetworkMessage, SpawnedPickup>(ref value)); break; case 11: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<PickupApplied>>(ref writer).WritePackable<PickupApplied>(ref Unsafe.As<IGameNetworkMessage, PickupApplied>(ref value)); break; case 12: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<PickupFollowingPlayer>>(ref writer).WritePackable<PickupFollowingPlayer>(ref Unsafe.As<IGameNetworkMessage, PickupFollowingPlayer>(ref value)); break; case 13: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedChest>>(ref writer).WritePackable<SpawnedChest>(ref Unsafe.As<IGameNetworkMessage, SpawnedChest>(ref value)); break; case 14: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<ChestOpened>>(ref writer).WritePackable<ChestOpened>(ref Unsafe.As<IGameNetworkMessage, ChestOpened>(ref value)); break; case 15: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<WeaponAdded>>(ref writer).WritePackable<WeaponAdded>(ref Unsafe.As<IGameNetworkMessage, WeaponAdded>(ref value)); break; case 16: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<InteractableUsed>>(ref writer).WritePackable<InteractableUsed>(ref Unsafe.As<IGameNetworkMessage, InteractableUsed>(ref value)); break; case 17: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<StartingChargingShrine>>(ref writer).WritePackable<StartingChargingShrine>(ref Unsafe.As<IGameNetworkMessage, StartingChargingShrine>(ref value)); break; case 18: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<StoppingChargingShrine>>(ref writer).WritePackable<StoppingChargingShrine>(ref Unsafe.As<IGameNetworkMessage, StoppingChargingShrine>(ref value)); break; case 19: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<EnemyExploder>>(ref writer).WritePackable<EnemyExploder>(ref Unsafe.As<IGameNetworkMessage, EnemyExploder>(ref value)); break; case 20: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<EnemyDamaged>>(ref writer).WritePackable<EnemyDamaged>(ref Unsafe.As<IGameNetworkMessage, EnemyDamaged>(ref value)); break; case 21: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedEnemySpecialAttack>>(ref writer).WritePackable<SpawnedEnemySpecialAttack>(ref Unsafe.As<IGameNetworkMessage, SpawnedEnemySpecialAttack>(ref value)); break; case 22: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<StartingChargingPylon>>(ref writer).WritePackable<StartingChargingPylon>(ref Unsafe.As<IGameNetworkMessage, StartingChargingPylon>(ref value)); break; case 23: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<StoppingChargingPylon>>(ref writer).WritePackable<StoppingChargingPylon>(ref Unsafe.As<IGameNetworkMessage, StoppingChargingPylon>(ref value)); break; case 24: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<FinalBossOrbSpawned>>(ref writer).WritePackable<FinalBossOrbSpawned>(ref Unsafe.As<IGameNetworkMessage, FinalBossOrbSpawned>(ref value)); break; case 25: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<FinalBossOrbDestroyed>>(ref writer).WritePackable<FinalBossOrbDestroyed>(ref Unsafe.As<IGameNetworkMessage, FinalBossOrbDestroyed>(ref value)); break; case 26: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<StartedSwarmEvent>>(ref writer).WritePackable<StartedSwarmEvent>(ref Unsafe.As<IGameNetworkMessage, StartedSwarmEvent>(ref value)); break; case 27: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<GameOver>>(ref writer).WritePackable<GameOver>(ref Unsafe.As<IGameNetworkMessage, GameOver>(ref value)); break; case 28: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<PlayerDied>>(ref writer).WritePackable<PlayerDied>(ref Unsafe.As<IGameNetworkMessage, PlayerDied>(ref value)); break; case 29: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<RetargetedEnemies>>(ref writer).WritePackable<RetargetedEnemies>(ref Unsafe.As<IGameNetworkMessage, RetargetedEnemies>(ref value)); break; case 30: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<Introduced>>(ref writer).WritePackable<Introduced>(ref Unsafe.As<IGameNetworkMessage, Introduced>(ref value)); break; case 31: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<PlayerDisconnected>>(ref writer).WritePackable<PlayerDisconnected>(ref Unsafe.As<IGameNetworkMessage, PlayerDisconnected>(ref value)); break; case 32: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<RunStarted>>(ref writer).WritePackable<RunStarted>(ref Unsafe.As<IGameNetworkMessage, RunStarted>(ref value)); break; case 33: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedAxeProjectile>>(ref writer).WritePackable<SpawnedAxeProjectile>(ref Unsafe.As<IGameNetworkMessage, SpawnedAxeProjectile>(ref value)); break; case 34: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedBlackHoleProjectile>>(ref writer).WritePackable<SpawnedBlackHoleProjectile>(ref Unsafe.As<IGameNetworkMessage, SpawnedBlackHoleProjectile>(ref value)); break; case 35: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedCringeSwordProjectile>>(ref writer).WritePackable<SpawnedCringeSwordProjectile>(ref Unsafe.As<IGameNetworkMessage, SpawnedCringeSwordProjectile>(ref value)); break; case 36: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedFireFieldProjectile>>(ref writer).WritePackable<SpawnedFireFieldProjectile>(ref Unsafe.As<IGameNetworkMessage, SpawnedFireFieldProjectile>(ref value)); break; case 37: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedHeroSwordProjectile>>(ref writer).WritePackable<SpawnedHeroSwordProjectile>(ref Unsafe.As<IGameNetworkMessage, SpawnedHeroSwordProjectile>(ref value)); break; case 38: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<SpawnedRocketProjectile>>(ref writer).WritePackable<SpawnedRocketProjectile>(ref Unsafe.As<IGameNetworkMessage, SpawnedRocketProjectile>(ref value)); break; case 39: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<ProjectilesUpdate>>(ref writer).WritePackable<ProjectilesUpdate>(ref Unsafe.As<IGameNetworkMessage, ProjectilesUpdate>(ref value)); break; case 40: Unsafe.As<MemoryPackWriter<TBufferWriter>, MemoryPackWriter<TomeAdded>>(ref write
MegabonkTogether/Tomlyn.dll
Decompiled 2 hours 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.Versioning; using System.Text; using Microsoft.CodeAnalysis; using Tomlyn.Collections; using Tomlyn.Helpers; using Tomlyn.Model; using Tomlyn.Model.Accessors; using Tomlyn.Parsing; using Tomlyn.Syntax; using Tomlyn.Text; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Alexandre Mutel")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Alexandre Mutel")] [assembly: AssemblyDescription("Tomlyn is a TOML parser, validator and authoring library for .NET.")] [assembly: AssemblyFileVersion("0.17.0.0")] [assembly: AssemblyInformationalVersion("0.17.0+ffcc7340e7345fa51b5cac49d0f19d16d1d56e94")] [assembly: AssemblyProduct("Tomlyn")] [assembly: AssemblyTitle("Tomlyn")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/xoofx/Tomlyn")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("0.17.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter)] internal class NotNullWhenAttribute : Attribute { [ExcludeFromCodeCoverage] public NotNullWhenAttribute(bool returnValue) { } } } namespace Tomlyn { public static class Toml { public static readonly string Version = ((AssemblyFileVersionAttribute)typeof(Toml).Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), inherit: false)[0]).Version; public static DocumentSyntax Parse(string text, string? sourcePath = null, TomlParserOptions options = TomlParserOptions.ParseAndValidate) { DocumentSyntax documentSyntax = new Parser<StringSourceView>(new Lexer<StringSourceView, StringCharacterIterator>(new StringSourceView(text, sourcePath ?? string.Empty))).Run(); if (!documentSyntax.HasErrors && options == TomlParserOptions.ParseAndValidate) { Validate(documentSyntax); } return documentSyntax; } public static DocumentSyntax Parse(byte[] utf8Bytes, string? sourcePath = null, TomlParserOptions options = TomlParserOptions.ParseAndValidate) { DocumentSyntax documentSyntax = new Parser<StringUtf8SourceView>(new Lexer<StringUtf8SourceView, StringCharacterUtf8Iterator>(new StringUtf8SourceView(utf8Bytes, sourcePath ?? string.Empty))).Run(); if (!documentSyntax.HasErrors && options == TomlParserOptions.ParseAndValidate) { Validate(documentSyntax); } return documentSyntax; } public static DocumentSyntax Validate(DocumentSyntax doc) { if (doc == null) { throw new ArgumentNullException("doc"); } if (doc.HasErrors) { return doc; } new SyntaxValidator(doc.Diagnostics).Visit(doc); return doc; } public static string FromModel(object model, TomlModelOptions? options = null) { if (TryFromModel(model, out string modelAsToml, out DiagnosticsBag diagnostics, options)) { return modelAsToml; } throw new TomlException(diagnostics); } public static bool TryFromModel(object model, [NotNullWhen(true)] out string? modelAsToml, out DiagnosticsBag diagnostics, TomlModelOptions? options = null) { modelAsToml = null; StringWriter stringWriter = new StringWriter(); if (!TryFromModel(model, stringWriter, out diagnostics, options)) { return false; } modelAsToml = stringWriter.ToString(); return true; } public static bool TryFromModel(object model, TextWriter writer, out DiagnosticsBag diagnostics, TomlModelOptions? options = null) { DynamicModelWriteContext dynamicModelWriteContext = new DynamicModelWriteContext(options ?? new TomlModelOptions(), writer); new ModelToTomlTransform(model, dynamicModelWriteContext).Run(); diagnostics = dynamicModelWriteContext.Diagnostics; return !dynamicModelWriteContext.Diagnostics.HasErrors; } public static TomlTable ToModel(string text, string? sourcePath = null, TomlModelOptions? options = null) { return ToModel<TomlTable>(text, sourcePath, options); } public static T ToModel<T>(string text, string? sourcePath = null, TomlModelOptions? options = null) where T : class, new() { DocumentSyntax documentSyntax = Parse(text, sourcePath); if (documentSyntax.HasErrors) { throw new TomlException(documentSyntax.Diagnostics); } return documentSyntax.ToModel<T>(options); } public static bool TryToModel<T>(string text, [NotNullWhen(true)] out T? model, [NotNullWhen(false)] out DiagnosticsBag? diagnostics, string? sourcePath = null, TomlModelOptions? options = null) where T : class, new() { DocumentSyntax documentSyntax = Parse(text, sourcePath); if (documentSyntax.HasErrors) { diagnostics = documentSyntax.Diagnostics; model = null; return false; } return documentSyntax.TryToModel<T>(out model, out diagnostics, options); } public static TomlTable ToModel(this DocumentSyntax syntax) { if (syntax == null) { throw new ArgumentNullException("syntax"); } return TomlTable.From(syntax); } public static T ToModel<T>(this DocumentSyntax syntax, TomlModelOptions? options = null) where T : class, new() { if (!syntax.TryToModel<T>(out T model, out DiagnosticsBag diagnostics, options)) { throw new TomlException(diagnostics); } return model; } public static bool TryToModel<T>(this DocumentSyntax syntax, [NotNullWhen(true)] out T? model, out DiagnosticsBag diagnostics, TomlModelOptions? options = null) where T : class, new() { model = new T(); DynamicModelReadContext dynamicModelReadContext = new DynamicModelReadContext(options ?? new TomlModelOptions()); new SyntaxToModelTransform(dynamicModelReadContext, model).Visit(syntax); diagnostics = dynamicModelReadContext.Diagnostics; return !dynamicModelReadContext.Diagnostics.HasErrors; } } public record struct TomlDateTime(DateTimeOffset DateTime, int SecondPrecision, TomlDateTimeKind Kind) : IConvertible { public TomlDateTime(DateTimeOffset DateTime, int SecondPrecision, TomlDateTimeKind Kind) { this.DateTime = DateTime; this.SecondPrecision = SecondPrecision; this.Kind = Kind; } public TomlDateTime(int year, int month, int day) : this(new DateTimeOffset(new DateTime(year, month, day)), 0, TomlDateTimeKind.LocalDate) { } public TomlDateTime(DateTime datetime) : this(new DateTimeOffset(datetime), 0, TomlDateTimeKind.LocalDateTime) { } public override string ToString() { return ((IConvertible)this).ToString((IFormatProvider?)CultureInfo.InvariantCulture); } [ExcludeFromCodeCoverage] TypeCode IConvertible.GetTypeCode() { return TypeCode.Object; } [ExcludeFromCodeCoverage] bool IConvertible.ToBoolean(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] byte IConvertible.ToByte(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] char IConvertible.ToChar(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] DateTime IConvertible.ToDateTime(IFormatProvider? provider) { return DateTime.DateTime; } [ExcludeFromCodeCoverage] decimal IConvertible.ToDecimal(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] double IConvertible.ToDouble(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] short IConvertible.ToInt16(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] int IConvertible.ToInt32(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] long IConvertible.ToInt64(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] sbyte IConvertible.ToSByte(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] float IConvertible.ToSingle(IFormatProvider? provider) { throw new NotSupportedException(); } string IConvertible.ToString(IFormatProvider? provider) { switch (Kind) { case TomlDateTimeKind.LocalDateTime: if (DateTime.Millisecond == 0) { return DateTime.ToString("yyyy-MM-dd'T'HH:mm:ss", provider); } return DateTime.ToString("yyyy-MM-dd'T'HH:mm:ss." + GetFormatPrecision(SecondPrecision), provider); case TomlDateTimeKind.LocalDate: return DateTime.ToString("yyyy-MM-dd", provider); case TomlDateTimeKind.LocalTime: if (DateTime.Millisecond == 0) { return DateTime.ToString("HH:mm:ss", provider); } return DateTime.ToString("HH:mm:ss." + GetFormatPrecision(SecondPrecision), provider); case TomlDateTimeKind.OffsetDateTimeByNumber: { DateTimeOffset dateTimeOffset2 = DateTime.ToLocalTime(); if (dateTimeOffset2.Millisecond == 0) { return dateTimeOffset2.ToString("yyyy-MM-dd'T'HH:mm:sszzz", provider); } return dateTimeOffset2.ToString("yyyy-MM-dd'T'HH:mm:ss." + GetFormatPrecision(SecondPrecision) + "zzz", provider); } default: { DateTimeOffset dateTimeOffset = DateTime.ToUniversalTime(); if (dateTimeOffset.Millisecond == 0) { return dateTimeOffset.ToString("yyyy-MM-dd'T'HH:mm:ssZ", provider); } return dateTimeOffset.ToString("yyyy-MM-dd'T'HH:mm:ss." + GetFormatPrecision(SecondPrecision) + "Z", provider); } } } object IConvertible.ToType(Type conversionType, IFormatProvider? provider) { if (conversionType == typeof(DateTime)) { return DateTime.DateTime; } if (conversionType == typeof(DateTimeOffset)) { return DateTime; } throw new InvalidCastException("Unable to convert TomlDateTime to destination type " + conversionType.FullName); } [ExcludeFromCodeCoverage] ushort IConvertible.ToUInt16(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] uint IConvertible.ToUInt32(IFormatProvider? provider) { throw new NotSupportedException(); } [ExcludeFromCodeCoverage] ulong IConvertible.ToUInt64(IFormatProvider? provider) { throw new NotSupportedException(); } public static string GetFormatPrecision(int precision) { return precision switch { 1 => "f", 2 => "ff", 3 => "fff", 4 => "ffff", 5 => "fffff", 6 => "ffffff", 7 => "fffffff", _ => "fff", }; } public static implicit operator TomlDateTime(DateTime dateTime) { return new TomlDateTime(dateTime, 0, TomlDateTimeKind.LocalDateTime); } } public enum TomlDateTimeKind { OffsetDateTimeByZ, OffsetDateTimeByNumber, LocalDateTime, LocalDate, LocalTime } public class TomlException : Exception { public DiagnosticsBag Diagnostics { get; } public TomlException(DiagnosticsBag diagnostics) : base(diagnostics.ToString()) { Diagnostics = diagnostics; } } public class TomlModelOptions { public static readonly Func<Type, ObjectKind, object> DefaultCreateInstance = DefaultCreateInstanceImpl; public static readonly Func<string, string> DefaultConvertPropertyName = TomlNamingHelper.PascalToSnakeCase; public static readonly Func<string, string> DefaultConvertFieldName = TomlNamingHelper.PascalToSnakeCase; public Func<PropertyInfo, string?> GetPropertyName { get; set; } public Func<FieldInfo, string?> GetFieldName { get; set; } public Func<string, string> ConvertPropertyName { get; set; } public Func<string, string> ConvertFieldName { get; set; } public Func<Type, ObjectKind, object> CreateInstance { get; set; } [Obsolete("Use ConvertToModel instead")] public Func<object, Type, object?>? ConvertTo { get { return ConvertToModel; } set { ConvertToModel = value; } } public Func<object, Type, object?>? ConvertToModel { get; set; } public Func<object, object?>? ConvertToToml { get; set; } public List<string> AttributeListForIgnore { get; } public List<string> AttributeListForGetName { get; } public bool IgnoreMissingProperties { get; set; } public bool IncludeFields { get; set; } public TomlModelOptions() { GetPropertyName = DefaultGetPropertyNameImpl; GetFieldName = DefaultGetFieldNameImpl; CreateInstance = DefaultCreateInstance; ConvertPropertyName = DefaultConvertPropertyName; ConvertFieldName = DefaultConvertFieldName; IgnoreMissingProperties = false; IncludeFields = false; AttributeListForIgnore = new List<string> { "System.Runtime.Serialization.IgnoreDataMemberAttribute", "System.Text.Json.Serialization.JsonIgnoreAttribute" }; AttributeListForGetName = new List<string> { "System.Runtime.Serialization.DataMemberAttribute", "System.Text.Json.Serialization.JsonPropertyNameAttribute" }; } private string? DefaultGetPropertyNameImpl(PropertyInfo prop) { string text = null; foreach (Attribute customAttribute in prop.GetCustomAttributes()) { string fullName = customAttribute.GetType().FullName; foreach (string item in AttributeListForIgnore) { if (fullName == item) { return null; } } foreach (string item2 in AttributeListForGetName) { if (!(fullName == item2)) { continue; } PropertyInfo property = customAttribute.GetType().GetProperty("Name"); if (property != null && property.PropertyType == typeof(string)) { text = property.GetValue(customAttribute) as string; if (text != null) { break; } } } } return ConvertPropertyName(text ?? prop.Name); } private string? DefaultGetFieldNameImpl(FieldInfo field) { string text = null; foreach (Attribute customAttribute in field.GetCustomAttributes()) { string fullName = customAttribute.GetType().FullName; foreach (string item in AttributeListForIgnore) { if (fullName == item) { return null; } } foreach (string item2 in AttributeListForGetName) { if (!(fullName == item2)) { continue; } PropertyInfo property = customAttribute.GetType().GetProperty("Name"); if (property != null && property.PropertyType == typeof(string)) { text = property.GetValue(customAttribute) as string; if (text != null) { break; } } } } return ConvertFieldName(text ?? field.Name); } private static object DefaultCreateInstanceImpl(Type type, ObjectKind kind) { if (type == typeof(object)) { switch (kind) { case ObjectKind.InlineTable: case ObjectKind.Table: return new TomlTable(kind == ObjectKind.InlineTable); case ObjectKind.TableArray: return new TomlTableArray(); default: return new TomlArray(); } } return Activator.CreateInstance(type) ?? throw new InvalidOperationException("Failed to create an instance of type '" + type.FullName + "'"); } } public enum TomlParserOptions { ParseAndValidate, ParseOnly } } namespace Tomlyn.Text { internal readonly struct char32 { public int Code { get; } public char32(int code) { Code = code; } public static implicit operator int(char32 c) { return c.Code; } public static implicit operator char32(int c) { return new char32(c); } public override string ToString() { return char.ConvertFromUtf32(Code); } } internal interface CharacterIterator : Iterator<char32, int> { } internal static class CharHelper { public static readonly Func<char32, bool> IsHexFunc = IsHex; public static readonly Func<char32, bool> IsOctalFunc = IsOctal; public static readonly Func<char32, bool> IsBinaryFunc = IsBinary; public static readonly Func<char32, int> HexToDecFunc = HexToDecimal; public static readonly Func<char32, int> OctalToDecFunc = OctalToDecimal; public static readonly Func<char32, int> BinaryToDecFunc = BinaryToDecimal; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsControlCharacter(char32 c) { if ((int)c > 31) { return (int)c == 127; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsKeyStart(char32 c) { if (((int)c < 97 || (int)c > 122) && ((int)c < 65 || (int)c > 90) && (int)c != 95 && (int)c != 45) { if ((int)c >= 48) { return (int)c <= 57; } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsKeyContinue(char32 c) { if (((int)c < 97 || (int)c > 122) && ((int)c < 65 || (int)c > 90) && (int)c != 95 && (int)c != 45) { if ((int)c >= 48) { return (int)c <= 57; } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsIdentifierStart(char32 c) { if ((int)c < 97 || (int)c > 122) { if ((int)c >= 65) { return (int)c <= 90; } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsIdentifierContinue(char32 c) { if ((int)c < 97 || (int)c > 122) { if ((int)c >= 65) { return (int)c <= 90; } return false; } return true; } public static bool IsValidUnicodeScalarValue(char32 c) { if ((int)c < 0 || (int)c > 55295) { if ((int)c >= 57344) { return (int)c < 1114111; } return false; } return true; } public static bool IsDigit(char32 c) { if ((int)c >= 48) { return (int)c <= 57; } return false; } public static bool IsDateTime(char32 c) { if (!IsDigit(c) && (int)c != 58 && (int)c != 45 && (int)c != 90 && (int)c != 84 && (int)c != 122 && (int)c != 116 && (int)c != 43) { return (int)c == 46; } return true; } public static string EscapeForToml(this string text, bool allowNewLinesAndSpace = false) { StringBuilder stringBuilder = null; for (int i = 0; i < text.Length; i++) { char c = text[i]; string text2 = null; if (allowNewLinesAndSpace) { if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n') { text2 = "\r\n"; i++; c = '\n'; } else { switch (c) { case '\n': text2 = "\n"; break; case '\t': text2 = "\t"; break; } } } if (text2 == null) { text2 = EscapeChar(text[i]); } if (text2 != null) { if (stringBuilder == null) { stringBuilder = new StringBuilder(text.Length * 2); stringBuilder.Append(text.Substring(0, i)); } stringBuilder.Append(text2); } else { stringBuilder?.Append(c); } } return stringBuilder?.ToString() ?? text; } private static string? EscapeChar(char c) { if (c < ' ' || c == '"' || c == '\\' || char.IsControl(c)) { return c switch { '\b' => "\\b", '\t' => "\\t", '\n' => "\\n", '\f' => "\\f", '\r' => "\\r", '"' => "\\\"", '\\' => "\\\\", _ => $"\\u{(ushort)c:X4}", }; } return null; } public static string? ToPrintableString(this string? text) { if (text == null) { return null; } StringBuilder stringBuilder = null; for (int i = 0; i < text.Length; i++) { char value = text[i]; string text2 = text[i].ToPrintableString(); if (text2 != null) { if (stringBuilder == null) { stringBuilder = new StringBuilder(text.Length * 2); stringBuilder.Append(text.Substring(0, i)); } stringBuilder.Append(text2); } else { stringBuilder?.Append(value); } } return stringBuilder?.ToString() ?? text; } public static string? ToPrintableString(this char c) { if (c < ' ' || IsWhiteSpace(c)) { return c switch { ' ' => " ", '\b' => "\\b", '\r' => "␍", '\n' => "", '\t' => "\\t", '\a' => "\\a", '\v' => "\\v", '\f' => "\\f", _ => $"\\u{(int)c:X};", }; } return null; } public static bool IsWhiteSpace(char32 c) { if ((int)c != 32) { return (int)c == 9; } return true; } public static bool IsWhiteSpaceOrNewLine(char32 c) { if ((int)c != 32 && (int)c != 9 && (int)c != 13) { return (int)c == 10; } return true; } public static bool IsNewLine(char32 c) { if ((int)c != 13) { return (int)c == 10; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char32? ToUtf8(byte[] buffer, ref int position) { if (position < buffer.Length) { sbyte b = (sbyte)buffer[position++]; return (b >= 0) ? ((char32)b) : DecodeUTF8_24(buffer, ref position, b); } position = buffer.Length; return null; } private static char32 DecodeUTF8_24(byte[] buffer, ref int position, sbyte c1) { int num = 0; while (c1 < 0) { c1 <<= 1; num++; } if (num > 4 || position + num - 1 > buffer.Length) { throw new CharReaderException($"Invalid UTF8 character at position {position}"); } int num2 = (c1 << 6 - num) | (buffer[position++] & 0x3F); if (num == 2) { return num2; } if (num >= 3) { num2 = (num2 << 6) | (buffer[position++] & 0x3F); } if (num == 4) { num2 = (num2 << 6) | (buffer[position++] & 0x3F); } return num2; } public static int HexToDecimal(char32 c) { if ((int)c < 48 || (int)c > 57) { if ((int)c < 97 || (int)c > 102) { return (int)c - 65 + 10; } return (int)c - 97 + 10; } return (int)c - 48; } public static int OctalToDecimal(char32 c) { return (int)c - 48; } public static int BinaryToDecimal(char32 c) { return (int)c - 48; } private static bool IsHex(char32 c) { if (((int)c < 48 || (int)c > 57) && ((int)c < 97 || (int)c > 102)) { if ((int)c >= 65) { return (int)c <= 70; } return false; } return true; } private static bool IsOctal(char32 c) { if ((int)c >= 48) { return (int)c <= 55; } return false; } private static bool IsBinary(char32 c) { if ((int)c != 48) { return (int)c == 49; } return true; } public static void AppendUtf32(this StringBuilder builder, char32 utf32) { if ((int)utf32 < 65536) { builder.Append((char)(int)utf32); return; } utf32 = (int)utf32 - 65536; builder.Append((char)((int)utf32 / 1024 + 55296)); builder.Append((char)((int)utf32 % 1024 + 56320)); } } internal sealed class CharReaderException : Exception { public CharReaderException(string message) : base(message) { } } internal interface ISourceView : IStringView { string SourcePath { get; } } internal interface ISourceView<out TCharIterator> : ISourceView, IStringView, IStringView<TCharIterator> where TCharIterator : struct, CharacterIterator { } internal interface IStringView { string? GetString(int offset, int length); } internal interface IStringView<out TCharIterator> : IStringView where TCharIterator : struct, CharacterIterator { TCharIterator GetIterator(); } internal struct StringCharacterIterator : CharacterIterator, Iterator<char32, int> { private readonly string _text; public int Start => 0; public StringCharacterIterator(string text) { _text = text; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public char32? TryGetNext(ref int position) { if (position < _text.Length) { char c = _text[position]; position++; return char.IsHighSurrogate(c) ? NextCharWithSurrogate(ref position, c) : c; } position = _text.Length; return null; } private int NextCharWithSurrogate(ref int position, char c1) { if (position < _text.Length) { char c2 = _text[position]; position++; if (char.IsLowSurrogate(c2)) { return char.ConvertToUtf32(c1, c2); } throw new CharReaderException("Unexpected character after high-surrogate char"); } throw new CharReaderException("Unexpected EOF after high-surrogate char"); } } internal struct StringCharacterUtf8Iterator : CharacterIterator, Iterator<char32, int> { private readonly byte[] _text; private readonly int _start; public int Start => _start; public StringCharacterUtf8Iterator(byte[] text) { _text = text; _start = ((text.Length >= 3 && text[0] == 239 && text[1] == 187 && text[0] == 191) ? 3 : 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public char32? TryGetNext(ref int position) { return CharHelper.ToUtf8(_text, ref position); } } internal struct StringSourceView : ISourceView<StringCharacterIterator>, ISourceView, IStringView, IStringView<StringCharacterIterator> { private readonly string _text; public string SourcePath { get; } public StringSourceView(string text, string sourcePath) { _text = text; SourcePath = sourcePath; } public string? GetString(int offset, int length) { if (offset + length <= _text.Length) { return _text.Substring(offset, length); } return null; } public StringCharacterIterator GetIterator() { return new StringCharacterIterator(_text); } } internal struct StringUtf8SourceView : ISourceView<StringCharacterUtf8Iterator>, ISourceView, IStringView, IStringView<StringCharacterUtf8Iterator> { private readonly byte[] _text; public string SourcePath { get; } public StringUtf8SourceView(byte[] text, string sourcePath) { _text = text; SourcePath = sourcePath; } public string? GetString(int offset, int length) { if (offset + length <= _text.Length) { return Encoding.UTF8.GetString(_text, offset, length); } return null; } public StringCharacterUtf8Iterator GetIterator() { return new StringCharacterUtf8Iterator(_text); } } } namespace Tomlyn.Syntax { public sealed class ArrayItemSyntax : SyntaxNode { private ValueSyntax? _value; private SyntaxToken? _comma; public ValueSyntax? Value { get { return _value; } set { ParentToThis(ref _value, value); } } public SyntaxToken? Comma { get { return _comma; } set { ParentToThis(ref _comma, value, TokenKind.Comma); } } public override int ChildrenCount => 2; public ArrayItemSyntax() : base(SyntaxKind.ArrayItem) { } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { if (index != 0) { return Comma; } return Value; } } public sealed class ArraySyntax : ValueSyntax { private SyntaxToken? _openBracket; private SyntaxToken? _closeBracket; public SyntaxToken? OpenBracket { get { return _openBracket; } set { ParentToThis(ref _openBracket, value, TokenKind.OpenBracket); } } public SyntaxList<ArrayItemSyntax> Items { get; } public SyntaxToken? CloseBracket { get { return _closeBracket; } set { ParentToThis(ref _closeBracket, value, TokenKind.CloseBracket); } } public override int ChildrenCount => 3; public ArraySyntax() : base(SyntaxKind.Array) { Items = new SyntaxList<ArrayItemSyntax> { Parent = this }; } public ArraySyntax(int[] values) : this() { if (values == null) { throw new ArgumentNullException("values"); } OpenBracket = SyntaxFactory.Token(TokenKind.OpenBracket); CloseBracket = SyntaxFactory.Token(TokenKind.CloseBracket); for (int i = 0; i < values.Length; i++) { ArrayItemSyntax arrayItemSyntax = new ArrayItemSyntax { Value = new IntegerValueSyntax(values[i]) }; if (i + 1 < values.Length) { arrayItemSyntax.Comma = SyntaxFactory.Token(TokenKind.Comma); arrayItemSyntax.Comma.AddTrailingWhitespace(); } Items.Add(arrayItemSyntax); } } public ArraySyntax(string[] values) : this() { if (values == null) { throw new ArgumentNullException("values"); } OpenBracket = SyntaxFactory.Token(TokenKind.OpenBracket); CloseBracket = SyntaxFactory.Token(TokenKind.CloseBracket); for (int i = 0; i < values.Length; i++) { ArrayItemSyntax arrayItemSyntax = new ArrayItemSyntax { Value = new StringValueSyntax(values[i]) }; if (i + 1 < values.Length) { arrayItemSyntax.Comma = SyntaxFactory.Token(TokenKind.Comma); arrayItemSyntax.Comma.AddTrailingWhitespace(); } Items.Add(arrayItemSyntax); } } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return index switch { 0 => OpenBracket, 1 => Items, _ => CloseBracket, }; } protected override string ToDebuggerDisplay() { return $"{base.ToDebuggerDisplay()} Count = {Items.ChildrenCount}"; } } public abstract class BareKeyOrStringValueSyntax : ValueSyntax { internal BareKeyOrStringValueSyntax(SyntaxKind kind) : base(kind) { } } public sealed class BareKeySyntax : BareKeyOrStringValueSyntax { private SyntaxToken? _key; public SyntaxToken? Key { get { return _key; } set { ParentToThis(ref _key, value, TokenKind.BasicKey); } } public override int ChildrenCount => 1; public BareKeySyntax() : base(SyntaxKind.BasicKey) { } public BareKeySyntax(string name) : this() { if (!IsBareKey(name)) { throw new ArgumentOutOfRangeException("The key `" + name + "` does not contain valid characters [A-Za-z0-9_\\-]"); } Key = new SyntaxToken(TokenKind.BasicKey, name); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return Key; } public static bool IsBareKey(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0 || string.IsNullOrWhiteSpace(name)) { return false; } for (int i = 0; i < name.Length; i++) { if (!CharHelper.IsKeyContinue(name[i])) { return false; } } return true; } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + ": " + ((Key != null) ? TomlFormatHelper.ToString(Key.ToString(), TomlPropertyDisplayKind.Default) : string.Empty); } } public sealed class BooleanValueSyntax : ValueSyntax { private SyntaxToken? _token; private bool _value; public SyntaxToken? Token { get { return _token; } set { ParentToThis(ref _token, value, TokenKind.True, TokenKind.False); } } public bool Value { get { return _value; } set { _value = value; } } public override int ChildrenCount => 1; public BooleanValueSyntax() : base(SyntaxKind.Boolean) { } public BooleanValueSyntax(bool value) : this() { TokenKind tokenKind = (value ? TokenKind.True : TokenKind.False); Token = new SyntaxToken(tokenKind, tokenKind.ToText()); Value = value; } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return Token; } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + ": " + TomlFormatHelper.ToString(Value); } } public sealed class DateTimeValueSyntax : ValueSyntax { private SyntaxToken? _token; public SyntaxToken? Token { get { return _token; } set { ParentToThis(ref _token, value, value?.TokenKind.IsDateTime() ?? false, $"The token kind `{value?.TokenKind}` is not a datetime token"); } } public TomlDateTime Value { get; set; } public override int ChildrenCount => 1; public DateTimeValueSyntax(SyntaxKind kind) : base(CheckDateTimeKind(kind)) { } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return Token; } private static SyntaxKind CheckDateTimeKind(SyntaxKind kind) { if ((uint)(kind - 4) <= 4u) { return kind; } throw new ArgumentOutOfRangeException("kind", kind, null); } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + ": " + TomlFormatHelper.ToString(Value); } } public class DiagnosticMessage { public DiagnosticMessageKind Kind { get; } public SourceSpan Span { get; } public string Message { get; } public DiagnosticMessage(DiagnosticMessageKind kind, SourceSpan span, string message) { Kind = kind; Span = span; Message = message; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(Span.ToStringSimple()); stringBuilder.Append(" : "); switch (Kind) { case DiagnosticMessageKind.Error: stringBuilder.Append("error"); break; case DiagnosticMessageKind.Warning: stringBuilder.Append("warning"); break; default: throw new InvalidOperationException($"Message type [{Kind}] not supported"); } stringBuilder.Append(" : "); if (Message != null) { stringBuilder.Append(Message); } return stringBuilder.ToString(); } } public enum DiagnosticMessageKind { Error, Warning } [DebuggerDisplay("{Count} Errors: {HasErrors}")] public class DiagnosticsBag : IEnumerable<DiagnosticMessage>, IEnumerable { private readonly List<DiagnosticMessage> _messages; public int Count => _messages.Count; public DiagnosticMessage this[int index] => _messages[index]; public bool HasErrors { get; private set; } public DiagnosticsBag() { _messages = new List<DiagnosticMessage>(); } public DiagnosticsBag(IEnumerable<DiagnosticMessage> messages) : this() { foreach (DiagnosticMessage message in messages) { Add(message); } } public void Add(DiagnosticMessage message) { if (message == null) { throw new ArgumentNullException("message"); } _messages.Add(message); if (message.Kind == DiagnosticMessageKind.Error) { HasErrors = true; } } public void AddRange(IEnumerable<DiagnosticMessage> messages) { foreach (DiagnosticMessage message in messages) { Add(message); } } public void Clear() { _messages.Clear(); HasErrors = false; } public void Warning(SourceSpan span, string text) { Add(new DiagnosticMessage(DiagnosticMessageKind.Warning, span, text)); } public void Error(SourceSpan span, string text) { Add(new DiagnosticMessage(DiagnosticMessageKind.Error, span, text)); } public List<DiagnosticMessage>.Enumerator GetEnumerator() { return _messages.GetEnumerator(); } IEnumerator<DiagnosticMessage> IEnumerable<DiagnosticMessage>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_messages).GetEnumerator(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); foreach (DiagnosticMessage message in _messages) { stringBuilder.AppendLine(message.ToString()); } return stringBuilder.ToString(); } } public sealed class DocumentSyntax : SyntaxNode { public DiagnosticsBag Diagnostics { get; } public bool HasErrors => Diagnostics.HasErrors; public SyntaxList<KeyValueSyntax> KeyValues { get; } public SyntaxList<TableSyntaxBase> Tables { get; } public override int ChildrenCount => 2; public DocumentSyntax() : base(SyntaxKind.Document) { KeyValues = new SyntaxList<KeyValueSyntax> { Parent = this }; Tables = new SyntaxList<TableSyntaxBase> { Parent = this }; Diagnostics = new DiagnosticsBag(); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode GetChildImpl(int index) { if (index != 0) { return Tables; } return KeyValues; } } public sealed class DottedKeyItemSyntax : ValueSyntax { private SyntaxToken? _dot; private BareKeyOrStringValueSyntax? _key; public SyntaxToken? Dot { get { return _dot; } set { ParentToThis(ref _dot, value, TokenKind.Dot); } } public BareKeyOrStringValueSyntax? Key { get { return _key; } set { ParentToThis(ref _key, value); } } public override int ChildrenCount => 2; public DottedKeyItemSyntax() : base(SyntaxKind.DottedKeyItem) { } public DottedKeyItemSyntax(string key) : this() { if (key == null) { throw new ArgumentNullException("key"); } Dot = SyntaxFactory.Token(TokenKind.Dot); Key = (BareKeySyntax.IsBareKey(key) ? ((BareKeyOrStringValueSyntax)new BareKeySyntax(key)) : ((BareKeyOrStringValueSyntax)new StringValueSyntax(key))); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { if (index != 0) { return Key; } return Dot; } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + ": " + ToString(); } } public sealed class FloatValueSyntax : ValueSyntax { private SyntaxToken? _token; private const string FloatFormat = "g16"; public SyntaxToken? Token { get { return _token; } set { ParentToThis(ref _token, value, value?.TokenKind.IsFloat() ?? false, TokenKind.Float); } } public double Value { get; set; } public override int ChildrenCount => 1; public FloatValueSyntax() : base(SyntaxKind.Float) { } public FloatValueSyntax(double value) : this() { if (double.IsNaN(value)) { Token = new SyntaxToken(TokenKind.Nan, (value < 0.0) ? TokenKind.NegativeNan.ToText() : TokenKind.Nan.ToText()); } else if (double.IsPositiveInfinity(value)) { Token = new SyntaxToken(TokenKind.PositiveInfinite, TokenKind.PositiveInfinite.ToText()); } else if (double.IsNegativeInfinity(value)) { Token = new SyntaxToken(TokenKind.NegativeInfinite, TokenKind.NegativeInfinite.ToText()); } else { Token = new SyntaxToken(TokenKind.Float, value.ToString("g16", CultureInfo.InvariantCulture)); } Value = value; } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return Token; } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + ": " + TomlFormatHelper.ToString(Value); } } public sealed class InlineTableItemSyntax : SyntaxNode { private KeyValueSyntax? _keyValue; private SyntaxToken? _comma; public KeyValueSyntax? KeyValue { get { return _keyValue; } set { ParentToThis(ref _keyValue, value); } } public SyntaxToken? Comma { get { return _comma; } set { ParentToThis(ref _comma, value, TokenKind.Comma); } } public override int ChildrenCount => 2; public InlineTableItemSyntax() : base(SyntaxKind.InlineTable) { } public InlineTableItemSyntax(KeyValueSyntax keyValue) : this() { KeyValue = keyValue ?? throw new ArgumentNullException("keyValue"); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { if (index != 0) { return Comma; } return KeyValue; } } public sealed class InlineTableSyntax : ValueSyntax { private SyntaxToken? _openBrace; private SyntaxToken? _closeBrace; public SyntaxToken? OpenBrace { get { return _openBrace; } set { ParentToThis(ref _openBrace, value, TokenKind.OpenBrace); } } public SyntaxList<InlineTableItemSyntax> Items { get; } public SyntaxToken? CloseBrace { get { return _closeBrace; } set { ParentToThis(ref _closeBrace, value, TokenKind.CloseBrace); } } public override int ChildrenCount => 3; public InlineTableSyntax() : base(SyntaxKind.InlineTable) { Items = new SyntaxList<InlineTableItemSyntax> { Parent = this }; } public InlineTableSyntax(params KeyValueSyntax[] keyValues) : this() { if (keyValues == null) { throw new ArgumentNullException("keyValues"); } OpenBrace = SyntaxFactory.Token(TokenKind.OpenBrace).AddTrailingWhitespace(); CloseBrace = SyntaxFactory.Token(TokenKind.CloseBrace).AddLeadingWhitespace(); for (int i = 0; i < keyValues.Length; i++) { KeyValueSyntax keyValue = keyValues[i]; Items.Add(new InlineTableItemSyntax(keyValue) { Comma = ((i + 1 < keyValues.Length) ? SyntaxFactory.Token(TokenKind.Comma).AddTrailingWhitespace() : null) }); } } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return index switch { 0 => OpenBrace, 1 => Items, _ => CloseBrace, }; } protected override string ToDebuggerDisplay() { return $"{base.ToDebuggerDisplay()} Count = {Items.ChildrenCount}"; } } public sealed class IntegerValueSyntax : ValueSyntax { private SyntaxToken? _token; public SyntaxToken? Token { get { return _token; } set { ParentToThis(ref _token, value, value?.TokenKind.IsInteger() ?? false, "decimal/hex/binary/octal integer"); } } public long Value { get; set; } public override int ChildrenCount => 1; public IntegerValueSyntax() : base(SyntaxKind.Integer) { } public IntegerValueSyntax(long value) : this() { Token = new SyntaxToken(TokenKind.Integer, value.ToString(CultureInfo.InvariantCulture)); Value = value; } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return Token; } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + ": " + TomlFormatHelper.ToString(Value); } } public sealed class InvalidSyntaxToken : SyntaxToken { public TokenKind InvalidKind { get; set; } } public sealed class KeySyntax : ValueSyntax { private BareKeyOrStringValueSyntax? _key; public BareKeyOrStringValueSyntax? Key { get { return _key; } set { ParentToThis(ref _key, value); } } public SyntaxList<DottedKeyItemSyntax> DotKeys { get; } public override int ChildrenCount => 2; public KeySyntax() : base(SyntaxKind.Key) { DotKeys = new SyntaxList<DottedKeyItemSyntax> { Parent = this }; } public KeySyntax(string key) : this() { Key = (BareKeySyntax.IsBareKey(key) ? ((BareKeyOrStringValueSyntax)new BareKeySyntax(key)) : ((BareKeyOrStringValueSyntax)new StringValueSyntax(key))); } public KeySyntax(string key, string dotKey1) : this() { if (key == null) { throw new ArgumentNullException("key"); } if (dotKey1 == null) { throw new ArgumentNullException("dotKey1"); } Key = (BareKeySyntax.IsBareKey(key) ? ((BareKeyOrStringValueSyntax)new BareKeySyntax(key)) : ((BareKeyOrStringValueSyntax)new StringValueSyntax(key))); DotKeys.Add(new DottedKeyItemSyntax(dotKey1)); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { if (index == 0) { return Key; } return DotKeys; } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + ": " + ToString(); } } public sealed class KeyValueSyntax : SyntaxNode { private KeySyntax? _key; private SyntaxToken? _equalToken; private ValueSyntax? _value; private SyntaxToken? _endOfLineToken; public KeySyntax? Key { get { return _key; } set { ParentToThis(ref _key, value); } } public SyntaxToken? EqualToken { get { return _equalToken; } set { ParentToThis(ref _equalToken, value, TokenKind.Equal); } } public ValueSyntax? Value { get { return _value; } set { ParentToThis(ref _value, value); } } public SyntaxToken? EndOfLineToken { get { return _endOfLineToken; } set { ParentToThis(ref _endOfLineToken, value, TokenKind.NewLine, TokenKind.Eof); } } public override int ChildrenCount => 4; public KeyValueSyntax() : base(SyntaxKind.KeyValue) { } public KeyValueSyntax(string key, ValueSyntax value) : this() { if (key == null) { throw new ArgumentNullException("key"); } Key = new KeySyntax(key); Value = value ?? throw new ArgumentNullException("value"); EqualToken = SyntaxFactory.Token(TokenKind.Equal); EqualToken.AddLeadingWhitespace(); EqualToken.AddTrailingWhitespace(); EndOfLineToken = SyntaxFactory.NewLine(); } public KeyValueSyntax(KeySyntax key, ValueSyntax value) : this() { Key = key ?? throw new ArgumentNullException("key"); Value = value ?? throw new ArgumentNullException("value"); EqualToken = SyntaxFactory.Token(TokenKind.Equal); EqualToken.AddLeadingWhitespace(); EqualToken.AddTrailingWhitespace(); EndOfLineToken = SyntaxFactory.NewLine(); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return index switch { 0 => Key, 1 => EqualToken, 2 => Value, _ => EndOfLineToken, }; } protected override string ToDebuggerDisplay() { return $"{base.ToDebuggerDisplay()}: {Key} = {Value}"; } } public struct SourceSpan { public string FileName; public TextPosition Start; public TextPosition End; public int Offset => Start.Offset; public int Length => End.Offset - Start.Offset + 1; public SourceSpan(string fileName, TextPosition start, TextPosition end) { FileName = fileName; Start = start; End = end; } public override string ToString() { return $"{FileName}{Start}-{End}"; } public string ToStringSimple() { return $"{FileName}{Start}"; } } public sealed class StringValueSyntax : BareKeyOrStringValueSyntax { private SyntaxToken? _token; public SyntaxToken? Token { get { return _token; } set { ParentToThis(ref _token, value, value?.TokenKind.IsString() ?? false, "string"); } } public string? Value { get; set; } public override int ChildrenCount => 1; public StringValueSyntax() : base(SyntaxKind.String) { } public StringValueSyntax(string text) : this() { if (text == null) { throw new ArgumentNullException("text"); } Token = new SyntaxToken(TokenKind.String, "\"" + text.EscapeForToml() + "\""); Value = text; } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return Token; } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + ": " + ((Value != null) ? TomlFormatHelper.ToString(Value, TomlPropertyDisplayKind.Default) : string.Empty); } } public static class SyntaxFactory { public static SyntaxTrivia Whitespace() { return new SyntaxTrivia(TokenKind.Whitespaces, " "); } public static SyntaxTrivia NewLineTrivia() { return new SyntaxTrivia(TokenKind.NewLine, "\n"); } public static SyntaxTrivia Comment(string comment) { if (comment == null) { throw new ArgumentNullException("comment"); } return new SyntaxTrivia(TokenKind.Comment, "# " + comment); } public static SyntaxToken NewLine() { return new SyntaxToken(TokenKind.NewLine, "\n"); } public static SyntaxToken Token(TokenKind kind) { if (kind == TokenKind.NewLine || !kind.IsToken()) { throw new ArgumentOutOfRangeException($"The token kind `{kind}` is not supported for a plain token without a predefined value"); } string text = kind.ToText(); return new SyntaxToken(kind, text); } } public enum SyntaxKind { Array, ArrayItem, BasicKey, Boolean, OffsetDateTimeByZ, OffsetDateTimeByNumber, LocalDateTime, LocalDate, LocalTime, Document, DottedKeyItem, Float, InlineTable, Integer, Key, KeyValue, List, String, Table, TableArray, Token } public abstract class SyntaxList : SyntaxNode { protected readonly List<SyntaxNode> Children; public sealed override int ChildrenCount => Children.Count; internal SyntaxList() : base(SyntaxKind.List) { Children = new List<SyntaxNode>(); } protected override SyntaxNode GetChildImpl(int index) { return Children[index]; } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } } public sealed class SyntaxList<TSyntaxNode> : SyntaxList, IEnumerable<TSyntaxNode>, IEnumerable where TSyntaxNode : SyntaxNode { public struct Enumerator : IEnumerator<TSyntaxNode>, IEnumerator, IDisposable { private readonly List<SyntaxNode> _nodes; private int _index; public TSyntaxNode Current { get { if (_index < 0) { throw new InvalidOperationException("MoveNext must be called before accessing Current"); } return (TSyntaxNode)_nodes[_index]; } } object IEnumerator.Current => Current; public Enumerator(List<SyntaxNode> nodes) { _nodes = nodes; _index = -1; } public bool MoveNext() { if (_index + 1 == _nodes.Count) { return false; } _index++; return true; } public void Reset() { _index = -1; } public void Dispose() { } } public void Add(TSyntaxNode node) { if (node == null) { throw new ArgumentNullException("node"); } if (node.Parent != null) { throw ThrowHelper.GetExpectingNoParentException(); } Children.Add(node); node.Parent = this; } public new TSyntaxNode? GetChild(int index) { return (TSyntaxNode)base.GetChild(index); } protected override SyntaxNode GetChildImpl(int index) { return Children[index]; } public void RemoveChildAt(int index) { SyntaxNode syntaxNode = Children[index]; Children.RemoveAt(index); syntaxNode.Parent = null; } public void RemoveChild(TSyntaxNode node) { if (node == null) { throw new ArgumentNullException("node"); } if (node.Parent != this) { throw new InvalidOperationException("The node is not part of this list"); } Children.Remove(node); node.Parent = null; } public Enumerator GetEnumerator() { return new Enumerator(Children); } IEnumerator<TSyntaxNode> IEnumerable<TSyntaxNode>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public abstract class SyntaxNode : SyntaxNodeBase { private readonly struct ExpectedTuple2<T1, T2> { public readonly T1 Value1; public readonly T2 Value2; public ExpectedTuple2(T1 value1, T2 value2) { Value1 = value1; Value2 = value2; } public override string ToString() { return $"`{Value1}` or `{Value2}`"; } } public SyntaxKind Kind { get; } public List<SyntaxTrivia>? LeadingTrivia { get; set; } public List<SyntaxTrivia>? TrailingTrivia { get; set; } public abstract int ChildrenCount { get; } protected SyntaxNode(SyntaxKind kind) { Kind = kind; } public SyntaxNode? GetChild(int index) { if (index < 0) { throw ThrowHelper.GetIndexNegativeArgumentOutOfRangeException(); } if (index > ChildrenCount) { throw ThrowHelper.GetIndexArgumentOutOfRangeException(ChildrenCount); } return GetChildImpl(index); } protected abstract SyntaxNode? GetChildImpl(int index); public override string ToString() { StringWriter stringWriter = new StringWriter(); WriteTo(stringWriter); return stringWriter.ToString(); } public void WriteTo(TextWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } WriteToInternal(writer); } private void WriteToInternal(TextWriter writer) { WriteTriviaTo(LeadingTrivia, writer); if (this is SyntaxToken syntaxToken) { writer.Write(syntaxToken.TokenKind.ToText() ?? syntaxToken.Text); } else { int childrenCount = ChildrenCount; for (int i = 0; i < childrenCount; i++) { GetChild(i)?.WriteToInternal(writer); } } WriteTriviaTo(TrailingTrivia, writer); } private static void WriteTriviaTo(List<SyntaxTrivia>? trivias, TextWriter writer) { if (trivias == null) { return; } foreach (SyntaxTrivia trivia in trivias) { if (trivia != null) { writer.Write(trivia.Text); } } } protected void ParentToThis<TSyntaxNode>(ref TSyntaxNode? set, TSyntaxNode? node) where TSyntaxNode : SyntaxNode { if (node?.Parent != null) { throw ThrowHelper.GetExpectingNoParentException(); } if (set != null) { set.Parent = null; } if (node != null) { node.Parent = this; } set = node; } protected void ParentToThis<TSyntaxNode>(ref TSyntaxNode? set, TSyntaxNode? node, TokenKind expectedKind) where TSyntaxNode : SyntaxToken { ParentToThis(ref set, node, node != null && node.TokenKind == expectedKind, expectedKind); } protected void ParentToThis<TSyntaxNode, TExpected>(ref TSyntaxNode? set, TSyntaxNode? node, bool expectedKindSuccess, TExpected expectedMessage) where TSyntaxNode : SyntaxToken { if (node != null && !expectedKindSuccess) { throw new InvalidOperationException($"Unexpected node kind `{node.TokenKind}` while expecting `{expectedMessage}`"); } ParentToThis(ref set, node); } protected void ParentToThis<TSyntaxNode>(ref TSyntaxNode? set, TSyntaxNode? node, TokenKind expectedKind1, TokenKind expectedKind2) where TSyntaxNode : SyntaxToken { int expectedKindSuccess; if (node == null || node.TokenKind != expectedKind1) { expectedKindSuccess = ((node != null && node.TokenKind == expectedKind2) ? 1 : 0); } else { expectedKindSuccess = 1; } ParentToThis(ref set, node, (byte)expectedKindSuccess != 0, new ExpectedTuple2<TokenKind, TokenKind>(expectedKind1, expectedKind2)); } } [DebuggerDisplay("{ToDebuggerDisplay(),nq}")] public abstract class SyntaxNodeBase { public SourceSpan Span; public SyntaxNode? Parent { get; internal set; } public abstract void Accept(SyntaxVisitor visitor); protected virtual string ToDebuggerDisplay() { return GetType().Name ?? ""; } } public static class SyntaxNodeExtensions { public static IEnumerable<SyntaxNodeBase> Tokens(this SyntaxNode node, bool includeCommentsAndWhitespaces = true) { foreach (SyntaxNodeBase item in node.Descendants(includeTokensCommentsAndWhitespaces: true)) { if (item is SyntaxTrivia) { if (!includeCommentsAndWhitespaces) { continue; } } else if (!(item is SyntaxToken)) { continue; } yield return item; } } public static IEnumerable<SyntaxNodeBase> Descendants(this SyntaxNode node, bool includeTokensCommentsAndWhitespaces = false) { if (!includeTokensCommentsAndWhitespaces && node is SyntaxToken) { yield break; } if (includeTokensCommentsAndWhitespaces && node.LeadingTrivia != null) { foreach (SyntaxTrivia leadingTrivium in node.LeadingTrivia) { yield return leadingTrivium; } } int childrenCount = node.ChildrenCount; for (int i = 0; i < childrenCount; i++) { SyntaxNode child = node.GetChild(i); if (child is SyntaxList list) { int subChildrenCount = list.ChildrenCount; for (int j = 0; j < subChildrenCount; j++) { SyntaxNode child2 = list.GetChild(j); if (child2 == null) { continue; } foreach (SyntaxNodeBase item in child2.Descendants(includeTokensCommentsAndWhitespaces)) { yield return item; } } } else { if (child == null) { continue; } foreach (SyntaxNodeBase item2 in child.Descendants(includeTokensCommentsAndWhitespaces)) { yield return item2; } } } yield return node; if (!includeTokensCommentsAndWhitespaces || node.TrailingTrivia == null) { yield break; } foreach (SyntaxTrivia trailingTrivium in node.TrailingTrivia) { yield return trailingTrivium; } } public static void Add(this SyntaxList<KeyValueSyntax> list, string name, int value) { if (list == null) { throw new ArgumentNullException("list"); } list.Add(new KeyValueSyntax(name, new IntegerValueSyntax(value))); } public static void Add(this SyntaxList<KeyValueSyntax> list, string name, long value) { if (list == null) { throw new ArgumentNullException("list"); } list.Add(new KeyValueSyntax(name, new IntegerValueSyntax(value))); } public static void Add(this SyntaxList<KeyValueSyntax> list, string name, bool value) { if (list == null) { throw new ArgumentNullException("list"); } list.Add(new KeyValueSyntax(name, new BooleanValueSyntax(value))); } public static void Add(this SyntaxList<KeyValueSyntax> list, string name, double value) { if (list == null) { throw new ArgumentNullException("list"); } list.Add(new KeyValueSyntax(name, new FloatValueSyntax(value))); } public static void Add(this SyntaxList<KeyValueSyntax> list, string name, string value) { if (list == null) { throw new ArgumentNullException("list"); } list.Add(new KeyValueSyntax(name, new StringValueSyntax(value))); } public static void Add(this SyntaxList<KeyValueSyntax> list, string name, int[] values) { if (list == null) { throw new ArgumentNullException("list"); } list.Add(new KeyValueSyntax(name, new ArraySyntax(values))); } public static void Add(this SyntaxList<KeyValueSyntax> list, string name, string[] values) { if (list == null) { throw new ArgumentNullException("list"); } list.Add(new KeyValueSyntax(name, new ArraySyntax(values))); } public static void Add(this SyntaxList<KeyValueSyntax> list, string name, DateTimeValueSyntax value) { if (list == null) { throw new ArgumentNullException("list"); } list.Add(new KeyValueSyntax(name, value)); } public static KeyValueSyntax AddTrailingComment(this KeyValueSyntax keyValue, string comment) { if (keyValue == null) { throw new ArgumentNullException("keyValue"); } if (keyValue.Value == null) { throw new InvalidOperationException("The Value must not be null on the KeyValueSyntax"); } keyValue.Value.AddTrailingWhitespace().AddTrailingComment(comment); return keyValue; } public static T AddLeadingWhitespace<T>(this T node) where T : SyntaxNode { return node.AddLeadingTrivia(SyntaxFactory.Whitespace()); } public static T AddTrailingWhitespace<T>(this T node) where T : SyntaxNode { return node.AddTrailingTrivia(SyntaxFactory.Whitespace()); } public static T AddLeadingTrivia<T>(this T node, SyntaxTrivia trivia) where T : SyntaxNode { if (node == null) { throw new ArgumentNullException("node"); } List<SyntaxTrivia> list = node.LeadingTrivia; if (list == null) { list = (node.LeadingTrivia = new List<SyntaxTrivia>()); } list.Add(trivia); return node; } public static T AddTrailingTrivia<T>(this T node, SyntaxTrivia trivia) where T : SyntaxNode { if (node == null) { throw new ArgumentNullException("node"); } List<SyntaxTrivia> list = node.TrailingTrivia; if (list == null) { list = (node.TrailingTrivia = new List<SyntaxTrivia>()); } list.Add(trivia); return node; } public static T AddLeadingComment<T>(this T node, string comment) where T : SyntaxNode { return node.AddLeadingTrivia(SyntaxFactory.Comment(comment)); } public static T AddTrailingComment<T>(this T node, string comment) where T : SyntaxNode { return node.AddTrailingTrivia(SyntaxFactory.Comment(comment)); } public static T AddLeadingTriviaNewLine<T>(this T node) where T : SyntaxNode { return node.AddLeadingTrivia(SyntaxFactory.NewLineTrivia()); } public static T AddTrailingTriviaNewLine<T>(this T node) where T : SyntaxNode { return node.AddTrailingTrivia(SyntaxFactory.NewLineTrivia()); } } public class SyntaxToken : SyntaxNode { public TokenKind TokenKind { get; set; } public string? Text { get; set; } public override int ChildrenCount => 0; public SyntaxToken() : base(SyntaxKind.Token) { } public SyntaxToken(TokenKind tokenKind, string? text) : this() { TokenKind = tokenKind; Text = text; } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override SyntaxNode? GetChildImpl(int index) { return null; } protected override string ToDebuggerDisplay() { return $"{base.ToDebuggerDisplay()}: {TokenKind} {((Text != null) ? TomlFormatHelper.ToString(Text, TomlPropertyDisplayKind.Default) : string.Empty)}"; } } public sealed class SyntaxTrivia : SyntaxNodeBase { public TokenKind Kind { get; set; } public string? Text { get; set; } public SyntaxTrivia() { } public SyntaxTrivia(TokenKind kind, string text) { if (!kind.IsTrivia()) { throw new ArgumentOutOfRangeException("kind", $"The kind `{kind}` is not a trivia"); } Kind = kind; Text = text ?? throw new ArgumentNullException("text"); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + " " + ((Text != null) ? TomlFormatHelper.ToString(Text, TomlPropertyDisplayKind.Default) : string.Empty); } } internal class SyntaxValidator : SyntaxVisitor { private class ObjectPath : List<ObjectPathItem> { private int _hashCode; public void Add(string key) { _hashCode = (_hashCode * 397) ^ key.GetHashCode(); Add(new ObjectPathItem(key)); } public void Add(int index) { _hashCode = (_hashCode * 397) ^ index; Add(new ObjectPathItem(index)); } public ObjectPath Clone() { return (ObjectPath)MemberwiseClone(); } public override bool Equals(object? obj) { ObjectPath objectPath = obj as ObjectPath; if (objectPath?.Count != base.Count) { return false; } if (objectPath._hashCode != _hashCode) { return false; } for (int i = 0; i < base.Count; i++) { if (base[i] != objectPath[i]) { return false; } } return true; } public override int GetHashCode() { return _hashCode; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < base.Count; i++) { if (i > 0) { stringBuilder.Append('.'); } stringBuilder.Append(base[i]); } return stringBuilder.ToString(); } } [DebuggerDisplay("{Node} - {Kind}")] private class ObjectPathValue { public readonly SyntaxNode Node; public readonly ObjectKind Kind; public readonly bool IsImplicit; public readonly bool FromDottedKeys; public int ArrayIndex; public ObjectPathValue(SyntaxNode node, ObjectKind kind, bool isImplicit, bool fromDottedKeys) { FromDottedKeys = fromDottedKeys; Node = node; Kind = kind; IsImplicit = isImplicit; } } private readonly struct ObjectPathItem : IEquatable<ObjectPathItem> { public readonly string? Key; public readonly int Index; public ObjectPathItem(string key) { this = default(ObjectPathItem); Key = key; } public ObjectPathItem(int index) { this = default(ObjectPathItem); Index = index; } public bool Equals(ObjectPathItem other) { if (string.Equals(Key, other.Key)) { return Index == other.Index; } return false; } public override bool Equals(object? obj) { if (obj == null) { return false; } if (obj is ObjectPathItem other) { return Equals(other); } return false; } public override int GetHashCode() { return (((Key != null) ? Key.GetHashCode() : 0) * 397) ^ Index; } public static bool operator ==(ObjectPathItem left, ObjectPathItem right) { return left.Equals(right); } public static bool operator !=(ObjectPathItem left, ObjectPathItem right) { return !left.Equals(right); } public override string ToString() { return Key ?? $"[{Index}]"; } } private enum KeySource { Table, KeyValue } private readonly DiagnosticsBag _diagnostics; private ObjectPath _currentPath; private readonly Dictionary<ObjectPath, ObjectPathValue> _maps; private int _currentArrayIndex; public SyntaxValidator(DiagnosticsBag diagnostics) { _diagnostics = diagnostics ?? throw new ArgumentNullException("diagnostics"); _currentPath = new ObjectPath(); _maps = new Dictionary<ObjectPath, ObjectPathValue>(); } public override void Visit(KeyValueSyntax keyValue) { ObjectPath currentPath = _currentPath.Clone(); if (keyValue.Key == null) { _diagnostics.Error(keyValue.Span, "A KeyValueSyntax must have a non null Key"); } else { if (!KeyNameToObjectPath(keyValue.Key, ObjectKind.Table, fromDottedKeys: true)) { return; } ValueSyntax value = keyValue.Value; ObjectKind kind; if (!(value is ArraySyntax)) { if (!(value is BooleanValueSyntax)) { if (value is DateTimeValueSyntax dateTimeValueSyntax) { kind = dateTimeValueSyntax.Kind switch { SyntaxKind.OffsetDateTimeByZ => ObjectKind.OffsetDateTimeByZ, SyntaxKind.OffsetDateTimeByNumber => ObjectKind.OffsetDateTimeByNumber, SyntaxKind.LocalDateTime => ObjectKind.LocalDateTime, SyntaxKind.LocalDate => ObjectKind.LocalDate, SyntaxKind.LocalTime => ObjectKind.LocalTime, _ => throw new NotSupportedException($"Unsupported datetime kind `{dateTimeValueSyntax.Kind}` for the key-value `{keyValue}`"), }; } else if (!(value is FloatValueSyntax)) { if (!(value is InlineTableSyntax)) { if (!(value is IntegerValueSyntax)) { if (!(value is StringValueSyntax)) { _diagnostics.Error(keyValue.Span, (keyValue.Value == null) ? "A KeyValueSyntax must have a non null Value" : $"Not supported type `{keyValue.Value.Kind}` for the value of a KeyValueSyntax"); return; } kind = ObjectKind.String; } else { kind = ObjectKind.Integer; } } else { kind = ObjectKind.InlineTable; } } else { kind = ObjectKind.Float; } } else { kind = ObjectKind.Boolean; } } else { kind = ObjectKind.Array; } AddObjectPath(keyValue, kind, isImplicit: false, fromDottedKeys: true); base.Visit(keyValue); _currentPath = currentPath; } } public override void Visit(StringValueSyntax stringValue) { if (stringValue.Token == null) { _diagnostics.Error(stringValue.Span, "A StringValueSyntax must have a non null Token"); } base.Visit(stringValue); } public override void Visit(IntegerValueSyntax integerValue) { if (integerValue.Token == null) { _diagnostics.Error(integerValue.Span, "A IntegerValueSyntax must have a non null Token"); } base.Visit(integerValue); } public override void Visit(BooleanValueSyntax boolValue) { if (boolValue.Token == null) { _diagnostics.Error(boolValue.Span, "A BooleanValueSyntax must have a non null Token"); } base.Visit(boolValue); } public override void Visit(FloatValueSyntax floatValue) { if (floatValue.Token == null) { _diagnostics.Error(floatValue.Span, "A FloatValueSyntax must have a non null Token"); } base.Visit(floatValue); } public override void Visit(TableSyntax table) { VerifyTable(table); ObjectPath currentPath = _currentPath.Clone(); if (table.Name != null && KeyNameToObjectPath(table.Name, ObjectKind.Table)) { AddObjectPath(table, ObjectKind.Table, isImplicit: false, fromDottedKeys: false); base.Visit(table); _currentPath = currentPath; } } public override void Visit(TableArraySyntax table) { VerifyTable(table); ObjectPath currentPath = _currentPath.Clone(); if (table.Name != null && KeyNameToObjectPath(table.Name, ObjectKind.TableArray)) { ObjectPathValue objectPathValue = AddObjectPath(table, ObjectKind.TableArray, isImplicit: false, fromDottedKeys: false); int currentArrayIndex = _currentArrayIndex; _currentArrayIndex = objectPathValue.ArrayIndex; base.Visit(table); objectPathValue.ArrayIndex++; _currentArrayIndex = currentArrayIndex; _currentPath = currentPath; } } public override void Visit(BareKeySyntax bareKey) { if (bareKey.Key == null) { _diagnostics.Error(bareKey.Span, "A BareKeySyntax must have a non null property Key"); } base.Visit(bareKey); } public override void Visit(KeySyntax key) { if (key.Key == null) { _diagnostics.Error(key.Span, "A KeySyntax must have a non null property Key"); } base.Visit(key); } public override void Visit(DateTimeValueSyntax dateTime) { if (dateTime.Token == null) { _diagnostics.Error(dateTime.Span, "A DateTimeValueSyntax must have a non null Token"); } base.Visit(dateTime); } private void VerifyTable(TableSyntaxBase table) { bool flag = table is TableArraySyntax; if (table.OpenBracket == null) { _diagnostics.Error(table.Span, string.Format("The table{0} must have an {1} `{2}`", flag ? " array" : string.Empty, table.OpenTokenKind, table.OpenTokenKind.ToText())); } if (table.CloseBracket == null) { _diagnostics.Error(table.Span, string.Format("The table{0} must have an {1} `{2}`", flag ? " array" : string.Empty, table.CloseTokenKind, table.CloseTokenKind.ToText())); } if (table.EndOfLineToken == null && table.Items.ChildrenCount > 0) { _diagnostics.Error(table.Span, "The table" + (flag ? " array" : string.Empty) + " must have a EndOfLine set after the open/closing brackets and before any elements"); } if (table.Name == null) { _diagnostics.Error(table.Span, "The table" + (flag ? " array" : string.Empty) + " must have a name"); } } private bool KeyNameToObjectPath(KeySyntax key, ObjectKind kind, bool fromDottedKeys = false) { if (key.Key == null) { _diagnostics.Error(key.Span, "The property KeySyntax.Key cannot be null"); } string stringFromBasic = GetStringFromBasic(key.Key); if (string.IsNullOrWhiteSpace(stringFromBasic)) { return false; } _currentPath.Add(stringFromBasic); SyntaxList<DottedKeyItemSyntax> dotKeys = key.DotKeys; for (int i = 0; i < dotKeys.ChildrenCount; i++) { AddObjectPath(key, kind, isImplicit: true, fromDottedKeys); string stringFromBasic2 = GetStringFromBasic(dotKeys.GetChild(i).Key); if (string.IsNullOrWhiteSpace(stringFromBasic2)) { return false; } _currentPath.Add(stringFromBasic2); } return true; } private ObjectPathValue AddObjectPath(SyntaxNode node, ObjectKind kind, bool isImplicit, bool fromDottedKeys) { ObjectPath objectPath = _currentPath.Clone(); if (kind == ObjectKind.TableArray && isImplicit) { kind = ObjectKind.Table; } if (_maps.TryGetValue(objectPath, out ObjectPathValue value)) { bool num = kind != ObjectKind.Table || (value.IsImplicit && (!value.FromDottedKeys || (fromDottedKeys && value.FromDottedKeys))) || (isImplicit && !fromDottedKeys); bool flag = (value.Kind == ObjectKind.TableArray && (kind == ObjectKind.TableArray || (kind == ObjectKind.Table && isImplicit))) || (value.Kind == ObjectKind.Table && kind == ObjectKind.Table); if (!(num && flag)) { _diagnostics.Error(node.Span, $"The key `{objectPath}` is already defined at {value.Node.Span.Start} with `{value.Node.ToString().TrimEnd('\r', '\n').ToPrintableString()}` and cannot be redefined"); } else if (value.Kind == ObjectKind.TableArray) { _currentPath.Add(value.ArrayIndex); } } else { value = new ObjectPathValue(node, kind, isImplicit, fromDottedKeys); _maps.Add(objectPath, value); } return value; } private string? GetStringFromBasic(BareKeyOrStringValueSyntax value) { if (value is BareKeySyntax bareKeySyntax) { return bareKeySyntax.Key?.Text; } return ((StringValueSyntax)value).Value; } public override void Visit(ArraySyntax array) { int currentArrayIndex = _currentArrayIndex; if (array.OpenBracket == null) { _diagnostics.Error(array.Span, "The array must have an OpenBracket `[`"); } else if (array.CloseBracket == null) { _diagnostics.Error(array.Span, "The array must have an CloseBracket `[`"); } SyntaxList<ArrayItemSyntax> items = array.Items; for (int i = 0; i < items.ChildrenCount; i++) { ArrayItemSyntax child = items.GetChild(i); ValueSyntax value = child.Value; if (i == 0) { _ = value.Kind; } if (i + 1 < items.ChildrenCount && child.Comma == null) { _diagnostics.Error(child.Span, $"The array item [{i}] must have a comma `,`"); } } base.Visit(array); _currentArrayIndex = currentArrayIndex; } public override void Visit(InlineTableItemSyntax inlineTableItem) { base.Visit(inlineTableItem); } public override void Visit(ArrayItemSyntax arrayItem) { _currentPath.Add(_currentArrayIndex); if (arrayItem.Value == null) { _diagnostics.Error(arrayItem.Span, $"The array item [{_currentArrayIndex}] must have a non null value"); } base.Visit(arrayItem); _currentArrayIndex++; } public override void Visit(DottedKeyItemSyntax dottedKeyItem) { base.Visit(dottedKeyItem); } public override void Visit(InlineTableSyntax inlineTable) { base.Visit(inlineTable); } } public abstract class SyntaxVisitor { public virtual void Visit(SyntaxList list) { DefaultVisit(list); } public virtual void Visit(DocumentSyntax document) { DefaultVisit(document); } public virtual void Visit(KeyValueSyntax keyValue) { DefaultVisit(keyValue); } public virtual void Visit(StringValueSyntax stringValue) { DefaultVisit(stringValue); } public virtual void Visit(IntegerValueSyntax integerValue) { DefaultVisit(integerValue); } public virtual void Visit(BooleanValueSyntax boolValue) { DefaultVisit(boolValue); } public virtual void Visit(FloatValueSyntax floatValue) { DefaultVisit(floatValue); } public virtual void Visit(TableSyntax table) { DefaultVisit(table); } public virtual void Visit(TableArraySyntax table) { DefaultVisit(table); } public virtual void Visit(SyntaxToken token) { DefaultVisit(token); } public virtual void Visit(SyntaxTrivia trivia) { } public virtual void Visit(BareKeySyntax bareKey) { DefaultVisit(bareKey); } public virtual void Visit(KeySyntax key) { DefaultVisit(key); } public virtual void Visit(DateTimeValueSyntax dateTime) { DefaultVisit(dateTime); } public virtual void Visit(ArraySyntax array) { DefaultVisit(array); } public virtual void Visit(InlineTableItemSyntax inlineTableItem) { DefaultVisit(inlineTableItem); } public virtual void Visit(ArrayItemSyntax arrayItem) { DefaultVisit(arrayItem); } public virtual void Visit(DottedKeyItemSyntax dottedKeyItem) { DefaultVisit(dottedKeyItem); } public virtual void Visit(InlineTableSyntax inlineTable) { DefaultVisit(inlineTable); } public virtual void DefaultVisit(SyntaxNode? node) { if (node != null) { VisitTrivias(node.LeadingTrivia); for (int i = 0; i < node.ChildrenCount; i++) { node.GetChild(i)?.Accept(this); } VisitTrivias(node.TrailingTrivia); } } private void VisitTrivias(List<SyntaxTrivia>? trivias) { if (trivias == null) { return; } foreach (SyntaxTrivia trivia in trivias) { trivia?.Accept(this); } } } public sealed class TableArraySyntax : TableSyntaxBase { internal override TokenKind OpenTokenKind => TokenKind.OpenBracketDouble; internal override TokenKind CloseTokenKind => TokenKind.CloseBracketDouble; public TableArraySyntax() : base(SyntaxKind.TableArray) { } public TableArraySyntax(string name) : this() { if (name == null) { throw new ArgumentNullException("name"); } base.Name = new KeySyntax(name); base.OpenBracket = SyntaxFactory.Token(TokenKind.OpenBracketDouble); base.CloseBracket = SyntaxFactory.Token(TokenKind.CloseBracketDouble); base.EndOfLineToken = SyntaxFactory.NewLine(); } public TableArraySyntax(KeySyntax name) : this() { base.Name = name ?? throw new ArgumentNullException("name"); base.OpenBracket = SyntaxFactory.Token(TokenKind.OpenBracketDouble); base.CloseBracket = SyntaxFactory.Token(TokenKind.CloseBracketDouble); base.EndOfLineToken = SyntaxFactory.NewLine(); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + " [[" + ((base.Name != null) ? base.Name.ToString() : string.Empty) + "]]"; } } public sealed class TableSyntax : TableSyntaxBase { internal override TokenKind OpenTokenKind => TokenKind.OpenBracket; internal override TokenKind CloseTokenKind => TokenKind.CloseBracket; public TableSyntax() : base(SyntaxKind.Table) { } public TableSyntax(string name) : this() { if (name == null) { throw new ArgumentNullException("name"); } base.OpenBracket = SyntaxFactory.Token(TokenKind.OpenBracket); base.Name = new KeySyntax(name); base.CloseBracket = SyntaxFactory.Token(TokenKind.CloseBracket); base.EndOfLineToken = SyntaxFactory.NewLine(); } public TableSyntax(KeySyntax name) : this() { base.Name = name ?? throw new ArgumentNullException("name"); base.OpenBracket = SyntaxFactory.Token(TokenKind.OpenBracket); base.CloseBracket = SyntaxFactory.Token(TokenKind.CloseBracket); base.EndOfLineToken = SyntaxFactory.NewLine(); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } protected override string ToDebuggerDisplay() { return base.ToDebuggerDisplay() + " [" + ((base.Name != null) ? base.Name.ToString() : string.Empty) + "]"; } } public abstract class TableSyntaxBase : SyntaxNode { private SyntaxToken? _openBracket; private KeySyntax? _name; private SyntaxToken? _closeBracket; private SyntaxToken? _endOfLineToken; public SyntaxToken? OpenBracket { get { return _openBracket; } set { ParentToThis(ref _openBracket, value, OpenTokenKind); } } public KeySyntax? Name { get { return _name; } set { ParentToThis(ref _name, value); } } public SyntaxToken? CloseBracket { get { return _closeBracket; } set { ParentToThis(ref _closeBracket, value, CloseTokenKind); } } public SyntaxToken? EndOfLineToken { get { return _endOfLineToken; } set { ParentToThis(ref _endOfLineToken, value, TokenKind.NewLine, TokenKind.Eof); } } public SyntaxList<KeyValueSyntax> Items { get; } public override int ChildrenCount => 5; internal abstract TokenKind OpenTokenKind { get; } internal abstract TokenKind CloseTokenKind { get; } internal TableSyntaxBase(SyntaxKind kind) : base(kind) { Items = new SyntaxList<KeyValueSyntax> { Parent = this }; } protected override SyntaxNode? GetChildImpl(int index) { return index switch { 0 => OpenBracket, 1 => Name, 2 => CloseBracket, 3 => EndOfLineToken, _ => Items, }; } } public struct TextPosition : IEquatable<TextPosition> { public static readonly TextPosition Eof = new TextPosition(-1, -1, -1); public int Offset { get; set; } public int Column { get; set; } public int Line { get; set; } public TextPosition(int offset, int line, int column) { Offset = offset; Column = column; Line = line; } public override string ToString() { return $"({Line + 1},{Column + 1})"; } public bool Equals(TextPosition other) { if (Offset == other.Offset && Column == other.Column) { return Line == other.Line; } return false; } public override bool Equals(object? obj) { if (obj == null) { return false; } if (obj is TextPosition) { return Equals((TextPosition)obj); } return false; } public override int GetHashCode() { return Offset; } public static bool operator ==(TextPosition left, TextPosition right) { return left.Equals(right); } public static bool operator !=(TextPosition left, TextPosition right) { return !left.Equals(right); } } public enum TokenKind { Invalid, Eof, Whitespaces, NewLine, Comment, OffsetDateTimeByZ, OffsetDateTimeByNumber, LocalDateTime, LocalDate, LocalTime, Integer, IntegerHexa, IntegerOctal, IntegerBinary, Float, String, StringMulti, StringLiteral, StringLiteralMulti, Comma, Dot, Equal, OpenBracket, OpenBracketDouble, CloseBracket, CloseBracketDouble, OpenBrace, CloseBrace, True, False, Infinite, PositiveInfinite, NegativeInfinite, Nan, PositiveNan, NegativeNan, BasicKey } public static class TokenKindExtensions { public static bool IsHidden(this TokenKind tokenKind, bool hideNewLine = true) { if (tokenKind != TokenKind.Whitespaces && tokenKind != TokenKind.Comment) { return tokenKind == TokenKind.NewLine && hideNewLine; } return true; } public static string? ToText(this TokenKind kind) { return kind switch { TokenKind.Comma => ",", TokenKind.Dot => ".", TokenKind.Equal => "=", TokenKind.OpenBracket => "[", TokenKind.OpenBracketDouble => "[[", TokenKind.CloseBracket => "]", TokenKind.CloseBracketDouble => "]]", TokenKind.OpenBrace => "{", TokenKind.CloseBrace => "}", TokenKind.True => "true", TokenKind.False => "false", TokenKind.Infinite => "inf", TokenKind.PositiveInfinite => "+inf", TokenKind.NegativeInfinite => "-inf", TokenKind.Nan => "nan", TokenKind.PositiveNan => "+nan", TokenKind.NegativeNan => "-nan", _ => null, }; } public static bool IsFloat(this TokenKind kind) { if (kind == TokenKind.Float || (uint)(kind - 30) <= 5u) { return true; } return false; } public static bool IsInteger(this TokenKind kind) { if ((uint)(kind - 10) <= 3u) { return true; } return false; } public static bool IsDateTime(this TokenKind kind) { if ((uint)(kind - 5) <= 4u) { return true; } return false; } public static bool IsString(this TokenKind kind) { if ((uint)(kind - 15) <= 3u) { return true; } return false; } public static bool IsTrivia(this TokenKind kind) { if ((uint)(kind - 2) <= 2u) { return true; } return false; } public static bool IsToken(this TokenKind kind) { if (kind == TokenKind.NewLine || (uint)(kind - 19) <= 16u) { return true; } return false; } } public abstract class ValueSyntax : SyntaxNode { internal ValueSyntax(SyntaxKind kind) : base(kind) { } } } namespace Tomlyn.Parsing { internal interface ITokenProvider<out TSourceView> where TSourceView : ISourceView { bool HasErrors { get; } TSourceView Source { get; } LexerState State { get; set; } SyntaxTokenValue Token { get; } IEnumerable<DiagnosticMessage> Errors { get; } bool MoveNext(); } internal class Lexer<TSourceView, TCharReader> : ITokenProvider<TSourceView> where TSourceView : struct, ISourceView<TCharReader> where TCharReader : struct, CharacterIterator { private SyntaxTokenValue _token; private List<DiagnosticMessage>? _errors; private TCharReader _reader; private const int Eof = -1; private TSourceView _sourceView; private readonly StringBuilder _textBuilder; private readonly List<char32> _currentIdentifierChars; private LexerInternalState? _preview1; private LexerInternalState _current; public TSourceView Source => _sourceView; public bool HasErrors { get { if (_errors != null) { return _errors.Count > 0; } return false; } } public IEnumerable<DiagnosticMessage> Errors { get { IEnumerable<DiagnosticMessage> errors = _errors; return errors ?? Enumerable.Empty<DiagnosticMessage>(); } } public SyntaxTokenValue Token => _token; public LexerState State { get; set; } private TextPosition _position => _current.Position; private char32 _c => _current.CurrentChar; public Lexer(TSourceView sourceView) { _sourceView = sourceView; _reader = sourceView.GetIterator(); _currentIdentifierChars = new List<char32>(); _textBuilder = new StringBuilder(); Reset(); } public bool MoveNext() { if (_token.Kind == TokenKind.Eof) { return false; } if (State == LexerState.Key) { NextTokenForKey(); } else { NextTokenForValue(); } return true; } private void NextTokenForKey() { TextPosition position = _position; switch (_c) { case 10L: _token = new SyntaxTokenValue(TokenKind.NewLine, position, position); NextChar(); return; case 13L: NextChar(); if ((int)_c == 10) { _token = new SyntaxTokenValue(TokenKind.NewLine, position, _position); NextChar(); } else { AddError("Invalid \\r not followed by \\n", position, position); _token = new SyntaxTokenValue(TokenKind.NewLine, position, position); } return; case 35L: NextChar(); ReadComment(position); return; case 46L: NextChar(); _token = new SyntaxTokenValue(TokenKind.Dot, position, position); return; case 61L: NextChar(); _token = new SyntaxTokenValue(TokenKind.Equal, position, position); return; case 123L: _token = new SyntaxTokenValue(TokenKind.OpenBrace, _position, _position); NextChar(); return; case 125L: _token = new SyntaxTokenValue(TokenKind.CloseBrace, _position, _position); NextChar(); return; case 91L: NextChar(); if ((int)_c == 91) { _token = new SyntaxTokenValue(TokenKind.OpenBracketDouble, position, _position); NextChar(); } else { _token = new SyntaxTokenValue(TokenKind.OpenBracket, position, position); } return; case 93L: NextChar(); if ((int)_c == 93) { _token = new SyntaxTokenValue(TokenKind.CloseBracketDouble, position, _position); NextChar(); } else { _token = new SyntaxTokenValue(TokenKind.CloseBracket, position, position); } return; case 34L: ReadString(position, allowMultiline: false); return; case 39L: ReadStringLiteral(position, allowMultiline: false); return; case -1L: _token = new SyntaxTokenValue(TokenKind.Eof, _position, _position); return; } if (!ConsumeWhitespace()) { if (CharHelper.IsKeyStart(_c)) { ReadKey(); return; } _token = new SyntaxTokenValue(TokenKind.Invalid, _position, _position); NextChar(); } } private void NextTokenForValue() { TextPosition position = _position; switch (_c) { case 10L: _token = new SyntaxTokenValue(TokenKind.NewLine, position, _position); NextChar(); return; case 13L: NextChar(); if ((int)_c == 10) { _token = new SyntaxTokenValue(TokenKind.NewLine, position, _position); NextChar(); } else { _token = new SyntaxTokenValue(TokenKind.NewLine, position, position); } return; case 35L: NextChar(); ReadComment(position); return; case 44L: _token = new SyntaxTokenValue(TokenKind.Comma, position, position); NextChar(); return; case 91L: NextChar(); _token = new SyntaxTokenValue(TokenKind.OpenBracket, position, position); return; case 93L: NextChar(); _token = new SyntaxTokenValue(TokenKind.CloseBracket, position, position); return; case 123L: _token = new SyntaxTokenValue(TokenKind.OpenBrace, _position, _position); NextChar(); return; case 125L: _token = new SyntaxTokenValue(TokenKind.CloseBrace, _position, _position); NextChar(); return; case 34L: ReadString(position, allowMultiline: true); return; case 39L: ReadStringLiteral(position, allowMultiline: true); return; case -1L: _token = new SyntaxTokenValue(TokenKind.Eof, _position, _position); return; } if (!ConsumeWhitespace()) { if ((int)_c == 43 || (int)_c == 45 || CharHelper.IsIdentifierStart(_c)) { ReadSpecialToken(); return; } if (CharHelper.IsDigit(_c)) { ReadNumberOrDate(); return; } _token = new SyntaxTokenValue(TokenKind.Invalid, _position, _position); NextChar(); } } private bool ConsumeWhitespace() { TextPosition position = _position; TextPosition position2 = _position; while (CharHelper.IsWhiteSpace(_c)) { position2 = _position; NextChar(); } if (position != _position) { _token = new SyntaxTokenValue(TokenKind.Whitespaces, position, position2); return true; } return false; } private void ReadKey() { TextPosition position = _position; TextPosition position2 = _position; while (CharHelper.IsKeyContinue(_c)) { position2 = _position; NextChar(); } _token = new SyntaxTokenValue(TokenKind.BasicKey, position, position2); } private void ReadSpecialToken() { TextPosition position = _position; TextPosition position2 = _position; _currentIdentifierChars.Clear(); char32 c = _c; _currentIdentifierChars.Add(_c); NextChar(); if (((int)c == 43 || (int)c == 45) && CharHelper.IsDigit(_c)) { _currentIdentifierChars.Clear(); ReadNumberOrDate(c, position); return; } while (CharHelper.IsIdentifierContinue(_c)) { _currentIdentifierChars.Add(_c); position2 = _position; NextChar(); } if (MatchCurrentIdentifier("true")) { _token = new SyntaxTokenValue(TokenKind.True, position, position2, BoxedValues.True); } else if (MatchCurrentIdentifier("false")) { _token = new SyntaxTokenValue(TokenKind.False, position, position2, BoxedValues.False); } else if (MatchCurrentIdentifier("inf")) { _token = new SyntaxTokenValue(TokenKind.Infinite, position, position2, BoxedValues.FloatPositiveInfinity); } else if (MatchCurrentIdentifier("+inf")) { _token = new SyntaxTokenValue(TokenKind.PositiveInfinite, position, position2, BoxedValues.FloatPositiveInfinity); } else if (MatchCurrentIdentifier("-inf")) { _token = new SyntaxTokenValue(TokenKind.NegativeInfinite, position, position2, BoxedValues.FloatNegativeInfinity); } else if (MatchCurrentIdentifier("nan")) { _token = new SyntaxTokenValue(TokenKind.Nan, position, position2, BoxedValues.FloatNan); } else if (MatchCurrentIdentifier("+nan")) { _token = new SyntaxTokenValue(TokenKind.PositiveNan, position, position2, BoxedValues.FloatPositiveNaN); } else if (MatchCurrentIdentifier("-nan")) { _token = new SyntaxTokenValue(TokenKind.NegativeNan, position, position2, BoxedValues.FloatNegativeNaN); } else { _token = new SyntaxTokenValue(TokenKind.Invalid, position, position2); } _currentIdentifierChars.Clear(); } private bool MatchCurrentIdentifier(string text) { if (_currentIdentifierChars.Count != text.Length) { return false; } for (int i = 0; i < text.Length; i++) { if ((int)_currentIdentifierChars[i] != text[i]) { return false; } } return true; } private void ReadNumberOrDate(char32? signPrefix = null, TextPosition? signPrefixPos = null) { TextPosition textPosition = signPrefixPos ?? _position; TextPosition end = _position; bool flag = false; TextPosition position = _position; bool hasValue = signPrefix.HasValue; bool flag2 = (int)_c == 48; _textBuilder.Length = 0; if (hasValue) { _textBuilder.AppendUtf32(signPrefix.Value); } if (flag2) { NextChar(); if (!hasValue && ((int)_c == 120 || (int)_c == 88 || (int)_c == 111 || (int)_c == 79 || (int)_c == 98 || (int)_c == 66)) { string text; string text2; string text3; Func<char32, bool> func; Func<char32, int> func2; int num; TokenKind kind; if ((int)_c == 120 || (int)_c == 88) { text = "hexadecimal"; text2 = "[0-9a-zA-Z]"; text3 = "0x"; func = CharHelper.IsHexFunc; func2 = CharHelper.HexToDecFunc; num = 4; kind = TokenKind.IntegerHexa; if ((int)_c == 88) { AddError("Invalid capital X for hexadecimal. Use `x` instead.", _position, _position); } } else if ((int)_c == 111 || (int)_c == 79) { text = "octal"; text2 = "[0-7]"; text3 = "0o"; func = CharHelper.IsOctalFunc; func2 = CharHelper.OctalToDecFunc; num = 3; kind = TokenKind.IntegerOctal; if ((int)_c == 79) { AddError("Invalid capital O for octal. Use `o` instead.", _position, _position); } } else { text = "binary"; text2 = "0 or 1"; text3 = "0b"; func = CharHelper.IsBinaryFunc; func2 = CharHelper.BinaryToDecFunc; num = 1; kind = TokenKind.IntegerBinary; if ((int)_c == 66) { AddError("Invalid capital B for binary. Use `b` instead.", _position, _position); } } end = _position; NextChar(); int num2 = 64 / num; int num3 = num2; bool flag3 = false; bool flag4 = false; ulong num4 = 0uL; while (true) { bool flag5 = false; if ((int)_c != 95 && !(flag5 = func(_c))) { break; } bool flag6 = (int)_c != 95; if (!flag4 && !flag6) { AddError("An underscore must be surrounded by at least one " + text + " digit on each side", textPosition, textPosition); } else if (flag6) { num4 = (num4 << num) + (ulong)func2(_c); num3--; if (num3 == -1) { AddError($"Invalid size of {text} integer. Expecting less than or equal {num2} {text} digits", textPosition, textPosition); } } flag4 = flag6; if (flag5) { flag3 = true; } end = _position; NextChar(); } if (!flag3) { AddError("Invalid " + text + " integer. Expecting at least one " + text2 + " after " + text3, textPosition, textPosition); _token = new SyntaxTokenValue(TokenKind.Invalid, textPosition, end); } else if (!flag4) { AddError("Invalid " + text + " integer. Expecting a " + text2 + " after the last character", textPosition, textPosition); _token = new SyntaxTokenValue(TokenKind.Invalid, textPosition, end); } else { _token = new SyntaxTokenValue(kind, textPosition, end, (long)num4); } return; } _textBuilder.Append('0'); } TextPosition position2 = _position; bool flag7 = false; bool flag8 = false; if (flag2) { int num5 = 0; flag8 = true; while ((int)_c == 48 || (int)_c == 95) { flag8 = (int)_c == 48; if (flag8) { _textBuilder.Append((char)(int)_c); num5++; } end = _position; NextChar(); } flag7 = num5 > 0; } ReadDigits(ref end, flag8); if ((int)_c == 45 || (int)_c == 58) { while (CharHelper.IsDateTime(_c)) { _textBuilder.AppendUtf32(_c); end = _position; NextChar(); } if (CharHelper.IsWhiteSpace(_c) && CharHelper.IsDateTime(PeekChar())) { _textBuilder.AppendUtf32(_c); NextChar(); while (CharHelper.IsDateTime(_c)) { _textBuilder.AppendUtf32(_c); end = _position; NextChar(); } } string text4 = _textBuilder.ToString(); if (hasValue) { AddError($"Invalid prefix `{signPrefix.Value}` for the following offset/local date/time `{text4}`", textPosition, end); text4 = text4.Substring(1); } DateTime result; if (DateTimeRFC3339.TryParseOffsetDateTime(text4, out var time)) { TokenKind kind2 = ((time.Kind == TomlDateTimeKind.OffsetDateTimeByZ) ? TokenKind.OffsetDateTimeByZ : TokenKind.OffsetDateTimeByNumber); _token = new SyntaxTokenValue(kind2, textPosition, end, time); } else if (DateTimeRFC3339.TryParseLocalDateTime(text4, out time)) { _token = new SyntaxTokenValue(TokenKind.LocalDateTime, textPosition, end, time); } else if (DateTimeRFC3339.TryParseLocalDate(text4, out time)) { _token = new SyntaxTokenValue(TokenKind.LocalDate, textPosition, end, time); } else if (DateTimeRFC3339.TryParseLocalTime(text4, out time)) { _token = new SyntaxTokenValue(TokenKind.LocalTime, textPosition, end, time); } else if (DateTime.TryParse(text4, CultureInfo.InvariantCulture, DateTimeStyles.AllowInnerWhite, out result)) { _token = new SyntaxTokenValue(value: new TomlDateTime(result, 0, TomlDateTimeKind.LocalDateTime), kind: TokenKind.LocalDateTime, start: textPosition, end: end); AddError("Invalid format of date time/offset `" + text4 + "` not following RFC3339", textPosition, end); } else { _token = new SyntaxTokenValue(value: new TomlDateTime(DateTimeOffset.MinValue, 0, TomlDateTimeKind.LocalDateTime), kind: TokenKind.LocalDateTime, start: textPosition, end: end); AddError("Unable to parse the date time/offset `" + text4 + "`", textPosition, end); } return; } if (flag7) { AddError("Multiple leading 0 are not allowed", position2, position2); } if ((int)_c == 46) { _textBuilder.Append('.'); end = _position; NextChar(); if (!CharHelper.IsDigit(_c)) { AddError("Expecting at least one digit after the float dot .", _position, _position); _token = new SyntaxTokenValue(TokenKind.Invalid, textPosition, end); return; } flag = true; ReadDigits(ref end, isPreviousDigit: false); } if ((int)_c == 101 || (int)_c == 69) { flag = true; _textBuilder.AppendUtf32(_c); end = _position; NextChar(); if ((int)_c == 43 || (int)_c == 45) { _textBuilder.AppendUtf32(_c); end = _position; NextChar(); } if (!CharHelper.IsDigit(_c)) { AddError("Expecting at least one digit after the exponent", _position, _position); _token = new SyntaxTokenValue(TokenKind.Invalid, textPosition, end); return; } ReadDigits(ref end, isPreviousDigit: false); } string text5 = _textBuilder.ToString(); object value3; if (flag) { if (!double.TryParse(text5, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { AddError("Unable to parse floating point `" + text5 + "`", textPosition, end); } if ((int)result2 != 0 && flag2) { AddError("Unexpected leading zero (`0`) for float `" + text5 + "`", position, position); } value3 = ((result2 == 0.0) ? BoxedValues.FloatZero : ((result2 == 1.0) ? BoxedValues.FloatOne : ((object)result2))); } else { if (!long.TryParse(text5, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result3)) { if (!ulong.TryParse(text5, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result4)) { AddError("Unable to parse integer `" + text5 + "`", textPosition, end); } else { result3 = (long)result4; } } if (flag2 &
MegabonkTogether/Microsoft.Extensions.Logging.Console.dll
Decompiled 2 hours agousing System; using System.Buffers; 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.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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Console.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Console")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Console logger provider implementation for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.Console")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } 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 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 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; [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool GetConsoleMode(IntPtr handle, out int mode); internal static bool IsGetConsoleModeCallSuccessful(IntPtr handle) { int mode; return GetConsoleMode(handle, out mode); } [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool SetConsoleMode(IntPtr handle, int mode); [DllImport("kernel32.dll")] internal static extern IntPtr GetStdHandle(int nStdHandle); } } namespace FxResources.Microsoft.Extensions.Logging.Console { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Text.Json { internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, IDisposable { private byte[] _rentedBuffer; private int _index; private const int MinimumBufferSize = 256; public ReadOnlyMemory<byte> WrittenMemory => _rentedBuffer.AsMemory(0, _index); public int WrittenCount => _index; public int Capacity => _rentedBuffer.Length; public int FreeCapacity => _rentedBuffer.Length - _index; public PooledByteBufferWriter(int initialCapacity) { _rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } public void Clear() { ClearHelper(); } private void ClearHelper() { _rentedBuffer.AsSpan(0, _index).Clear(); _index = 0; } public void Dispose() { if (_rentedBuffer != null) { ClearHelper(); byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = null; ArrayPool<byte>.Shared.Return(rentedBuffer); } } public void Advance(int count) { _index += count; } public Memory<byte> GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _rentedBuffer.AsMemory(_index); } public Span<byte> GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); return _rentedBuffer.AsSpan(_index); } internal Task WriteToStreamAsync(Stream destination, CancellationToken cancellationToken) { return destination.WriteAsync(_rentedBuffer, 0, _index, cancellationToken); } internal void WriteToStream(Stream destination) { destination.Write(_rentedBuffer, 0, _index); } private void CheckAndResizeBuffer(int sizeHint) { 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) { System.Text.Json.ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4); } } byte[] rentedBuffer = _rentedBuffer; _rentedBuffer = ArrayPool<byte>.Shared.Rent(num4); Span<byte> span = rentedBuffer.AsSpan(0, _index); span.CopyTo(_rentedBuffer); span.Clear(); ArrayPool<byte>.Shared.Return(rentedBuffer); } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.NoInlining)] [DoesNotReturn] public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity) { throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity)); } } } namespace Microsoft.Extensions.Logging { [UnsupportedOSPlatform("browser")] public static class ConsoleLoggerExtensions { internal const string TrimmingRequiresUnreferencedCodeMessage = "TOptions's dependent types may have their members trimmed. Ensure all required members are preserved."; [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) { builder.AddConfiguration(); builder.AddConsoleFormatter<JsonConsoleFormatter, JsonConsoleFormatterOptions>(); builder.AddConsoleFormatter<SystemdConsoleFormatter, ConsoleFormatterOptions>(); builder.AddConsoleFormatter<SimpleConsoleFormatter, SimpleConsoleFormatterOptions>(); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, ConsoleLoggerProvider>()); LoggerProviderOptions.RegisterProviderOptions<ConsoleLoggerOptions, ConsoleLoggerProvider>(builder.Services); return builder; } public static ILoggingBuilder AddConsole(this ILoggingBuilder builder, Action<ConsoleLoggerOptions> configure) { if (configure == null) { throw new ArgumentNullException("configure"); } builder.AddConsole(); builder.Services.Configure(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("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("json", configure); } public static ILoggingBuilder AddSystemdConsole(this ILoggingBuilder builder, Action<ConsoleFormatterOptions> configure) { return builder.AddConsoleWithFormatter("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 { if (configure == null) { throw new ArgumentNullException("configure"); } builder.AddFormatterWithName(name); builder.Services.Configure(configure); return builder; } private static ILoggingBuilder AddFormatterWithName(this ILoggingBuilder builder, string name) { return builder.AddConsole(delegate(ConsoleLoggerOptions options) { options.FormatterName = name; }); } [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TFormatter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this ILoggingBuilder builder) where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions { builder.AddConfiguration(); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ConsoleFormatter, TFormatter>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<TOptions>, ConsoleLoggerFormatterConfigureOptions<TFormatter, TOptions>>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IOptionsChangeTokenSource<TOptions>, ConsoleLoggerFormatterOptionsChangeTokenSource<TFormatter, TOptions>>()); return builder; } [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TFormatter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this ILoggingBuilder builder, Action<TOptions> configure) where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions { if (configure == null) { throw new ArgumentNullException("configure"); } builder.AddConsoleFormatter<TFormatter, TOptions>(); builder.Services.Configure(configure); return builder; } } [UnsupportedOSPlatform("browser")] internal sealed class ConsoleLoggerFormatterConfigureOptions<TFormatter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions> : ConfigureFromConfigurationOptions<TOptions> where TFormatter : ConsoleFormatter where TOptions : ConsoleFormatterOptions { [RequiresUnreferencedCode("TOptions's dependent types may have their members trimmed. Ensure all required members are preserved.")] public ConsoleLoggerFormatterConfigureOptions(ILoggerProviderConfiguration<ConsoleLoggerProvider> providerConfiguration) : base((IConfiguration)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) : base((IConfiguration)providerConfiguration.Configuration.GetSection("FormatterOptions")) { } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { public static IExternalScopeProvider Instance { get; } = new Microsoft.Extensions.Logging.NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } IDisposable IExternalScopeProvider.Push(object state) { return Microsoft.Extensions.Logging.NullScope.Instance; } } internal sealed class NullScope : IDisposable { public static Microsoft.Extensions.Logging.NullScope Instance { get; } = new Microsoft.Extensions.Logging.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 ? System.Console.Error : System.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) { if (onParseWrite == null) { throw new ArgumentNullException("onParseWrite"); } _onParseWrite = onParseWrite; } public void Parse(string message) { int num = -1; int arg = 0; ConsoleColor? arg2 = null; ConsoleColor? arg3 = null; ReadOnlySpan<char> readOnlySpan = message.AsSpan(); ConsoleColor? color = null; bool isBright = false; int num2; for (num2 = 0; num2 < readOnlySpan.Length; num2++) { if (readOnlySpan[num2] == '\u001b' && readOnlySpan.Length >= num2 + 4 && readOnlySpan[num2 + 1] == '[') { if (readOnlySpan[num2 + 3] == 'm') { if (IsDigit(readOnlySpan[num2 + 2])) { int num3 = readOnlySpan[num2 + 2] - 48; if (num != -1) { _onParseWrite(message, num, arg, arg3, arg2); num = -1; arg = 0; } if (num3 == 1) { isBright = true; } num2 += 3; continue; } } else if (readOnlySpan.Length >= num2 + 5 && readOnlySpan[num2 + 4] == 'm' && IsDigit(readOnlySpan[num2 + 2]) && IsDigit(readOnlySpan[num2 + 3])) { int num3 = (readOnlySpan[num2 + 2] - 48) * 10 + (readOnlySpan[num2 + 3] - 48); if (num != -1) { _onParseWrite(message, num, arg, arg3, arg2); num = -1; arg = 0; } if (TryGetForegroundColor(num3, isBright, out color)) { arg2 = color; isBright = false; } else if (TryGetBackgroundColor(num3, out color)) { arg3 = color; } num2 += 4; continue; } } if (num == -1) { num = num2; } int num4 = -1; if (num2 < message.Length - 1) { num4 = message.IndexOf('\u001b', num2 + 1); } if (num4 < 0) { arg = message.Length - num; break; } arg = num4 - num; num2 = num4 - 1; } if (num != -1) { _onParseWrite(message, num, arg, arg3, arg2); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsDigit(char c) { return (uint)(c - 48) <= 9u; } internal static string GetForegroundColorEscapeCode(ConsoleColor color) { return color switch { ConsoleColor.Black => "\u001b[30m", ConsoleColor.DarkRed => "\u001b[31m", ConsoleColor.DarkGreen => "\u001b[32m", ConsoleColor.DarkYellow => "\u001b[33m", ConsoleColor.DarkBlue => "\u001b[34m", ConsoleColor.DarkMagenta => "\u001b[35m", ConsoleColor.DarkCyan => "\u001b[36m", ConsoleColor.Gray => "\u001b[37m", ConsoleColor.Red => "\u001b[1m\u001b[31m", ConsoleColor.Green => "\u001b[1m\u001b[32m", ConsoleColor.Yellow => "\u001b[1m\u001b[33m", ConsoleColor.Blue => "\u001b[1m\u001b[34m", ConsoleColor.Magenta => "\u001b[1m\u001b[35m", ConsoleColor.Cyan => "\u001b[1m\u001b[36m", ConsoleColor.White => "\u001b[1m\u001b[37m", _ => "\u001b[39m\u001b[22m", }; } internal static string GetBackgroundColorEscapeCode(ConsoleColor color) { return color switch { ConsoleColor.Black => "\u001b[40m", ConsoleColor.DarkRed => "\u001b[41m", ConsoleColor.DarkGreen => "\u001b[42m", ConsoleColor.DarkYellow => "\u001b[43m", ConsoleColor.DarkBlue => "\u001b[44m", ConsoleColor.DarkMagenta => "\u001b[45m", ConsoleColor.DarkCyan => "\u001b[46m", ConsoleColor.Gray => "\u001b[47m", _ => "\u001b[49m", }; } private static bool TryGetForegroundColor(int number, bool isBright, out ConsoleColor? color) { color = number switch { 30 => ConsoleColor.Black, 31 => isBright ? ConsoleColor.Red : ConsoleColor.DarkRed, 32 => isBright ? ConsoleColor.Green : ConsoleColor.DarkGreen, 33 => isBright ? ConsoleColor.Yellow : ConsoleColor.DarkYellow, 34 => (!isBright) ? ConsoleColor.DarkBlue : ConsoleColor.Blue, 35 => isBright ? ConsoleColor.Magenta : ConsoleColor.DarkMagenta, 36 => isBright ? ConsoleColor.Cyan : ConsoleColor.DarkCyan, 37 => isBright ? ConsoleColor.White : ConsoleColor.Gray, _ => null, }; if (!color.HasValue) { return number == 39; } return true; } private static bool TryGetBackgroundColor(int number, out ConsoleColor? color) { color = number switch { 40 => ConsoleColor.Black, 41 => ConsoleColor.DarkRed, 42 => ConsoleColor.DarkGreen, 43 => ConsoleColor.DarkYellow, 44 => ConsoleColor.DarkBlue, 45 => ConsoleColor.DarkMagenta, 46 => ConsoleColor.DarkCyan, 47 => ConsoleColor.Gray, _ => 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 ? System.Console.Error : System.Console.Out); _parser = new AnsiParser(WriteToConsole); } public void Write(string message) { _parser.Parse(message); } private bool SetColor(ConsoleColor? background, ConsoleColor? foreground) { bool flag = SetBackgroundColor(background); return SetForegroundColor(foreground) || flag; } private bool SetBackgroundColor(ConsoleColor? background) { if (background.HasValue) { System.Console.BackgroundColor = background.Value; return true; } return false; } private bool SetForegroundColor(ConsoleColor? foreground) { if (foreground.HasValue) { System.Console.ForegroundColor = foreground.Value; return true; } return false; } private void ResetColor() { System.Console.ResetColor(); } private void WriteToConsole(string message, int startIndex, int length, ConsoleColor? background, ConsoleColor? foreground) { ReadOnlySpan<char> buffer = message.AsSpan(startIndex, length); bool flag = SetColor(background, foreground); _textWriter.Write(buffer); if (flag) { ResetColor(); } } } public abstract class ConsoleFormatter { public string Name { get; } protected ConsoleFormatter(string name) { Name = name ?? throw new ArgumentNullException("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 { public bool IncludeScopes { get; set; } public string TimestampFormat { get; set; } public bool UseUtcTimestamp { get; set; } } [UnsupportedOSPlatform("browser")] internal sealed class ConsoleLogger : ILogger { private readonly string _name; private readonly ConsoleLoggerProcessor _queueProcessor; [ThreadStatic] private static StringWriter t_stringWriter; internal ConsoleFormatter Formatter { get; set; } internal IExternalScopeProvider ScopeProvider { get; set; } internal ConsoleLoggerOptions Options { get; set; } internal ConsoleLogger(string name, ConsoleLoggerProcessor loggerProcessor) { if (name == null) { throw new ArgumentNullException("name"); } _name = name; _queueProcessor = loggerProcessor; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } if (formatter == null) { throw new ArgumentNullException("formatter"); } if (t_stringWriter == null) { t_stringWriter = new StringWriter(); } LogEntry<TState> logEntry = new LogEntry<TState>(logLevel, _name, eventId, state, exception, formatter); Formatter.Write(in logEntry, ScopeProvider, t_stringWriter); StringBuilder stringBuilder = t_stringWriter.GetStringBuilder(); if (stringBuilder.Length != 0) { string message = stringBuilder.ToString(); stringBuilder.Clear(); if (stringBuilder.Capacity > 1024) { stringBuilder.Capacity = 1024; } _queueProcessor.EnqueueMessage(new LogMessageEntry(message, logLevel >= Options.LogToStandardErrorThreshold)); } } public bool IsEnabled(LogLevel logLevel) { return logLevel != LogLevel.None; } public IDisposable BeginScope<TState>(TState state) { return ScopeProvider?.Push(state) ?? Microsoft.Extensions.Logging.NullScope.Instance; } } [Obsolete("ConsoleLoggerFormat has been deprecated.")] public enum ConsoleLoggerFormat { Default, Systemd } public class ConsoleLoggerOptions { private ConsoleLoggerFormat _format; [Obsolete("ConsoleLoggerOptions.DisableColors has been deprecated. Use SimpleConsoleFormatterOptions.ColorBehavior instead.")] public bool DisableColors { get; set; } [Obsolete("ConsoleLoggerOptions.Format has been deprecated. Use ConsoleLoggerOptions.FormatterName instead.")] public ConsoleLoggerFormat Format { get { return _format; } set { if (value < ConsoleLoggerFormat.Default || value > ConsoleLoggerFormat.Systemd) { throw new ArgumentOutOfRangeException("value"); } _format = value; } } public string FormatterName { get; set; } [Obsolete("ConsoleLoggerOptions.IncludeScopes has been deprecated. Use ConsoleFormatterOptions.IncludeScopes instead.")] public bool IncludeScopes { get; set; } public LogLevel LogToStandardErrorThreshold { get; set; } = LogLevel.None; [Obsolete("ConsoleLoggerOptions.TimestampFormat has been deprecated. Use ConsoleFormatterOptions.TimestampFormat instead.")] public string TimestampFormat { get; set; } [Obsolete("ConsoleLoggerOptions.UseUtcTimestamp has been deprecated. Use ConsoleFormatterOptions.UseUtcTimestamp instead.")] public bool UseUtcTimestamp { get; set; } } [UnsupportedOSPlatform("browser")] internal class ConsoleLoggerProcessor : IDisposable { private const int _maxQueuedMessages = 1024; private readonly BlockingCollection<LogMessageEntry> _messageQueue = new BlockingCollection<LogMessageEntry>(1024); private readonly Thread _outputThread; public IConsole Console; public IConsole ErrorConsole; public ConsoleLoggerProcessor() { _outputThread = new Thread(ProcessLogQueue) { IsBackground = true, Name = "Console logger queue processing thread" }; _outputThread.Start(); } public virtual void EnqueueMessage(LogMessageEntry message) { if (!_messageQueue.IsAddingCompleted) { try { _messageQueue.Add(message); return; } catch (InvalidOperationException) { } } try { WriteMessage(message); } catch (Exception) { } } internal virtual void WriteMessage(LogMessageEntry entry) { IConsole console = (entry.LogAsError ? ErrorConsole : Console); console.Write(entry.Message); } private void ProcessLogQueue() { try { foreach (LogMessageEntry item in _messageQueue.GetConsumingEnumerable()) { WriteMessage(item); } } catch { try { _messageQueue.CompleteAdding(); } catch { } } } public void Dispose() { _messageQueue.CompleteAdding(); try { _outputThread.Join(1500); } catch (ThreadStateException) { } } } [UnsupportedOSPlatform("browser")] [ProviderAlias("Console")] public class ConsoleLoggerProvider : ILoggerProvider, IDisposable, ISupportExternalScope { private readonly IOptionsMonitor<ConsoleLoggerOptions> _options; private readonly ConcurrentDictionary<string, ConsoleLogger> _loggers; private ConcurrentDictionary<string, ConsoleFormatter> _formatters; private readonly ConsoleLoggerProcessor _messageQueue; private IDisposable _optionsReloadToken; private IExternalScopeProvider _scopeProvider = Microsoft.Extensions.Logging.NullExternalScopeProvider.Instance; public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options) : this(options, Array.Empty<ConsoleFormatter>()) { } public ConsoleLoggerProvider(IOptionsMonitor<ConsoleLoggerOptions> options, IEnumerable<ConsoleFormatter> formatters) { _options = options; _loggers = new ConcurrentDictionary<string, ConsoleLogger>(); SetFormatters(formatters); ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = _options.OnChange(ReloadLoggerOptions); _messageQueue = new ConsoleLoggerProcessor(); if (DoesConsoleSupportAnsi()) { _messageQueue.Console = new AnsiLogConsole(); _messageQueue.ErrorConsole = new AnsiLogConsole(stdErr: true); } else { _messageQueue.Console = new AnsiParsingLogConsole(); _messageQueue.ErrorConsole = new AnsiParsingLogConsole(stdErr: true); } } [UnsupportedOSPlatformGuard("windows")] private static bool DoesConsoleSupportAnsi() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return true; } IntPtr stdHandle = global::Interop.Kernel32.GetStdHandle(-11); if (!global::Interop.Kernel32.GetConsoleMode(stdHandle, out var mode)) { return false; } return ((ulong)mode & 4uL) == 4; } private void SetFormatters(IEnumerable<ConsoleFormatter> formatters = null) { ConcurrentDictionary<string, ConsoleFormatter> concurrentDictionary = new ConcurrentDictionary<string, ConsoleFormatter>(StringComparer.OrdinalIgnoreCase); bool flag = false; if (formatters != null) { foreach (ConsoleFormatter formatter in formatters) { concurrentDictionary.TryAdd(formatter.Name, formatter); flag = true; } } if (!flag) { concurrentDictionary.TryAdd("simple", new SimpleConsoleFormatter(new FormatterOptionsMonitor<SimpleConsoleFormatterOptions>(new SimpleConsoleFormatterOptions()))); concurrentDictionary.TryAdd("systemd", new SystemdConsoleFormatter(new FormatterOptionsMonitor<ConsoleFormatterOptions>(new ConsoleFormatterOptions()))); concurrentDictionary.TryAdd("json", new JsonConsoleFormatter(new FormatterOptionsMonitor<JsonConsoleFormatterOptions>(new JsonConsoleFormatterOptions()))); } _formatters = concurrentDictionary; } private void ReloadLoggerOptions(ConsoleLoggerOptions options) { if (options.FormatterName == null || !_formatters.TryGetValue(options.FormatterName, out var value)) { ConsoleLoggerFormat format = options.Format; ConsoleFormatter consoleFormatter = ((format != ConsoleLoggerFormat.Systemd) ? _formatters["simple"] : _formatters["systemd"]); value = consoleFormatter; if (options.FormatterName == null) { UpdateFormatterOptions(value, options); } } foreach (KeyValuePair<string, ConsoleLogger> logger in _loggers) { logger.Value.Options = options; logger.Value.Formatter = value; } } public ILogger CreateLogger(string name) { if (_options.CurrentValue.FormatterName == null || !_formatters.TryGetValue(_options.CurrentValue.FormatterName, out var value)) { ConsoleLoggerFormat format = _options.CurrentValue.Format; ConsoleFormatter consoleFormatter = ((format != ConsoleLoggerFormat.Systemd) ? _formatters["simple"] : _formatters["systemd"]); value = consoleFormatter; if (_options.CurrentValue.FormatterName == null) { UpdateFormatterOptions(value, _options.CurrentValue); } } if (!_loggers.TryGetValue(name, out var value2)) { return _loggers.GetOrAdd(name, new ConsoleLogger(name, _messageQueue) { Options = _options.CurrentValue, ScopeProvider = _scopeProvider, Formatter = value }); } return value2; } private void UpdateFormatterOptions(ConsoleFormatter formatter, ConsoleLoggerOptions deprecatedFromOptions) { if (formatter is SimpleConsoleFormatter simpleConsoleFormatter) { simpleConsoleFormatter.FormatterOptions = new SimpleConsoleFormatterOptions { ColorBehavior = ((!deprecatedFromOptions.DisableColors) ? LoggerColorBehavior.Enabled : LoggerColorBehavior.Disabled), 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) { _scopeProvider = scopeProvider; foreach (KeyValuePair<string, ConsoleLogger> logger in _loggers) { logger.Value.ScopeProvider = _scopeProvider; } } } internal sealed class FormatterOptionsMonitor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] 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 IDisposable OnChange(Action<TOptions, string> listener) { return null; } } internal interface IConsole { void Write(string message); } internal sealed class JsonConsoleFormatter : ConsoleFormatter, IDisposable { private IDisposable _optionsReloadToken; internal JsonConsoleFormatterOptions FormatterOptions { get; set; } public JsonConsoleFormatter(IOptionsMonitor<JsonConsoleFormatterOptions> options) : base("json") { ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = options.OnChange(ReloadLoggerOptions); } public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider scopeProvider, TextWriter textWriter) { string text = logEntry.Formatter(logEntry.State, logEntry.Exception); if (logEntry.Exception == null && text == null) { return; } LogLevel logLevel = logEntry.LogLevel; string category = logEntry.Category; int id = logEntry.EventId.Id; Exception exception = logEntry.Exception; using (System.Text.Json.PooledByteBufferWriter pooledByteBufferWriter = new System.Text.Json.PooledByteBufferWriter(1024)) { using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(pooledByteBufferWriter, FormatterOptions.JsonWriterOptions)) { utf8JsonWriter.WriteStartObject(); string timestampFormat = FormatterOptions.TimestampFormat; if (timestampFormat != null) { utf8JsonWriter.WriteString("Timestamp", (FormatterOptions.UseUtcTimestamp ? DateTimeOffset.UtcNow : DateTimeOffset.Now).ToString(timestampFormat)); } utf8JsonWriter.WriteNumber("EventId", id); utf8JsonWriter.WriteString("LogLevel", GetLogLevelString(logLevel)); utf8JsonWriter.WriteString("Category", category); utf8JsonWriter.WriteString("Message", text); if (exception != null) { string text2 = exception.ToString(); if (!FormatterOptions.JsonWriterOptions.Indented) { text2 = text2.Replace(Environment.NewLine, " "); } utf8JsonWriter.WriteString("Exception", text2); } if (logEntry.State != null) { utf8JsonWriter.WriteStartObject("State"); utf8JsonWriter.WriteString("Message", logEntry.State.ToString()); if ((object)logEntry.State is IReadOnlyCollection<KeyValuePair<string, object>> readOnlyCollection) { foreach (KeyValuePair<string, object> item in readOnlyCollection) { WriteItem(utf8JsonWriter, item); } } utf8JsonWriter.WriteEndObject(); } WriteScopeInformation(utf8JsonWriter, scopeProvider); utf8JsonWriter.WriteEndObject(); utf8JsonWriter.Flush(); } textWriter.Write(Encoding.UTF8.GetString(pooledByteBufferWriter.WrittenMemory.Span)); } textWriter.Write(Environment.NewLine); } private static string GetLogLevelString(LogLevel logLevel) { return logLevel switch { LogLevel.Trace => "Trace", LogLevel.Debug => "Debug", LogLevel.Information => "Information", LogLevel.Warning => "Warning", LogLevel.Error => "Error", LogLevel.Critical => "Critical", _ => throw new ArgumentOutOfRangeException("logLevel"), }; } private void WriteScopeInformation(Utf8JsonWriter writer, IExternalScopeProvider scopeProvider) { if (!FormatterOptions.IncludeScopes || scopeProvider == null) { return; } writer.WriteStartArray("Scopes"); scopeProvider.ForEachScope(delegate(object scope, Utf8JsonWriter state) { if (scope is IEnumerable<KeyValuePair<string, object>> enumerable) { state.WriteStartObject(); state.WriteString("Message", scope.ToString()); foreach (KeyValuePair<string, object> item in enumerable) { WriteItem(state, item); } state.WriteEndObject(); } else { state.WriteStringValue(ToInvariantString(scope)); } }, writer); writer.WriteEndArray(); } private void WriteItem(Utf8JsonWriter writer, KeyValuePair<string, object> item) { string key = item.Key; object value = item.Value; if (!(value is bool value2)) { if (!(value is byte value3)) { if (!(value is sbyte value4)) { if (!(value is char reference)) { if (!(value is decimal value5)) { if (!(value is double value6)) { if (!(value is float value7)) { if (!(value is int value8)) { if (!(value is uint value9)) { if (!(value is long value10)) { if (!(value is ulong value11)) { if (!(value is short value12)) { if (!(value is ushort value13)) { if (value == null) { writer.WriteNull(key); } else { writer.WriteString(key, ToInvariantString(item.Value)); } } else { writer.WriteNumber(key, value13); } } else { writer.WriteNumber(key, value12); } } else { writer.WriteNumber(key, value11); } } else { writer.WriteNumber(key, value10); } } else { writer.WriteNumber(key, value9); } } else { writer.WriteNumber(key, value8); } } else { writer.WriteNumber(key, value7); } } else { writer.WriteNumber(key, value6); } } else { writer.WriteNumber(key, value5); } } else { writer.WriteString(key, MemoryMarshal.CreateSpan(ref reference, 1)); } } else { writer.WriteNumber(key, value4); } } else { writer.WriteNumber(key, value3); } } else { writer.WriteBoolean(key, value2); } } private static string ToInvariantString(object obj) { return Convert.ToString(obj, CultureInfo.InvariantCulture); } private void ReloadLoggerOptions(JsonConsoleFormatterOptions options) { FormatterOptions = options; } public void Dispose() { _optionsReloadToken?.Dispose(); } } public class JsonConsoleFormatterOptions : ConsoleFormatterOptions { public JsonWriterOptions JsonWriterOptions { get; 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, IDisposable { private readonly struct ConsoleColors { public ConsoleColor? Foreground { get; } public ConsoleColor? Background { get; } public ConsoleColors(ConsoleColor? foreground, ConsoleColor? background) { Foreground = foreground; Background = background; } } private const string LoglevelPadding = ": "; private static readonly string _messagePadding = new string(' ', GetLogLevelString(LogLevel.Information).Length + ": ".Length); private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding; private IDisposable _optionsReloadToken; internal SimpleConsoleFormatterOptions FormatterOptions { get; set; } public SimpleConsoleFormatter(IOptionsMonitor<SimpleConsoleFormatterOptions> options) : base("simple") { ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = options.OnChange(ReloadLoggerOptions); } 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) { string text = logEntry.Formatter(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) { text2 = GetCurrentDateTime().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) { bool singleLine = FormatterOptions.SingleLine; int id = logEntry.EventId.Id; Exception exception = logEntry.Exception; textWriter.Write(": "); textWriter.Write(logEntry.Category); textWriter.Write('['); Span<char> destination = stackalloc char[10]; if (id.TryFormat(destination, out var charsWritten)) { textWriter.Write(destination.Slice(0, charsWritten)); } 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, exception.ToString(), singleLine); } if (singleLine) { textWriter.Write(Environment.NewLine); } } private 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); } } static void WriteReplacing(TextWriter writer, string oldValue, string newValue, string message) { string value = message.Replace(oldValue, newValue); writer.Write(value); } } private DateTimeOffset GetCurrentDateTime() { if (!FormatterOptions.UseUtcTimestamp) { return DateTimeOffset.Now; } return DateTimeOffset.UtcNow; } private static string GetLogLevelString(LogLevel logLevel) { return logLevel switch { LogLevel.Trace => "trce", LogLevel.Debug => "dbug", LogLevel.Information => "info", LogLevel.Warning => "warn", LogLevel.Error => "fail", LogLevel.Critical => "crit", _ => throw new ArgumentOutOfRangeException("logLevel"), }; } private ConsoleColors GetLogLevelConsoleColors(LogLevel logLevel) { if (FormatterOptions.ColorBehavior == LoggerColorBehavior.Disabled || (FormatterOptions.ColorBehavior == LoggerColorBehavior.Default && System.Console.IsOutputRedirected)) { return new ConsoleColors(null, null); } return logLevel switch { LogLevel.Trace => new ConsoleColors(ConsoleColor.Gray, ConsoleColor.Black), LogLevel.Debug => new ConsoleColors(ConsoleColor.Gray, ConsoleColor.Black), LogLevel.Information => new ConsoleColors(ConsoleColor.DarkGreen, ConsoleColor.Black), LogLevel.Warning => new ConsoleColors(ConsoleColor.Yellow, ConsoleColor.Black), LogLevel.Error => new ConsoleColors(ConsoleColor.Black, ConsoleColor.DarkRed), LogLevel.Critical => new ConsoleColors(ConsoleColor.White, ConsoleColor.DarkRed), _ => new ConsoleColors(null, null), }; } private void WriteScopeInformation(TextWriter textWriter, IExternalScopeProvider scopeProvider, bool singleLine) { if (!FormatterOptions.IncludeScopes || scopeProvider == null) { return; } bool paddingNeeded = !singleLine; scopeProvider.ForEachScope(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 { public LoggerColorBehavior ColorBehavior { get; set; } public bool SingleLine { get; set; } } internal sealed class SystemdConsoleFormatter : ConsoleFormatter, IDisposable { private IDisposable _optionsReloadToken; internal ConsoleFormatterOptions FormatterOptions { get; set; } public SystemdConsoleFormatter(IOptionsMonitor<ConsoleFormatterOptions> options) : base("systemd") { ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = options.OnChange(ReloadLoggerOptions); } 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) { string text = logEntry.Formatter(logEntry.State, logEntry.Exception); if (logEntry.Exception != null || text != null) { LogLevel logLevel = logEntry.LogLevel; string category = logEntry.Category; int id = logEntry.EventId.Id; Exception exception = logEntry.Exception; string syslogSeverityString = GetSyslogSeverityString(logLevel); textWriter.Write(syslogSeverityString); string timestampFormat = FormatterOptions.TimestampFormat; if (timestampFormat != null) { textWriter.Write(GetCurrentDateTime().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, exception.ToString()); } textWriter.Write(Environment.NewLine); } static void WriteReplacingNewLine(TextWriter writer, string message) { string value = message.Replace(Environment.NewLine, " "); writer.Write(value); } } private DateTimeOffset GetCurrentDateTime() { if (!FormatterOptions.UseUtcTimestamp) { return DateTimeOffset.Now; } return DateTimeOffset.UtcNow; } private static string GetSyslogSeverityString(LogLevel logLevel) { return logLevel switch { LogLevel.Trace => "<7>", LogLevel.Debug => "<7>", LogLevel.Information => "<6>", LogLevel.Warning => "<4>", LogLevel.Error => "<3>", LogLevel.Critical => "<2>", _ => throw new ArgumentOutOfRangeException("logLevel"), }; } private void WriteScopeInformation(TextWriter textWriter, IExternalScopeProvider scopeProvider) { if (FormatterOptions.IncludeScopes) { scopeProvider?.ForEachScope(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) { 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"); } } } }
MegabonkTogether/Microsoft.Extensions.FileSystemGlobbing.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.FileSystemGlobbing.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.FileSystemGlobbing")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.FileSystemGlobbing")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.FileSystemGlobbing { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string CannotDeclarePathSegment => GetResourceString("CannotDeclarePathSegment"); internal static string CannotTestDirectory => GetResourceString("CannotTestDirectory"); internal static string CannotTestFile => GetResourceString("CannotTestFile"); 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.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> { public string Path { get; } public string Stem { get; } public FilePatternMatch(string path, string stem) { Path = path; Stem = stem; } public bool Equals(FilePatternMatch other) { if (string.Equals(other.Path, Path, StringComparison.OrdinalIgnoreCase)) { return string.Equals(other.Stem, Stem, StringComparison.OrdinalIgnoreCase); } return false; } public override bool Equals(object obj) { return Equals((FilePatternMatch)obj); } 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 { private static readonly char[] DirectorySeparators = new char[2] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; private readonly IEnumerable<string> _files; public override string FullName { get; } public override string Name { get; } public override DirectoryInfoBase ParentDirectory => new InMemoryDirectoryInfo(Path.GetDirectoryName(FullName), _files, normalized: true); public InMemoryDirectoryInfo(string rootDir, IEnumerable<string> files) : this(rootDir, files, normalized: false) { } private InMemoryDirectoryInfo(string rootDir, IEnumerable<string> files, bool normalized) { if (string.IsNullOrEmpty(rootDir)) { throw new ArgumentNullException("rootDir"); } if (files == null) { files = new List<string>(); } Name = Path.GetFileName(rootDir); if (normalized) { _files = files; FullName = rootDir; return; } List<string> list = new List<string>(files.Count()); foreach (string file in files) { list.Add(Path.GetFullPath(file.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar))); } _files = list; FullName = Path.GetFullPath(rootDir.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); } public override IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos() { Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); foreach (string file in _files) { if (!IsRootDirectory(FullName, file)) { continue; } int length = file.Length; int num = FullName.Length + 1; int num2 = file.IndexOfAny(DirectorySeparators, num, length - num); if (num2 == -1) { yield return new InMemoryFileInfo(file, this); continue; } string key = file.Substring(0, num2); if (!dict.TryGetValue(key, out var value)) { dict[key] = new List<string> { file }; } else { value.Add(file); } } foreach (KeyValuePair<string, List<string>> item in dict) { yield return new InMemoryDirectoryInfo(item.Key, item.Value, normalized: true); } } private bool IsRootDirectory(string rootDir, string filePath) { int length = rootDir.Length; if (filePath.StartsWith(rootDir, StringComparison.Ordinal)) { 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.Ordinal)) { 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)); foreach (string file in _files) { if (string.Equals(file, fullPath)) { return new InMemoryFileInfo(file, this); } } return null; } } public class Matcher { private readonly IList<IPattern> _includePatterns = new List<IPattern>(); private readonly IList<IPattern> _excludePatterns = new List<IPattern>(); private readonly PatternBuilder _builder; private readonly StringComparison _comparison; public Matcher() : this(StringComparison.OrdinalIgnoreCase) { } public Matcher(StringComparison comparisonType) { _comparison = comparisonType; _builder = new PatternBuilder(comparisonType); } public virtual Matcher AddInclude(string pattern) { _includePatterns.Add(_builder.Build(pattern)); return this; } public virtual Matcher AddExclude(string pattern) { _excludePatterns.Add(_builder.Build(pattern)); return this; } public virtual PatternMatchingResult Execute(DirectoryInfoBase directoryInfo) { MatcherContext matcherContext = new MatcherContext(_includePatterns, _excludePatterns, directoryInfo, _comparison); return matcherContext.Execute(); } } public static class MatcherExtensions { public static void AddExcludePatterns(this Matcher matcher, params IEnumerable<string>[] excludePatternsGroups) { foreach (IEnumerable<string> enumerable in excludePatternsGroups) { foreach (string item in enumerable) { matcher.AddExclude(item); } } } public static void AddIncludePatterns(this Matcher matcher, params IEnumerable<string>[] includePatternsGroups) { foreach (IEnumerable<string> enumerable in includePatternsGroups) { foreach (string item in enumerable) { matcher.AddInclude(item); } } } public static IEnumerable<string> GetResultsInFullPath(this Matcher matcher, string directoryPath) { IEnumerable<FilePatternMatch> files = matcher.Execute(new DirectoryInfoWrapper(new DirectoryInfo(directoryPath))).Files; return files.Select((FilePatternMatch match) => Path.GetFullPath(Path.Combine(directoryPath, match.Path))).ToArray(); } public static PatternMatchingResult Match(this Matcher matcher, string file) { return matcher.Match(Directory.GetCurrentDirectory(), new List<string> { file }); } public static PatternMatchingResult Match(this Matcher matcher, string rootDir, string file) { return matcher.Match(rootDir, new List<string> { file }); } public static PatternMatchingResult Match(this Matcher matcher, IEnumerable<string> files) { return matcher.Match(Directory.GetCurrentDirectory(), files); } public static PatternMatchingResult Match(this Matcher matcher, string rootDir, IEnumerable<string> files) { if (matcher == null) { throw new ArgumentNullException("matcher"); } return matcher.Execute(new InMemoryDirectoryInfo(rootDir, files)); } } public class PatternMatchingResult { public IEnumerable<FilePatternMatch> Files { get; set; } public bool HasMatches { get; } public PatternMatchingResult(IEnumerable<FilePatternMatch> files) : this(files, files.Any()) { Files = files; } public PatternMatchingResult(IEnumerable<FilePatternMatch> files, bool hasMatches) { Files = files; HasMatches = hasMatches; } } } namespace Microsoft.Extensions.FileSystemGlobbing.Util { internal static class StringComparisonHelper { public static StringComparer GetStringComparer(StringComparison comparisonType) { return comparisonType switch { StringComparison.CurrentCulture => StringComparer.CurrentCulture, StringComparison.CurrentCultureIgnoreCase => StringComparer.CurrentCultureIgnoreCase, StringComparison.Ordinal => StringComparer.Ordinal, StringComparison.OrdinalIgnoreCase => StringComparer.OrdinalIgnoreCase, StringComparison.InvariantCulture => StringComparer.InvariantCulture, StringComparison.InvariantCultureIgnoreCase => StringComparer.InvariantCultureIgnoreCase, _ => throw new InvalidOperationException(System.SR.Format(System.SR.UnexpectedStringComparisonType, comparisonType)), }; } } } namespace Microsoft.Extensions.FileSystemGlobbing.Internal { public interface ILinearPattern : IPattern { IList<IPathSegment> Segments { get; } } internal sealed class InMemoryFileInfo : FileInfoBase { private InMemoryDirectoryInfo _parent; public override string FullName { get; } public override string Name { 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 { IList<IPathSegment> Segments { get; } IList<IPathSegment> StartsWith { get; } IList<IList<IPathSegment>> Contains { get; } 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> _declaredLiteralFolderSegments = new HashSet<LiteralPathSegment>(); private readonly HashSet<LiteralPathSegment> _declaredLiteralFileSegments = new HashSet<LiteralPathSegment>(); private bool _declaredParentPathSegment; private bool _declaredWildcardPathSegment; private readonly StringComparison _comparisonType; public MatcherContext(IEnumerable<IPattern> includePatterns, IEnumerable<IPattern> excludePatterns, DirectoryInfoBase directoryInfo, StringComparison comparison) { _root = directoryInfo; _files = new List<FilePatternMatch>(); _comparisonType = comparison; _includePatternContexts = includePatterns.Select((IPattern pattern) => pattern.CreatePatternContextForInclude()).ToList(); _excludePatternContexts = excludePatterns.Select((IPattern pattern) => pattern.CreatePatternContextForExclude()).ToList(); _declaredLiteralFolderSegmentInString = new HashSet<string>(StringComparisonHelper.GetStringComparer(comparison)); } public PatternMatchingResult Execute() { _files.Clear(); Match(_root, null); return new PatternMatchingResult(_files, _files.Count > 0); } private void Match(DirectoryInfoBase directory, string parentRelativePath) { PushDirectory(directory); Declare(); List<FileSystemInfoBase> list = new List<FileSystemInfoBase>(); if (_declaredWildcardPathSegment || _declaredLiteralFileSegments.Any()) { list.AddRange(directory.EnumerateFileSystemInfos()); } else { IEnumerable<DirectoryInfoBase> enumerable = directory.EnumerateFileSystemInfos().OfType<DirectoryInfoBase>(); foreach (DirectoryInfoBase item in enumerable) { if (_declaredLiteralFolderSegmentInString.Contains(item.Name)) { list.Add(item); } } } if (_declaredParentPathSegment) { list.Add(directory.GetDirectory("..")); } List<DirectoryInfoBase> list2 = new List<DirectoryInfoBase>(); foreach (FileSystemInfoBase item2 in list) { if (item2 is FileInfoBase fileInfoBase) { PatternTestResult patternTestResult = MatchPatternContexts(fileInfoBase, (IPatternContext pattern, FileInfoBase file) => pattern.Test(file)); if (patternTestResult.IsSuccessful) { _files.Add(new FilePatternMatch(CombinePath(parentRelativePath, fileInfoBase.Name), patternTestResult.Stem)); } } else if (item2 is DirectoryInfoBase directoryInfoBase && MatchPatternContexts(directoryInfoBase, (IPatternContext pattern, DirectoryInfoBase dir) => pattern.Test(dir))) { list2.Add(directoryInfoBase); } } foreach (DirectoryInfoBase item3 in list2) { string parentRelativePath2 = CombinePath(parentRelativePath, item3.Name); Match(item3, parentRelativePath2); } PopDirectory(); } private void Declare() { _declaredLiteralFileSegments.Clear(); _declaredLiteralFolderSegments.Clear(); _declaredParentPathSegment = false; _declaredWildcardPathSegment = false; foreach (IPatternContext includePatternContext in _includePatternContexts) { includePatternContext.Declare(DeclareInclude); } } private void DeclareInclude(IPathSegment patternSegment, bool isLastSegment) { if (patternSegment is LiteralPathSegment literalPathSegment) { if (isLastSegment) { _declaredLiteralFileSegments.Add(literalPathSegment); return; } _declaredLiteralFolderSegments.Add(literalPathSegment); _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, (IPatternContext ctx, TFileInfoBase file) => test(ctx, file) ? PatternTestResult.Success(string.Empty) : PatternTestResult.Failed).IsSuccessful; } private PatternTestResult MatchPatternContexts<TFileInfoBase>(TFileInfoBase fileinfo, Func<IPatternContext, TFileInfoBase, PatternTestResult> test) { PatternTestResult result = PatternTestResult.Failed; foreach (IPatternContext includePatternContext in _includePatternContexts) { PatternTestResult patternTestResult = test(includePatternContext, fileinfo); if (patternTestResult.IsSuccessful) { result = patternTestResult; break; } } if (!result.IsSuccessful) { return PatternTestResult.Failed; } foreach (IPatternContext excludePatternContext in _excludePatternContexts) { if (test(excludePatternContext, fileinfo).IsSuccessful) { return PatternTestResult.Failed; } } return result; } private void PopDirectory() { foreach (IPatternContext excludePatternContext in _excludePatternContexts) { excludePatternContext.PopDirectory(); } foreach (IPatternContext includePatternContext in _includePatternContexts) { includePatternContext.PopDirectory(); } } private void PushDirectory(DirectoryInfoBase directory) { foreach (IPatternContext includePatternContext in _includePatternContexts) { includePatternContext.PushDirectory(directory); } foreach (IPatternContext excludePatternContext in _excludePatternContexts) { excludePatternContext.PushDirectory(directory); } } } public struct PatternTestResult { public static readonly PatternTestResult Failed = new PatternTestResult(isSuccessful: false, null); public bool IsSuccessful { get; } public string Stem { 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 { public IList<IPathSegment> Segments { get; } public LinearPattern(List<IPathSegment> allSegments) { Segments = allSegments; } public IPatternContext CreatePatternContextForInclude() { return new PatternContextLinearInclude(this); } public IPatternContext CreatePatternContextForExclude() { return new PatternContextLinearExclude(this); } } private sealed class RaggedPattern : IRaggedPattern, IPattern { public IList<IList<IPathSegment>> Contains { get; } public IList<IPathSegment> EndsWith { get; } public IList<IPathSegment> Segments { get; } public IList<IPathSegment> StartsWith { get; } public RaggedPattern(List<IPathSegment> allSegments, IList<IPathSegment> segmentsPatternStartsWith, IList<IPathSegment> segmentsPatternEndsWith, IList<IList<IPathSegment>> segmentsPatternContains) { Segments = 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] { '*' }; public StringComparison ComparisonType { get; } public PatternBuilder() { ComparisonType = StringComparison.OrdinalIgnoreCase; } public PatternBuilder(StringComparison comparisonType) { ComparisonType = comparisonType; } public IPattern Build(string pattern) { if (pattern == null) { throw new ArgumentNullException("pattern"); } pattern = pattern.TrimStart(_slashes); if (pattern.TrimEnd(_slashes).Length < pattern.Length) { pattern = pattern.TrimEnd(_slashes) + "/**"; } List<IPathSegment> list = new List<IPathSegment>(); bool flag = true; IList<IPathSegment> list2 = null; IList<IList<IPathSegment>> list3 = null; IList<IPathSegment> list4 = 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> list5 = 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) { list5.Add(Portion(pattern, num5, num6)); } num4 = num6 + 1; } if (pathSegment == null) { pathSegment = new WildcardPathSegment(beginsWith, list5, endsWith, ComparisonType); } } if (!(pathSegment is ParentPathSegment)) { flag = false; } if (!(pathSegment is CurrentPathSegment)) { if (pathSegment is RecursiveWildcardSegment) { if (list2 == null) { list2 = new List<IPathSegment>(list); list4 = new List<IPathSegment>(); list3 = new List<IList<IPathSegment>>(); } else if (list4.Count != 0) { list3.Add(list4); list4 = new List<IPathSegment>(); } } else { list4?.Add(pathSegment); } list.Add(pathSegment); } num = num3 + 1; } if (list2 == null) { return new LinearPattern(list); } return new RaggedPattern(list, list2, list4, list3); } 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 { 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 IList<string> _stemItems; public IList<string> StemItems => _stemItems ?? (_stemItems = new List<string>()); public string Stem { get { if (_stemItems != null) { return string.Join("/", _stemItems); } return null; } } } protected ILinearPattern Pattern { get; } public PatternContextLinear(ILinearPattern pattern) { Pattern = pattern; } public override PatternTestResult Test(FileInfoBase file) { 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; frame.StemItems.Add(directory.Name); } frame.SegmentIndex++; } } PushDataFrame(frame); } protected bool IsLastSegment() { return Frame.SegmentIndex == Pattern.Segments.Count - 1; } protected bool TestMatchingSegment(string value) { if (Frame.SegmentIndex >= 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) { 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) { if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotDeclarePathSegment); } if (!Frame.IsNotApplicable && Frame.SegmentIndex < base.Pattern.Segments.Count) { onDeclare(base.Pattern.Segments[Frame.SegmentIndex], IsLastSegment()); } } public override bool Test(DirectoryInfoBase directory) { 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 IList<IPathSegment> SegmentGroup; public int BacktrackAvailable; public int SegmentIndex; public bool InStem; private IList<string> _stemItems; public IList<string> StemItems => _stemItems ?? (_stemItems = new List<string>()); public string Stem { get { if (_stemItems != null) { return string.Join("/", _stemItems); } return null; } } } protected IRaggedPattern Pattern { get; } public PatternContextRagged(IRaggedPattern pattern) { Pattern = pattern; } public override PatternTestResult Test(FileInfoBase file) { 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 = Frame.SegmentGroup.Count; frame.BacktrackAvailable = 0; } else { frame.BacktrackAvailable++; } } if (frame.InStem) { frame.StemItems.Add(directory.Name); } while (frame.SegmentIndex == frame.SegmentGroup.Count && frame.SegmentGroupIndex != Pattern.Contains.Count) { frame.SegmentGroupIndex++; frame.SegmentIndex = 0; if (frame.SegmentGroupIndex < 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 (Frame.StemItems.Count > 0) { Frame.StemItems.RemoveAt(Frame.StemItems.Count - 1); } } protected bool IsStartingGroup() { return Frame.SegmentGroupIndex == -1; } protected bool IsEndingGroup() { return Frame.SegmentGroupIndex == Pattern.Contains.Count; } protected bool TestMatchingSegment(string value) { if (Frame.SegmentIndex >= Frame.SegmentGroup.Count) { return false; } return Frame.SegmentGroup[Frame.SegmentIndex].Match(value); } protected bool TestMatchingGroup(FileSystemInfoBase value) { int count = 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 (!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) { if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotTestDirectory); } if (Frame.IsNotApplicable) { return false; } if (IsEndingGroup() && TestMatchingGroup(directory)) { return true; } if (base.Pattern.EndsWith.Count == 0 && Frame.SegmentGroupIndex == 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) { if (IsStackEmpty()) { throw new InvalidOperationException(System.SR.CannotDeclarePathSegment); } if (!Frame.IsNotApplicable) { if (IsStartingGroup() && Frame.SegmentIndex < Frame.SegmentGroup.Count) { onDeclare(Frame.SegmentGroup[Frame.SegmentIndex], arg2: false); } else { onDeclare(WildcardPathSegment.MatchAll, arg2: false); } } } public override bool Test(DirectoryInfoBase directory) { 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; public string Value { get; } public LiteralPathSegment(string value, StringComparison comparisonType) { if (value == null) { throw new ArgumentNullException("value"); } Value = value; _comparisonType = comparisonType; } public bool Match(string value) { return string.Equals(Value, value, _comparisonType); } public override bool Equals(object obj) { if (obj is LiteralPathSegment literalPathSegment && _comparisonType == literalPathSegment._comparisonType) { return string.Equals(literalPathSegment.Value, Value, _comparisonType); } return false; } public override int GetHashCode() { 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.Ordinal); } } 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.OrdinalIgnoreCase); private readonly StringComparison _comparisonType; public bool CanProduceStem => true; public string BeginsWith { get; } public List<string> Contains { get; } public string EndsWith { get; } public WildcardPathSegment(string beginsWith, List<string> contains, string endsWith, StringComparison comparisonType) { BeginsWith = beginsWith; Contains = contains; EndsWith = endsWith; _comparisonType = comparisonType; } public bool Match(string value) { 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 IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos(); public abstract DirectoryInfoBase GetDirectory(string path); public abstract FileInfoBase GetFile(string path); } public class DirectoryInfoWrapper : DirectoryInfoBase { private readonly DirectoryInfo _directoryInfo; private readonly bool _isParentPath; public override string Name { get { if (!_isParentPath) { return _directoryInfo.Name; } return ".."; } } public override string FullName => _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; } public override IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos() { if (!_directoryInfo.Exists) { yield break; } IEnumerable<FileSystemInfo> enumerable; try { enumerable = _directoryInfo.EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } catch (DirectoryNotFoundException) { yield break; } foreach (FileSystemInfo item in enumerable) { if (item is DirectoryInfo directoryInfo) { yield return new DirectoryInfoWrapper(directoryInfo); } else { yield return new FileInfoWrapper((FileInfo)item); } } } public override DirectoryInfoBase GetDirectory(string name) { bool flag = string.Equals(name, "..", StringComparison.Ordinal); if (flag) { return new DirectoryInfoWrapper(new DirectoryInfo(Path.Combine(_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 {_directoryInfo.FullName} with name {name}."); } public override FileInfoBase GetFile(string name) { return new FileInfoWrapper(new FileInfo(Path.Combine(_directoryInfo.FullName, name))); } } public abstract class FileInfoBase : FileSystemInfoBase { } public class FileInfoWrapper : FileInfoBase { private readonly FileInfo _fileInfo; public override string Name => _fileInfo.Name; public override string FullName => _fileInfo.FullName; public override DirectoryInfoBase ParentDirectory => new DirectoryInfoWrapper(_fileInfo.Directory); public FileInfoWrapper(FileInfo fileInfo) { _fileInfo = fileInfo; } } public abstract class FileSystemInfoBase { public abstract string Name { get; } public abstract string FullName { get; } public abstract DirectoryInfoBase ParentDirectory { get; } } }
MegabonkTogether/Microsoft.Extensions.Logging.EventSource.dll
Decompiled 2 hours agousing System; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.EventSource.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.EventSource")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("EventSource/EventListener logger provider implementation for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging.EventSource")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } 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 item in filterRules) { options.Rules.Add(item); } } } internal sealed class EventLogFiltersConfigureOptionsChangeSource : IOptionsChangeTokenSource<LoggerFilterOptions> { private readonly LoggingEventSource _eventSource; public string Name { get; } public EventLogFiltersConfigureOptionsChangeSource(LoggingEventSource eventSource) { _eventSource = eventSource; } public IChangeToken GetChangeToken() { return _eventSource.GetFilterChangeToken(); } } public static class EventSourceLoggerFactoryExtensions { public static ILoggingBuilder AddEventSourceLogger(this ILoggingBuilder builder) { if (builder == null) { throw new ArgumentNullException("builder"); } builder.Services.TryAddSingleton(LoggingEventSource.Instance); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, EventSourceLoggerProvider>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>, EventLogFiltersConfigureOptions>()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IOptionsChangeTokenSource<LoggerFilterOptions>, EventLogFiltersConfigureOptionsChangeSource>()); return builder; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { public static IExternalScopeProvider Instance { get; } = new Microsoft.Extensions.Logging.NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } IDisposable IExternalScopeProvider.Push(object state) { return Microsoft.Extensions.Logging.NullScope.Instance; } } internal sealed class NullScope : IDisposable { public static Microsoft.Extensions.Logging.NullScope Instance { get; } = new Microsoft.Extensions.Logging.NullScope(); private NullScope() { } public void Dispose() { } } } namespace Microsoft.Extensions.Logging.EventSource { internal sealed class EventSourceLogger : ILogger { private sealed class ActivityScope : 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; public string CategoryName { get; } public LogLevel Level { get; set; } public EventSourceLogger Next { get; } public EventSourceLogger(string categoryName, int factoryID, LoggingEventSource eventSource, EventSourceLogger next) { CategoryName = categoryName; Level = LogLevel.Trace; _factoryID = factoryID; _eventSource = eventSource; Next = next; } public bool IsEnabled(LogLevel logLevel) { if (logLevel != LogLevel.None) { return logLevel >= Level; } return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } string text = null; if (_eventSource.IsEnabled(EventLevel.Critical, (EventKeywords)4L)) { text = formatter(state, exception); _eventSource.FormattedMessage(logLevel, _factoryID, CategoryName, eventId.Id, eventId.Name, text); } if (_eventSource.IsEnabled(EventLevel.Critical, (EventKeywords)2L)) { ExceptionInfo exceptionInfo = GetExceptionInfo(exception); IReadOnlyList<KeyValuePair<string, string>> properties = GetProperties(state); _eventSource.Message(logLevel, _factoryID, CategoryName, eventId.Id, eventId.Name, exceptionInfo, properties); } if (_eventSource.IsEnabled(EventLevel.Critical, (EventKeywords)8L)) { 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); } IReadOnlyList<KeyValuePair<string, string>> properties2 = GetProperties(state); if (text == null) { text = formatter(state, exception); } _eventSource.MessageJson(logLevel, _factoryID, CategoryName, eventId.Id, eventId.Name, exceptionJson, ToJson(properties2), text); } } public IDisposable BeginScope<TState>(TState state) { if (!IsEnabled(LogLevel.Critical)) { return Microsoft.Extensions.Logging.NullScope.Instance; } int num = Interlocked.Increment(ref _activityIds); if (_eventSource.IsEnabled(EventLevel.Critical, (EventKeywords)8L)) { 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.IsEnabled(EventLevel.Critical, (EventKeywords)2L) || _eventSource.IsEnabled(EventLevel.Critical, (EventKeywords)4L)) { IReadOnlyList<KeyValuePair<string, string>> properties2 = GetProperties(state); _eventSource.ActivityStart(num, _factoryID, CategoryName, properties2); return new ActivityScope(_eventSource, CategoryName, num, _factoryID, isJsonStop: false); } return Microsoft.Extensions.Logging.NullScope.Instance; } private ExceptionInfo GetExceptionInfo(Exception exception) { if (exception == null) { return ExceptionInfo.Empty; } return new ExceptionInfo(exception); } private IReadOnlyList<KeyValuePair<string, string>> GetProperties(object state) { if (state is IReadOnlyList<KeyValuePair<string, object>> readOnlyList) { KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[readOnlyList.Count]; for (int i = 0; i < readOnlyList.Count; i++) { KeyValuePair<string, object> keyValuePair = readOnlyList[i]; array[i] = new KeyValuePair<string, string>(keyValuePair.Key, keyValuePair.Value?.ToString()); } return array; } return Array.Empty<KeyValuePair<string, string>>(); } private string ToJson(IReadOnlyList<KeyValuePair<string, string>> keyValues) { using MemoryStream memoryStream = new MemoryStream(); using Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter((Stream)memoryStream, default(JsonWriterOptions)); utf8JsonWriter.WriteStartObject(); foreach (KeyValuePair<string, string> keyValue in keyValues) { utf8JsonWriter.WriteString(keyValue.Key, keyValue.Value); } utf8JsonWriter.WriteEndObject(); utf8JsonWriter.Flush(); if (!memoryStream.TryGetBuffer(out var buffer)) { buffer = new ArraySegment<byte>(memoryStream.ToArray()); } return Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count); } } [ProviderAlias("EventSource")] public class EventSourceLoggerProvider : ILoggerProvider, IDisposable { private static int _globalFactoryID; private readonly int _factoryID; private EventSourceLogger _loggers; private readonly LoggingEventSource _eventSource; public EventSourceLoggerProvider(LoggingEventSource eventSource) { if (eventSource == null) { throw new ArgumentNullException("eventSource"); } _eventSource = eventSource; _factoryID = Interlocked.Increment(ref _globalFactoryID); } public ILogger CreateLogger(string categoryName) { return _loggers = new EventSourceLogger(categoryName, _factoryID, _eventSource, _loggers); } public void Dispose() { for (EventSourceLogger eventSourceLogger = _loggers; eventSourceLogger != null; eventSourceLogger = eventSourceLogger.Next) { eventSourceLogger.Level = LogLevel.None; } } } [EventData(Name = "ExceptionInfo")] internal sealed class ExceptionInfo { public static ExceptionInfo Empty { get; } = new ExceptionInfo(); public string TypeName { get; } public string Message { get; } public int HResult { get; } public string VerboseMessage { get; } private ExceptionInfo() { } public ExceptionInfo(Exception exception) { TypeName = exception.GetType().FullName; Message = exception.Message; HResult = exception.HResult; VerboseMessage = exception.ToString(); } } [EventSource(Name = "Microsoft-Extensions-Logging")] public sealed class LoggingEventSource : System.Diagnostics.Tracing.EventSource { public static class Keywords { public const EventKeywords Meta = (EventKeywords)1L; public const EventKeywords Message = (EventKeywords)2L; public const EventKeywords FormattedMessage = (EventKeywords)4L; public const EventKeywords JsonMessage = (EventKeywords)8L; } internal static readonly LoggingEventSource Instance = new LoggingEventSource(); private LoggerFilterRule[] _filterSpec = 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.EtwSelfDescribingEventFormat) { } [Event(1, Keywords = (EventKeywords)4L, Level = EventLevel.LogAlways)] [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 (!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 = stackalloc EventData[6]; SetEventData(ref *ptr2, ref Level, null); SetEventData(ref ptr2[1], ref FactoryID, null); SetEventData(ref ptr2[2], ref LoggerName, pinnedString3); SetEventData(ref ptr2[3], ref EventId, null); SetEventData(ref ptr2[4], ref EventName, pinnedString); SetEventData(ref ptr2[5], ref FormattedMessage, pinnedString2); WriteEventCore(1, 6, ptr2); } return; } fixed (char* ptr3 = &EventName.GetPinnableReference()) { char* pinnedString; intPtr = (pinnedString = ptr3); fixed (char* ptr = FormattedMessage) { char* pinnedString2 = ptr; EventData* ptr2 = stackalloc EventData[6]; SetEventData(ref *ptr2, ref Level, null); SetEventData(ref ptr2[1], ref FactoryID, null); SetEventData(ref ptr2[2], ref LoggerName, pinnedString3); SetEventData(ref ptr2[3], ref EventId, null); SetEventData(ref ptr2[4], ref EventName, pinnedString); SetEventData(ref ptr2[5], ref FormattedMessage, pinnedString2); WriteEventCore(1, 6, ptr2); } } } } [Event(2, Keywords = (EventKeywords)2L, Level = EventLevel.LogAlways)] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(KeyValuePair<string, string>))] [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, IEnumerable<KeyValuePair<string, string>> Arguments) { if (IsEnabled()) { WriteEvent(2, Level, FactoryID, LoggerName, EventId, EventName, Exception, Arguments); } } [Event(3, Keywords = (EventKeywords)6L, Level = EventLevel.LogAlways, ActivityOptions = EventActivityOptions.Recursive)] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(KeyValuePair<string, string>))] [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, IEnumerable<KeyValuePair<string, string>> Arguments) { if (IsEnabled()) { WriteEvent(3, ID, FactoryID, LoggerName, Arguments); } } [Event(4, Keywords = (EventKeywords)6L, Level = EventLevel.LogAlways)] [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 (IsEnabled()) { if (LoggerName == null) { LoggerName = ""; } fixed (char* pinnedString = LoggerName) { EventData* ptr = stackalloc EventData[3]; SetEventData(ref *ptr, ref ID, null); SetEventData(ref ptr[1], ref FactoryID, null); SetEventData(ref ptr[2], ref LoggerName, pinnedString); WriteEventCore(4, 3, ptr); } } } [Event(5, Keywords = (EventKeywords)8L, Level = EventLevel.LogAlways)] [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 (!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 = stackalloc EventData[8]; SetEventData(ref *ptr3, ref Level, null); SetEventData(ref ptr3[1], ref FactoryID, null); SetEventData(ref ptr3[2], ref LoggerName, pinnedString5); SetEventData(ref ptr3[3], ref EventId, null); SetEventData(ref ptr3[4], ref EventName, pinnedString); SetEventData(ref ptr3[5], ref ExceptionJson, pinnedString2); SetEventData(ref ptr3[6], ref ArgumentsJson, pinnedString3); SetEventData(ref ptr3[7], ref FormattedMessage, pinnedString4); WriteEventCore(5, 8, ptr3); } return; } fixed (char* ptr4 = &ArgumentsJson.GetPinnableReference()) { char* pinnedString3; intPtr2 = (pinnedString3 = ptr4); fixed (char* ptr2 = FormattedMessage) { char* pinnedString4 = ptr2; EventData* ptr3 = stackalloc EventData[8]; SetEventData(ref *ptr3, ref Level, null); SetEventData(ref ptr3[1], ref FactoryID, null); SetEventData(ref ptr3[2], ref LoggerName, pinnedString5); SetEventData(ref ptr3[3], ref EventId, null); SetEventData(ref ptr3[4], ref EventName, pinnedString); SetEventData(ref ptr3[5], ref ExceptionJson, pinnedString2); SetEventData(ref ptr3[6], ref ArgumentsJson, pinnedString3); SetEventData(ref ptr3[7], ref FormattedMessage, pinnedString4); 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 = stackalloc EventData[8]; SetEventData(ref *ptr3, ref Level, null); SetEventData(ref ptr3[1], ref FactoryID, null); SetEventData(ref ptr3[2], ref LoggerName, pinnedString5); SetEventData(ref ptr3[3], ref EventId, null); SetEventData(ref ptr3[4], ref EventName, pinnedString); SetEventData(ref ptr3[5], ref ExceptionJson, pinnedString2); SetEventData(ref ptr3[6], ref ArgumentsJson, pinnedString3); SetEventData(ref ptr3[7], ref FormattedMessage, pinnedString4); WriteEventCore(5, 8, ptr3); } return; } fixed (char* ptr4 = &ArgumentsJson.GetPinnableReference()) { char* pinnedString3; intPtr2 = (pinnedString3 = ptr4); fixed (char* ptr2 = FormattedMessage) { char* pinnedString4 = ptr2; EventData* ptr3 = stackalloc EventData[8]; SetEventData(ref *ptr3, ref Level, null); SetEventData(ref ptr3[1], ref FactoryID, null); SetEventData(ref ptr3[2], ref LoggerName, pinnedString5); SetEventData(ref ptr3[3], ref EventId, null); SetEventData(ref ptr3[4], ref EventName, pinnedString); SetEventData(ref ptr3[5], ref ExceptionJson, pinnedString2); SetEventData(ref ptr3[6], ref ArgumentsJson, pinnedString3); SetEventData(ref ptr3[7], ref FormattedMessage, pinnedString4); WriteEventCore(5, 8, ptr3); } } } } } } [Event(6, Keywords = (EventKeywords)12L, Level = EventLevel.LogAlways, ActivityOptions = EventActivityOptions.Recursive)] [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 (!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 = stackalloc EventData[4]; SetEventData(ref *ptr, ref ID, null); SetEventData(ref ptr[1], ref FactoryID, null); SetEventData(ref ptr[2], ref LoggerName, pinnedString2); SetEventData(ref ptr[3], ref ArgumentsJson, pinnedString); WriteEventCore(6, 4, ptr); return; } fixed (char* ptr2 = &ArgumentsJson.GetPinnableReference()) { char* pinnedString; intPtr = (pinnedString = ptr2); EventData* ptr = stackalloc EventData[4]; SetEventData(ref *ptr, ref ID, null); SetEventData(ref ptr[1], ref FactoryID, null); SetEventData(ref ptr[2], ref LoggerName, pinnedString2); SetEventData(ref ptr[3], ref ArgumentsJson, pinnedString); WriteEventCore(6, 4, ptr); } } } [Event(7, Keywords = (EventKeywords)12L, Level = EventLevel.LogAlways)] [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 (IsEnabled()) { if (LoggerName == null) { LoggerName = ""; } fixed (char* pinnedString = LoggerName) { EventData* ptr = stackalloc EventData[3]; SetEventData(ref *ptr, ref ID, null); SetEventData(ref ptr[1], ref FactoryID, null); SetEventData(ref ptr[2], ref LoggerName, pinnedString); WriteEventCore(7, 3, ptr); } } } protected override void OnEventCommand(EventCommandEventArgs command) { if (command.Command == EventCommand.Update || command.Command == EventCommand.Enable) { if (!command.Arguments.TryGetValue("FilterSpecs", out string value)) { value = string.Empty; } SetFilterSpec(value); } else if (command.Command == EventCommand.Disable) { SetFilterSpec(null); } } [NonEvent] private void SetFilterSpec(string filterSpec) { _filterSpec = ParseFilterSpec(filterSpec, GetDefaultLevel()); FireChangeToken(); } [NonEvent] internal IChangeToken GetFilterChangeToken() { CancellationTokenSource cancellationTokenSource = LazyInitializer.EnsureInitialized(ref _cancellationTokenSource, () => new CancellationTokenSource()); return new CancellationChangeToken(cancellationTokenSource.Token); } [NonEvent] private void FireChangeToken() { Interlocked.Exchange(ref _cancellationTokenSource, null)?.Cancel(); } [NonEvent] private static LoggerFilterRule[] ParseFilterSpec(string filterSpec, LogLevel defaultLevel) { if (filterSpec == string.Empty) { return new LoggerFilterRule[1] { new LoggerFilterRule(typeof(EventSourceLoggerProvider).FullName, null, defaultLevel, null) }; } if (filterSpec == null) { return new LoggerFilterRule[1] { new LoggerFilterRule(typeof(EventSourceLoggerProvider).FullName, null, LogLevel.None, null) }; } List<LoggerFilterRule> list = new List<LoggerFilterRule>(); int num = 0; string[] array = filterSpec.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (array.Length != 0 && array[0].Equals("UseAppFilters", StringComparison.OrdinalIgnoreCase)) { num = 1; } else { list.Add(new LoggerFilterRule(typeof(EventSourceLoggerProvider).FullName, null, LogLevel.None, 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)) { list.Add(new LoggerFilterRule(typeof(EventSourceLoggerProvider).FullName, text2, ret, null)); } } } return list.ToArray(); } [NonEvent] private static bool TryParseLevel(LogLevel defaultLevel, string levelString, out LogLevel ret) { ret = defaultLevel; if (levelString.Length == 0) { ret = defaultLevel; return true; } switch (levelString) { case "Trace": ret = LogLevel.Trace; break; case "Debug": ret = LogLevel.Debug; break; case "Information": ret = LogLevel.Information; break; case "Warning": ret = LogLevel.Warning; break; case "Error": ret = LogLevel.Error; break; case "Critical": ret = LogLevel.Critical; break; default: { if (!int.TryParse(levelString, out var result)) { return false; } if (0 > result || result > 6) { return false; } ret = (LogLevel)result; break; } } return true; } [NonEvent] private LogLevel GetDefaultLevel() { EventKeywords keywords = (EventKeywords)14L; if (IsEnabled(EventLevel.Verbose, keywords)) { return LogLevel.Debug; } if (IsEnabled(EventLevel.Informational, keywords)) { return LogLevel.Information; } if (IsEnabled(EventLevel.Warning, keywords)) { return LogLevel.Warning; } if (IsEnabled(EventLevel.Error, keywords)) { return LogLevel.Error; } return LogLevel.Critical; } [NonEvent] internal LoggerFilterRule[] GetFilterRules() { return _filterSpec; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [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.DataPointer = (IntPtr)pinnedString; eventData.Size = checked((text.Length + 1) * 2); } else { eventData.DataPointer = (IntPtr)Unsafe.AsPointer(ref value); eventData.Size = Unsafe.SizeOf<T>(); } } } }
MegabonkTogether/Microsoft.Extensions.FileProviders.Abstractions.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using FxResources.Microsoft.Extensions.FileProviders.Abstractions; using Microsoft.Extensions.Primitives; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.FileProviders.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [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("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.FileProviders.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace FxResources.Microsoft.Extensions.FileProviders.Abstractions { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace Microsoft.Extensions.FileProviders { public interface IDirectoryContents : IEnumerable<IFileInfo>, 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, IEnumerable<IFileInfo>, IEnumerable { public static NotFoundDirectoryContents Singleton { get; } = new NotFoundDirectoryContents(); public bool Exists => false; public IEnumerator<IFileInfo> GetEnumerator() { return Enumerable.Empty<IFileInfo>().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class NotFoundFileInfo : IFileInfo { public bool Exists => false; public bool IsDirectory => false; public DateTimeOffset LastModified => DateTimeOffset.MinValue; public long Length => -1L; public string Name { get; } public string PhysicalPath => null; public NotFoundFileInfo(string name) { Name = name; } public Stream CreateReadStream() { throw new FileNotFoundException(System.SR.Format(System.SR.FileNotExists, Name)); } } public class NullChangeToken : IChangeToken { public static NullChangeToken Singleton { get; } = new NullChangeToken(); public bool HasChanged => false; public bool ActiveChangeCallbacks => false; private NullChangeToken() { } public 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 NullChangeToken.Singleton; } } internal sealed class EmptyDisposable : IDisposable { public static EmptyDisposable Instance { get; } = new EmptyDisposable(); private EmptyDisposable() { } public void Dispose() { } } }
MegabonkTogether/Microsoft.Extensions.Hosting.dll
Decompiled 2 hours agousing System; 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.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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Hosting")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Hosting and startup infrastructures for applications.")] [assembly: AssemblyFileVersion("6.0.222.6406")] [assembly: AssemblyInformationalVersion("6.0.2+839cdfb0ecca5e0be3dbccd926e7651ef50fdf10")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Hosting")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace FxResources.Microsoft.Extensions.Hosting { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string BackgroundServiceExceptionStoppedHost => GetResourceString("BackgroundServiceExceptionStoppedHost"); internal static string BuildCalled => GetResourceString("BuildCalled"); internal static string CreateBuilderCallBeforeCreateServiceProvider => GetResourceString("CreateBuilderCallBeforeCreateServiceProvider"); 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace 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(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class { if (optionsBuilder == null) { throw new ArgumentNullException("optionsBuilder"); } optionsBuilder.Services.AddHostedService<ValidationHostedService>(); optionsBuilder.Services.AddOptions<ValidatorOptions>().Configure(delegate(ValidatorOptions vo, IOptionsMonitor<TOptions> options) { vo.Validators[(typeof(TOptions), optionsBuilder.Name)] = delegate { options.Get(optionsBuilder.Name); }; }); return optionsBuilder; } } internal sealed class ValidationHostedService : IHostedService { private readonly IDictionary<(Type, string), Action> _validators; public ValidationHostedService(IOptions<ValidatorOptions> validatorOptions) { _validators = validatorOptions?.Value?.Validators ?? throw new ArgumentNullException("validatorOptions"); } public Task StartAsync(CancellationToken cancellationToken) { List<Exception> list = new List<Exception>(); foreach (Action value in _validators.Values) { try { value(); } catch (OptionsValidationException item) { list.Add(item); } } if (list.Count == 1) { ExceptionDispatchInfo.Capture(list[0]).Throw(); } if (list.Count > 1) { throw new AggregateException(list); } return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } internal sealed class ValidatorOptions { public IDictionary<(Type optionsType, string optionsName), Action> Validators { get; } = new Dictionary<(Type, string), Action>(); } } namespace Microsoft.Extensions.Hosting { public enum BackgroundServiceExceptionBehavior { StopHost, Ignore } public class ConsoleLifetimeOptions { public bool SuppressStatusMessages { get; set; } } public static class Host { public static IHostBuilder CreateDefaultBuilder() { return CreateDefaultBuilder(null); } public static IHostBuilder CreateDefaultBuilder(string[] args) { HostBuilder builder = new HostBuilder(); return builder.ConfigureDefaults(args); } } public class HostBuilder : IHostBuilder { 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 = new ServiceFactoryAdapter<IServiceCollection>(new DefaultServiceProviderFactory()); private bool _hostBuilt; private IConfiguration _hostConfiguration; private IConfiguration _appConfiguration; private HostBuilderContext _hostBuilderContext; private HostingEnvironment _hostingEnvironment; private IServiceProvider _appServices; private PhysicalFileProvider _defaultProvider; public IDictionary<object, object> Properties { get; } = new Dictionary<object, object>(); public IHostBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate) { _configureHostConfigActions.Add(configureDelegate ?? throw new ArgumentNullException("configureDelegate")); return this; } public IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate) { _configureAppConfigActions.Add(configureDelegate ?? throw new ArgumentNullException("configureDelegate")); return this; } public IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate) { _configureServicesActions.Add(configureDelegate ?? throw new ArgumentNullException("configureDelegate")); return this; } public IHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory) { _serviceProviderFactory = new ServiceFactoryAdapter<TContainerBuilder>(factory ?? throw new ArgumentNullException("factory")); return this; } public IHostBuilder UseServiceProviderFactory<TContainerBuilder>(Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory) { _serviceProviderFactory = new ServiceFactoryAdapter<TContainerBuilder>(() => _hostBuilderContext, factory ?? throw new ArgumentNullException("factory")); return this; } public IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate) { _configureContainerActions.Add(new ConfigureContainerAdapter<TContainerBuilder>(configureDelegate ?? throw new ArgumentNullException("configureDelegate"))); return this; } public IHost Build() { if (_hostBuilt) { throw new InvalidOperationException(System.SR.BuildCalled); } _hostBuilt = true; using DiagnosticListener diagnosticListener = new DiagnosticListener("Microsoft.Extensions.Hosting"); if (diagnosticListener.IsEnabled() && diagnosticListener.IsEnabled("HostBuilding")) { Write(diagnosticListener, "HostBuilding", this); } BuildHostConfiguration(); CreateHostingEnvironment(); CreateHostBuilderContext(); BuildAppConfiguration(); CreateServiceProvider(); IHost requiredService = _appServices.GetRequiredService<IHost>(); if (diagnosticListener.IsEnabled() && diagnosticListener.IsEnabled("HostBuilt")) { Write(diagnosticListener, "HostBuilt", requiredService); } return requiredService; } [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, value); } private void BuildHostConfiguration() { IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().AddInMemoryCollection(); foreach (Action<IConfigurationBuilder> configureHostConfigAction in _configureHostConfigActions) { configureHostConfigAction(configurationBuilder); } _hostConfiguration = configurationBuilder.Build(); } private void CreateHostingEnvironment() { _hostingEnvironment = new HostingEnvironment { ApplicationName = _hostConfiguration[HostDefaults.ApplicationKey], EnvironmentName = (_hostConfiguration[HostDefaults.EnvironmentKey] ?? Environments.Production), ContentRootPath = ResolveContentRootPath(_hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory) }; if (string.IsNullOrEmpty(_hostingEnvironment.ApplicationName)) { _hostingEnvironment.ApplicationName = Assembly.GetEntryAssembly()?.GetName().Name; } _hostingEnvironment.ContentRootFileProvider = (_defaultProvider = new PhysicalFileProvider(_hostingEnvironment.ContentRootPath)); } private 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); } private void CreateHostBuilderContext() { _hostBuilderContext = new HostBuilderContext(Properties) { HostingEnvironment = _hostingEnvironment, Configuration = _hostConfiguration }; } private void BuildAppConfiguration() { IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(_hostingEnvironment.ContentRootPath).AddConfiguration(_hostConfiguration, shouldDisposeConfiguration: true); foreach (Action<HostBuilderContext, IConfigurationBuilder> configureAppConfigAction in _configureAppConfigActions) { configureAppConfigAction(_hostBuilderContext, configurationBuilder); } _appConfiguration = configurationBuilder.Build(); _hostBuilderContext.Configuration = _appConfiguration; } private void CreateServiceProvider() { ServiceCollection serviceCollection = new ServiceCollection(); ((IServiceCollection)serviceCollection).AddSingleton((IHostingEnvironment)_hostingEnvironment); ((IServiceCollection)serviceCollection).AddSingleton((IHostEnvironment)_hostingEnvironment); serviceCollection.AddSingleton(_hostBuilderContext); serviceCollection.AddSingleton((IServiceProvider _) => _appConfiguration); serviceCollection.AddSingleton((IServiceProvider s) => (IApplicationLifetime)s.GetService<IHostApplicationLifetime>()); serviceCollection.AddSingleton<IHostApplicationLifetime, ApplicationLifetime>(); AddLifetime(serviceCollection); ((IServiceCollection)serviceCollection).AddSingleton((Func<IServiceProvider, IHost>)((IServiceProvider _) => new Microsoft.Extensions.Hosting.Internal.Host(_appServices, _hostingEnvironment, _defaultProvider, _appServices.GetRequiredService<IHostApplicationLifetime>(), _appServices.GetRequiredService<ILogger<Microsoft.Extensions.Hosting.Internal.Host>>(), _appServices.GetRequiredService<IHostLifetime>(), _appServices.GetRequiredService<IOptions<HostOptions>>()))); serviceCollection.AddOptions().Configure(delegate(HostOptions options) { options.Initialize(_hostConfiguration); }); serviceCollection.AddLogging(); foreach (Action<HostBuilderContext, IServiceCollection> configureServicesAction in _configureServicesActions) { configureServicesAction(_hostBuilderContext, serviceCollection); } object containerBuilder = _serviceProviderFactory.CreateBuilder(serviceCollection); foreach (IConfigureContainerAdapter configureContainerAction in _configureContainerActions) { configureContainerAction.ConfigureContainer(_hostBuilderContext, containerBuilder); } _appServices = _serviceProviderFactory.CreateServiceProvider(containerBuilder); if (_appServices == null) { throw new InvalidOperationException(System.SR.NullIServiceProvider); } _appServices.GetService<IConfiguration>(); } private static void AddLifetime(ServiceCollection services) { if (!OperatingSystem.IsAndroid() && !OperatingSystem.IsBrowser() && !OperatingSystem.IsIOS() && !OperatingSystem.IsTvOS()) { services.AddSingleton<IHostLifetime, ConsoleLifetime>(); } else { services.AddSingleton<IHostLifetime, NullLifetime>(); } } } public static class HostingHostBuilderExtensions { public static IHostBuilder UseEnvironment(this IHostBuilder hostBuilder, string environment) { return hostBuilder.ConfigureHostConfiguration(delegate(IConfigurationBuilder configBuilder) { configBuilder.AddInMemoryCollection(new KeyValuePair<string, string>[1] { new KeyValuePair<string, string>(HostDefaults.EnvironmentKey, environment ?? throw new ArgumentNullException("environment")) }); }); } public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, string contentRoot) { return hostBuilder.ConfigureHostConfiguration(delegate(IConfigurationBuilder configBuilder) { configBuilder.AddInMemoryCollection(new KeyValuePair<string, string>[1] { new KeyValuePair<string, string>(HostDefaults.ContentRootKey, contentRoot ?? throw new ArgumentNullException("contentRoot")) }); }); } public static IHostBuilder UseDefaultServiceProvider(this IHostBuilder hostBuilder, Action<ServiceProviderOptions> configure) { return hostBuilder.UseDefaultServiceProvider(delegate(HostBuilderContext context, ServiceProviderOptions options) { configure(options); }); } public static IHostBuilder UseDefaultServiceProvider(this IHostBuilder hostBuilder, Action<HostBuilderContext, ServiceProviderOptions> configure) { return hostBuilder.UseServiceProviderFactory(delegate(HostBuilderContext context) { ServiceProviderOptions serviceProviderOptions = new ServiceProviderOptions(); configure(context, serviceProviderOptions); return new DefaultServiceProviderFactory(serviceProviderOptions); }); } public static IHostBuilder ConfigureLogging(this IHostBuilder hostBuilder, Action<HostBuilderContext, ILoggingBuilder> configureLogging) { return hostBuilder.ConfigureServices(delegate(HostBuilderContext context, IServiceCollection collection) { collection.AddLogging(delegate(ILoggingBuilder builder) { configureLogging(context, builder); }); }); } public static IHostBuilder ConfigureLogging(this IHostBuilder hostBuilder, Action<ILoggingBuilder> configureLogging) { return hostBuilder.ConfigureServices(delegate(HostBuilderContext context, IServiceCollection collection) { collection.AddLogging(delegate(ILoggingBuilder builder) { configureLogging(builder); }); }); } public static IHostBuilder ConfigureHostOptions(this IHostBuilder hostBuilder, Action<HostBuilderContext, HostOptions> configureOptions) { return hostBuilder.ConfigureServices(delegate(HostBuilderContext context, IServiceCollection collection) { collection.Configure(delegate(HostOptions options) { configureOptions(context, options); }); }); } public static IHostBuilder ConfigureHostOptions(this IHostBuilder hostBuilder, Action<HostOptions> configureOptions) { return hostBuilder.ConfigureServices(delegate(IServiceCollection collection) { collection.Configure(configureOptions); }); } public static IHostBuilder ConfigureAppConfiguration(this IHostBuilder hostBuilder, Action<IConfigurationBuilder> configureDelegate) { return hostBuilder.ConfigureAppConfiguration(delegate(HostBuilderContext context, IConfigurationBuilder builder) { configureDelegate(builder); }); } public static IHostBuilder ConfigureServices(this IHostBuilder hostBuilder, Action<IServiceCollection> configureDelegate) { return hostBuilder.ConfigureServices(delegate(HostBuilderContext context, IServiceCollection collection) { configureDelegate(collection); }); } public static IHostBuilder ConfigureContainer<TContainerBuilder>(this IHostBuilder hostBuilder, Action<TContainerBuilder> configureDelegate) { return hostBuilder.ConfigureContainer(delegate(HostBuilderContext context, TContainerBuilder builder) { configureDelegate(builder); }); } public static IHostBuilder ConfigureDefaults(this IHostBuilder builder, string[] args) { builder.UseContentRoot(Directory.GetCurrentDirectory()); builder.ConfigureHostConfiguration(delegate(IConfigurationBuilder config) { config.AddEnvironmentVariables("DOTNET_"); if (args != null && args.Length > 0) { config.AddCommandLine(args); } }); builder.ConfigureAppConfiguration(delegate(HostBuilderContext hostingContext, IConfigurationBuilder config) { IHostEnvironment hostingEnvironment = hostingContext.HostingEnvironment; bool reloadConfigOnChangeValue = GetReloadConfigOnChangeValue(hostingContext); config.AddJsonFile("appsettings.json", optional: true, reloadConfigOnChangeValue).AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", optional: true, reloadConfigOnChangeValue); if (hostingEnvironment.IsDevelopment()) { string applicationName = hostingEnvironment.ApplicationName; if (applicationName != null && applicationName.Length > 0) { Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName)); if ((object)assembly != null) { config.AddUserSecrets(assembly, optional: true, reloadConfigOnChangeValue); } } } config.AddEnvironmentVariables(); if (args != null && args.Length > 0) { config.AddCommandLine(args); } }).ConfigureLogging(delegate(HostBuilderContext hostingContext, ILoggingBuilder logging) { bool flag2 = OperatingSystem.IsWindows(); if (flag2) { logging.AddFilter<EventLogLoggerProvider>((LogLevel level) => level >= LogLevel.Warning); } logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); if (!OperatingSystem.IsBrowser()) { logging.AddConsole(); } logging.AddDebug(); logging.AddEventSourceLogger(); if (flag2) { logging.AddEventLog(); } logging.Configure(delegate(LoggerFactoryOptions options) { options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId | ActivityTrackingOptions.TraceId | ActivityTrackingOptions.ParentId; }); }).UseDefaultServiceProvider(delegate(HostBuilderContext context, ServiceProviderOptions options) { bool validateOnBuild = (options.ValidateScopes = context.HostingEnvironment.IsDevelopment()); options.ValidateOnBuild = validateOnBuild; }); return builder; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Calling IConfiguration.GetValue is safe when the T is bool.")] static bool GetReloadConfigOnChangeValue(HostBuilderContext hostingContext) { return hostingContext.Configuration.GetValue("hostBuilder:reloadConfigOnChange", defaultValue: true); } } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static IHostBuilder UseConsoleLifetime(this IHostBuilder hostBuilder) { return hostBuilder.ConfigureServices(delegate(IServiceCollection collection) { collection.AddSingleton<IHostLifetime, ConsoleLifetime>(); }); } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static IHostBuilder UseConsoleLifetime(this IHostBuilder hostBuilder, Action<ConsoleLifetimeOptions> configureOptions) { return hostBuilder.ConfigureServices(delegate(IServiceCollection collection) { collection.AddSingleton<IHostLifetime, ConsoleLifetime>(); collection.Configure(configureOptions); }); } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static Task RunConsoleAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default(CancellationToken)) { return hostBuilder.UseConsoleLifetime().Build().RunAsync(cancellationToken); } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static Task RunConsoleAsync(this IHostBuilder hostBuilder, Action<ConsoleLifetimeOptions> configureOptions, CancellationToken cancellationToken = default(CancellationToken)) { return hostBuilder.UseConsoleLifetime(configureOptions).Build().RunAsync(cancellationToken); } } public class HostOptions { public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5.0); public BackgroundServiceExceptionBehavior BackgroundServiceExceptionBehavior { get; set; } internal void Initialize(IConfiguration configuration) { string text = configuration["shutdownTimeoutSeconds"]; if (!string.IsNullOrEmpty(text) && int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var result)) { ShutdownTimeout = TimeSpan.FromSeconds(result); } } } } 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) { _logger = logger; } public void StopApplication() { lock (_stoppingSource) { try { ExecuteHandlers(_stoppingSource); } catch (Exception exception) { _logger.ApplicationError(LoggerEventIds.ApplicationStoppingException, "An error occurred stopping the application", exception); } } } public void NotifyStarted() { try { ExecuteHandlers(_startedSource); } catch (Exception exception) { _logger.ApplicationError(LoggerEventIds.ApplicationStartupException, "An error occurred starting the application", exception); } } public void NotifyStopped() { try { ExecuteHandlers(_stoppedSource); } catch (Exception exception) { _logger.ApplicationError(LoggerEventIds.ApplicationStoppedException, "An error occurred stopping the application", exception); } } private void ExecuteHandlers(CancellationTokenSource cancel) { if (!cancel.IsCancellationRequested) { cancel.Cancel(throwOnFirstException: false); } } } internal sealed class ConfigureContainerAdapter<TContainerBuilder> : IConfigureContainerAdapter { private Action<HostBuilderContext, TContainerBuilder> _action; public ConfigureContainerAdapter(Action<HostBuilderContext, TContainerBuilder> action) { _action = action ?? throw new ArgumentNullException("action"); } public void ConfigureContainer(HostBuilderContext hostContext, object containerBuilder) { _action(hostContext, (TContainerBuilder)containerBuilder); } } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public class ConsoleLifetime : IHostLifetime, IDisposable { private CancellationTokenRegistration _applicationStartedRegistration; private CancellationTokenRegistration _applicationStoppingRegistration; private PosixSignalRegistration _sigIntRegistration; private PosixSignalRegistration _sigQuitRegistration; private PosixSignalRegistration _sigTermRegistration; private ConsoleLifetimeOptions Options { get; } private IHostEnvironment Environment { get; } private IHostApplicationLifetime ApplicationLifetime { get; } private HostOptions HostOptions { get; } private ILogger Logger { get; } public ConsoleLifetime(IOptions<ConsoleLifetimeOptions> options, IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, IOptions<HostOptions> hostOptions) : this(options, environment, applicationLifetime, hostOptions, NullLoggerFactory.Instance) { } public ConsoleLifetime(IOptions<ConsoleLifetimeOptions> options, IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, IOptions<HostOptions> hostOptions, ILoggerFactory loggerFactory) { Options = options?.Value ?? throw new ArgumentNullException("options"); Environment = environment ?? throw new ArgumentNullException("environment"); ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException("applicationLifetime"); HostOptions = hostOptions?.Value ?? throw new ArgumentNullException("hostOptions"); Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime"); } public Task WaitForStartAsync(CancellationToken cancellationToken) { if (!Options.SuppressStatusMessages) { _applicationStartedRegistration = ApplicationLifetime.ApplicationStarted.Register(delegate(object state) { ((ConsoleLifetime)state).OnApplicationStarted(); }, this); _applicationStoppingRegistration = ApplicationLifetime.ApplicationStopping.Register(delegate(object state) { ((ConsoleLifetime)state).OnApplicationStopping(); }, this); } RegisterShutdownHandlers(); return Task.CompletedTask; } private void RegisterShutdownHandlers() { Action<PosixSignalContext> handler = HandlePosixSignal; _sigIntRegistration = PosixSignalRegistration.Create(PosixSignal.SIGINT, handler); _sigQuitRegistration = PosixSignalRegistration.Create(PosixSignal.SIGQUIT, handler); _sigTermRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, handler); } private void OnApplicationStarted() { Logger.LogInformation("Application started. Press Ctrl+C to shut down."); Logger.LogInformation("Hosting environment: {envName}", Environment.EnvironmentName); Logger.LogInformation("Content root path: {contentRoot}", Environment.ContentRootPath); } private void OnApplicationStopping() { Logger.LogInformation("Application is shutting down..."); } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public void Dispose() { UnregisterShutdownHandlers(); _applicationStartedRegistration.Dispose(); _applicationStoppingRegistration.Dispose(); } private void UnregisterShutdownHandlers() { _sigIntRegistration?.Dispose(); _sigQuitRegistration?.Dispose(); _sigTermRegistration?.Dispose(); } private void HandlePosixSignal(PosixSignalContext context) { context.Cancel = true; ApplicationLifetime.StopApplication(); } } internal sealed class Host : IHost, IDisposable, IAsyncDisposable { 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 IEnumerable<IHostedService> _hostedServices; private volatile bool _stopCalled; public IServiceProvider Services { get; } public Host(IServiceProvider services, IHostEnvironment hostEnvironment, PhysicalFileProvider defaultProvider, IHostApplicationLifetime applicationLifetime, ILogger<Host> logger, IHostLifetime hostLifetime, IOptions<HostOptions> options) { Services = services ?? throw new ArgumentNullException("services"); _applicationLifetime = (applicationLifetime ?? throw new ArgumentNullException("applicationLifetime")) as ApplicationLifetime; _hostEnvironment = hostEnvironment; _defaultProvider = defaultProvider; if (_applicationLifetime == null) { throw new ArgumentException("Replacing IHostApplicationLifetime is not supported.", "applicationLifetime"); } _logger = logger ?? throw new ArgumentNullException("logger"); _hostLifetime = hostLifetime ?? throw new ArgumentNullException("hostLifetime"); _options = options?.Value ?? throw new ArgumentNullException("options"); } public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) { _logger.Starting(); using CancellationTokenSource combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _applicationLifetime.ApplicationStopping); CancellationToken combinedCancellationToken = combinedCancellationTokenSource.Token; await _hostLifetime.WaitForStartAsync(combinedCancellationToken).ConfigureAwait(continueOnCapturedContext: false); combinedCancellationToken.ThrowIfCancellationRequested(); _hostedServices = Services.GetService<IEnumerable<IHostedService>>(); foreach (IHostedService hostedService in _hostedServices) { await hostedService.StartAsync(combinedCancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (hostedService is BackgroundService backgroundService) { TryExecuteBackgroundServiceAsync(backgroundService); } } _applicationLifetime.NotifyStarted(); _logger.Started(); } private async Task TryExecuteBackgroundServiceAsync(BackgroundService backgroundService) { Task backgroundTask = backgroundService.ExecuteTask; if (backgroundTask == null) { return; } try { await backgroundTask.ConfigureAwait(continueOnCapturedContext: false); } catch (Exception ex) { if (!_stopCalled || !backgroundTask.IsCanceled || !(ex is OperationCanceledException)) { _logger.BackgroundServiceFaulted(ex); if (_options.BackgroundServiceExceptionBehavior == BackgroundServiceExceptionBehavior.StopHost) { _logger.BackgroundServiceStoppingHost(ex); _applicationLifetime.StopApplication(); } } } } public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken)) { _stopCalled = true; _logger.Stopping(); using (CancellationTokenSource cts = new CancellationTokenSource(_options.ShutdownTimeout)) { using CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken); CancellationToken token = linkedCts.Token; _applicationLifetime.StopApplication(); IList<Exception> exceptions = new List<Exception>(); if (_hostedServices != null) { foreach (IHostedService item3 in _hostedServices.Reverse()) { try { await item3.StopAsync(token).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception item) { exceptions.Add(item); } } } _applicationLifetime.NotifyStopped(); try { await _hostLifetime.StopAsync(token).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception item2) { exceptions.Add(item2); } if (exceptions.Count > 0) { AggregateException ex = new AggregateException("One or more hosted services failed to stop.", exceptions); _logger.StoppedWithException(ex); throw ex; } } _logger.Stopped(); } public void Dispose() { DisposeAsync().AsTask().GetAwaiter().GetResult(); } public async ValueTask DisposeAsync() { if (_hostEnvironment.ContentRootFileProvider != _defaultProvider) { await DisposeAsync(_hostEnvironment.ContentRootFileProvider).ConfigureAwait(continueOnCapturedContext: false); await DisposeAsync(_defaultProvider).ConfigureAwait(continueOnCapturedContext: false); } else { await DisposeAsync(_hostEnvironment.ContentRootFileProvider).ConfigureAwait(continueOnCapturedContext: false); } await DisposeAsync(Services).ConfigureAwait(continueOnCapturedContext: false); static async ValueTask DisposeAsync(object o) { if (!(o is IAsyncDisposable asyncDisposable)) { if (o is IDisposable disposable) { disposable.Dispose(); } } else { await asyncDisposable.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } } } } public class HostingEnvironment : IHostingEnvironment, IHostEnvironment { public string EnvironmentName { get; set; } public string ApplicationName { get; set; } public string ContentRootPath { get; set; } public IFileProvider ContentRootFileProvider { get; set; } } internal static class HostingLoggerExtensions { public static void ApplicationError(this ILogger logger, EventId eventId, string message, Exception exception) { if (exception is ReflectionTypeLoadException ex) { Exception[] loaderExceptions = ex.LoaderExceptions; foreach (Exception ex2 in loaderExceptions) { message = message + Environment.NewLine + ex2.Message; } } string message2 = message; logger.LogCritical(eventId, exception, message2); } public static void Starting(this ILogger logger) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug(LoggerEventIds.Starting, "Hosting starting"); } } public static void Started(this ILogger logger) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug(LoggerEventIds.Started, "Hosting started"); } } public static void Stopping(this ILogger logger) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug(LoggerEventIds.Stopping, "Hosting stopping"); } } public static void Stopped(this ILogger logger) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug(LoggerEventIds.Stopped, "Hosting stopped"); } } public static void StoppedWithException(this ILogger logger, Exception ex) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug(LoggerEventIds.StoppedWithException, ex, "Hosting shutdown exception"); } } public static void BackgroundServiceFaulted(this ILogger logger, Exception ex) { if (logger.IsEnabled(LogLevel.Error)) { logger.LogError(LoggerEventIds.BackgroundServiceFaulted, ex, "BackgroundService failed"); } } public static void BackgroundServiceStoppingHost(this ILogger logger, Exception ex) { if (logger.IsEnabled(LogLevel.Critical)) { logger.LogCritical(LoggerEventIds.BackgroundServiceStoppingHost, ex, System.SR.BackgroundServiceExceptionStoppedHost); } } } internal interface IConfigureContainerAdapter { void ConfigureContainer(HostBuilderContext hostContext, object containerBuilder); } internal interface IServiceFactoryAdapter { object CreateBuilder(IServiceCollection services); IServiceProvider CreateServiceProvider(object containerBuilder); } internal static class LoggerEventIds { public static readonly EventId Starting = new EventId(1, "Starting"); public static readonly EventId Started = new EventId(2, "Started"); public static readonly EventId Stopping = new EventId(3, "Stopping"); public static readonly EventId Stopped = new EventId(4, "Stopped"); public static readonly EventId StoppedWithException = new EventId(5, "StoppedWithException"); public static readonly EventId ApplicationStartupException = new EventId(6, "ApplicationStartupException"); public static readonly EventId ApplicationStoppingException = new EventId(7, "ApplicationStoppingException"); public static readonly EventId ApplicationStoppedException = new EventId(8, "ApplicationStoppedException"); public static readonly EventId BackgroundServiceFaulted = new EventId(9, "BackgroundServiceFaulted"); public static readonly EventId BackgroundServiceStoppingHost = new EventId(10, "BackgroundServiceStoppingHost"); } internal class NullLifetime : IHostLifetime { public Task WaitForStartAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } internal sealed class ServiceFactoryAdapter<TContainerBuilder> : IServiceFactoryAdapter { private IServiceProviderFactory<TContainerBuilder> _serviceProviderFactory; private readonly Func<HostBuilderContext> _contextResolver; private Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> _factoryResolver; public ServiceFactoryAdapter(IServiceProviderFactory<TContainerBuilder> serviceProviderFactory) { _serviceProviderFactory = serviceProviderFactory ?? throw new ArgumentNullException("serviceProviderFactory"); } public ServiceFactoryAdapter(Func<HostBuilderContext> contextResolver, Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factoryResolver) { _contextResolver = contextResolver ?? throw new ArgumentNullException("contextResolver"); _factoryResolver = factoryResolver ?? throw new ArgumentNullException("factoryResolver"); } public object CreateBuilder(IServiceCollection services) { if (_serviceProviderFactory == null) { _serviceProviderFactory = _factoryResolver(_contextResolver()); if (_serviceProviderFactory == null) { throw new InvalidOperationException(System.SR.ResolverReturnedNull); } } return _serviceProviderFactory.CreateBuilder(services); } public IServiceProvider CreateServiceProvider(object containerBuilder) { if (_serviceProviderFactory == null) { throw new InvalidOperationException(System.SR.CreateBuilderCallBeforeCreateServiceProvider); } return _serviceProviderFactory.CreateServiceProvider((TContainerBuilder)containerBuilder); } } }
MegabonkTogether/Microsoft.Extensions.Configuration.UserSecrets.dll
Decompiled 2 hours agousing System; using System.Diagnostics; 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(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.Configuration.UserSecrets.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Configuration.UserSecrets")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("User secrets configuration provider implementation for Microsoft.Extensions.Configuration.")] [assembly: AssemblyFileVersion("6.0.222.6406")] [assembly: AssemblyInformationalVersion("6.0.2+839cdfb0ecca5e0be3dbccd926e7651ef50fdf10")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Configuration.UserSecrets")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } } namespace FxResources.Microsoft.Extensions.Configuration.UserSecrets { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace 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) { if (configuration == null) { throw new ArgumentNullException("configuration"); } if (assembly == null) { throw new ArgumentNullException("assembly"); } UserSecretsIdAttribute customAttribute = assembly.GetCustomAttribute<UserSecretsIdAttribute>(); if (customAttribute != null) { return AddUserSecretsInternal(configuration, customAttribute.UserSecretsId, optional, reloadOnChange); } if (!optional) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_Missing_UserSecretsIdAttribute, 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) { if (configuration == null) { throw new ArgumentNullException("configuration"); } if (userSecretsId == null) { throw new ArgumentNullException("userSecretsId"); } return AddSecretsFile(configuration, PathHelper.GetSecretsPathFromSecretsId(userSecretsId), optional, reloadOnChange); } private static IConfigurationBuilder AddSecretsFile(IConfigurationBuilder configuration, string secretPath, bool optional, bool reloadOnChange) { string directoryName = Path.GetDirectoryName(secretPath); PhysicalFileProvider provider = (Directory.Exists(directoryName) ? new PhysicalFileProvider(directoryName) : null); return configuration.AddJsonFile(provider, "secrets.json", optional, reloadOnChange); } } } namespace Microsoft.Extensions.Configuration.UserSecrets { public class PathHelper { internal const string SecretsFileName = "secrets.json"; public static string GetSecretsPathFromSecretsId(string userSecretsId) { 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, userSecretsId[num], num)); } string environmentVariable = Environment.GetEnvironmentVariable("APPDATA"); string text = environmentVariable ?? Environment.GetEnvironmentVariable("HOME") ?? Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) ?? Environment.GetEnvironmentVariable("DOTNET_USER_SECRETS_FALLBACK_DIR"); if (string.IsNullOrEmpty(text)) { throw new InvalidOperationException(System.SR.Format(System.SR.Error_Missing_UserSecretsLocation, "DOTNET_USER_SECRETS_FALLBACK_DIR")); } if (string.IsNullOrEmpty(environmentVariable)) { return Path.Combine(text, ".microsoft", "usersecrets", userSecretsId, "secrets.json"); } return Path.Combine(text, "Microsoft", "UserSecrets", userSecretsId, "secrets.json"); } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] public class UserSecretsIdAttribute : Attribute { public string UserSecretsId { get; } public UserSecretsIdAttribute(string userSecretId) { if (string.IsNullOrEmpty(userSecretId)) { throw new ArgumentException(System.SR.Common_StringNullOrEmpty, "userSecretId"); } UserSecretsId = userSecretId; } } }
MegabonkTogether/MemoryPack.Core.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Numerics; 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.RegularExpressions; using System.Threading; using System.Threading.Tasks; using MemoryPack.Compression; using MemoryPack.Formatters; using MemoryPack.Internal; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Cysharp")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Cysharp, Inc.")] [assembly: AssemblyDescription("Core libraries(attribute, logics) of MemoryPack.")] [assembly: AssemblyFileVersion("1.21.4.0")] [assembly: AssemblyInformationalVersion("1.21.4+0f2fe0827907940768293b7bb81b9605a7d8cba8")] [assembly: AssemblyProduct("MemoryPack.Core")] [assembly: AssemblyTitle("MemoryPack.Core")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Cysharp/MemoryPack")] [assembly: InternalsVisibleTo("MemoryPack.Streaming, PublicKey=00240000048000009400000006020000002400005253413100040000010001000144ec28f1e9ef7b17dacc47425a7a153aea0a7baa590743a2d1a86f4b3e10a8a12712c6e647966bfd8bd6e830048b23bd42bbc56f179585c15b8c19cf86c0eed1b73c993dd7a93a30051dd50fdda0e4d6b65e6874e30f1c37cf8bcbc7fe02c7f2e6a0a3327c0ccc1631bf645f40732521fa0b41a30c178d08f7dd779d42a1ee")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.21.4.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } internal sealed class IsExternalInit { } } namespace MemoryPack { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackableAttribute : Attribute { public GenerateType GenerateType { get; } public SerializeLayout SerializeLayout { get; } public MemoryPackableAttribute(GenerateType generateType = GenerateType.Object) { GenerateType = generateType; SerializeLayout = ((generateType == GenerateType.VersionTolerant || generateType == GenerateType.CircularReference) ? SerializeLayout.Explicit : SerializeLayout.Sequential); } public MemoryPackableAttribute(SerializeLayout serializeLayout) { GenerateType = GenerateType.Object; SerializeLayout = serializeLayout; } public MemoryPackableAttribute(GenerateType generateType, SerializeLayout serializeLayout) { GenerateType = generateType; SerializeLayout = serializeLayout; } } public enum GenerateType { Object, VersionTolerant, CircularReference, Collection, NoGenerate } public enum SerializeLayout { Sequential, Explicit } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] public sealed class MemoryPackUnionAttribute : Attribute { public ushort Tag { get; } public Type Type { get; } public MemoryPackUnionAttribute(ushort tag, Type type) { Tag = tag; Type = type; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackUnionFormatterAttribute : Attribute { public Type Type { get; } public MemoryPackUnionFormatterAttribute(Type type) { Type = type; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackAllowSerializeAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackOrderAttribute : Attribute { public int Order { get; } public MemoryPackOrderAttribute(int order) { Order = order; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public abstract class MemoryPackCustomFormatterAttribute<T> : Attribute { public abstract IMemoryPackFormatter<T> GetFormatter(); } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public abstract class MemoryPackCustomFormatterAttribute<TFormatter, T> : Attribute where TFormatter : IMemoryPackFormatter<T> { public abstract TFormatter GetFormatter(); } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackIncludeAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackOnSerializingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackOnSerializedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackOnDeserializingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class MemoryPackOnDeserializedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public sealed class GenerateTypeScriptAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public sealed class SuppressDefaultInitializationAttribute : Attribute { } public sealed class Utf8StringFormatterAttribute : MemoryPackCustomFormatterAttribute<Utf8StringFormatter, string> { public override Utf8StringFormatter GetFormatter() { return Utf8StringFormatter.Default; } } public sealed class Utf16StringFormatterAttribute : MemoryPackCustomFormatterAttribute<Utf16StringFormatter, string> { public override Utf16StringFormatter GetFormatter() { return Utf16StringFormatter.Default; } } public sealed class OrdinalIgnoreCaseStringDictionaryFormatter<TValue> : MemoryPackCustomFormatterAttribute<DictionaryFormatter<string, TValue?>, Dictionary<string, TValue?>> { private static readonly DictionaryFormatter<string, TValue?> formatter = new DictionaryFormatter<string, TValue>(StringComparer.OrdinalIgnoreCase); public override DictionaryFormatter<string, TValue?> GetFormatter() { return formatter; } } public sealed class InternStringFormatterAttribute : MemoryPackCustomFormatterAttribute<InternStringFormatter, string> { public override InternStringFormatter GetFormatter() { return InternStringFormatter.Default; } } public sealed class BitPackFormatterAttribute : MemoryPackCustomFormatterAttribute<BitPackFormatter, bool[]> { public override BitPackFormatter GetFormatter() { return BitPackFormatter.Default; } } public sealed class BrotliFormatterAttribute : MemoryPackCustomFormatterAttribute<BrotliFormatter, byte[]> { public CompressionLevel CompressionLevel { get; } public int Window { get; } public int DecompressionSizeLimit { get; } public BrotliFormatterAttribute(CompressionLevel compressionLevel = CompressionLevel.Fastest, int window = 22, int decompressionSizeLimit = 134217728) { CompressionLevel = compressionLevel; Window = window; DecompressionSizeLimit = decompressionSizeLimit; } public override BrotliFormatter GetFormatter() { return new BrotliFormatter(CompressionLevel, Window, DecompressionSizeLimit); } } public sealed class BrotliFormatterAttribute<T> : MemoryPackCustomFormatterAttribute<BrotliFormatter<T>, T> { public CompressionLevel CompressionLevel { get; } public int Window { get; } public BrotliFormatterAttribute(CompressionLevel compressionLevel = CompressionLevel.Fastest, int window = 22) { CompressionLevel = compressionLevel; Window = window; } public override BrotliFormatter<T> GetFormatter() { return new BrotliFormatter<T>(CompressionLevel, Window); } } public sealed class BrotliStringFormatterAttribute : MemoryPackCustomFormatterAttribute<BrotliStringFormatter, string> { public CompressionLevel CompressionLevel { get; } public int Window { get; } public int DecompressionSizeLimit { get; } public BrotliStringFormatterAttribute(CompressionLevel compressionLevel = CompressionLevel.Fastest, int window = 22, int decompressionSizeLimit = 134217728) { CompressionLevel = compressionLevel; Window = window; DecompressionSizeLimit = decompressionSizeLimit; } public override BrotliStringFormatter GetFormatter() { return new BrotliStringFormatter(CompressionLevel, Window, DecompressionSizeLimit); } } public sealed class MemoryPoolFormatterAttribute<T> : MemoryPackCustomFormatterAttribute<MemoryPoolFormatter<T>, Memory<T?>> { private static readonly MemoryPoolFormatter<T> formatter = new MemoryPoolFormatter<T>(); public override MemoryPoolFormatter<T> GetFormatter() { return formatter; } } public sealed class ReadOnlyMemoryPoolFormatterAttribute<T> : MemoryPackCustomFormatterAttribute<ReadOnlyMemoryPoolFormatter<T>, ReadOnlyMemory<T?>> { private static readonly ReadOnlyMemoryPoolFormatter<T> formatter = new ReadOnlyMemoryPoolFormatter<T>(); public override ReadOnlyMemoryPoolFormatter<T> GetFormatter() { return formatter; } } public static class MemoryPackFormatterProvider { private static class Check<T> { public static bool registered; } private static class Cache<T> { public static MemoryPackFormatter<T> formatter; static Cache() { if (Check<T>.registered) { return; } try { Type typeFromHandle = typeof(T); if (TryInvokeRegisterFormatter(typeFromHandle)) { return; } if (TypeHelpers.IsAnonymous(typeFromHandle)) { formatter = new ErrorMemoryPackFormatter<T>("Serialize anonymous type is not supported, use record or tuple instead."); } else { bool typeIsReferenceOrContainsReferences = RuntimeHelpers.IsReferenceOrContainsReferences<T>(); formatter = (CreateGenericFormatter(typeFromHandle, typeIsReferenceOrContainsReferences) as MemoryPackFormatter<T>) ?? new ErrorMemoryPackFormatter<T>(); } } catch (Exception exception) { formatter = new ErrorMemoryPackFormatter<T>(exception); } formatters[typeof(T)] = formatter; Check<T>.registered = true; } } private static readonly Dictionary<Type, Type> ArrayLikeFormatters; private static readonly Dictionary<Type, Type> CollectionFormatters; private static readonly Dictionary<Type, Type> ImmutableCollectionFormatters; private static readonly Dictionary<Type, Type> InterfaceCollectionFormatters; private static readonly ConcurrentDictionary<Type, IMemoryPackFormatter> formatters; private static readonly ConcurrentDictionary<Type, Type> genericFormatterFactory; private static readonly ConcurrentDictionary<Type, Type> genericCollectionFormatterFactory; private static readonly Dictionary<Type, Type> KnownGenericTypeFormatters; static MemoryPackFormatterProvider() { ArrayLikeFormatters = new Dictionary<Type, Type>(4) { { typeof(ArraySegment<>), typeof(ArraySegmentFormatter<>) }, { typeof(Memory<>), typeof(MemoryFormatter<>) }, { typeof(ReadOnlyMemory<>), typeof(ReadOnlyMemoryFormatter<>) }, { typeof(ReadOnlySequence<>), typeof(ReadOnlySequenceFormatter<>) } }; CollectionFormatters = new Dictionary<Type, Type>(18) { { typeof(List<>), typeof(ListFormatter<>) }, { typeof(Stack<>), typeof(StackFormatter<>) }, { typeof(Queue<>), typeof(QueueFormatter<>) }, { typeof(LinkedList<>), typeof(LinkedListFormatter<>) }, { typeof(HashSet<>), typeof(HashSetFormatter<>) }, { typeof(SortedSet<>), typeof(SortedSetFormatter<>) }, { typeof(ObservableCollection<>), typeof(ObservableCollectionFormatter<>) }, { typeof(Collection<>), typeof(CollectionFormatter<>) }, { typeof(ConcurrentQueue<>), typeof(ConcurrentQueueFormatter<>) }, { typeof(ConcurrentStack<>), typeof(ConcurrentStackFormatter<>) }, { typeof(ConcurrentBag<>), typeof(ConcurrentBagFormatter<>) }, { typeof(Dictionary<, >), typeof(DictionaryFormatter<, >) }, { typeof(SortedDictionary<, >), typeof(SortedDictionaryFormatter<, >) }, { typeof(SortedList<, >), typeof(SortedListFormatter<, >) }, { typeof(ConcurrentDictionary<, >), typeof(ConcurrentDictionaryFormatter<, >) }, { typeof(ReadOnlyCollection<>), typeof(ReadOnlyCollectionFormatter<>) }, { typeof(ReadOnlyObservableCollection<>), typeof(ReadOnlyObservableCollectionFormatter<>) }, { typeof(BlockingCollection<>), typeof(BlockingCollectionFormatter<>) } }; ImmutableCollectionFormatters = new Dictionary<Type, Type> { { typeof(ImmutableArray<>), typeof(ImmutableArrayFormatter<>) }, { typeof(ImmutableList<>), typeof(ImmutableListFormatter<>) }, { typeof(ImmutableQueue<>), typeof(ImmutableQueueFormatter<>) }, { typeof(ImmutableStack<>), typeof(ImmutableStackFormatter<>) }, { typeof(ImmutableDictionary<, >), typeof(ImmutableDictionaryFormatter<, >) }, { typeof(ImmutableSortedDictionary<, >), typeof(ImmutableSortedDictionaryFormatter<, >) }, { typeof(ImmutableSortedSet<>), typeof(ImmutableSortedSetFormatter<>) }, { typeof(ImmutableHashSet<>), typeof(ImmutableHashSetFormatter<>) }, { typeof(IImmutableList<>), typeof(InterfaceImmutableListFormatter<>) }, { typeof(IImmutableQueue<>), typeof(InterfaceImmutableQueueFormatter<>) }, { typeof(IImmutableStack<>), typeof(InterfaceImmutableStackFormatter<>) }, { typeof(IImmutableDictionary<, >), typeof(InterfaceImmutableDictionaryFormatter<, >) }, { typeof(IImmutableSet<>), typeof(InterfaceImmutableSetFormatter<>) } }; InterfaceCollectionFormatters = new Dictionary<Type, Type>(11) { { typeof(IEnumerable<>), typeof(InterfaceEnumerableFormatter<>) }, { typeof(ICollection<>), typeof(InterfaceCollectionFormatter<>) }, { typeof(IReadOnlyCollection<>), typeof(InterfaceReadOnlyCollectionFormatter<>) }, { typeof(IList<>), typeof(InterfaceListFormatter<>) }, { typeof(IReadOnlyList<>), typeof(InterfaceReadOnlyListFormatter<>) }, { typeof(IDictionary<, >), typeof(InterfaceDictionaryFormatter<, >) }, { typeof(IReadOnlyDictionary<, >), typeof(InterfaceReadOnlyDictionaryFormatter<, >) }, { typeof(ILookup<, >), typeof(InterfaceLookupFormatter<, >) }, { typeof(IGrouping<, >), typeof(InterfaceGroupingFormatter<, >) }, { typeof(ISet<>), typeof(InterfaceSetFormatter<>) } }; formatters = new ConcurrentDictionary<Type, IMemoryPackFormatter>(Environment.ProcessorCount, 150); genericFormatterFactory = new ConcurrentDictionary<Type, Type>(); genericCollectionFormatterFactory = new ConcurrentDictionary<Type, Type>(); KnownGenericTypeFormatters = new Dictionary<Type, Type>(3) { { typeof(KeyValuePair<, >), typeof(KeyValuePairFormatter<, >) }, { typeof(Lazy<>), typeof(LazyFormatter<>) }, { typeof(Nullable<>), typeof(NullableFormatter<>) } }; RegisterWellKnownTypesFormatters(); } public static bool IsRegistered<T>() { return Check<T>.registered; } public static void Register<T>(MemoryPackFormatter<T> formatter) { Check<T>.registered = true; formatters[typeof(T)] = formatter; Cache<T>.formatter = formatter; } public static void RegisterGenericType(Type genericType, Type genericFormatterType) { if (genericType.IsGenericType && genericFormatterType.IsGenericType) { genericFormatterFactory[genericType] = genericFormatterType; } else { MemoryPackSerializationException.ThrowMessage("Registered type is not generic type. genericType:" + genericType.FullName + ", formatterType:" + genericFormatterType.FullName); } } public static void RegisterCollection<TCollection, TElement>() where TCollection : ICollection<TElement?>, new() { Register(new GenericCollectionFormatter<TCollection, TElement>()); } public static void RegisterCollection(Type genericCollectionType) { if (genericCollectionType.IsGenericType && genericCollectionType.GetGenericArguments().Length == 1) { genericCollectionFormatterFactory[genericCollectionType] = typeof(GenericCollectionFormatter<, >); } else { MemoryPackSerializationException.ThrowMessage("Registered generic collection is not filled generic formatter constraint. type: " + genericCollectionType.FullName); } } public static void RegisterSet<TSet, TElement>() where TSet : ISet<TElement?>, new() { Register(new GenericSetFormatter<TSet, TElement>()); } public static void RegisterSet(Type genericSetType) { if (genericSetType.IsGenericType && genericSetType.GetGenericArguments().Length == 1) { genericCollectionFormatterFactory[genericSetType] = typeof(GenericSetFormatter<, >); } else { MemoryPackSerializationException.ThrowMessage("Registered generic set is not filled generic formatter constraint. type: " + genericSetType.FullName); } } public static void RegisterDictionary<TDictionary, TKey, TValue>() where TDictionary : IDictionary<TKey, TValue?>, new() where TKey : notnull { Register(new GenericDictionaryFormatter<TDictionary, TKey, TValue>()); } public static void RegisterDictionary(Type genericDictionaryType) { if (genericDictionaryType.IsGenericType && genericDictionaryType.GetGenericArguments().Length == 2) { genericCollectionFormatterFactory[genericDictionaryType] = typeof(GenericDictionaryFormatter<, , >); } else { MemoryPackSerializationException.ThrowMessage("Registered generic collection is not filled generic formatter constraint. type: " + genericDictionaryType.FullName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static MemoryPackFormatter<T> GetFormatter<T>() { return Cache<T>.formatter; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static IMemoryPackFormatter GetFormatter(Type type) { if (formatters.TryGetValue(type, out IMemoryPackFormatter value)) { return value; } if (TryInvokeRegisterFormatter(type) && formatters.TryGetValue(type, out value)) { return value; } if (TypeHelpers.IsAnonymous(type)) { value = new ErrorMemoryPackFormatter(type, "Serialize anonymous type is not supported, use record or tuple instead."); } else { IMemoryPackFormatter memoryPackFormatter = CreateGenericFormatter(type, typeIsReferenceOrContainsReferences: true) as IMemoryPackFormatter; if (memoryPackFormatter == null) { memoryPackFormatter = new ErrorMemoryPackFormatter(type); } value = memoryPackFormatter; } formatters[type] = value; return value; } private static bool TryInvokeRegisterFormatter(Type type) { if (typeof(IMemoryPackFormatterRegister).IsAssignableFrom(type)) { MethodInfo method = type.GetMethod("MemoryPack.IMemoryPackFormatterRegister.RegisterFormatter", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) { method = type.GetMethod("RegisterFormatter", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } if (method == null) { throw new InvalidOperationException("Type implements IMemoryPackFormatterRegister but can not found RegisterFormatter. Type: " + type.FullName); } method.Invoke(null, null); return true; } return false; } internal static object? CreateGenericFormatter(Type type, bool typeIsReferenceOrContainsReferences) { Type type2 = null; if (type.IsArray) { if (type.IsSZArray) { type2 = (typeIsReferenceOrContainsReferences ? typeof(ArrayFormatter<>).MakeGenericType(type.GetElementType()) : typeof(DangerousUnmanagedArrayFormatter<>).MakeGenericType(type.GetElementType())); } else { switch (type.GetArrayRank()) { case 2: type2 = typeof(TwoDimensionalArrayFormatter<>).MakeGenericType(type.GetElementType()); break; case 3: type2 = typeof(ThreeDimensionalArrayFormatter<>).MakeGenericType(type.GetElementType()); break; case 4: type2 = typeof(FourDimensionalArrayFormatter<>).MakeGenericType(type.GetElementType()); break; default: return null; } } } else if (type.IsEnum || !typeIsReferenceOrContainsReferences) { type2 = typeof(DangerousUnmanagedFormatter<>).MakeGenericType(type); } else { type2 = TryCreateGenericFormatterType(type, TupleFormatterTypes.TupleFormatters); if (!(type2 != null)) { type2 = TryCreateGenericFormatterType(type, KnownGenericTypeFormatters); if (!(type2 != null)) { type2 = TryCreateGenericFormatterType(type, ArrayLikeFormatters); if (!(type2 != null)) { type2 = TryCreateGenericFormatterType(type, CollectionFormatters); if (!(type2 != null)) { type2 = TryCreateGenericFormatterType(type, ImmutableCollectionFormatters); if (!(type2 != null)) { type2 = TryCreateGenericFormatterType(type, InterfaceCollectionFormatters); if (!(type2 != null)) { type2 = TryCreateGenericFormatterType(type, genericFormatterFactory); if (!(type2 != null)) { type2 = TryCreateGenericCollectionFormatterType(type); if (!(type2 != null)) { return null; } } } } } } } } } return Activator.CreateInstance(type2); } private static Type? TryCreateGenericFormatterType(Type type, IDictionary<Type, Type> knownTypes) { if (type.IsGenericType) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (knownTypes.TryGetValue(genericTypeDefinition, out Type value)) { return value.MakeGenericType(type.GetGenericArguments()); } } return null; } private static Type? TryCreateGenericCollectionFormatterType(Type type) { if (type.IsGenericType && genericCollectionFormatterFactory.TryGetValue(type, out Type value)) { Type[] genericArguments = type.GetGenericTypeDefinition().GetGenericArguments(); return value.MakeGenericType(genericArguments.Prepend(type).ToArray()); } return null; } internal static void RegisterWellKnownTypesFormatters() { Register(new UnmanagedFormatter<sbyte>()); Register(new UnmanagedArrayFormatter<sbyte>()); Register(new NullableFormatter<sbyte>()); Register(new UnmanagedFormatter<byte>()); Register(new UnmanagedArrayFormatter<byte>()); Register(new NullableFormatter<byte>()); Register(new UnmanagedFormatter<short>()); Register(new UnmanagedArrayFormatter<short>()); Register(new NullableFormatter<short>()); Register(new UnmanagedFormatter<ushort>()); Register(new UnmanagedArrayFormatter<ushort>()); Register(new NullableFormatter<ushort>()); Register(new UnmanagedFormatter<int>()); Register(new UnmanagedArrayFormatter<int>()); Register(new NullableFormatter<int>()); Register(new UnmanagedFormatter<uint>()); Register(new UnmanagedArrayFormatter<uint>()); Register(new NullableFormatter<uint>()); Register(new UnmanagedFormatter<long>()); Register(new UnmanagedArrayFormatter<long>()); Register(new NullableFormatter<long>()); Register(new UnmanagedFormatter<ulong>()); Register(new UnmanagedArrayFormatter<ulong>()); Register(new NullableFormatter<ulong>()); Register(new UnmanagedFormatter<char>()); Register(new UnmanagedArrayFormatter<char>()); Register(new NullableFormatter<char>()); Register(new UnmanagedFormatter<float>()); Register(new UnmanagedArrayFormatter<float>()); Register(new NullableFormatter<float>()); Register(new UnmanagedFormatter<double>()); Register(new UnmanagedArrayFormatter<double>()); Register(new NullableFormatter<double>()); Register(new UnmanagedFormatter<decimal>()); Register(new UnmanagedArrayFormatter<decimal>()); Register(new NullableFormatter<decimal>()); Register(new UnmanagedFormatter<bool>()); Register(new UnmanagedArrayFormatter<bool>()); Register(new NullableFormatter<bool>()); Register(new UnmanagedFormatter<IntPtr>()); Register(new UnmanagedArrayFormatter<IntPtr>()); Register(new NullableFormatter<IntPtr>()); Register(new UnmanagedFormatter<UIntPtr>()); Register(new UnmanagedArrayFormatter<UIntPtr>()); Register(new NullableFormatter<UIntPtr>()); Register(new UnmanagedFormatter<DateTime>()); Register(new UnmanagedArrayFormatter<DateTime>()); Register(new NullableFormatter<DateTime>()); Register(new UnmanagedFormatter<DateTimeOffset>()); Register(new UnmanagedArrayFormatter<DateTimeOffset>()); Register(new NullableFormatter<DateTimeOffset>()); Register(new UnmanagedFormatter<TimeSpan>()); Register(new UnmanagedArrayFormatter<TimeSpan>()); Register(new NullableFormatter<TimeSpan>()); Register(new UnmanagedFormatter<Guid>()); Register(new UnmanagedArrayFormatter<Guid>()); Register(new NullableFormatter<Guid>()); Register(new UnmanagedFormatter<Complex>()); Register(new UnmanagedArrayFormatter<Complex>()); Register(new NullableFormatter<Complex>()); Register(new UnmanagedFormatter<Plane>()); Register(new UnmanagedArrayFormatter<Plane>()); Register(new NullableFormatter<Plane>()); Register(new UnmanagedFormatter<Quaternion>()); Register(new UnmanagedArrayFormatter<Quaternion>()); Register(new NullableFormatter<Quaternion>()); Register(new UnmanagedFormatter<Matrix3x2>()); Register(new UnmanagedArrayFormatter<Matrix3x2>()); Register(new NullableFormatter<Matrix3x2>()); Register(new UnmanagedFormatter<Matrix4x4>()); Register(new UnmanagedArrayFormatter<Matrix4x4>()); Register(new NullableFormatter<Matrix4x4>()); Register(new UnmanagedFormatter<Vector2>()); Register(new UnmanagedArrayFormatter<Vector2>()); Register(new NullableFormatter<Vector2>()); Register(new UnmanagedFormatter<Vector3>()); Register(new UnmanagedArrayFormatter<Vector3>()); Register(new NullableFormatter<Vector3>()); Register(new UnmanagedFormatter<Vector4>()); Register(new UnmanagedArrayFormatter<Vector4>()); Register(new NullableFormatter<Vector4>()); Register(new StringFormatter()); Register(new ArrayFormatter<string>()); Register(new VersionFormatter()); Register(new ArrayFormatter<Version>()); Register(new UriFormatter()); Register(new ArrayFormatter<Uri>()); Register(new TimeZoneInfoFormatter()); Register(new ArrayFormatter<TimeZoneInfo>()); Register(new BigIntegerFormatter()); Register(new ArrayFormatter<BigInteger>()); Register(new BitArrayFormatter()); Register(new ArrayFormatter<BitArray>()); Register(new StringBuilderFormatter()); Register(new ArrayFormatter<StringBuilder>()); Register(new TypeFormatter()); Register(new ArrayFormatter<Type>()); Register(new CultureInfoFormatter()); Register(new ArrayFormatter<CultureInfo>()); } } public interface IMemoryPackFormatterRegister { } public interface IMemoryPackable<T> : IMemoryPackFormatterRegister { } [Preserve] public interface IMemoryPackFormatter { [Preserve] void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref object? value) where TBufferWriter : class, IBufferWriter<byte>; [Preserve] void Deserialize(ref MemoryPackReader reader, scoped ref object? value); } [Preserve] public interface IMemoryPackFormatter<T> { [Preserve] void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref T? value) where TBufferWriter : class, IBufferWriter<byte>; [Preserve] void Deserialize(ref MemoryPackReader reader, scoped ref T? value); } [Preserve] public abstract class MemoryPackFormatter<T> : IMemoryPackFormatter<T>, IMemoryPackFormatter { [Preserve] public abstract void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref T? value) where TBufferWriter : class, IBufferWriter<byte>; [Preserve] public abstract void Deserialize(ref MemoryPackReader reader, scoped ref T? value); [Preserve] void IMemoryPackFormatter.Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref object? value) { T value2 = ((value == null) ? default(T) : ((T)value)); Serialize(ref writer, ref value2); } [Preserve] void IMemoryPackFormatter.Deserialize(ref MemoryPackReader reader, scoped ref object? value) { T value2 = ((value == null) ? default(T) : ((T)value)); Deserialize(ref reader, ref value2); value = value2; } } public static class MemoryPackCode { public const int NullCollection = -1; public const byte WideTag = 250; public const byte ReferenceId = 250; public const byte Reserved1 = 250; public const byte Reserved2 = 251; public const byte Reserved3 = 252; public const byte Reserved4 = 253; public const byte Reserved5 = 254; public const byte NullObject = byte.MaxValue; internal static ReadOnlySpan<byte> NullCollectionData => new byte[4] { 255, 255, 255, 255 }; internal static ReadOnlySpan<byte> ZeroCollectionData => new byte[4] { 0, 0, 0, 0 }; } internal sealed class ErrorMemoryPackFormatter : IMemoryPackFormatter { private readonly Type type; private readonly string? message; public ErrorMemoryPackFormatter(Type type) { this.type = type; message = null; } public ErrorMemoryPackFormatter(Type type, string message) { this.type = type; this.message = message; } public void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref object? value) where TBufferWriter : class, IBufferWriter<byte> { Throw(); } public void Deserialize(ref MemoryPackReader reader, scoped ref object? value) { Throw(); } [DoesNotReturn] private void Throw() { if (message != null) { MemoryPackSerializationException.ThrowMessage(message); } else { MemoryPackSerializationException.ThrowNotRegisteredInProvider(type); } } } internal sealed class ErrorMemoryPackFormatter<T> : MemoryPackFormatter<T> { private readonly Exception? exception; private readonly string? message; public ErrorMemoryPackFormatter() { exception = null; message = null; } public ErrorMemoryPackFormatter(Exception exception) { this.exception = exception; message = null; } public ErrorMemoryPackFormatter(string message) { exception = null; this.message = message; } public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref T? value) { Throw(); } public override void Deserialize(ref MemoryPackReader reader, scoped ref T? value) { Throw(); } [DoesNotReturn] private void Throw() { if (exception != null) { MemoryPackSerializationException.ThrowRegisterInProviderFailed(typeof(T), exception); } else if (message != null) { MemoryPackSerializationException.ThrowMessage(message); } else { MemoryPackSerializationException.ThrowNotRegisteredInProvider(typeof(T)); } } } [StructLayout(LayoutKind.Auto)] public ref struct MemoryPackReader { private ReadOnlySequence<byte> bufferSource; private readonly long totalLength; private ReadOnlySpan<byte> bufferReference; private int bufferLength; private byte[]? rentBuffer; private int advancedCount; private int consumed; private readonly MemoryPackReaderOptionalState optionalState; public int Consumed => consumed; public long Remaining => totalLength - consumed; public MemoryPackReaderOptionalState OptionalState => optionalState; public MemoryPackSerializerOptions Options => optionalState.Options; public MemoryPackReader(in ReadOnlySequence<byte> sequence, MemoryPackReaderOptionalState optionalState) { bufferSource = (sequence.IsSingleSegment ? ReadOnlySequence<byte>.Empty : sequence); ReadOnlySpan<byte> readOnlySpan = (bufferReference = sequence.FirstSpan); bufferLength = readOnlySpan.Length; advancedCount = 0; consumed = 0; rentBuffer = null; totalLength = sequence.Length; this.optionalState = optionalState; } public MemoryPackReader(ReadOnlySpan<byte> buffer, MemoryPackReaderOptionalState optionalState) { bufferSource = ReadOnlySequence<byte>.Empty; bufferReference = buffer; bufferLength = buffer.Length; advancedCount = 0; consumed = 0; rentBuffer = null; totalLength = buffer.Length; this.optionalState = optionalState; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref byte GetSpanReference(int sizeHint) { if (sizeHint <= bufferLength) { return ref MemoryMarshal.GetReference(bufferReference); } return ref GetNextSpan(sizeHint); } [MethodImpl(MethodImplOptions.NoInlining)] private ref byte GetNextSpan(int sizeHint) { if (rentBuffer != null) { ArrayPool<byte>.Shared.Return(rentBuffer); rentBuffer = null; } if (Remaining == 0L) { MemoryPackSerializationException.ThrowSequenceReachedEnd(); } try { bufferSource = bufferSource.Slice(advancedCount); } catch (ArgumentOutOfRangeException) { MemoryPackSerializationException.ThrowSequenceReachedEnd(); } advancedCount = 0; if (sizeHint <= Remaining) { if (sizeHint <= bufferSource.FirstSpan.Length) { bufferReference = bufferSource.FirstSpan; bufferLength = bufferSource.FirstSpan.Length; return ref MemoryMarshal.GetReference(bufferReference); } rentBuffer = ArrayPool<byte>.Shared.Rent(sizeHint); ReadOnlySequence<byte> source = bufferSource.Slice(0, sizeHint); BuffersExtensions.CopyTo(in source, rentBuffer); Span<byte> span = rentBuffer.AsSpan(0, sizeHint); bufferReference = span; bufferLength = span.Length; return ref MemoryMarshal.GetReference(bufferReference); } MemoryPackSerializationException.ThrowSequenceReachedEnd(); return ref MemoryMarshal.GetReference(bufferReference); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Advance(int count) { if (count != 0) { int num = bufferLength - count; if (num >= 0 || !TryAdvanceSequence(count)) { bufferLength = num; bufferReference = bufferReference.Slice(count); advancedCount += count; consumed += count; } } } [MethodImpl(MethodImplOptions.NoInlining)] private bool TryAdvanceSequence(int count) { if (bufferSource.Length - count < 0) { MemoryPackSerializationException.ThrowInvalidAdvance(); } bufferSource = bufferSource.Slice(advancedCount + count); bufferReference = bufferSource.FirstSpan; bufferLength = bufferSource.FirstSpan.Length; advancedCount = 0; consumed += count; return true; } public void GetRemainingSource(out ReadOnlySpan<byte> singleSource, out ReadOnlySequence<byte> remainingSource) { if (bufferSource.IsEmpty) { remainingSource = ReadOnlySequence<byte>.Empty; singleSource = bufferReference; return; } if (bufferSource.IsSingleSegment) { remainingSource = ReadOnlySequence<byte>.Empty; singleSource = bufferSource.FirstSpan.Slice(advancedCount); return; } singleSource = default(ReadOnlySpan<byte>); remainingSource = bufferSource.Slice(advancedCount); if (remainingSource.IsSingleSegment) { singleSource = remainingSource.FirstSpan; remainingSource = ReadOnlySequence<byte>.Empty; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { if (rentBuffer != null) { ArrayPool<byte>.Shared.Return(rentBuffer); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IMemoryPackFormatter GetFormatter(Type type) { return MemoryPackFormatterProvider.GetFormatter(type); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IMemoryPackFormatter<T> GetFormatter<T>() { return MemoryPackFormatterProvider.GetFormatter<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryReadObjectHeader(out byte memberCount) { memberCount = GetSpanReference(1); Advance(1); return memberCount != byte.MaxValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryReadUnionHeader(out ushort tag) { byte spanReference = GetSpanReference(1); Advance(1); if (spanReference < 250) { tag = spanReference; return true; } if (spanReference == 250) { ReadUnmanaged<ushort>(out tag); return true; } tag = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryReadCollectionHeader(out int length) { length = Unsafe.ReadUnaligned<int>(ref GetSpanReference(4)); Advance(4); if (Remaining < length) { MemoryPackSerializationException.ThrowInsufficientBufferUnless(length); } return length != -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool PeekIsNull() { return GetSpanReference(1) == byte.MaxValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPeekObjectHeader(out byte memberCount) { memberCount = GetSpanReference(1); return memberCount != byte.MaxValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPeekUnionHeader(out ushort tag) { byte spanReference = GetSpanReference(1); if (spanReference < 250) { tag = spanReference; return true; } if (spanReference == 250) { tag = Unsafe.ReadUnaligned<ushort>(ref Unsafe.Add(ref GetSpanReference(3), 1)); return true; } tag = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPeekCollectionHeader(out int length) { length = Unsafe.ReadUnaligned<int>(ref GetSpanReference(4)); if (Remaining < length) { MemoryPackSerializationException.ThrowInsufficientBufferUnless(length); } return length != -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool DangerousTryReadCollectionHeader(out int length) { length = Unsafe.ReadUnaligned<int>(ref GetSpanReference(4)); Advance(4); return length != -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public string? ReadString() { if (!TryReadCollectionHeader(out var length)) { return null; } if (length == 0) { return ""; } if (length > 0) { return ReadUtf16(length); } return ReadUtf8(length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private string ReadUtf16(int length) { int num = checked(length * 2); string result = new string(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As<byte, char>(ref GetSpanReference(num)), length)); Advance(num); return result; } [MethodImpl(MethodImplOptions.NoInlining)] private string ReadUtf8(int utf8Length) { utf8Length = ~utf8Length; ref byte spanReference = ref GetSpanReference(utf8Length + 4); int num = Unsafe.ReadUnaligned<int>(ref spanReference); string @string; if (num <= 0) { ReadOnlySpan<byte> bytes = MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref spanReference, 4), utf8Length); @string = Encoding.UTF8.GetString(bytes); } else { long num2 = (Remaining + 1) * 3; if (num2 < 0) { num2 = 2147483647L; } if (num2 < num) { MemoryPackSerializationException.ThrowInsufficientBufferUnless(utf8Length); } ReadOnlySpan<byte> bytes2 = MemoryMarshal.CreateReadOnlySpan(ref Unsafe.Add(ref spanReference, 4), utf8Length); @string = Encoding.UTF8.GetString(bytes2); } Advance(utf8Length + 4); return @string; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T1 ReadUnmanaged<T1>() where T1 : unmanaged { int num = Unsafe.SizeOf<T1>(); T1 result = Unsafe.ReadUnaligned<T1>(ref GetSpanReference(num)); Advance(num); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadPackable<T>(scoped ref T? value) where T : IMemoryPackable<T> { ReadValue(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T? ReadPackable<T>() where T : IMemoryPackable<T> { return ReadValue<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadValue<T>(scoped ref T? value) { GetFormatter<T>().Deserialize(ref this, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T? ReadValue<T>() { T value = default(T); GetFormatter<T>().Deserialize(ref this, ref value); return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadValue(Type type, ref object? value) { GetFormatter(type).Deserialize(ref this, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public object? ReadValue(Type type) { object value = null; GetFormatter(type).Deserialize(ref this, ref value); return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadValueWithFormatter<TFormatter, T>(TFormatter formatter, scoped ref T? value) where TFormatter : IMemoryPackFormatter<T> { formatter.Deserialize(ref this, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T? ReadValueWithFormatter<TFormatter, T>(TFormatter formatter) where TFormatter : IMemoryPackFormatter<T> { T value = default(T); formatter.Deserialize(ref this, ref value); return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T?[]? ReadArray<T>() { T[] value = null; ReadArray(ref value); return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadArray<T>(scoped ref T?[]? value) { if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { DangerousReadUnmanagedArray(ref value); return; } if (!TryReadCollectionHeader(out var length)) { value = null; return; } if (length == 0) { value = Array.Empty<T>(); return; } if (value == null || value.Length != length) { value = new T[length]; } IMemoryPackFormatter<T> formatter = GetFormatter<T>(); for (int i = 0; i < length; i++) { formatter.Deserialize(ref this, ref value[i]); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadSpan<T>(scoped ref Span<T?> value) { if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { DangerousReadUnmanagedSpan(ref value); return; } if (!TryReadCollectionHeader(out var length)) { value = default(Span<T>); return; } if (length == 0) { value = Array.Empty<T>(); return; } if (value.Length != length) { value = new T[length]; } IMemoryPackFormatter<T> formatter = GetFormatter<T>(); for (int i = 0; i < length; i++) { formatter.Deserialize(ref this, ref value[i]); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T?[]? ReadPackableArray<T>() where T : IMemoryPackable<T> { T[] value = null; ReadPackableArray(ref value); return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadPackableArray<T>(scoped ref T?[]? value) where T : IMemoryPackable<T> { ReadArray(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadPackableSpan<T>(scoped ref Span<T?> value) where T : IMemoryPackable<T> { ReadSpan(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[]? ReadUnmanagedArray<T>() where T : unmanaged { return DangerousReadUnmanagedArray<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanagedArray<T>(scoped ref T[]? value) where T : unmanaged { DangerousReadUnmanagedArray(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanagedSpan<T>(scoped ref Span<T> value) where T : unmanaged { DangerousReadUnmanagedSpan(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[]? DangerousReadUnmanagedArray<T>() { if (!TryReadCollectionHeader(out var length)) { return null; } if (length == 0) { return Array.Empty<T>(); } int num = length * Unsafe.SizeOf<T>(); ref byte spanReference = ref GetSpanReference(num); T[] array = MemoryMarshalEx.AllocateUninitializedArray<T>(length); Unsafe.CopyBlockUnaligned(ref Unsafe.As<T, byte>(ref MemoryMarshalEx.GetArrayDataReference(array)), ref spanReference, (uint)num); Advance(num); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanagedArray<T>(scoped ref T[]? value) { if (!TryReadCollectionHeader(out var length)) { value = null; return; } if (length == 0) { value = Array.Empty<T>(); return; } int num = length * Unsafe.SizeOf<T>(); ref byte spanReference = ref GetSpanReference(num); if (value == null || value.Length != length) { value = MemoryMarshalEx.AllocateUninitializedArray<T>(length); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<T, byte>(ref MemoryMarshalEx.GetArrayDataReference(value)), ref spanReference, (uint)num); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanagedSpan<T>(scoped ref Span<T> value) { if (!TryReadCollectionHeader(out var length)) { value = default(Span<T>); return; } if (length == 0) { value = Array.Empty<T>(); return; } int num = length * Unsafe.SizeOf<T>(); ref byte spanReference = ref GetSpanReference(num); if (value == null || value.Length != length) { value = MemoryMarshalEx.AllocateUninitializedArray<T>(length); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), ref spanReference, (uint)num); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadSpanWithoutReadLengthHeader<T>(int length, scoped ref Span<T?> value) { if (length == 0) { value = Array.Empty<T>(); } else if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { if (value.Length != length) { value = MemoryMarshalEx.AllocateUninitializedArray<T>(length); } int num = length * Unsafe.SizeOf<T>(); ref byte spanReference = ref GetSpanReference(num); Unsafe.CopyBlockUnaligned(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), ref spanReference, (uint)num); Advance(num); } else { if (value.Length != length) { value = new T[length]; } IMemoryPackFormatter<T> formatter = GetFormatter<T>(); for (int i = 0; i < length; i++) { formatter.Deserialize(ref this, ref value[i]); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadPackableSpanWithoutReadLengthHeader<T>(int length, scoped ref Span<T?> value) where T : IMemoryPackable<T> { ReadSpanWithoutReadLengthHeader(length, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanagedSpanView<T>(out bool isNull, out ReadOnlySpan<byte> view) { if (!TryReadCollectionHeader(out var length)) { isNull = true; view = default(ReadOnlySpan<byte>); return; } isNull = false; if (length == 0) { view = Array.Empty<byte>(); return; } int num = length * Unsafe.SizeOf<T>(); ReadOnlySpan<byte> readOnlySpan = MemoryMarshal.CreateReadOnlySpan(ref GetSpanReference(num), num); Advance(num); view = readOnlySpan; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1>(out T1 value1) where T1 : unmanaged { int num = Unsafe.SizeOf<T1>(); value1 = Unsafe.ReadUnaligned<T1>(ref GetSpanReference(num)); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2>(out T1 value1, out T2 value2) where T1 : unmanaged where T2 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3>(out T1 value1, out T2 value2, out T3 value3) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4>(out T1 value1, out T2 value2, out T3 value3, out T4 value4) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged where T8 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged where T8 : unmanaged where T9 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged where T8 : unmanaged where T9 : unmanaged where T10 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10, out T11 value11) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged where T8 : unmanaged where T9 : unmanaged where T10 : unmanaged where T11 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); value11 = Unsafe.ReadUnaligned<T11>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10, out T11 value11, out T12 value12) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged where T8 : unmanaged where T9 : unmanaged where T10 : unmanaged where T11 : unmanaged where T12 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); value11 = Unsafe.ReadUnaligned<T11>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>())); value12 = Unsafe.ReadUnaligned<T12>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10, out T11 value11, out T12 value12, out T13 value13) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged where T8 : unmanaged where T9 : unmanaged where T10 : unmanaged where T11 : unmanaged where T12 : unmanaged where T13 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>() + Unsafe.SizeOf<T13>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); value11 = Unsafe.ReadUnaligned<T11>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>())); value12 = Unsafe.ReadUnaligned<T12>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>())); value13 = Unsafe.ReadUnaligned<T13>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10, out T11 value11, out T12 value12, out T13 value13, out T14 value14) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged where T8 : unmanaged where T9 : unmanaged where T10 : unmanaged where T11 : unmanaged where T12 : unmanaged where T13 : unmanaged where T14 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>() + Unsafe.SizeOf<T13>() + Unsafe.SizeOf<T14>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); value11 = Unsafe.ReadUnaligned<T11>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>())); value12 = Unsafe.ReadUnaligned<T12>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>())); value13 = Unsafe.ReadUnaligned<T13>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>())); value14 = Unsafe.ReadUnaligned<T14>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>() + Unsafe.SizeOf<T13>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10, out T11 value11, out T12 value12, out T13 value13, out T14 value14, out T15 value15) where T1 : unmanaged where T2 : unmanaged where T3 : unmanaged where T4 : unmanaged where T5 : unmanaged where T6 : unmanaged where T7 : unmanaged where T8 : unmanaged where T9 : unmanaged where T10 : unmanaged where T11 : unmanaged where T12 : unmanaged where T13 : unmanaged where T14 : unmanaged where T15 : unmanaged { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>() + Unsafe.SizeOf<T13>() + Unsafe.SizeOf<T14>() + Unsafe.SizeOf<T15>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); value11 = Unsafe.ReadUnaligned<T11>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>())); value12 = Unsafe.ReadUnaligned<T12>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>())); value13 = Unsafe.ReadUnaligned<T13>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>())); value14 = Unsafe.ReadUnaligned<T14>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>() + Unsafe.SizeOf<T13>())); value15 = Unsafe.ReadUnaligned<T15>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>() + Unsafe.SizeOf<T13>() + Unsafe.SizeOf<T14>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1>(out T1 value1) { int num = Unsafe.SizeOf<T1>(); value1 = Unsafe.ReadUnaligned<T1>(ref GetSpanReference(num)); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2>(out T1 value1, out T2 value2) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3>(out T1 value1, out T2 value2, out T3 value3) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4>(out T1 value1, out T2 value2, out T3 value3, out T4 value4) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5, T6>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5, T6, T7>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10, out T11 value11) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); value11 = Unsafe.ReadUnaligned<T11>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10, out T11 value11, out T12 value12) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); value11 = Unsafe.ReadUnaligned<T11>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>())); value12 = Unsafe.ReadUnaligned<T12>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>())); Advance(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousReadUnmanaged<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(out T1 value1, out T2 value2, out T3 value3, out T4 value4, out T5 value5, out T6 value6, out T7 value7, out T8 value8, out T9 value9, out T10 value10, out T11 value11, out T12 value12, out T13 value13) { int num = Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>() + Unsafe.SizeOf<T12>() + Unsafe.SizeOf<T13>(); ref byte spanReference = ref GetSpanReference(num); value1 = Unsafe.ReadUnaligned<T1>(ref spanReference); value2 = Unsafe.ReadUnaligned<T2>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>())); value3 = Unsafe.ReadUnaligned<T3>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>())); value4 = Unsafe.ReadUnaligned<T4>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>())); value5 = Unsafe.ReadUnaligned<T5>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>())); value6 = Unsafe.ReadUnaligned<T6>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>())); value7 = Unsafe.ReadUnaligned<T7>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>())); value8 = Unsafe.ReadUnaligned<T8>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>())); value9 = Unsafe.ReadUnaligned<T9>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>())); value10 = Unsafe.ReadUnaligned<T10>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>())); value11 = Unsafe.ReadUnaligned<T11>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>())); value12 = Unsafe.ReadUnaligned<T12>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<T4>() + Unsafe.SizeOf<T5>() + Unsafe.SizeOf<T6>() + Unsafe.SizeOf<T7>() + Unsafe.SizeOf<T8>() + Unsafe.SizeOf<T9>() + Unsafe.SizeOf<T10>() + Unsafe.SizeOf<T11>())); value13 = Unsafe.ReadUnaligned<T13>(ref Unsafe.Add(ref spanReference, Unsafe.SizeOf<T1>() + Unsafe.SizeOf<T2>() + Unsafe.SizeOf<T3>() + Unsafe.SizeOf<
MegabonkTogether/Microsoft.Extensions.Logging.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; 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.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Logging infrastructure default implementation for Microsoft.Extensions.Logging.")] [assembly: AssemblyFileVersion("6.0.21.52210")] [assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.Logging")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] namespace FxResources.Microsoft.Extensions.Logging { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string 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(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace 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) { if (services == null) { throw new ArgumentNullException("services"); } services.AddOptions(); services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>()); services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>))); services.TryAddEnumerable(ServiceDescriptor.Singleton((IConfigureOptions<LoggerFilterOptions>)new DefaultLoggerLevelConfigureOptions(LogLevel.Information))); configure(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) { options.MinLevel = level; }) { } } public static class FilterLoggingBuilderExtensions { public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<string, string, LogLevel, bool> filter) { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(filter); }); } public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<string, LogLevel, bool> categoryLevelFilter) { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(categoryLevelFilter); }); } public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, Func<string, LogLevel, bool> categoryLevelFilter) where T : ILoggerProvider { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter<T>(categoryLevelFilter); }); } public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, Func<LogLevel, bool> levelFilter) { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(levelFilter); }); } public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter<T>(levelFilter); }); } public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, string category, LogLevel level) { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(category, level); }); } public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, string category, LogLevel level) where T : ILoggerProvider { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter<T>(category, level); }); } public static ILoggingBuilder AddFilter(this ILoggingBuilder builder, string category, Func<LogLevel, bool> levelFilter) { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter(category, levelFilter); }); } public static ILoggingBuilder AddFilter<T>(this ILoggingBuilder builder, string category, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider { return builder.ConfigureFilter(delegate(LoggerFilterOptions options) { options.AddFilter<T>(category, levelFilter); }); } 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) { return AddRule(builder, null, null, null, (string type, string name, LogLevel level) => categoryLevelFilter(name, level)); } public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, Func<string, LogLevel, bool> categoryLevelFilter) where T : ILoggerProvider { return AddRule(builder, typeof(T).FullName, null, null, (string type, string name, LogLevel level) => categoryLevelFilter(name, level)); } public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, Func<LogLevel, bool> levelFilter) { return AddRule(builder, null, null, null, (string type, string name, LogLevel level) => levelFilter(level)); } public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider { return AddRule(builder, typeof(T).FullName, null, null, (string type, string name, LogLevel level) => levelFilter(level)); } public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, string category, LogLevel level) { return AddRule(builder, null, category, level); } public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, string category, LogLevel level) where T : ILoggerProvider { return AddRule(builder, typeof(T).FullName, category, level); } public static LoggerFilterOptions AddFilter(this LoggerFilterOptions builder, string category, Func<LogLevel, bool> levelFilter) { return AddRule(builder, null, category, null, (string type, string name, LogLevel level) => levelFilter(level)); } public static LoggerFilterOptions AddFilter<T>(this LoggerFilterOptions builder, string category, Func<LogLevel, bool> levelFilter) where T : ILoggerProvider { return AddRule(builder, typeof(T).FullName, category, null, (string type, string name, LogLevel level) => levelFilter(level)); } private static ILoggingBuilder ConfigureFilter(this ILoggingBuilder builder, Action<LoggerFilterOptions> configureOptions) { builder.Services.Configure(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) { 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 : IDisposable { private bool _isDisposed; private IDisposable _disposable0; private IDisposable _disposable1; private readonly IDisposable[] _disposable; public Scope(int count) { if (count > 2) { _disposable = new IDisposable[count - 2]; } } public void SetDisposable(int index, 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++) { if (_disposable[i] != null) { _disposable[i].Dispose(); } } } _isDisposed = true; } } public LoggerInformation[] Loggers { get; set; } public MessageLogger[] MessageLoggers { get; set; } public ScopeLogger[] ScopeLoggers { get; set; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { MessageLogger[] messageLoggers = MessageLoggers; if (messageLoggers == null) { return; } List<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); } static void LoggerLog(LogLevel logLevel, EventId eventId, ILogger logger, Exception exception, Func<TState, Exception, string> formatter, ref List<Exception> exceptions, in TState state) { try { logger.Log(logLevel, eventId, state, exception, formatter); } catch (Exception item) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(item); } } } public bool IsEnabled(LogLevel logLevel) { MessageLogger[] messageLoggers = MessageLoggers; if (messageLoggers == null) { return false; } List<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; static bool LoggerIsEnabled(LogLevel logLevel, ILogger logger, ref List<Exception> exceptions) { try { if (logger.IsEnabled(logLevel)) { return true; } } catch (Exception item) { if (exceptions == null) { exceptions = new List<Exception>(); } exceptions.Add(item); } return false; } } public IDisposable BeginScope<TState>(TState state) { ScopeLogger[] scopeLoggers = ScopeLoggers; if (scopeLoggers == null) { return Microsoft.Extensions.Logging.NullScope.Instance; } if (scopeLoggers.Length == 1) { return scopeLoggers[0].CreateScope(state); } Scope scope = new Scope(scopeLoggers.Length); List<Exception> list = null; for (int i = 0; i < scopeLoggers.Length; i++) { ref ScopeLogger reference = ref scopeLoggers[i]; try { scope.SetDisposable(i, reference.CreateScope(state)); } catch (Exception item) { if (list == null) { list = new List<Exception>(); } list.Add(item); } } if (list != null && list.Count > 0) { ThrowLoggingError(list); } return scope; } private static void ThrowLoggingError(List<Exception> exceptions) { throw new AggregateException("An error occurred while writing to logger(s).", exceptions); } } public class LoggerFactory : ILoggerFactory, IDisposable { private struct ProviderRegistration { public ILoggerProvider Provider; public bool ShouldDispose; } private sealed class DisposingLoggerFactory : ILoggerFactory, 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>(StringComparer.Ordinal); private readonly List<ProviderRegistration> _providerRegistrations = new List<ProviderRegistration>(); private readonly object _sync = new object(); private volatile bool _disposed; private IDisposable _changeTokenRegistration; private LoggerFilterOptions _filterOptions; private LoggerFactoryScopeProvider _scopeProvider; private LoggerFactoryOptions _factoryOptions; public LoggerFactory() : this(Array.Empty<ILoggerProvider>()) { } public LoggerFactory(IEnumerable<ILoggerProvider> providers) : this(providers, new StaticFilterOptionsMonitor(new LoggerFilterOptions())) { } public LoggerFactory(IEnumerable<ILoggerProvider> providers, LoggerFilterOptions filterOptions) : this(providers, new StaticFilterOptionsMonitor(filterOptions)) { } public LoggerFactory(IEnumerable<ILoggerProvider> providers, IOptionsMonitor<LoggerFilterOptions> filterOption) : this(providers, filterOption, null) { } public LoggerFactory(IEnumerable<ILoggerProvider> providers, IOptionsMonitor<LoggerFilterOptions> filterOption, IOptions<LoggerFactoryOptions> options = null) { _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"); } foreach (ILoggerProvider provider in providers) { AddProviderRegistration(provider, dispose: false); } _changeTokenRegistration = filterOption.OnChange(RefreshFilters); RefreshFilters(filterOption.CurrentValue); } public static ILoggerFactory Create(Action<ILoggingBuilder> configure) { ServiceCollection services = new ServiceCollection(); services.AddLogging(configure); ServiceProvider serviceProvider = services.BuildServiceProvider(); ILoggerFactory service = serviceProvider.GetService<ILoggerFactory>(); return new DisposingLoggerFactory(service, serviceProvider); } private void RefreshFilters(LoggerFilterOptions filterOptions) { lock (_sync) { _filterOptions = filterOptions; foreach (KeyValuePair<string, Logger> logger2 in _loggers) { Logger value = logger2.Value; (value.MessageLoggers, value.ScopeLoggers) = ApplyFilters(value.Loggers); } } } public ILogger CreateLogger(string categoryName) { if (CheckDisposed()) { throw new ObjectDisposedException("LoggerFactory"); } lock (_sync) { if (!_loggers.TryGetValue(categoryName, out var value)) { value = new Logger { Loggers = CreateLoggers(categoryName) }; (value.MessageLoggers, value.ScopeLoggers) = ApplyFilters(value.Loggers); _loggers[categoryName] = value; } return value; } } public void AddProvider(ILoggerProvider provider) { if (CheckDisposed()) { throw new ObjectDisposedException("LoggerFactory"); } if (provider == null) { throw new ArgumentNullException("provider"); } lock (_sync) { AddProviderRegistration(provider, dispose: true); foreach (KeyValuePair<string, Logger> logger2 in _loggers) { Logger value = logger2.Value; LoggerInformation[] array = value.Loggers; int num = array.Length; Array.Resize(ref array, array.Length + 1); array[num] = new LoggerInformation(provider, logger2.Key); value.Loggers = array; (value.MessageLoggers, value.ScopeLoggers) = ApplyFilters(value.Loggers); } } } private void AddProviderRegistration(ILoggerProvider provider, bool dispose) { _providerRegistrations.Add(new ProviderRegistration { Provider = provider, ShouldDispose = dispose }); if (provider is ISupportExternalScope supportExternalScope) { if (_scopeProvider == null) { _scopeProvider = new LoggerFactoryScopeProvider(_factoryOptions.ActivityTrackingOptions); } supportExternalScope.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 (MessageLogger[] MessageLoggers, ScopeLogger[] ScopeLoggers) ApplyFilters(LoggerInformation[] loggers) { List<MessageLogger> list = new List<MessageLogger>(); List<ScopeLogger> list2 = (_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 || !(minLevel > LogLevel.Critical)) { list.Add(new MessageLogger(loggerInformation.Logger, loggerInformation.Category, loggerInformation.ProviderType.FullName, minLevel, filter)); if (!loggerInformation.ExternalScope) { list2?.Add(new ScopeLogger(loggerInformation.Logger, null)); } } } if (_scopeProvider != null) { list2?.Add(new ScopeLogger(null, _scopeProvider)); } return (list.ToArray(), list2?.ToArray()); } protected virtual bool CheckDisposed() { return _disposed; } public void Dispose() { if (_disposed) { return; } _disposed = true; _changeTokenRegistration?.Dispose(); foreach (ProviderRegistration providerRegistration in _providerRegistrations) { try { if (providerRegistration.ShouldDispose) { providerRegistration.Provider.Dispose(); } } catch { } } } } public class LoggerFactoryOptions { public ActivityTrackingOptions ActivityTrackingOptions { get; set; } } internal sealed class LoggerFactoryScopeProvider : IExternalScopeProvider { private sealed class Scope : IDisposable { private readonly LoggerFactoryScopeProvider _provider; private bool _isDisposed; public Scope Parent { get; } public object State { get; } internal Scope(LoggerFactoryScopeProvider provider, object state, Scope parent) { _provider = provider; State = state; Parent = parent; } public override string ToString() { return State?.ToString(); } public void Dispose() { if (!_isDisposed) { _provider._currentScope.Value = Parent; _isDisposed = true; } } } private sealed class ActivityLogScope : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>> { private string _cachedToString; private const int MaxItems = 5; private KeyValuePair<string, object>[] _items = new KeyValuePair<string, object>[5]; public int Count { get; } public KeyValuePair<string, object> this[int index] { get { if (index >= Count) { throw new ArgumentOutOfRangeException("index"); } return _items[index]; } } public ActivityLogScope(Activity activity, ActivityTrackingOptions activityTrackingOption) { int num = 0; if ((activityTrackingOption & ActivityTrackingOptions.SpanId) != 0) { _items[num++] = new KeyValuePair<string, object>("SpanId", activity.GetSpanId()); } if ((activityTrackingOption & ActivityTrackingOptions.TraceId) != 0) { _items[num++] = new KeyValuePair<string, object>("TraceId", activity.GetTraceId()); } if ((activityTrackingOption & ActivityTrackingOptions.ParentId) != 0) { _items[num++] = new KeyValuePair<string, object>("ParentId", activity.GetParentId()); } if ((activityTrackingOption & ActivityTrackingOptions.TraceState) != 0) { _items[num++] = new KeyValuePair<string, object>("TraceState", activity.TraceStateString); } if ((activityTrackingOption & ActivityTrackingOptions.TraceFlags) != 0) { _items[num++] = new KeyValuePair<string, object>("TraceFlags", activity.ActivityTraceFlags); } Count = num; } public override string ToString() { if (_cachedToString == null) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(_items[0].Key); stringBuilder.Append(':'); stringBuilder.Append(_items[0].Value); for (int i = 1; i < Count; i++) { stringBuilder.Append(", "); stringBuilder.Append(_items[i].Key); stringBuilder.Append(':'); stringBuilder.Append(_items[i].Value); } _cachedToString = stringBuilder.ToString(); } return _cachedToString; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { int i = 0; while (i < Count) { yield return this[i]; int num = i + 1; i = num; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private sealed class ActivityBaggageLogScopeWrapper : IEnumerable<KeyValuePair<string, string>>, IEnumerable { private readonly IEnumerable<KeyValuePair<string, string>> _items; private StringBuilder _stringBuilder; public ActivityBaggageLogScopeWrapper(IEnumerable<KeyValuePair<string, string>> items) { _items = items; } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return _items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _items.GetEnumerator(); } public override string ToString() { lock (this) { IEnumerator<KeyValuePair<string, string>> enumerator = _items.GetEnumerator(); if (!enumerator.MoveNext()) { return string.Empty; } if (_stringBuilder == null) { _stringBuilder = new StringBuilder(); } _stringBuilder.Append(enumerator.Current.Key); _stringBuilder.Append(':'); _stringBuilder.Append(enumerator.Current.Value); while (enumerator.MoveNext()) { _stringBuilder.Append(", "); _stringBuilder.Append(enumerator.Current.Key); _stringBuilder.Append(':'); _stringBuilder.Append(enumerator.Current.Value); } string result = _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__", activityLogScope); } callback(activityLogScope, state); if ((_activityTrackingOption & ActivityTrackingOptions.Tags) != 0 && current2.TagObjects.GetEnumerator().MoveNext()) { callback(current2.TagObjects, state); } if ((_activityTrackingOption & ActivityTrackingOptions.Baggage) != 0) { IEnumerable<KeyValuePair<string, string>> baggage = current2.Baggage; if (baggage.GetEnumerator().MoveNext()) { ActivityBaggageLogScopeWrapper orCreateActivityBaggageLogScopeWrapper = GetOrCreateActivityBaggageLogScopeWrapper(current2, baggage); callback(orCreateActivityBaggageLogScopeWrapper, state); } } } } Report(_currentScope.Value); void Report(Scope current) { if (current != null) { Report(current.Parent); callback(current.State, state); } } } private static ActivityBaggageLogScopeWrapper GetOrCreateActivityBaggageLogScopeWrapper(Activity activity, IEnumerable<KeyValuePair<string, string>> items) { ActivityBaggageLogScopeWrapper activityBaggageLogScopeWrapper = activity.GetCustomProperty("__ActivityBaggageItemsLogScope__") as ActivityBaggageLogScopeWrapper; if (activityBaggageLogScopeWrapper == null) { activityBaggageLogScopeWrapper = new ActivityBaggageLogScopeWrapper(items); activity.SetCustomProperty("__ActivityBaggageItemsLogScope__", activityBaggageLogScopeWrapper); } return activityBaggageLogScopeWrapper; } public 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) { return (string)((activity.IdFormat switch { ActivityIdFormat.Hierarchical => activity.Id, ActivityIdFormat.W3C => activity.SpanId.ToHexString(), _ => null, }) ?? string.Empty); } public static string GetTraceId(this Activity activity) { return (string)((activity.IdFormat switch { ActivityIdFormat.Hierarchical => activity.RootId, ActivityIdFormat.W3C => activity.TraceId.ToHexString(), _ => null, }) ?? string.Empty); } public static string GetParentId(this Activity activity) { return (string)((activity.IdFormat switch { ActivityIdFormat.Hierarchical => activity.ParentId, ActivityIdFormat.W3C => activity.ParentSpanId.ToHexString(), _ => null, }) ?? string.Empty); } } public class LoggerFilterOptions { public bool CaptureScopes { get; set; } = true; public LogLevel MinLevel { get; set; } public IList<LoggerFilterRule> Rules => RulesInternal; internal List<LoggerFilterRule> RulesInternal { get; } = new List<LoggerFilterRule>(); } public class LoggerFilterRule { public string ProviderName { get; } public string CategoryName { get; } public LogLevel? LogLevel { get; } public Func<string, string, LogLevel, bool> Filter { get; } public LoggerFilterRule(string providerName, string categoryName, LogLevel? logLevel, Func<string, string, LogLevel, bool> filter) { ProviderName = providerName; CategoryName = categoryName; LogLevel = logLevel; Filter = filter; } public override string ToString() { return string.Format("{0}: '{1}', {2}: '{3}', {4}: '{5}', {6}: '{7}'", "ProviderName", ProviderName, "CategoryName", CategoryName, "LogLevel", LogLevel, "Filter", Filter); } } internal readonly struct MessageLogger { public ILogger Logger { get; } public string Category { get; } private string ProviderTypeFullName { get; } public LogLevel? MinLevel { get; } public Func<string, string, LogLevel, bool> Filter { 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) { if (MinLevel.HasValue && level < MinLevel) { return false; } if (Filter != null) { return Filter(ProviderTypeFullName, Category, level); } return true; } } internal readonly struct ScopeLogger { public ILogger Logger { get; } public IExternalScopeProvider ExternalScopeProvider { get; } public ScopeLogger(ILogger logger, IExternalScopeProvider externalScopeProvider) { Logger = logger; ExternalScopeProvider = externalScopeProvider; } public IDisposable CreateScope<TState>(TState state) { if (ExternalScopeProvider != null) { return ExternalScopeProvider.Push(state); } return Logger.BeginScope(state); } } internal readonly struct LoggerInformation { public ILogger Logger { get; } public string Category { get; } public Type ProviderType { get; } public bool ExternalScope { get; } public LoggerInformation(ILoggerProvider provider, string category) { this = default(LoggerInformation); ProviderType = provider.GetType(); Logger = provider.CreateLogger(category); Category = category; ExternalScope = provider is ISupportExternalScope; } } internal static class LoggerRuleSelector { public static void Select(LoggerFilterOptions options, Type providerType, string category, out LogLevel? minLevel, out Func<string, string, LogLevel, bool> filter) { filter = null; minLevel = options.MinLevel; string alias = ProviderAliasUtilities.GetAlias(providerType); LoggerFilterRule loggerFilterRule = null; foreach (LoggerFilterRule item in options.RulesInternal) { if (IsBetter(item, loggerFilterRule, providerType.FullName, category) || (!string.IsNullOrEmpty(alias) && IsBetter(item, loggerFilterRule, alias, category))) { loggerFilterRule = item; } } if (loggerFilterRule != null) { filter = loggerFilterRule.Filter; minLevel = loggerFilterRule.LogLevel; } } private static bool IsBetter(LoggerFilterRule rule, LoggerFilterRule current, string logger, string category) { 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); } ReadOnlySpan<char> value; ReadOnlySpan<char> value2; if (num == -1) { value = categoryName.AsSpan(); value2 = default(ReadOnlySpan<char>); } else { value = categoryName.AsSpan(0, num); value2 = categoryName.AsSpan(num + 1); } if (!category.AsSpan().StartsWith(value, StringComparison.OrdinalIgnoreCase) || !category.AsSpan().EndsWith(value2, StringComparison.OrdinalIgnoreCase)) { 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 { public IServiceCollection Services { get; } public LoggingBuilder(IServiceCollection services) { Services = services; } } public static class LoggingBuilderExtensions { public static ILoggingBuilder SetMinimumLevel(this ILoggingBuilder builder, LogLevel level) { builder.Services.Add(ServiceDescriptor.Singleton((IConfigureOptions<LoggerFilterOptions>)new DefaultLoggerLevelConfigureOptions(level))); return builder; } public static ILoggingBuilder AddProvider(this ILoggingBuilder builder, ILoggerProvider provider) { builder.Services.AddSingleton(provider); return builder; } public static ILoggingBuilder ClearProviders(this ILoggingBuilder builder) { builder.Services.RemoveAll<ILoggerProvider>(); return builder; } public static ILoggingBuilder Configure(this ILoggingBuilder builder, Action<LoggerFactoryOptions> action) { builder.Services.Configure(action); return builder; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ProviderAliasAttribute : Attribute { public string Alias { get; } public ProviderAliasAttribute(string alias) { Alias = alias; } } internal sealed class StaticFilterOptionsMonitor : IOptionsMonitor<LoggerFilterOptions> { public LoggerFilterOptions CurrentValue { get; } public StaticFilterOptionsMonitor(LoggerFilterOptions currentValue) { CurrentValue = currentValue; } public IDisposable OnChange(Action<LoggerFilterOptions, string> listener) { return null; } public LoggerFilterOptions Get(string name) { return CurrentValue; } } internal static class ProviderAliasUtilities { private const string AliasAttibuteTypeFullName = "Microsoft.Extensions.Logging.ProviderAliasAttribute"; internal static string GetAlias(Type providerType) { IList<CustomAttributeData> customAttributes = CustomAttributeData.GetCustomAttributes(providerType); for (int i = 0; i < customAttributes.Count; i++) { CustomAttributeData customAttributeData = customAttributes[i]; if (customAttributeData.AttributeType.FullName == "Microsoft.Extensions.Logging.ProviderAliasAttribute" && customAttributeData.ConstructorArguments.Count > 0) { return customAttributeData.ConstructorArguments[0].Value?.ToString(); } } return null; } } internal sealed class NullExternalScopeProvider : IExternalScopeProvider { public static IExternalScopeProvider Instance { get; } = new Microsoft.Extensions.Logging.NullExternalScopeProvider(); private NullExternalScopeProvider() { } void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state) { } IDisposable IExternalScopeProvider.Push(object state) { return Microsoft.Extensions.Logging.NullScope.Instance; } } internal sealed class NullScope : IDisposable { public static Microsoft.Extensions.Logging.NullScope Instance { get; } = new Microsoft.Extensions.Logging.NullScope(); private NullScope() { } public void Dispose() { } } }