Example #1
0
 static void Main(string[] args)
 {
     _exLogger = new ExceptionLogger();
     try
     {
         menuCollection = new List<Menu>();
         InitializeData(menuCollection);
         var roots = from menu in menuCollection
                     where menu.ParentId == null
                     select menu;
         Menu m = new Menu { Id = 0, Title = "Main" };
         MenuNode rootNode = new MenuNode(m);
         foreach (var r in roots)
         {
             Console.WriteLine();
             MenuNode node = rootNode.AddNode(r);
             node.MenuItem = r;
             PopulateTree(node);
         }
         Console.WriteLine("---------------------------------------------------------------------");
         PrintTree(rootNode, 0);
         Console.ReadKey();
     }
     catch(System.Exception ex)
     {
         _exLogger.addErrorLog(ex);
     }
 }
        public MethodLogger(ILogFactory logFactory, IExceptionLogger exceptionLogger)
        {
            Check.IsNotNull(exceptionLogger, "exceptionLogger");
            Check.IsNotNull(logFactory, "logFactory");

            _exceptionLogger = exceptionLogger;
            _logFactory = logFactory;
        }
        public TransactionInterceptor(ITransactionManager transactionManager, IExceptionLogger exceptionLogger)
        {
            ParameterCheck.ParameterRequired(transactionManager, "transactionManager");
            ParameterCheck.ParameterRequired(exceptionLogger, "exceptionLogger");

            this.transactionManager = transactionManager;
            this.exceptionLogger = exceptionLogger;
        }
 public ProgressLogger(IProgressUi progressUi, int uiMin, int uiMax, int steps, IExceptionLogger exceptionLogger)
 {
     _progressUi = progressUi;
       _uiTicksPerStepTick = (uiMax - uiMin) / (double) steps;
       _currentValue = uiMin;
       _uiMax = uiMax;
       _exceptionLogger = exceptionLogger;
 }
        internal HttpRouteExceptionHandler(ExceptionDispatchInfo exceptionInfo,
            IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler)
        {
            Contract.Assert(exceptionInfo != null);
            Contract.Assert(exceptionLogger != null);
            Contract.Assert(exceptionHandler != null);

            _exceptionInfo = exceptionInfo;
            _exceptionLogger = exceptionLogger;
            _exceptionHandler = exceptionHandler;
        }
 public CommandsTransmitter(IInfoQueue<BaseInfo> infoQueue,
                            IExceptionLogger exceptionLogger,
                            ISimpleHttp simpleHttp,
                            Uri serverUri,
                            string logFilePath)
 {
     _infoQueue = infoQueue;
     _logFilePath = logFilePath;
     _exceptionLogger = exceptionLogger;
     _simpleHttp = simpleHttp;
     _serverUri = serverUri;
 }
Example #7
0
        public ExceptionFilterResult(CommandHandlerContext context, IExceptionFilter[] filters, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler, ICommandHandlerResult innerResult)
        {
            Contract.Requires(context != null);
            Contract.Requires(filters != null);
            Contract.Requires(exceptionLogger != null);
            Contract.Requires(exceptionHandler != null);
            Contract.Requires(innerResult != null);

            this.context = context;
            this.filters = filters;
            this.exceptionLogger = exceptionLogger;
            this.exceptionHandler = exceptionHandler;
            this.innerResult = innerResult;
        }
        public ExceptionFilterResult(HttpActionContext context, IExceptionFilter[] filters,
            IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler, IHttpActionResult innerResult)
        {
            Contract.Assert(context != null);
            Contract.Assert(filters != null);
            Contract.Assert(exceptionLogger != null);
            Contract.Assert(exceptionHandler != null);
            Contract.Assert(innerResult != null);

            _context = context;
            _filters = filters;
            _exceptionLogger = exceptionLogger;
            _exceptionHandler = exceptionHandler;
            _innerResult = innerResult;
        }
        /// <summary>Initializes a new instance of the <see cref="HttpMessageHandlerAdapter"/> class.</summary>
        /// <param name="next">The next component in the pipeline.</param>
        /// <param name="options">The options to configure this adapter.</param>
        public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandlerOptions options)
            : base(next)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _messageHandler = options.MessageHandler;

            if (_messageHandler == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                    typeof(HttpMessageHandlerOptions).Name, "MessageHandler"), "options");
            }

            _messageInvoker = new HttpMessageInvoker(_messageHandler);
            _bufferPolicySelector = options.BufferPolicySelector;

            if (_bufferPolicySelector == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                    typeof(HttpMessageHandlerOptions).Name, "BufferPolicySelector"), "options");
            }

            _exceptionLogger = options.ExceptionLogger;

            if (_exceptionLogger == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                    typeof(HttpMessageHandlerOptions).Name, "ExceptionLogger"), "options");
            }

            _exceptionHandler = options.ExceptionHandler;

            if (_exceptionHandler == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                    typeof(HttpMessageHandlerOptions).Name, "ExceptionHandler"), "options");
            }

            _appDisposing = options.AppDisposing;

            if (_appDisposing.CanBeCanceled)
            {
                _appDisposing.Register(OnAppDisposing);
            }
        }
Example #10
0
        public void Loggers_ContainsSpecifiedInstances()
        {
            // Arrange
            IExceptionLogger        expectedLogger  = CreateDummyLogger();
            List <IExceptionLogger> expectedLoggers = new List <IExceptionLogger> {
                expectedLogger
            };
            CompositeExceptionLogger product = CreateProductUnderTest(expectedLoggers);

            // Act
            IEnumerable <IExceptionLogger> loggers = product.Loggers;

            // Assert
            Assert.NotNull(loggers);
            IExceptionLogger logger = Assert.Single(loggers);

            Assert.Same(expectedLogger, logger);
        }
        public HttpRequestService(IDictionary<string, string> additionalHeaders, bool catchExceptions = true, IExceptionLogger logger = null)
            : base(catchExceptions, logger)
        {
            _client = new HttpClient(
                new HttpClientHandler
                {
                    AutomaticDecompression = DecompressionMethods.GZip
                                             | DecompressionMethods.Deflate
                });

            _client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
            if (additionalHeaders != null)
                foreach (var additionalHeader in additionalHeaders)
                {
                    _client.DefaultRequestHeaders.TryAddWithoutValidation(additionalHeader.Key,
                        additionalHeader.Value);
                }
        }
 public EventProcessorFactory(IEventHubSettings settings,
                              IHandlerActivator handlerActivator,
                              IExceptionLogger exceptionLogger,
                              IHubEventErrorBus hubEventErrorBus,
                              IHubCommandErrorBus hubCommandErrorBus,
                              IDictionary <Type, Type> commandHandlers,
                              IDictionary <Type, ISet <Type> > eventHandlers,
                              ILogger logger)
 {
     _settings           = settings;
     _handlerActivator   = handlerActivator;
     _exceptionLogger    = exceptionLogger;
     _hubEventErrorBus   = hubEventErrorBus;
     _hubCommandErrorBus = hubCommandErrorBus;
     _commandHandlers    = commandHandlers;
     _eventHandlers      = eventHandlers;
     _logger             = logger;
 }
Example #13
0
        public void ExceptionHandlerGet_ReturnsSpecifiedInstance()
        {
            // Arrange
            IExceptionLogger  exceptionLogger          = CreateDummyExceptionLogger();
            IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();

            using (HttpConfiguration configuration = CreateConfiguration())
                using (HttpMessageHandler dispatcher = CreateDummyMessageHandler())
                    using (HttpServer product = CreateProductUnderTest(configuration, dispatcher, exceptionLogger,
                                                                       expectedExceptionHandler))
                    {
                        // Act
                        IExceptionHandler exceptionHandler = product.ExceptionHandler;

                        // Assert
                        Assert.Same(expectedExceptionHandler, exceptionHandler);
                    }
        }
        public void ProcessRequestAsync_IfHandlerHandles_UsesHandlerResult()
        {
            // Arrange
            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo();

            IExceptionLogger logger = CreateStubExceptionLogger();

            HttpStatusCode           expectedStatusCode = HttpStatusCode.Ambiguous;
            Mock <IExceptionHandler> handlerMock        = new Mock <IExceptionHandler>(MockBehavior.Strict);

            handlerMock
            .Setup(h => h.HandleAsync(It.IsAny <ExceptionHandlerContext>(), It.IsAny <CancellationToken>()))
            .Returns <ExceptionHandlerContext, CancellationToken>((c, i) =>
            {
                c.Result = new StatusCodeResult(expectedStatusCode, new HttpRequestMessage());
                return(Task.FromResult(0));
            });
            IExceptionHandler handler = handlerMock.Object;

            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);

            int statusCode = 0;
            Mock <HttpResponseBase> responseBaseMock = new Mock <HttpResponseBase>();

            responseBaseMock.SetupSet(r => r.StatusCode = It.IsAny <int>()).Callback <int>((c) => statusCode = c);
            responseBaseMock.SetupGet(r => r.Cache).Returns(() => new Mock <HttpCachePolicyBase>().Object);
            HttpResponseBase responseBase = responseBaseMock.Object;
            HttpContextBase  contextBase  = CreateStubContextBase(responseBase);

            using (HttpRequestMessage request = CreateRequest())
            {
                contextBase.SetHttpRequestMessage(request);

                // Act
                Task task = product.ProcessRequestAsync(contextBase);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();
                Assert.Equal(TaskStatus.RanToCompletion, task.Status);

                Assert.Equal((int)expectedStatusCode, statusCode);
            }
        }
        public async Task ProcessRequestAsync_IfExceptionIsHttpResponseException_DisposesRequestAndResponse()
        {
            // Arrange
            using (HttpResponseMessage response = CreateResponse())
                using (HttpRequestMessage request = CreateRequest())
                    using (SpyDisposable spy = new SpyDisposable())
                    {
                        request.RegisterForDispose(spy);

                        ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(
                            new HttpResponseException(response)
                            );
                        IExceptionLogger  logger  = CreateDummyLogger();
                        IExceptionHandler handler = CreateDummyHandler();

                        HttpRouteExceptionHandler product = CreateProductUnderTest(
                            exceptionInfo,
                            logger,
                            handler
                            );

                        Mock <HttpResponseBase> responseBaseMock = new Mock <HttpResponseBase>();
                        responseBaseMock
                        .SetupGet(r => r.Cache)
                        .Returns(() => new Mock <HttpCachePolicyBase>().Object);
                        HttpResponseBase responseBase = responseBaseMock.Object;
                        HttpContextBase  contextBase  = CreateStubContextBase(responseBase);
                        contextBase.SetHttpRequestMessage(request);

                        // Act
                        await product.ProcessRequestAsync(contextBase);

                        // Assert
                        Assert.True(spy.Disposed);
                        Assert.ThrowsObjectDisposed(
                            () => request.Method = HttpMethod.Get,
                            typeof(HttpRequestMessage).FullName
                            );
                        Assert.ThrowsObjectDisposed(
                            () => response.StatusCode = HttpStatusCode.OK,
                            typeof(HttpResponseMessage).FullName
                            );
                    }
        }
Example #16
0
        public void Constructor_CapturesLoggersContents()
        {
            // Arrange
            IExceptionLogger        expectedLogger  = CreateDummyLogger();
            List <IExceptionLogger> expectedLoggers = new List <IExceptionLogger> {
                expectedLogger
            };

            // Act
            CompositeExceptionLogger product = CreateProductUnderTest(expectedLoggers);

            // Assert
            expectedLoggers.Clear();
            IEnumerable <IExceptionLogger> loggers = product.Loggers;

            Assert.NotNull(loggers);
            Assert.Equal(1, loggers.Count());
            Assert.Same(expectedLogger, loggers.Single());
        }
        private static void AssertDelegatesTo(Mock <IExceptionLogger> expected, IExceptionLogger actual)
        {
            Assert.NotNull(actual);

            ExceptionLoggerContext context           = new ExceptionLoggerContext(new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer));
            CancellationToken      cancellationToken = CancellationToken.None;

            expected
            .Setup((l) => l.LogAsync(It.IsAny <ExceptionLoggerContext>(), It.IsAny <CancellationToken>()))
            .Returns(CreateCanceledTask());

            Task task = actual.LogAsync(context, cancellationToken);

            Assert.NotNull(task);
            task.WaitUntilCompleted();
            Assert.Equal(TaskStatus.Canceled, task.Status);

            expected.Verify((l) => l.LogAsync(context, cancellationToken), Times.Once());
        }
        public void UseWebApi_UsesAdapterAndConfigServices()
        {
            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())
            {
                var config = new HttpConfiguration();
                var bufferPolicySelector             = new Mock <IHostBufferPolicySelector>().Object;
                Mock <IExceptionLogger>  loggerMock  = new Mock <IExceptionLogger>();
                Mock <IExceptionHandler> handlerMock = new Mock <IExceptionHandler>();
                config.Services.Replace(typeof(IHostBufferPolicySelector), bufferPolicySelector);
                config.Services.Replace(typeof(IExceptionLogger), loggerMock.Object);
                config.Services.Replace(typeof(IExceptionHandler), handlerMock.Object);
                IExceptionLogger  exceptionLogger  = null;
                IExceptionHandler exceptionHandler = null;
                var appBuilder = new Mock <IAppBuilder>();
                CancellationToken            expectedAppDisposing = tokenSource.Token;
                IDictionary <string, object> properties           = new Dictionary <string, object>
                {
                    { "host.OnAppDisposing", expectedAppDisposing }
                };
                appBuilder.SetupGet(b => b.Properties).Returns(properties);
                appBuilder
                .Setup(ab => ab.Use(
                           typeof(HttpMessageHandlerAdapter),
                           It.Is <HttpMessageHandlerOptions>((o) => ((HttpServer)o.MessageHandler).Configuration == config &&
                                                             o.BufferPolicySelector == bufferPolicySelector &&
                                                             o.AppDisposing == expectedAppDisposing)))
                .Callback <object, object[]>((i, args) =>
                {
                    HttpMessageHandlerOptions options = (HttpMessageHandlerOptions)args[0];
                    exceptionLogger  = options.ExceptionLogger;
                    exceptionHandler = options.ExceptionHandler;
                })
                .Returns(appBuilder.Object)
                .Verifiable();

                IAppBuilder returnedAppBuilder = appBuilder.Object.UseWebApi(config);

                Assert.Equal(appBuilder.Object, returnedAppBuilder);
                appBuilder.Verify();
                AssertDelegatesTo(loggerMock, exceptionLogger);
                AssertDelegatesTo(handlerMock, exceptionHandler);
            }
        }
Example #19
0
        public void SendAsync_IfSendAsyncThrows_InControllerSelector_CallsExceptionServices()
        {
            // Arrange
            Exception expectedException = CreateException();

            Mock <IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();
            IExceptionLogger        exceptionLogger     = exceptionLoggerMock.Object;

            Mock <IExceptionHandler> exceptionHandlerMock = CreateStubExceptionHandlerMock();
            IExceptionHandler        exceptionHandler     = exceptionHandlerMock.Object;

            using (HttpRequestMessage expectedRequest = CreateRequestWithRouteData())
                using (HttpConfiguration configuration = CreateConfiguration())
                    using (HttpMessageHandler product = CreateProductUnderTest(configuration, exceptionLogger,
                                                                               exceptionHandler))
                    {
                        configuration.Services.Replace(typeof(IHttpControllerSelector),
                                                       CreateThrowingControllerSelector(expectedException));

                        CancellationToken cancellationToken = CreateCancellationToken();

                        Task <HttpResponseMessage> task = product.SendAsync(expectedRequest, cancellationToken);

                        // Act
                        task.WaitUntilCompleted();

                        // Assert
                        Func <ExceptionContext, bool> exceptionContextMatches = (c) =>
                                                                                c != null &&
                                                                                c.Exception == expectedException &&
                                                                                c.CatchBlock == ExceptionCatchBlocks.HttpControllerDispatcher &&
                                                                                c.Request == expectedRequest &&
                                                                                c.ControllerContext == null;

                        exceptionLoggerMock.Verify(l => l.LogAsync(
                                                       It.Is <ExceptionLoggerContext>(c => exceptionContextMatches(c.ExceptionContext)),
                                                       cancellationToken), Times.Once());

                        exceptionHandlerMock.Verify(h => h.HandleAsync(
                                                        It.Is <ExceptionHandlerContext>((c) => exceptionContextMatches(c.ExceptionContext)),
                                                        cancellationToken), Times.Once());
                    }
        }
        public void AddLogger(IExceptionLogger logger)
        {
            if (logger.IsNull())
            {
                throw new ArgumentNullException();
            }

            var recurrentLoggers = from tempLogger in loggers
                                   where tempLogger.GetType() == logger.GetType()
                                   select tempLogger;

            // Прерывает выполнение, если в списке логгеров уже есть логгер с данным типом.
            if (recurrentLoggers.GetEnumerator().MoveNext())
            {
                throw new InvalidOperationException();
            }

            loggers.Add(logger);
        }
Example #21
0
        /// <summary>
        /// Execute the request via the worker.
        /// </summary>
        /// <param name="request">The <see cref="HandlerRequest"/> to execute.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> to cancel the execution.</param>
        /// <returns>The result of the command, if any.</returns>
        public Task <HandlerResponse> ExecuteAsync(CommandHandlerRequest request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            cancellationToken.ThrowIfCancellationRequested();
            ServicesContainer        servicesContainer = request.Configuration.Services;
            ICommandHandlerSelector  handlerSelector   = servicesContainer.GetHandlerSelector();
            CommandHandlerDescriptor descriptor        = handlerSelector.SelectHandler(request);

            ICommandHandler commandHandler = descriptor.CreateHandler(request);

            if (commandHandler == null)
            {
                throw CreateHandlerNotFoundException(descriptor);
            }

            request.RegisterForDispose(commandHandler, true);
            CommandHandlerContext context = new CommandHandlerContext(request, descriptor);

            context.Handler = commandHandler;
            commandHandler.CommandContext = context;

            CommandFilterGrouping commandFilterGrouping = descriptor.GetFilterGrouping();

            ICommandHandlerResult result = new CommandHandlerFilterResult(context, servicesContainer, commandFilterGrouping.CommandHandlerFilters);

            if (descriptor.RetryPolicy != RetryPolicy.NoRetry)
            {
                result = new RetryHandlerResult(descriptor.RetryPolicy, result);
            }

            if (commandFilterGrouping.ExceptionFilters.Length > 0)
            {
                IExceptionLogger  exceptionLogger  = ExceptionServices.GetLogger(servicesContainer);
                IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(servicesContainer);
                result = new ExceptionFilterResult(context, commandFilterGrouping.ExceptionFilters, exceptionLogger, exceptionHandler, result);
            }

            return(result.ExecuteAsync(cancellationToken));
        }
Example #22
0
        public EventStream(IEnumerable <IEventSink> sinks, IExceptionLogger exceptionLogger, Func <DateTime> now)
        {
            if (sinks == null)
            {
                throw new ArgumentNullException("sinks");
            }
            if (exceptionLogger == null)
            {
                throw new ArgumentNullException("exceptionLogger");
            }
            if (now == null)
            {
                throw new ArgumentNullException("now");
            }

            _sinks           = sinks;
            _exceptionLogger = exceptionLogger;
            _now             = now;
        }
Example #23
0
        public void SendAsync_IfDispatcherTaskIsFaulted_CallsExceptionServices()
        {
            // Arrange
            Exception expectedException = CreateException();

            HttpMessageHandler dispatcher = CreateFaultingMessageHandler(expectedException);

            Mock <IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();
            IExceptionLogger        exceptionLogger     = exceptionLoggerMock.Object;

            Mock <IExceptionHandler> exceptionHandlerMock = CreateStubExceptionHandlerMock();
            IExceptionHandler        exceptionHandler     = exceptionHandlerMock.Object;

            using (HttpRequestMessage expectedRequest = CreateRequest())
                using (HttpConfiguration configuration = CreateConfiguration())
                    using (HttpServer product = CreateProductUnderTest(configuration, dispatcher, exceptionLogger,
                                                                       exceptionHandler))
                    {
                        CancellationToken cancellationToken = CreateCancellationToken();

                        Task <HttpResponseMessage> task = product.SendAsync(expectedRequest, cancellationToken);

                        // Act
                        task.WaitUntilCompleted();

                        // Assert
                        Func <ExceptionContext, bool> exceptionContextMatches = (c) =>
                                                                                c != null &&
                                                                                c.Exception == expectedException &&
                                                                                c.CatchBlock == ExceptionCatchBlocks.HttpServer &&
                                                                                c.Request == expectedRequest;

                        exceptionLoggerMock.Verify(l => l.LogAsync(
                                                       It.Is <ExceptionLoggerContext>(c => c.CanBeHandled == true &&
                                                                                      exceptionContextMatches(c.ExceptionContext)),
                                                       cancellationToken), Times.Once());

                        exceptionHandlerMock.Verify(h => h.HandleAsync(
                                                        It.Is <ExceptionHandlerContext>((c) => exceptionContextMatches(c.ExceptionContext)),
                                                        cancellationToken), Times.Once());
                    }
        }
Example #24
0
        public void ExecuteAsync_IfFilterChangesException_ThrowsUpdatedException()
        {
            // Arrange
            Exception expectedException = new NotImplementedException();

            using (HttpRequestMessage request = CreateRequest())
            {
                HttpActionContext context = CreateActionContext(request);

                Mock <IExceptionFilter> filterMock = new Mock <IExceptionFilter>();
                filterMock
                .Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny <HttpActionExecutedContext>(),
                                                          It.IsAny <CancellationToken>()))
                .Callback <HttpActionExecutedContext, CancellationToken>((c, t) =>
                {
                    c.Exception = expectedException;
                })
                .Returns(() => Task.FromResult <object>(null));
                IExceptionFilter   filter  = filterMock.Object;
                IExceptionFilter[] filters = new IExceptionFilter[] { filter };

                IExceptionLogger  exceptionLogger  = CreateStubExceptionLogger();
                IExceptionHandler exceptionHandler = CreateStubExceptionHandler();

                IHttpActionResult innerResult = CreateStubActionResult(
                    CreateFaultedTask <HttpResponseMessage>(CreateException()));

                IHttpActionResult product = CreateProductUnderTest(context, filters, exceptionLogger, exceptionHandler,
                                                                   innerResult);

                // Act
                Task <HttpResponseMessage> task = product.ExecuteAsync(CancellationToken.None);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();
                Assert.Equal(TaskStatus.Faulted, task.Status);
                Assert.NotNull(task.Exception);
                Exception exception = task.Exception.GetBaseException();
                Assert.Same(expectedException, exception);
            }
        }
Example #25
0
        public PersonnelController(IPersonnelService personnelService
                                   , IEmployeementTypeService employeementTypeService
                                   , IGroupCategoryService groupCategoryService
                                   , IWorkUnitService workUnitService
                                   , IPositionService positionService
                                   , IApprovalProcService approvalProcService
                                   , IDismissalService dismissalService, IDutyService dutyService
                                   , IExceptionLogger logger)
        {
            _personnelService        = personnelService;
            _employeementTypeService = employeementTypeService;
            _groupCategoryService    = groupCategoryService;
            _workUnitService         = workUnitService;
            _positionService         = positionService;
            _approvalProcService     = approvalProcService;
            _dismissalService        = dismissalService;
            _dutyService             = dutyService;

            _logger = logger;
        }
        public void GetExceptionLoggers_DelegatesToGetServices()
        {
            // Arrange
            IExceptionLogger expectedExceptionLogger = new Mock<IExceptionLogger>(MockBehavior.Strict).Object;
            IEnumerable<IExceptionLogger> expectedExceptionLoggers =
                new IExceptionLogger[] { expectedExceptionLogger };

            Mock<ServicesContainer> mock = new Mock<ServicesContainer>(MockBehavior.Strict);
            mock.Setup(s => s.GetServices(typeof(IExceptionLogger))).Returns(expectedExceptionLoggers);
            ServicesContainer services = mock.Object;

            // Act
            IEnumerable<IExceptionLogger> exceptionLoggers = ServicesExtensions.GetExceptionLoggers(services);

            // Assert
            mock.Verify(s => s.GetServices(typeof(IExceptionLogger)), Times.Once());
            Assert.NotNull(exceptionLoggers);
            Assert.Equal(1, exceptionLoggers.Count());
            Assert.Same(expectedExceptionLogger, exceptionLoggers.Single());
        }
Example #27
0
        public void ConstructorWithParams_SetsLoggers()
        {
            // Arrange
            IExceptionLogger expectedLogger1 = CreateDummyLogger();
            IExceptionLogger expectedLogger2 = CreateDummyLogger();

            // Act
            CompositeExceptionLogger product = new CompositeExceptionLogger(
                expectedLogger1,
                expectedLogger2
                );

            // Assert
            IEnumerable <IExceptionLogger> loggers = product.Loggers;

            Assert.NotNull(loggers);
            Assert.Equal(2, loggers.Count());
            Assert.Same(expectedLogger1, loggers.ElementAt(0));
            Assert.Same(expectedLogger2, loggers.ElementAt(1));
        }
        public ExceptionFilterResult(
            HttpActionContext context,
            IExceptionFilter[] filters,
            IExceptionLogger exceptionLogger,
            IExceptionHandler exceptionHandler,
            IHttpActionResult innerResult
            )
        {
            Contract.Assert(context != null);
            Contract.Assert(filters != null);
            Contract.Assert(exceptionLogger != null);
            Contract.Assert(exceptionHandler != null);
            Contract.Assert(innerResult != null);

            _context          = context;
            _filters          = filters;
            _exceptionLogger  = exceptionLogger;
            _exceptionHandler = exceptionHandler;
            _innerResult      = innerResult;
        }
Example #29
0
        public PersonnelShiftReplacementService(
            IRepository <PersonnelShiftReplacement> personnelShiftReplacementRepository
            , IRepository <Personnel> personnelRepository
            , IAuthService authService
            , IPersonnelShiftService personnelShiftService
            , IApprovalProcService approvalProcService, IMessageService messageService
            , IRequestMessageHandlerService requestMessageHandlerService
            , IExceptionLogger logger)
        {
            _personnelRepository = personnelRepository;
            _personnelShiftReplacementRepository = personnelShiftReplacementRepository;

            _authService                  = authService;
            _personnelShiftService        = personnelShiftService;
            _approvalProcService          = approvalProcService;
            _messageService               = messageService;
            _requestMessageHandlerService = requestMessageHandlerService;

            _logger = logger;
        }
Example #30
0
 public MonthlyEmailService(IMailService mailService,
                            IIntranetMemberService <IIntranetMember> intranetMemberService,
                            IExceptionLogger logger,
                            IBulletinsService <BulletinBase> bulletinsService,
                            IEventsService <EventBase> eventsService,
                            INewsService <NewsBase> newsService,
                            IUserTagRelationService userTagService,
                            IActivityLinkService activityLinkService,
                            NotificationSettingsService notificationSettingsService,
                            INotificationModelMapper <EmailNotifierTemplate, EmailNotificationMessage> notificationModelMapper,
                            IApplicationSettings applicationSettings)
     : base(mailService, intranetMemberService, logger, notificationSettingsService, applicationSettings)
 {
     _bulletinsService        = bulletinsService;
     _eventsService           = eventsService;
     _newsService             = newsService;
     _userTagService          = userTagService;
     _activityLinkService     = activityLinkService;
     _notificationModelMapper = notificationModelMapper;
 }
Example #31
0
        /// <summary>Calls an exception logger.</summary>
        /// <param name="logger">The unhandled exception logger.</param>
        /// <param name="context">The exception context.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A task representing the asynchronous exception logging operation.</returns>
        public static Task LogAsync(
            this IExceptionLogger logger,
            ExceptionContext context,
            CancellationToken cancellationToken
            )
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ExceptionLoggerContext loggerContext = new ExceptionLoggerContext(context);

            return(logger.LogAsync(loggerContext, cancellationToken));
        }
Example #32
0
        public void ExecuteAsync_IfInnerResultTaskIsFaulted_ExecutesFiltersAndReturnsResultIfHandled()
        {
            // Arrange
            List <string>     log           = new List <string>();
            HttpActionContext actionContext = ContextUtil.CreateActionContext();
            var exception = new Exception();
            HttpResponseMessage globalFilterResponse     = new HttpResponseMessage();
            HttpResponseMessage actionFilterResponse     = new HttpResponseMessage();
            HttpResponseMessage resultSeenByGlobalFilter = null;
            var globalFilter = CreateExceptionFilter((ec, ct) =>
            {
                log.Add("globalFilter");
                resultSeenByGlobalFilter = ec.Response;
                ec.Response = globalFilterResponse;
                return(Task.Factory.StartNew(() => { }));
            });
            var actionFilter = CreateExceptionFilter((ec, ct) =>
            {
                log.Add("actionFilter");
                ec.Response = actionFilterResponse;
                return(Task.Factory.StartNew(() => { }));
            });
            var filters = new IExceptionFilter[] { globalFilter, actionFilter };
            IExceptionLogger  exceptionLogger  = CreateStubExceptionLogger();
            IExceptionHandler exceptionHandler = CreateDummyExceptionHandler();
            var actionResult = CreateStubActionResult(TaskHelpers.FromError <HttpResponseMessage>(exception));

            IHttpActionResult product = CreateProductUnderTest(actionContext, filters, exceptionLogger,
                                                               exceptionHandler, actionResult);

            // Act
            var result = product.ExecuteAsync(CancellationToken.None);

            // Assert
            Assert.NotNull(result);
            result.WaitUntilCompleted();
            Assert.Equal(TaskStatus.RanToCompletion, result.Status);
            Assert.Same(globalFilterResponse, result.Result);
            Assert.Same(actionFilterResponse, resultSeenByGlobalFilter);
            Assert.Equal(new string[] { "actionFilter", "globalFilter" }, log.ToArray());
        }
        private static async Task WriteErrorResponseContentAsync(HttpResponseBase httpResponseBase,
                                                                 HttpRequestMessage request, HttpResponseMessage errorResponse, CancellationToken cancellationToken,
                                                                 IExceptionLogger exceptionLogger)
        {
            HttpRequestMessage ignoreUnused = request;

            try
            {
                Exception exception = null;
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    // Asynchronously write the content of the new error HttpResponseMessage
                    await errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream);

                    return;
                }
                catch (Exception ex)
                {
                    exception = ex;
                }

                Contract.Assert(exception != null);

                ExceptionContext exceptionContext = new ExceptionContext(exception,
                                                                         WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError, request, errorResponse);
                await exceptionLogger.LogAsync(exceptionContext, canBeHandled : false,
                                               cancellationToken : cancellationToken);

                // Failure writing the error response.  Likely cause is a formatter
                // serialization exception.  Create empty error response and
                // return a non-faulted task.
                SetEmptyErrorResponse(httpResponseBase);
            }
            finally
            {
                // Dispose the temporary HttpResponseMessage carrying the error response
                errorResponse.Dispose();
            }
        }
        internal static async Task CopyResponseAsync(HttpContextBase httpContextBase, HttpRequestMessage request,
                                                     HttpResponseMessage response, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,
                                                     CancellationToken cancellationToken)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(request != null);

            // A null response creates a 500 with no content
            if (response == null)
            {
                SetEmptyErrorResponse(httpContextBase.Response);
                return;
            }

            if (!await CopyResponseStatusAndHeadersAsync(httpContextBase, request, response, exceptionLogger,
                                                         cancellationToken))
            {
                return;
            }

            // TODO 335085: Consider this when coming up with our caching story
            if (response.Headers.CacheControl == null)
            {
                // DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.
                // However, we don't want requests to be cached by default.
                // If nobody set an explicit CacheControl then explicitly set to no-cache to override the
                // default behavior. This will cause the following response headers to be emitted:
                //     Cache-Control: no-cache
                //     Pragma: no-cache
                //     Expires: -1
                httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }

            // Asynchronously write the response body.  If there is no body, we use
            // a completed task to share the Finally() below.
            // The response-writing task will not fault -- it handles errors internally.
            if (response.Content != null)
            {
                await WriteResponseContentAsync(httpContextBase, request, response, exceptionLogger, exceptionHandler, cancellationToken);
            }
        }
        /// <summary>Initializes a new instance of the <see cref="HttpMessageHandlerAdapter"/> class.</summary>
        /// <param name="next">The next component in the pipeline.</param>
        /// <param name="options">The options to configure this adapter.</param>
        public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandlerOptions options)
            : base(next)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _messageHandler = options.MessageHandler;

            if (_messageHandler == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                                                         typeof(HttpMessageHandlerOptions).Name, "MessageHandler"), "options");
            }

            _messageInvoker       = new HttpMessageInvoker(_messageHandler);
            _bufferPolicySelector = options.BufferPolicySelector;

            if (_bufferPolicySelector == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                                                         typeof(HttpMessageHandlerOptions).Name, "BufferPolicySelector"), "options");
            }

            _exceptionLogger = options.ExceptionLogger;

            if (_exceptionLogger == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                                                         typeof(HttpMessageHandlerOptions).Name, "ExceptionLogger"), "options");
            }

            _exceptionHandler = options.ExceptionHandler;

            if (_exceptionHandler == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                                                         typeof(HttpMessageHandlerOptions).Name, "ExceptionHandler"), "options");
            }
        }
        public void ProcessRequestAsync_IfExceptionIsNotHttpResponseException_CallsExceptionServices()
        {
            // Arrange
            Exception             expectedException = CreateException();
            ExceptionDispatchInfo exceptionInfo     = CreateExceptionInfo(expectedException);

            Mock <IExceptionLogger>  loggerMock  = CreateStubExceptionLoggerMock();
            IExceptionLogger         logger      = loggerMock.Object;
            Mock <IExceptionHandler> handlerMock = CreateStubExceptionHandlerMock();
            IExceptionHandler        handler     = handlerMock.Object;

            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);

            HttpResponseBase responseBase = CreateStubResponseBase();
            HttpContextBase  contextBase  = CreateStubContextBase(responseBase);

            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())
            {
                contextBase.SetHttpRequestMessage(expectedRequest);

                // Act
                Task task = product.ProcessRequestAsync(contextBase);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();
                Assert.Equal(TaskStatus.Faulted, task.Status);

                Func <ExceptionContext, bool> exceptionContextMatches = (c) =>
                                                                        c != null &&
                                                                        c.Exception == expectedException &&
                                                                        c.CatchBlock == WebHostExceptionCatchBlocks.HttpWebRoute &&
                                                                        c.Request == expectedRequest;

                loggerMock.Verify(l => l.LogAsync(It.Is <ExceptionLoggerContext>(c =>
                                                                                 c.CanBeHandled == true && exceptionContextMatches(c.ExceptionContext)),
                                                  CancellationToken.None), Times.Once());
                handlerMock.Verify(l => l.HandleAsync(It.Is <ExceptionHandlerContext>(c =>
                                                                                      exceptionContextMatches(c.ExceptionContext)), CancellationToken.None), Times.Once());
            }
        }
        private static Task WriteResponseContentAsync(HttpContextBase httpContextBase, HttpRequestMessage request,
                                                      HttpResponseMessage response, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,
                                                      CancellationToken cancellationToken)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(response != null);
            Contract.Assert(request != null);
            Contract.Assert(response.Content != null);

            HttpResponseBase httpResponseBase = httpContextBase.Response;
            HttpContent      responseContent  = response.Content;

            CopyHeaders(responseContent.Headers, httpContextBase);

            // PrepareHeadersAsync already evaluated the buffer policy.
            bool isBuffered = httpResponseBase.BufferOutput;

            return(isBuffered
                    ? WriteBufferedResponseContentAsync(httpContextBase, request, response, exceptionLogger, exceptionHandler, cancellationToken)
                    : WriteStreamedResponseContentAsync(httpContextBase, request, response, exceptionLogger, cancellationToken));
        }
        public void GetExceptionLoggers_DelegatesToGetServices()
        {
            // Arrange
            IExceptionLogger expectedExceptionLogger = new Mock <IExceptionLogger>(MockBehavior.Strict).Object;
            IEnumerable <IExceptionLogger> expectedExceptionLoggers =
                new IExceptionLogger[] { expectedExceptionLogger };

            Mock <ServicesContainer> mock = new Mock <ServicesContainer>(MockBehavior.Strict);

            mock.Setup(s => s.GetServices(typeof(IExceptionLogger))).Returns(expectedExceptionLoggers);
            ServicesContainer services = mock.Object;

            // Act
            IEnumerable <IExceptionLogger> exceptionLoggers = ServicesExtensions.GetExceptionLoggers(services);

            // Assert
            mock.Verify(s => s.GetServices(typeof(IExceptionLogger)), Times.Once());
            Assert.NotNull(exceptionLoggers);
            Assert.Equal(1, exceptionLoggers.Count());
            Assert.Same(expectedExceptionLogger, exceptionLoggers.Single());
        }
Example #39
0
        public PersonnelDutyService(IRepository <PersonnelDuty> personnelDutyRepository
                                    , IRepository <Personnel> personnelRepository
                                    , IRepository <PersonnelDailyDuty> personnelDailyDuty
                                    , IRepository <PersonnelHourlyDuty> personnelHourlyDuty
                                    , IAuthService authService
                                    , IApprovalProcService approvalProcService, IMessageService messageService
                                    , IRequestMessageHandlerService requestMessageHandlerService
                                    , IExceptionLogger logger)
        {
            _personnelRepository           = personnelRepository;
            _personnelDutyRepository       = personnelDutyRepository;
            _personnelDailyDutyRepository  = personnelDailyDuty;
            _personnelHourlyDutyRepository = personnelHourlyDuty;

            _authService                  = authService;
            _approvalProcService          = approvalProcService;
            _messageService               = messageService;
            _requestMessageHandlerService = requestMessageHandlerService;

            _logger = logger;
        }
        protected ParseValidateCommitCommand(IParser <TInput, TOutput> parser, IValidator <TOutput> validator,
                                             TUnitOfWork unitOfWork, IExceptionLogger exceptionLogger)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }
            if (validator == null)
            {
                throw new ArgumentNullException("validator");
            }
            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWork");
            }

            _parser          = parser;
            _validator       = validator;
            UnitOfWork       = unitOfWork;
            _exceptionLogger = exceptionLogger;
        }
Example #41
0
        public BaseStrategyBasedUserServiceEF(IExceptionLogger logger,
                                              DbContext context,
                                              IUserRepository <TUser, TUserPK> userRepo,
                                              TRepository repo) : base(logger, context, userRepo)
        {
            Repository = repo;
            if (repo == null)
            {
                defaultRepository = new BaseRepositoryEF <TEntity, TEntityPK>(context);
            }
            else
            {
                var efRepo = Repository as BaseRepositoryEF;
                if (efRepo != null)
                {
                    efRepo.Context = context;
                }
            }

            InitStrategies(logger);
        }
Example #42
0
        public void ExecuteAsync_IfInnerResultTaskIsFaulted_CallsExceptionLogger()
        {
            // Arrange
            Exception expectedException = CreateException();

            using (HttpRequestMessage request = CreateRequest())
            {
                HttpActionContext  expectedActionContext = CreateActionContext(request);
                IExceptionFilter[] filters = new IExceptionFilter[0];

                Mock <IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();
                IExceptionLogger        exceptionLogger     = exceptionLoggerMock.Object;

                IExceptionHandler exceptionHandler = CreateStubExceptionHandler();
                IHttpActionResult innerResult      = CreateStubActionResult(
                    CreateFaultedTask <HttpResponseMessage>(expectedException));

                IHttpActionResult product = CreateProductUnderTest(expectedActionContext, filters, exceptionLogger,
                                                                   exceptionHandler, innerResult);

                CancellationToken cancellationToken = CreateCancellationToken();

                Task <HttpResponseMessage> task = product.ExecuteAsync(cancellationToken);

                // Act
                task.WaitUntilCompleted();

                // Assert
                Func <ExceptionContext, bool> exceptionContextMatches = (c) =>
                                                                        c != null &&
                                                                        c.Exception == expectedException &&
                                                                        c.CatchBlock == ExceptionCatchBlocks.IExceptionFilter &&
                                                                        c.ActionContext == expectedActionContext;

                exceptionLoggerMock.Verify(l => l.LogAsync(
                                               It.Is <ExceptionLoggerContext>(c => c.CanBeHandled == true &&
                                                                              exceptionContextMatches(c.ExceptionContext)),
                                               cancellationToken), Times.Once());
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ExceptionInterceptor"/> class.
 /// </summary>
 /// <param name="logger">Interface used for the logging.</param>
 public ExceptionInterceptor(IExceptionLogger logger)
 {
     _logger = logger;
 }
        public void LogAsync_IfLoggerIsNull_Throws()
        {
            // Arrange
            IEnumerable<IExceptionLogger> loggers = new IExceptionLogger[] { null };
            IExceptionLogger product = CreateProductUnderTest(loggers);

            ExceptionLoggerContext context = CreateMinimalValidContext();
            CancellationToken cancellationToken = CreateCancellationToken();

            // Act & Assert
            Assert.Throws<InvalidOperationException>(() => product.LogAsync(context, cancellationToken),
                "The IExceptionLogger instance must not be null.");

        }
 public TotalProgressLogger(IProgressUiFactory uiFactory, IExceptionLogger exceptionLogger)
 {
     _exceptionLogger = exceptionLogger;
       _progressUi = uiFactory.Create (3 * c_SingleStepTotal);
 }
        public void LogAsync_DelegatesToLoggers()
        {
            // Arrange
            Mock<IExceptionLogger> exceptionLogger1Mock = new Mock<IExceptionLogger>(MockBehavior.Strict);
            Mock<IExceptionLogger> exceptionLogger2Mock = new Mock<IExceptionLogger>(MockBehavior.Strict);
            exceptionLogger1Mock
                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(0));
            exceptionLogger2Mock
                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(0));
            IEnumerable<IExceptionLogger> loggers = new IExceptionLogger[]
            {
                exceptionLogger1Mock.Object,
                exceptionLogger2Mock.Object
            };
            IExceptionLogger product = CreateProductUnderTest(loggers);

            ExceptionLoggerContext expectedContext = CreateMinimalValidContext();
            CancellationToken expectedCancellationToken = CreateCancellationToken();

            // Act
            Task task = product.LogAsync(expectedContext, expectedCancellationToken);
            Assert.NotNull(task);
            task.WaitUntilCompleted();

            // Assert
            Assert.Equal(TaskStatus.RanToCompletion, task.Status);
            exceptionLogger1Mock.Verify(l => l.LogAsync(expectedContext, expectedCancellationToken), Times.Once());
            exceptionLogger2Mock.Verify(l => l.LogAsync(expectedContext, expectedCancellationToken), Times.Once());
        }
        internal static async Task<bool> PrepareHeadersAsync(HttpResponseBase responseBase, HttpRequestMessage request,
            HttpResponseMessage response, IExceptionLogger exceptionLogger, CancellationToken cancellationToken)
        {
            Contract.Assert(response != null);
            HttpResponseHeaders responseHeaders = response.Headers;
            Contract.Assert(responseHeaders != null);
            HttpContent content = response.Content;
            bool isTransferEncodingChunked = responseHeaders.TransferEncodingChunked == true;
            HttpHeaderValueCollection<TransferCodingHeaderValue> transferEncoding = responseHeaders.TransferEncoding;

            if (content != null)
            {
                HttpContentHeaders contentHeaders = content.Headers;
                Contract.Assert(contentHeaders != null);

                if (isTransferEncodingChunked)
                {
                    // According to section 4.4 of the HTTP 1.1 spec, HTTP responses that use chunked transfer
                    // encoding must not have a content length set. Chunked should take precedence over content
                    // length in this case because chunked is always set explicitly by users while the Content-Length
                    // header can be added implicitly by System.Net.Http.
                    contentHeaders.ContentLength = null;
                }
                else
                {
                    Exception exception = null;

                    // Copy the response content headers only after ensuring they are complete.
                    // We ask for Content-Length first because HttpContent lazily computes this
                    // and only afterwards writes the value into the content headers.
                    try
                    {
                        var unused = contentHeaders.ContentLength;
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }

                    if (exception != null)
                    {
                        ExceptionContext exceptionContext = new ExceptionContext(exception,
                            WebHostExceptionCatchBlocks.HttpControllerHandlerComputeContentLength, request, response);
                        await exceptionLogger.LogAsync(exceptionContext, cancellationToken);

                        SetEmptyErrorResponse(responseBase);
                        return false;
                    }
                }

                // Select output buffering based on the user-controlled buffering policy
                bool isBuffered = _bufferPolicySelector.Value != null ?
                    _bufferPolicySelector.Value.UseBufferedOutputStream(response) : true;
                responseBase.BufferOutput = isBuffered;
            }

            // Ignore the Transfer-Encoding header if it is just "chunked"; the host will provide it when no
            // Content-Length is present and BufferOutput is disabled (and this method guarantees those conditions).
            // HttpClient sets this header when it receives chunked content, but HttpContent does not include the
            // frames. The ASP.NET contract is to set this header only when writing chunked frames to the stream.
            // A Web API caller who desires custom framing would need to do a different Transfer-Encoding (such as
            // "identity, chunked").
            if (isTransferEncodingChunked && transferEncoding.Count == 1)
            {
                transferEncoding.Clear();

                // In the case of a conflict between a Transfer-Encoding: chunked header and the output buffering
                // policy, honor the Transnfer-Encoding: chunked header and ignore the buffer policy.
                // If output buffering is not disabled, ASP.NET will not write the TransferEncoding: chunked header.
                responseBase.BufferOutput = false;
            }

            return true;
        }
 public MappedExceptionFilterAttribute(IExceptionLogger exceptionLogger = null, bool returnUnhandledException = false)
 {
     _exceptionLogger = exceptionLogger ?? new NullExceptionLogger();
     DefaultMapping = new MapException(null, HttpStatusCode.InternalServerError, returnUnhandledException);
 }
 public UnitOfWorkInterceptor(ITransactionManager transactionManager, IExceptionLogger exceptionLogger)
     : base(transactionManager, exceptionLogger)
 {
 }
        internal static async Task<bool> CopyErrorResponseAsync(ExceptionContextCatchBlock catchBlock,
            HttpContextBase httpContextBase, HttpRequestMessage request, HttpResponseMessage response,
            Exception exception, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,
            CancellationToken cancellationToken)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(httpContextBase.Response != null);
            Contract.Assert(request != null);
            Contract.Assert(exception != null);
            Contract.Assert(catchBlock != null);
            Contract.Assert(catchBlock.CallsHandler);

            HttpResponseBase httpResponseBase = httpContextBase.Response;
            HttpResponseMessage errorResponse = null;
            HttpResponseException responseException = exception as HttpResponseException;

            // Ensure all headers and content are cleared to eliminate any partial results.
            ClearContentAndHeaders(httpResponseBase);

            // If the exception we are handling is HttpResponseException,
            // that becomes the error response.
            if (responseException != null)
            {
                errorResponse = responseException.Response;
            }
            else
            {
                ExceptionContext exceptionContext = new ExceptionContext(exception, catchBlock, request)
                {
                    Response = response
                };
                await exceptionLogger.LogAsync(exceptionContext, cancellationToken);
                errorResponse = await exceptionHandler.HandleAsync(exceptionContext, cancellationToken);

                if (errorResponse == null)
                {
                    return false;
                }
            }

            Contract.Assert(errorResponse != null);
            if (!await CopyResponseStatusAndHeadersAsync(httpContextBase, request, errorResponse, exceptionLogger,
                cancellationToken))
            {
                // Don't rethrow the original exception unless explicitly requested to do so. In this case, the
                // exception handler indicated it wanted to handle the exception; it simply failed create a stable
                // response to send.
                return true;
            }

            // The error response may return a null content if content negotiation
            // fails to find a formatter, or this may be an HttpResponseException without
            // content.  In either case, cleanup and return a completed task.

            if (errorResponse.Content == null)
            {
                errorResponse.Dispose();
                return true;
            }

            CopyHeaders(errorResponse.Content.Headers, httpContextBase);

            await WriteErrorResponseContentAsync(httpResponseBase, request, errorResponse, cancellationToken,
                exceptionLogger);
            return true;
        }
        internal static async Task WriteBufferedResponseContentAsync(HttpContextBase httpContextBase,
            HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,
            IExceptionHandler exceptionHandler, CancellationToken cancellationToken)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(httpContextBase.Response != null);
            Contract.Assert(request != null);
            Contract.Assert(response != null);
            Contract.Assert(response.Content != null);

            HttpResponseBase httpResponseBase = httpContextBase.Response;

            // Return a task that writes the response body asynchronously.
            // We guarantee we will handle all error responses internally
            // and always return a non-faulted task, except for custom error handlers that choose to propagate these
            // exceptions.
            ExceptionDispatchInfo exceptionInfo;
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                // Copy the HttpContent into the output stream asynchronously.
                await response.Content.CopyToAsync(httpResponseBase.OutputStream);
                return;
            }
            catch (Exception exception)
            {
                // Can't use await inside a catch block
                exceptionInfo = ExceptionDispatchInfo.Capture(exception);
            }

            Debug.Assert(exceptionInfo.SourceException != null);

            // If we were using a buffered stream, we can still set the headers and status code, and we can create an
            // error response with the exception.
            // We create a continuation task to write an error response that will run after returning from this Catch()
            // but before other continuations the caller appends to this task.
            // The error response writing task handles errors internally and will not show as faulted, except for
            // custom error handlers that choose to propagate these exceptions.
            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent;

            if (!await CopyErrorResponseAsync(catchBlock, httpContextBase, request, response,
                exceptionInfo.SourceException, exceptionLogger, exceptionHandler, cancellationToken))
            {
                exceptionInfo.Throw();
            }
        }
        internal static async Task WriteStreamedResponseContentAsync(HttpContextBase httpContextBase,
            HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,
            CancellationToken cancellationToken)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(httpContextBase.Response != null);
            Contract.Assert(request != null);
            Contract.Assert(response != null);
            Contract.Assert(response.Content != null);

            Exception exception = null;
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                // Copy the HttpContent into the output stream asynchronously.
                await response.Content.CopyToAsync(httpContextBase.Response.OutputStream);
                return;
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Contract.Assert(exception != null);

            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerStreamContent;
            ExceptionContext exceptionContext = new ExceptionContext(exception, catchBlock, request, response);
            await exceptionLogger.LogAsync(exceptionContext, cancellationToken);

            // Streamed content may have been written and cannot be recalled.
            // Our only choice is to abort the connection.
            httpContextBase.Request.Abort();
        }
        private static Task WriteResponseContentAsync(HttpContextBase httpContextBase, HttpRequestMessage request,
            HttpResponseMessage response, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,
            CancellationToken cancellationToken)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(response != null);
            Contract.Assert(request != null);
            Contract.Assert(response.Content != null);

            HttpResponseBase httpResponseBase = httpContextBase.Response;
            HttpContent responseContent = response.Content;

            CopyHeaders(responseContent.Headers, httpContextBase);

            // PrepareHeadersAsync already evaluated the buffer policy.
            bool isBuffered = httpResponseBase.BufferOutput;

            return isBuffered
                    ? WriteBufferedResponseContentAsync(httpContextBase, request, response, exceptionLogger, exceptionHandler, cancellationToken)
                    : WriteStreamedResponseContentAsync(httpContextBase, request, response, exceptionLogger, cancellationToken);
        }
        internal static async Task CopyResponseAsync(HttpContextBase httpContextBase, HttpRequestMessage request,
            HttpResponseMessage response, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,
            CancellationToken cancellationToken)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(request != null);

            // A null response creates a 500 with no content
            if (response == null)
            {
                SetEmptyErrorResponse(httpContextBase.Response);
                return;
            }

            if (!await CopyResponseStatusAndHeadersAsync(httpContextBase, request, response, exceptionLogger,
                cancellationToken))
            {
                return;
            }

            // TODO 335085: Consider this when coming up with our caching story
            if (response.Headers.CacheControl == null)
            {
                // DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.
                // However, we don't want requests to be cached by default.
                // If nobody set an explicit CacheControl then explicitly set to no-cache to override the
                // default behavior. This will cause the following response headers to be emitted:
                //     Cache-Control: no-cache
                //     Pragma: no-cache
                //     Expires: -1
                httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }

            // Asynchronously write the response body.  If there is no body, we use
            // a completed task to share the Finally() below.
            // The response-writing task will not fault -- it handles errors internally.
            if (response.Content != null)
            {
                await WriteResponseContentAsync(httpContextBase, request, response, exceptionLogger, exceptionHandler, cancellationToken);
            }
        }
 public TotalProgressContext(IProgressUiFactory progressUiFactory, int loadOperationThresholdForProgressDisplay, IExceptionLogger exceptionLogger)
 {
     _progressUiFactory = progressUiFactory;
       _loadOperationThresholdForProgressDisplay = loadOperationThresholdForProgressDisplay;
       _exceptionLogger = exceptionLogger;
 }
 public ExceptionInterceptor(IExceptionLogger logger)
 {
     this.exceptionFilter = logger;
 }
        public ExceptionHandlerInterceptor(IExceptionLogger exceptionLogger)
        {
            ParameterCheck.ParameterRequired(exceptionLogger, "exceptionLogger");

            this.exceptionLogger = exceptionLogger;
        }
        private static async Task WriteErrorResponseContentAsync(HttpResponseBase httpResponseBase,
            HttpRequestMessage request, HttpResponseMessage errorResponse, CancellationToken cancellationToken,
            IExceptionLogger exceptionLogger)
        {
            HttpRequestMessage ignoreUnused = request;

            try
            {
                Exception exception = null;
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    // Asynchronously write the content of the new error HttpResponseMessage
                    await errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream);
                    return;
                }
                catch (Exception ex)
                {
                    exception = ex;
                }

                Contract.Assert(exception != null);

                ExceptionContext exceptionContext = new ExceptionContext(exception,
                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError, request, errorResponse);
                await exceptionLogger.LogAsync(exceptionContext, cancellationToken);

                // Failure writing the error response.  Likely cause is a formatter
                // serialization exception.  Create empty error response and
                // return a non-faulted task.
                SetEmptyErrorResponse(httpResponseBase);
            }
            finally
            {
                // Dispose the temporary HttpResponseMessage carrying the error response
                errorResponse.Dispose();
            }
        }
 private static HttpRouteExceptionHandler CreateProductUnderTest(ExceptionDispatchInfo exceptionInfo,
     IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler)
 {
     return new HttpRouteExceptionHandler(exceptionInfo, exceptionLogger, exceptionHandler);
 }
        private static async Task<bool> CopyResponseStatusAndHeadersAsync(HttpContextBase httpContextBase,
            HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,
            CancellationToken cancellationToken)
        {
            Contract.Assert(httpContextBase != null);
            HttpResponseBase httpResponseBase = httpContextBase.Response;
            httpResponseBase.StatusCode = (int)response.StatusCode;
            httpResponseBase.StatusDescription = response.ReasonPhrase;
            httpResponseBase.TrySkipIisCustomErrors = true;
            EnsureSuppressFormsAuthenticationRedirect(httpContextBase);

            if (!await PrepareHeadersAsync(httpResponseBase, request, response, exceptionLogger, cancellationToken))
            {
                return false;
            }

            CopyHeaders(response.Headers, httpContextBase);
            return true;
        }