Handle() public method

public Handle ( System.Web.Http.ExceptionHandling.ExceptionHandlerContext context ) : void
context System.Web.Http.ExceptionHandling.ExceptionHandlerContext
return void
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            try {
                if (ValidateUser(_model, _isNew))
                {
                    var service = new SupportService(User);
                    if (_isNew)
                    {
                        service.InsertUser(_model.Model);
                    }
                    else
                    {
                        service.UpdateUser(_model.Model);
                    }

                    if (!string.IsNullOrEmpty(txtPassword.Password))
                    {
                        service.UpdateUserPassword(_model.UserName, txtPassword.Password);
                    }

                    this.DialogResult = true;
                    this.Close();
                }
            } catch (Exception ex) {
                GlobalExceptionHandler.Handle(ex);
            }
        }
        public async Task Handle_WhenContextHasNoHandlerFeatureEnabled_ShouldSetResponseStatusCodeAndContentType()
        {
            //Arrange
            _featuresMock
            .Setup(x => x.Get <IExceptionHandlerFeature>())
            .Returns <IExceptionHandlerFeature>(null);

            _responseMock
            .SetupProperty(x => x.StatusCode)
            .SetupProperty(x => x.ContentType);

            _httpContext = new MockHttpContext(_featuresMock.Object, response: _responseMock.Object);

            var expectedBody = _responseMock.Object.Body;

            var sut = new GlobalExceptionHandler(_exceptionWriterMock.Object, _loggerMock.Object);

            //Act
            await sut.Handle(_httpContext);

            //Assert
            _responseMock.Object.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError);
            _responseMock.Object.ContentType.Should().Be("application/json");

            _exceptionWriterMock.Verify(x => x.WriteResponse(_httpContext), Times.Never);
        }
        public async Task Handle_WhenContextHasHandlerFeatureEnabled_ShouldWriteResponse()
        {
            //Arrange
            var errorMessage = "TestMessage";

            _exceptionHandlerFeatureMock
            .Setup(x => x.Error.Message)
            .Returns(errorMessage);

            _featuresMock
            .Setup(x => x.Get <IExceptionHandlerFeature>())
            .Returns(_exceptionHandlerFeatureMock.Object);

            _responseMock
            .SetupProperty(x => x.StatusCode)
            .SetupProperty(x => x.ContentType);

            _httpContext = new MockHttpContext(_featuresMock.Object, response: _responseMock.Object);

            var sut = new GlobalExceptionHandler(_exceptionWriterMock.Object, _loggerMock.Object);

            //Act
            await sut.Handle(_httpContext);

            //Assert
            _exceptionWriterMock.Verify(x => x.WriteResponse(_httpContext), Times.Once);
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            if (!env.IsProduction())
            {
                app.UseOpenApi();
                app.UseSwaggerUi3();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseExceptionHandler(x => x.Run(GlobalExceptionHandler.Handle(env)));

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub <SignalrHub>("/hub");
            });
        }
Exemplo n.º 5
0
        public void GlobalExceptionHandler_Handle()
        {
            var handler = new GlobalExceptionHandler();
            var context = new ExceptionHandlerContext(new ExceptionContext(new Exception(), new ExceptionContextCatchBlock("Test", true, true), new HttpRequestMessage()));

            handler.Handle(context);

            ((TextPlainErrorResult)context.Result).Content.Should().NotBeEmpty();
        }
        public void FilesPersistenceControllerReturnsBadRequestHttpResponseExceptionForUnsupportedOperationException()
        {
            var exceptionContext        = new ExceptionContext(new UnsupportedOperationException("Unsupported operation"), new ExceptionContextCatchBlock("test", true, true));
            var exceptionHandlerContext = new ExceptionHandlerContext(exceptionContext);
            var globalExceptionHandler  = new GlobalExceptionHandler();

            globalExceptionHandler.Handle(exceptionHandlerContext);
            var result = exceptionHandlerContext.Result.ExecuteAsync(new CancellationToken()).Result;

            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
            Assert.AreEqual("Unsupported operation", result.Content.ReadAsStringAsync().Result);
        }
        public void FormsPersistenceControllerReturnsBadRequestHttpResponseExceptionForGeneralException()
        {
            var exceptionContext        = new ExceptionContext(new Exception("General error"), new ExceptionContextCatchBlock("test", true, true));
            var exceptionHandlerContext = new ExceptionHandlerContext(exceptionContext);
            var globalExceptionHandler  = new GlobalExceptionHandler();

            globalExceptionHandler.Handle(exceptionHandlerContext);
            var result = exceptionHandlerContext.Result.ExecuteAsync(new CancellationToken()).Result;

            Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode);
            Assert.AreEqual("Error occurred during API call - General error", result.Content.ReadAsStringAsync().Result);
        }
        public void FormsPersistenceControllerReturnsNotFoundHttpResponseExceptionForNotFoundException()
        {
            var exceptionContext        = new ExceptionContext(new NotFoundException("Not found error"), new ExceptionContextCatchBlock("test", true, true));
            var exceptionHandlerContext = new ExceptionHandlerContext(exceptionContext);
            var globalExceptionHandler  = new GlobalExceptionHandler();

            globalExceptionHandler.Handle(exceptionHandlerContext);
            var result = exceptionHandlerContext.Result.ExecuteAsync(new CancellationToken()).Result;

            Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
            Assert.AreEqual("Not found error", result.Content.ReadAsStringAsync().Result);
        }
Exemplo n.º 9
0
        public List <string> GetPlaceTypes()
        {
            var list = new List <string>();

            try {
                var sql = "SELECT DISTINCT tType FROM tblGaz";
                SelectReader(sql, (reader) => {
                    list.Add(reader[0] as string);
                });
            } catch (Exception ex) {
                GlobalExceptionHandler.Handle(ex);
            }

            return(list);
        }
Exemplo n.º 10
0
        public List <PlaceName> FindPlaceNames(string find, int maxrows = 1000)
        {
            List <PlaceName> list = new List <PlaceName>();

            try {
                string sql = "SELECT tPlace as Name, tType as PlaceType, tDivision as Division, tLatitude as LatitudeString, tLongitude as LongitudeString, dblLatitude as Latitude, dblLongitude as Longitude FROM tblGaz WHERE tPlace like @find ORDER BY tDivision, tPlace, tType LIMIT @limit";
                SelectReader(sql, (reader) => {
                    PlaceName place = new PlaceName();
                    MapperBase.ReflectMap(place, reader, null, null);
                    list.Add(place);
                }, new SQLiteParameter("@find", find + "%"), new SQLiteParameter("@limit", maxrows));
            } catch (Exception ex) {
                GlobalExceptionHandler.Handle(ex);
            }

            return(list);
        }
Exemplo n.º 11
0
        public int CountPlacesInBoundedBox(double x1, double y1, double x2, double y2, string placeType)
        {
            int count = 0;

            try {
                string sql = "SELECT Count(*) FROM tblGaz WHERE (dblLatitude BETWEEN @y1 AND @y2) AND (dblLongitude BETWEEN @x1 AND @x2)";
                if (!string.IsNullOrEmpty(placeType))
                {
                    sql += " and tType = @div";
                }
                SelectReader(sql, (reader) => {
                    count = reader.GetInt32(0);
                }, new SQLiteParameter("@y1", y1), new SQLiteParameter("@y2", y2), new SQLiteParameter("@x1", x1), new SQLiteParameter("@x2", x2), new SQLiteParameter("@div", placeType));
            } catch (Exception ex) {
                GlobalExceptionHandler.Handle(ex);
            }

            return(count);
        }
Exemplo n.º 12
0
        public List <CodeLabelPair> GetDivisions()
        {
            List <CodeLabelPair> results = new List <CodeLabelPair>();

            try {
                SelectReader("SELECT tDatabase, tAbbreviation FROM tblDivisions", (reader) => {
                    string code   = reader["tDatabase"] as string;
                    string abbrev = reader["tAbbreviation"] as string;
                    if (String.IsNullOrEmpty(abbrev))
                    {
                        abbrev = code;
                    }
                    results.Add(new CodeLabelPair(code, abbrev));
                });
            } catch (Exception ex) {
                GlobalExceptionHandler.Handle(ex);
            }

            return(results);
        }
Exemplo n.º 13
0
        public List <PlaceName> GetPlacesInBoundedBox(double x1, double y1, double x2, double y2, string placeType)
        {
            var list = new List <PlaceName>();

            try {
                string sql = "SELECT tPlace as Name, tType as PlaceType, tDivision as Division, tLatitude as LatitudeString, tLongitude as LongitudeString, dblLatitude as Latitude, dblLongitude as Longitude FROM tblGaz WHERE (dblLatitude BETWEEN @y1 AND @y2) AND (dblLongitude BETWEEN @x1 AND @x2)";
                if (!string.IsNullOrEmpty(placeType))
                {
                    sql += " and tType = @div";
                }
                SelectReader(sql, (reader) => {
                    PlaceName place = new PlaceName();
                    MapperBase.ReflectMap(place, reader, null, null);
                    list.Add(place);
                }, new SQLiteParameter("@y1", y1), new SQLiteParameter("@y2", y2), new SQLiteParameter("@x1", x1), new SQLiteParameter("@x2", x2), new SQLiteParameter("@div", placeType));
            } catch (Exception ex) {
                GlobalExceptionHandler.Handle(ex);
            }

            return(list);
        }
        public async Task Handle_WhenContextHasHandlerFeatureEnabled_ShouldLogInternalServerError()
        {
            //Arrange
            var errorMessage = "TestMessage";

            _exceptionHandlerFeatureMock
            .Setup(x => x.Error.Message)
            .Returns(errorMessage);

            _featuresMock
            .Setup(x => x.Get <IExceptionHandlerFeature>())
            .Returns(_exceptionHandlerFeatureMock.Object);

            _httpContext = new MockHttpContext(_featuresMock.Object, response: _responseMock.Object);

            var sut = new GlobalExceptionHandler(_exceptionWriterMock.Object, _loggerMock.Object);

            //Act
            await sut.Handle(_httpContext);

            //Assert
            _loggerMock.Verify(x =>
                               x.Write(LogLevel.Error, $"{EventCodes.InternalServerError} - {errorMessage}"), Times.Once);
        }
        private void DoSearch(string text)
        {
            try {
                if (_service == null)
                {
                    return;
                }

                lstResults.InvokeIfRequired(() => {
                    lstResults.Cursor  = Cursors.Wait;
                    lblResults.Content = _owner.GetCaption("Gazetteer.Search.Searching");
                });


                if (!String.IsNullOrEmpty(text))
                {
                    List <PlaceName> results = null;

                    bool limit = false;
                    chkLimit.InvokeIfRequired(() => {
                        limit = chkLimit.IsChecked.HasValue && chkLimit.IsChecked.Value;
                    });

                    string division = "";
                    if (limit)
                    {
                        cmbDivision.InvokeIfRequired(() => {
                            CodeLabelPair selected = cmbDivision.SelectedItem as CodeLabelPair;
                            if (selected != null)
                            {
                                division = selected.Code;
                            }
                        });
                    }

                    if (limit && (!String.IsNullOrEmpty(division)))
                    {
                        results = _service.FindPlaceNamesLimited(text, division, _maximumSearchResults + 1);
                    }
                    else
                    {
                        results = _service.FindPlaceNames(text, _maximumSearchResults + 1);
                    }

                    lstResults.InvokeIfRequired(() => {
                        if (results.Count > _maximumSearchResults)
                        {
                            lblResults.Content = _owner.GetCaption("Gazetteer.Search.Results.TooMany", _maximumSearchResults);
                        }
                        else
                        {
                            lblResults.Content = _owner.GetCaption("Gazetteer.Search.Results", results.Count);
                        }

                        _offsetControl.Clear();
                        _dirDistControl.Clear();
                        _searchModel.Clear();
                        foreach (PlaceName place in results)
                        {
                            _searchModel.Add(new PlaceNameViewModel(place));
                        }
                    });
                }
                else
                {
                    lblResults.Content = "";
                }
            } catch (Exception ex) {
                GlobalExceptionHandler.Handle(ex);
            } finally {
                lstResults.InvokeIfRequired(() => {
                    lstResults.Cursor = Cursors.Arrow;
                });
            }
        }
Exemplo n.º 16
0
 void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     GlobalExceptionHandler.Handle(e.ExceptionObject as Exception);
 }
Exemplo n.º 17
0
 void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     e.Handled = true;
     GlobalExceptionHandler.Handle(e.Exception);
 }
Exemplo n.º 18
0
        public ContextMenu BuildExplorerMenu()
        {
            ContextMenuBuilder builder = new ContextMenuBuilder(FormatterFunc);


            if (Explorer.IsUnlocked)
            {
                if (!Taxon.IsRootNode)
                {
                    builder.New("TaxonExplorer.menu.Delete", Taxon.DisplayLabel).Handler(() => { Explorer.DeleteTaxon(Taxon); });
                    builder.New("TaxonExplorer.menu.DeleteCurrentLevel", Taxon.DisplayLabel).Handler(() => { Explorer.DeleteLevel(Taxon); });
                    builder.New("TaxonExplorer.menu.Rename", Taxon.DisplayLabel).Handler(() => { Explorer.RenameTaxon(Taxon); });
                    builder.Separator();
                    builder.New("TaxonExplorer.menu.ChangeRank", Taxon.DisplayLabel).Handler(() => { Explorer.ChangeRank(Taxon); });
                    if (Taxon.AvailableName == true)
                    {
                        builder.New("TaxonExplorer.menu.ChangeToLiterature", Taxon.DisplayLabel).Handler(() => { Explorer.ChangeAvailable(Taxon); });
                    }
                    else if (Taxon.LiteratureName == true)
                    {
                        builder.New("TaxonExplorer.menu.ChangeToAvailable", Taxon.DisplayLabel).Handler(() => { Explorer.ChangeAvailable(Taxon); });
                    }
                }

                MenuItem addMenu = BuildAddMenuItems();
                if (addMenu != null && addMenu.Items.Count > 0)
                {
                    builder.Separator();
                    builder.AddMenuItem(addMenu);
                }
            }
            else
            {
                builder.New("TaxonExplorer.menu.Unlock").Handler(() => { Explorer.btnLock.IsChecked = true; });
            }

            builder.Separator();

            builder.New("TaxonExplorer.menu.ExpandAll").Handler(() => {
                JobExecutor.QueueJob(() => {
                    Explorer.tvwAllTaxa.InvokeIfRequired(() => {
                        try {
                            using (new OverrideCursor(Cursors.Wait)) {
                                Explorer.ExpandChildren(Taxon);
                            }
                        } catch (Exception ex) {
                            GlobalExceptionHandler.Handle(ex);
                        }
                    });
                });
            });

            MenuItem sortMenu = BuildSortMenuItems();

            if (sortMenu != null && sortMenu.HasItems)
            {
                builder.Separator();
                builder.AddMenuItem(sortMenu);
            }

            builder.Separator();
            builder.AddMenuItem(CreateFavoriteMenuItems());

            if (!Explorer.IsUnlocked)
            {
                builder.Separator();
                builder.New("TaxonExplorer.menu.Refresh").Handler(() => Explorer.Refresh()).End();
            }

            if (!Taxon.IsRootNode)
            {
                MenuItem reports = CreateReportMenuItems();
                if (reports != null && reports.HasItems)
                {
                    builder.Separator();
                    builder.New("Distribution _Map").Handler(() => { Explorer.DistributionMap(Taxon); }).End();
                    builder.AddMenuItem(reports);
                }

                builder.Separator();
                builder.New("Export (XML)").Handler(() => { Explorer.XMLIOExport(Taxon.TaxaID.Value); }).End();

                builder.Separator();
                var pinnable = Explorer.Owner.CreatePinnableTaxon(Taxon.TaxaID.Value);
                builder.New("_Pin to pin board").Handler(() => { PluginManager.Instance.PinObject(pinnable); }).End();
                builder.Separator();
                builder.New("_Permissions...").Handler(() => Explorer.EditBiotaPermissions(Taxon)).End();
                builder.Separator();
                builder.New("_Edit Name...").Handler(() => { Explorer.EditTaxonName(Taxon); });
                builder.New("_Edit Details...").Handler(() => { Explorer.EditTaxonDetails(Taxon.TaxaID); }).End();
            }

            return(builder.ContextMenu);
        }