コード例 #1
0
        private static RateLimitLease?CommonAcquireLogic(Exception?ex, RateLimitLease?lease, ref RateLimitLease[]?leases, int index, int length)
        {
            if (ex is not null)
            {
                AggregateException?innerEx = CommonDispose(leases, index);
                if (innerEx is not null)
                {
                    Exception[] exceptions = new Exception[innerEx.InnerExceptions.Count + 1];
                    innerEx.InnerExceptions.CopyTo(exceptions, 0);
                    exceptions[exceptions.Length - 1] = ex;
                    throw new AggregateException(exceptions);
                }
                throw ex;
            }

            if (!lease !.IsAcquired)
            {
                AggregateException?innerEx = CommonDispose(leases, index);
                return(innerEx is not null ? throw innerEx : lease);
            }

            leases ??= new RateLimitLease[length];
            leases[index] = lease;
            return(null);
        }
コード例 #2
0
        /// <summary>Adds the exception to the list, first initializing the list if the list is null.</summary>
        /// <param name="list">The list to add the exception to, and initialize if null.</param>
        /// <param name="exception">The exception to add or whose inner exception(s) should be added.</param>
        /// <param name="unwrapInnerExceptions">Unwrap and add the inner exception(s) rather than the specified exception directly.</param>
        /// <remarks>This method is not thread-safe, in that it manipulates <paramref name="list"/> without any synchronization.</remarks>
        internal static void AddException([NotNull] ref List <Exception>?list, Exception exception, bool unwrapInnerExceptions = false)
        {
            Debug.Assert(exception != null, "An exception to add is required.");
            Debug.Assert(!unwrapInnerExceptions || exception.InnerException != null,
                         "If unwrapping is requested, an inner exception is required.");

            // Make sure the list of exceptions is initialized (lazily).
            list ??= new List <Exception>();

            if (unwrapInnerExceptions)
            {
                AggregateException?aggregate = exception as AggregateException;
                if (aggregate != null)
                {
                    list.AddRange(aggregate.InnerExceptions);
                }
                else
                {
                    list.Add(exception.InnerException !);
                }
            }
            else
            {
                list.Add(exception);
            }
        }
コード例 #3
0
        private void OnTaskCompleted(Task task)
        {
            if (!task.IsFaulted)
            {
                return;
            }
            AggregateException?errs = task.Exception;

            if (errs == null)
            {
                return;
            }
            lock (_lockObject)
            {
                _exceptions.AddRange(errs.InnerExceptions);
                if (_promise != null)
                {
                    var err = Flush();
                    if (err != null)
                    {
                        _promise.SetResult(err);
                    }
                    _promise = null;
                }
            }
        }
コード例 #4
0
        /// <summary>
        /// Propagates completion of sourceCompletionTask to target synchronously.
        /// </summary>
        /// <param name="sourceCompletionTask">The task whose completion is to be propagated. It must be completed.</param>
        /// <param name="target">The block where completion is propagated.</param>
        /// <param name="exceptionHandler">Handler for exceptions from the target. May be null which would propagate the exception to the caller.</param>
        internal static void PropagateCompletion(Task sourceCompletionTask, IDataflowBlock target, Action <Exception>?exceptionHandler)
        {
            Debug.Assert(sourceCompletionTask != null, "sourceCompletionTask may not be null.");
            Debug.Assert(target != null, "The target where completion is to be propagated may not be null.");
            Debug.Assert(sourceCompletionTask.IsCompleted, "sourceCompletionTask must be completed in order to propagate its completion.");

            AggregateException?exception = sourceCompletionTask.IsFaulted ? sourceCompletionTask.Exception : null;

            try
            {
                if (exception != null)
                {
                    target.Fault(exception);
                }
                else
                {
                    target.Complete();
                }
            }
            catch (Exception exc)
            {
                if (exceptionHandler != null)
                {
                    exceptionHandler(exc);
                }
                else
                {
                    throw;
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Body"/> class.
        /// </summary>
        /// <param name="exception">The exception.</param>
        public Body(System.Exception exception)
        {
            Assumption.AssertNotNull(exception, nameof(exception));

            this.OriginalException = exception;

            AggregateException?aggregateException = exception as AggregateException;

            if (aggregateException != null)
            {
                TraceChain = aggregateException.InnerExceptions.Select(e => new Trace(e)).ToArray();
            }
            else if (exception.InnerException != null)
            {
                var exceptionList  = new List <System.Exception>();
                var outerException = exception;
                while (outerException != null)
                {
                    exceptionList.Add(outerException);
                    outerException = outerException.InnerException;
                }
                TraceChain = exceptionList.Select(e => new Trace(e)).ToArray();
            }
            else
            {
                Trace = new Trace(exception);
            }

            Validate();
        }
コード例 #6
0
ファイル: DefaultHostRunner.cs プロジェクト: Takym/ExapisSOP
 private Task PostHandleException(AggregateException?e1, Exception e2)
 {
     if (_loggerEnabled && _logger != null)
     {
         _logger.UnhandledException(e1 !, true);
         _logger.UnhandledException(e2, true);
     }
     return(Task.CompletedTask);
 }
コード例 #7
0
    public void GetResultWithoutInlining_Faulted()
    {
        var tcs = new TaskCompletionSource <int>();

        tcs.SetException(new InvalidOperationException());
        AggregateException?ex = Assert.Throws <AggregateException>(() => tcs.Task.GetResultWithoutInlining(throwOriginalException: false));

        ex.Handle(x => x is InvalidOperationException);
    }
コード例 #8
0
        public static IList <StackFrameInfo> GetFrames(Exception exception, out AggregateException?error)
        {
            var frames = new List <StackFrameInfo>();

            if (exception == null)
            {
                error = default;
                return(frames);
            }

            var needFileInfo = true;
            var stackTrace   = new System.Diagnostics.StackTrace(exception, needFileInfo);
            var stackFrames  = stackTrace.GetFrames();

            if (stackFrames == null)
            {
                error = default;
                return(frames);
            }

            List <Exception>?exceptions = null;

            for (var i = 0; i < stackFrames.Length; i++)
            {
                var frame  = stackFrames[i];
                var method = frame.GetMethod();

                // Always show last stackFrame
                if (!ShowInStackTrace(method) && i < stackFrames.Length - 1)
                {
                    continue;
                }

                var stackFrame = new StackFrameInfo
                {
                    StackFrame        = frame,
                    FilePath          = frame.GetFileName(),
                    LineNumber        = frame.GetFileLineNumber(),
                    MethodDisplayInfo = GetMethodDisplayString(frame.GetMethod()),
                };

                frames.Add(stackFrame);
            }

            if (exceptions != null)
            {
                error = new AggregateException(exceptions);
                return(frames);
            }

            error = default;
            return(frames);
        }
コード例 #9
0
ファイル: StackTraceHelper.cs プロジェクト: tarynt/AspNetCore
    public static IList <StackFrameInfo> GetFrames(Exception exception, out AggregateException?error)
    {
        if (exception == null)
        {
            error = default;
            return(Array.Empty <StackFrameInfo>());
        }

        var needFileInfo = true;
        var stackTrace   = new System.Diagnostics.StackTrace(exception, needFileInfo);
        var stackFrames  = stackTrace.GetFrames();

        if (stackFrames == null)
        {
            error = default;
            return(Array.Empty <StackFrameInfo>());
        }

        var frames = new List <StackFrameInfo>(stackFrames.Length);

        List <Exception>?exceptions = null;

        for (var i = 0; i < stackFrames.Length; i++)
        {
            var frame  = stackFrames[i];
            var method = frame.GetMethod();

            // MethodInfo should always be available for methods in the stack, but double check for null here.
            // Apps with trimming enabled may remove some metdata. Better to be safe than sorry.
            if (method == null)
            {
                continue;
            }

            // Always show last stackFrame
            if (!ShowInStackTrace(method) && i < stackFrames.Length - 1)
            {
                continue;
            }

            var stackFrame = new StackFrameInfo(frame.GetFileLineNumber(), frame.GetFileName(), frame, GetMethodDisplayString(method));
            frames.Add(stackFrame);
        }

        if (exceptions != null)
        {
            error = new AggregateException(exceptions);
            return(frames);
        }

        error = default;
        return(frames);
    }
コード例 #10
0
ファイル: ExtensionMethods.cs プロジェクト: ThomasReth/ITSS2
 public static String Format(this AggregateException?instance)
 {
     return(instance.Format(( StringBuilder buffer ) =>
     {
         if (instance is not null)
         {
             foreach (Exception innerException in instance.InnerExceptions)
             {
                 buffer.AppendLine(innerException.Format());
             }
         }
     }));
 }
コード例 #11
0
    private static Exception?UnwrapAggregateException(AggregateException?aggregateException)
    {
        if (aggregateException == null)
        {
            return(null);
        }

        if (aggregateException.InnerExceptions.Count == 1)
        {
            return(aggregateException.InnerExceptions[0]);
        }

        return(aggregateException);
    }
コード例 #12
0
ファイル: AggregateException.cs プロジェクト: pongba/corert
        /// <summary>
        /// Returns the <see cref="System.AggregateException"/> that is the root cause of this exception.
        /// </summary>
        public override Exception GetBaseException()
        {
            // Returns the first inner AggregateException that contains more or less than one inner exception

            // Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception
            Exception?         back            = this;
            AggregateException?backAsAggregate = this;

            while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1)
            {
                back            = back !.InnerException;
                backAsAggregate = back as AggregateException;
            }
            return(back !);
        }
コード例 #13
0
 public ConvertFileSystemToGraphResult(bool success, FSEntityAdjacencyGraph fSEntityAdjacencyGraph, IList <Exception> acceptableExceptions, AggregateException?aggregateException)
 {
     Success = success;
     FSEntityAdjacencyGraph        = fSEntityAdjacencyGraph;
     AcceptableExceptions          = acceptableExceptions;
     AggregateException            = aggregateException;
     DeepestDirectoryTree          = 0;
     LargestFile                   = 0;
     EarliestDirectoryCreationTime = DateTime.MaxValue;
     LatestDirectoryCreationTime   = DateTime.MinValue;
     EarliestFileCreationTime      = DateTime.MaxValue;
     LatestFileCreationTime        = DateTime.MinValue;
     EarliestFileModificationTime  = DateTime.MaxValue;
     LatestFileModificationTime    = DateTime.MinValue;
 }
コード例 #14
0
 // A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property.
 // http://stackoverflow.com/questions/7883052/a-tasks-exceptions-were-not-observed-either-by-waiting-on-the-task-or-accessi
 // Used for long-runnig Tasks with Task.Factory.StartNew() to create non-ThreadPool threads.
 public static Task LogUnobservedTaskExceptions(this Task p_task, string p_msg)
 {
     Utils.Logger.Info("LogUnobservedTaskExceptions().Registering for long running task" + p_msg);
     p_task.ContinueWith(t =>
     {
         AggregateException?aggException = t?.Exception?.Flatten();
         if (aggException != null)
         {
             foreach (var exception in aggException.InnerExceptions)
             {
                 Utils.Logger.Error(exception, "LogUnobservedTaskExceptions().ContinueWithTask(): " + p_msg);
             }
         }
     }, TaskContinuationOptions.OnlyOnFaulted);
     return(p_task);
 }
コード例 #15
0
        public async Task StopAsync_StopAfterStart_CommandsAreNotRequestedAfterStop()
        {
            // ARRANGE

            var contextMock = new Mock <ICommandLoopContext>();

            contextMock.SetupGet(x => x.HasNextIteration).Returns(true);
            contextMock.SetupGet(x => x.CanPlayerGiveCommand).Returns(true);
            var context = contextMock.Object;

            var command = Mock.Of <ICommand>();

            var commandPoolMock = new Mock <ICommandPool>();
            var semaphore       = new SemaphoreSlim(0, 1);

            commandPoolMock.Setup(x => x.Pop()).Returns(() =>
            {
                Task.Delay(100).Wait();
                semaphore.Release();
                return(command);
            });
            var commandPool = commandPoolMock.Object;

            var commandLoop = new CommandLoopUpdater(context, commandPool);

            // ACT
            var commandLoopTask = commandLoop.StartAsync(CancellationToken.None);
            AggregateException?commandLoopTaskException = null;

            await semaphore.WaitAsync().ConfigureAwait(false);

            await commandLoop.StopAsync().ConfigureAwait(false);

            Func <Task> act = async() =>
            {
                await commandLoopTask.ContinueWith(task => commandLoopTaskException = task.Exception,
                                                   TaskContinuationOptions.OnlyOnFaulted).ConfigureAwait(false);
            };

            // ASSERT
            commandPoolMock.Verify(x => x.Pop(), Times.AtMost(2));

            await act.Should().ThrowAsync <TaskCanceledException>().ConfigureAwait(false);

            commandLoopTaskException.Should().BeNull();
        }
コード例 #16
0
        /// <summary>
        /// Snaps the exception data as custom data.
        /// </summary>
        /// <param name="e">The e.</param>
        /// <param name="custom">The custom.</param>
        public static void SnapExceptionDataAsCustomData(
            System.Exception e,
            ref IDictionary <string, object?>?custom
            )
        {
            if (custom == null)
            {
                custom =
                    new Dictionary <string, object?>(capacity: e.Data != null ? e.Data.Count : 0);
            }

            const string nullObjPresentation = "<null>";

            if (e.Data != null)
            {
                string customKeyPrefix = $"{e.GetType().Name}.Data.";
                foreach (var key in e.Data.Keys)
                {
                    if (key == null)
                    {
                        continue;
                    }
                    object?valueObj  = e.Data[key];
                    string keyName   = key.ToString() ?? nullObjPresentation;
                    string customKey = $"{customKeyPrefix}{keyName}";
                    custom[customKey] = valueObj ?? nullObjPresentation;
                }
            }

            if (e.InnerException != null)
            {
                SnapExceptionDataAsCustomData(e.InnerException, ref custom);
            }

            // there could be more Data to capture in case of an AggregateException:
            AggregateException?aggregateException = e as AggregateException;

            if (aggregateException != null && aggregateException.InnerExceptions != null)
            {
                foreach (var aggregatedException in aggregateException.InnerExceptions)
                {
                    SnapExceptionDataAsCustomData(aggregatedException, ref custom);
                }
            }
        }
コード例 #17
0
        private void ExecuteHostingStartups()
        {
            var webHostOptions = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty);

            if (webHostOptions.PreventHostingStartup)
            {
                return;
            }

            var exceptions = new List <Exception>();
            var processed  = new HashSet <Assembly>();

            _hostingStartupWebHostBuilder = new HostingStartupWebHostBuilder(this);

            // Execute the hosting startup assemblies
            foreach (var assemblyName in webHostOptions.GetFinalHostingStartupAssemblies())
            {
                try
                {
                    var assembly = Assembly.Load(new AssemblyName(assemblyName));

                    if (!processed.Add(assembly))
                    {
                        // Already processed, skip it
                        continue;
                    }

                    foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>())
                    {
                        var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType) !;
                        hostingStartup.Configure(_hostingStartupWebHostBuilder);
                    }
                }
                catch (Exception ex)
                {
                    // Capture any errors that happen during startup
                    exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex));
                }
            }

            if (exceptions.Count > 0)
            {
                _hostingStartupErrors = new AggregateException(exceptions);
            }
        }
コード例 #18
0
        ServiceCollection BuildCommonServices(out AggregateException?hostingStartupErrors)
        {
            hostingStartupErrors = null;

            // Initialize the hosting environment
            _context.HostingEnvironment = _hostEnvironment;

            var services = new ServiceCollection();

            services.AddSingleton(_hostEnvironment);
            services.AddSingleton(_context);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(_hostEnvironment.ContentRootPath)
                          .AddInMemoryCollection(_config.AsEnumerable());

            foreach (var configureAppConfiguration in _configureAppConfigurationBuilderDelegates)
            {
                configureAppConfiguration(_context, builder);
            }

            var configuration = builder.Build();

            services.AddSingleton <IConfiguration>(configuration);
            _context.Configuration = configuration;
            services.AddHttpContextAccessor();
            services.AddOptions();

            // Conjure up a RequestServices
            services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            // Ensure object pooling is available everywhere.
            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

            foreach (var configureServices in _configureServicesDelegates)
            {
                configureServices(_context, services);
            }

            return(services);
        }
コード例 #19
0
ファイル: WebHost.cs プロジェクト: lzhang871228/aspnetcore
        public WebHost(
            IServiceCollection appServices,
            IServiceProvider hostingServiceProvider,
            WebHostOptions options,
            IConfiguration config,
            AggregateException?hostingStartupErrors)
        {
            if (appServices == null)
            {
                throw new ArgumentNullException(nameof(appServices));
            }

            if (hostingServiceProvider == null)
            {
                throw new ArgumentNullException(nameof(hostingServiceProvider));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            _config = config;
            _hostingStartupErrors = hostingStartupErrors;
            _options = options;
            _applicationServiceCollection = appServices;
            _hostingServiceProvider       = hostingServiceProvider;
            _applicationServiceCollection.AddSingleton <ApplicationLifetime>();
            // There's no way to to register multiple service types per definition. See https://github.com/aspnet/DependencyInjection/issues/360
#pragma warning disable CS8634 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.
            _applicationServiceCollection.AddSingleton(services
                                                       => services.GetService <ApplicationLifetime>() as IHostApplicationLifetime);
#pragma warning disable CS0618 // Type or member is obsolete
            _applicationServiceCollection.AddSingleton(services
                                                       => services.GetService <ApplicationLifetime>() as AspNetCore.Hosting.IApplicationLifetime);
            _applicationServiceCollection.AddSingleton(services
                                                       => services.GetService <ApplicationLifetime>() as Extensions.Hosting.IApplicationLifetime);
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning restore CS8634 // The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.
            _applicationServiceCollection.AddSingleton <HostedServiceExecutor>();
        }
コード例 #20
0
        private static void InitializeCore(OperationContext context, ILogger?logger, GrpcEnvironmentOptions options, bool overwriteSafeOptions)
        {
            lock (InitializationLock)
            {
                if (InitializationCompletionSource.Task.IsFaulted)
                {
                    AggregateException?exception = InitializationCompletionSource.Task.Exception;
                    var innerException           = exception?.InnerException;
                    Contract.AssertNotNull(innerException);
                    ExceptionDispatchInfo.Capture(innerException).Throw();
                }

                if (IsInitialized)
                {
                    Tracer.Info(context, "Attempt to initialize gRPC environment aborted due to a previous initialization.");
                    if (overwriteSafeOptions)
                    {
                        InitializeSafeGrpcOptions(context, options, logger);
                    }
                }
                else
                {
                    // We don't retry if this errors because it likely means that something broke in gRPC core
                    try
                    {
                        InitializeSafeGrpcOptions(context, options, logger);
                        InitializeUnsafeGrpcOptions(context, options);
                    }
                    catch (Exception e)
                    {
                        InitializationCompletionSource.SetException(e);
                        throw;
                    }

                    IsInitialized = true;
                    InitializationCompletionSource.SetResult(1);
                }
            }
        }
コード例 #21
0
    public WebHost(
        IServiceCollection appServices,
        IServiceProvider hostingServiceProvider,
        WebHostOptions options,
        IConfiguration config,
        AggregateException?hostingStartupErrors)
    {
        if (appServices == null)
        {
            throw new ArgumentNullException(nameof(appServices));
        }

        if (hostingServiceProvider == null)
        {
            throw new ArgumentNullException(nameof(hostingServiceProvider));
        }

        if (config == null)
        {
            throw new ArgumentNullException(nameof(config));
        }

        _config = config;
        _hostingStartupErrors = hostingStartupErrors;
        _options = options;
        _applicationServiceCollection = appServices;
        _hostingServiceProvider       = hostingServiceProvider;
        _applicationServiceCollection.AddSingleton <ApplicationLifetime>();
        // There's no way to to register multiple service types per definition. See https://github.com/aspnet/DependencyInjection/issues/360
        _applicationServiceCollection.AddSingleton <IHostApplicationLifetime>(services
                                                                              => services.GetService <ApplicationLifetime>() !);
#pragma warning disable CS0618 // Type or member is obsolete
        _applicationServiceCollection.AddSingleton <AspNetCore.Hosting.IApplicationLifetime>(services
                                                                                             => services.GetService <ApplicationLifetime>() !);
        _applicationServiceCollection.AddSingleton <Extensions.Hosting.IApplicationLifetime>(services
                                                                                             => services.GetService <ApplicationLifetime>() !);
#pragma warning restore CS0618 // Type or member is obsolete
        _applicationServiceCollection.AddSingleton <HostedServiceExecutor>();
    }
コード例 #22
0
        private void ExecuteHostingStartups()
        {
            var gtkHostOptions =
                new GtkHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty);

            if (gtkHostOptions.PreventHostingStartup)
            {
                return;
            }

            var exceptions = new List <Exception>();

            _hostingStartupGtkHostBuilder = new HostingStartupGtkHostBuilder(this);

            foreach (var assemblyName in gtkHostOptions.GetFinalHostingStartupAssemblies()
                     .Distinct(StringComparer.OrdinalIgnoreCase))
            {
                try
                {
                    var assembly = Assembly.Load(new AssemblyName(assemblyName));
                    foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>())
                    {
                        var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType) !;
                        hostingStartup.Configure(_hostingStartupGtkHostBuilder);
                    }
                }
                catch (Exception ex)
                {
                    exceptions.Add(new InvalidOperationException($"启动程序集{assemblyName}无法执行。有关更多详细信息,请参见内部异常。", ex));
                }
            }

            if (exceptions.Count > 0)
            {
                _hostingStartupErrors = new AggregateException(exceptions);
            }
        }
コード例 #23
0
        private static int ActualRun(string commandName, ITemplateEngineHost host, ITelemetryLogger telemetryLogger, New3Callbacks callbacks, string[] args, string?hivePath)
        {
            if (args.Any(x => string.Equals(x, "--debug:version", StringComparison.Ordinal)))
            {
                ShowVersion();
                return(0);
            }

            if (args.Any(x => string.Equals(x, "--debug:attach", StringComparison.Ordinal)))
            {
                Console.ReadLine();
            }

            int customHiveFlagIndex = args.ToList().IndexOf("--debug:custom-hive");

            if (customHiveFlagIndex >= 0)
            {
                if (customHiveFlagIndex + 1 >= args.Length)
                {
                    Reporter.Error.WriteLine("--debug:custom-hive requires 1 arg indicating the absolute or relative path to the custom hive".Bold().Red());
                    return(1);
                }

                hivePath = args[customHiveFlagIndex + 1];
                if (hivePath.StartsWith("-"))
                {
                    Reporter.Error.WriteLine("--debug:custom-hive requires 1 arg indicating the absolute or relative path to the custom hive".Bold().Red());
                    return(1);
                }

                hivePath = Path.GetFullPath(hivePath);
            }

            bool ephemeralHiveFlag = args.Any(x => string.Equals(x, "--debug:ephemeral-hive", StringComparison.Ordinal));

            if (args.Length == 0)
            {
                telemetryLogger.TrackEvent(commandName + TelemetryConstants.CalledWithNoArgsEventSuffix);
            }

            INewCommandInput commandInput = new NewCommandInputCli(commandName);
            New3Command      instance     = new New3Command(commandName, host, telemetryLogger, callbacks, commandInput, hivePath, virtualize: ephemeralHiveFlag);

            commandInput.OnExecute(instance.ExecuteAsync);

            int result;

            try
            {
                using (Timing.Over(host, "Execute"))
                {
                    result = commandInput.Execute(args);
                }
            }
            catch (Exception ex)
            {
                AggregateException?ax = ex as AggregateException;

                while (ax != null && ax.InnerExceptions.Count == 1)
                {
                    ex = ax.InnerException;
                    ax = ex as AggregateException;
                }

                Reporter.Error.WriteLine(ex.Message.Bold().Red());

                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    ax = ex as AggregateException;

                    while (ax != null && ax.InnerExceptions.Count == 1)
                    {
                        ex = ax.InnerException;
                        ax = ex as AggregateException;
                    }

                    Reporter.Error.WriteLine(ex.Message.Bold().Red());
                }

                Reporter.Error.WriteLine(ex.StackTrace.Bold().Red());
                result = 1;
            }
            finally
            {
                instance.EnvironmentSettings.Dispose();
            }

            return(result);
        }
コード例 #24
0
ファイル: WebHostBuilder.cs プロジェクト: shat90/aspnetcore
        private IServiceCollection BuildCommonServices(out AggregateException?hostingStartupErrors)
        {
            hostingStartupErrors = null;

            _options = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty);

            if (!_options.PreventHostingStartup)
            {
                var exceptions = new List <Exception>();
                var processed  = new HashSet <Assembly>();

                // Execute the hosting startup assemblies
                foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies())
                {
                    try
                    {
                        var assembly = Assembly.Load(new AssemblyName(assemblyName));

                        if (!processed.Add(assembly))
                        {
                            // Already processed, skip it
                            continue;
                        }

                        foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>())
                        {
                            var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType) !;
                            hostingStartup.Configure(this);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Capture any errors that happen during startup
                        exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex));
                    }
                }

                if (exceptions.Count > 0)
                {
                    hostingStartupErrors = new AggregateException(exceptions);
                }
            }

            var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory);

            // Initialize the hosting environment
            ((IWebHostEnvironment)_hostingEnvironment).Initialize(contentRootPath, _options);
            _context.HostingEnvironment = _hostingEnvironment;

            var services = new ServiceCollection();

            services.AddSingleton(_options);
            services.AddSingleton <IWebHostEnvironment>(_hostingEnvironment);
            services.AddSingleton <IHostEnvironment>(_hostingEnvironment);
#pragma warning disable CS0618 // Type or member is obsolete
            services.AddSingleton <AspNetCore.Hosting.IHostingEnvironment>(_hostingEnvironment);
            services.AddSingleton <Extensions.Hosting.IHostingEnvironment>(_hostingEnvironment);
#pragma warning restore CS0618 // Type or member is obsolete
            services.AddSingleton(_context);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(_hostingEnvironment.ContentRootPath)
                          .AddConfiguration(_config, shouldDisposeConfiguration: true);

            _configureAppConfigurationBuilder?.Invoke(_context, builder);

            var configuration = builder.Build();
            // register configuration as factory to make it dispose with the service provider
            services.AddSingleton <IConfiguration>(_ => configuration);
            _context.Configuration = configuration;

            services.TryAddSingleton(sp => new DiagnosticListener("Microsoft.AspNetCore"));
            services.TryAddSingleton <DiagnosticSource>(sp => sp.GetRequiredService <DiagnosticListener>());
            services.TryAddSingleton(sp => new ActivitySource("Microsoft.AspNetCore"));

            services.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
            services.AddTransient <IHttpContextFactory, DefaultHttpContextFactory>();
            services.AddScoped <IMiddlewareFactory, MiddlewareFactory>();
            services.AddOptions();
            services.AddLogging();

            services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            if (!string.IsNullOrEmpty(_options.StartupAssembly))
            {
                try
                {
                    var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);

                    if (typeof(IStartup).IsAssignableFrom(startupType))
                    {
                        services.AddSingleton(typeof(IStartup), startupType);
                    }
                    else
                    {
                        services.AddSingleton(typeof(IStartup), sp =>
                        {
                            var hostingEnvironment = sp.GetRequiredService <IHostEnvironment>();
                            var methods            = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName);
                            return(new ConventionBasedStartup(methods));
                        });
                    }
                }
                catch (Exception ex)
                {
                    var capture = ExceptionDispatchInfo.Capture(ex);
                    services.AddSingleton <IStartup>(_ =>
                    {
                        capture.Throw();
                        return(null);
                    });
                }
            }

            _configureServices?.Invoke(_context, services);

            return(services);
        }
コード例 #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnobservedTaskExceptionEventArgs"/> class
 /// with the unobserved exception.
 /// </summary>
 /// <param name="exception">The Exception that has gone unobserved.</param>
 public UnobservedTaskExceptionEventArgs(AggregateException?exception)
 {
     m_exception = exception;
 }