Beispiel #1
0
        public void should_use_the_assigned_reportId_factory_to_assign_a_report_id()
        {
            var dispatcher   = Substitute.For <IUploadDispatcher>();
            var config       = new CoderrConfiguration(dispatcher);
            var ex           = new Exception();
            var timesInvoked = 0;

            ReportIdGenerator.Assign(x => { timesInvoked++; return("a"); });

            var sut = new ExceptionProcessor(config);

            sut.Build(ex);
            sut.Build(ex, "Hello world");
            sut.Build(new ErrorReporterContext(this, ex));

            timesInvoked.Should().Be(3);
        }
        public void Should_be_able_to_filter_Reports()
        {
            var upl    = new TestUploader();
            var config = new CoderrConfiguration();
            var filter = Substitute.For <IReportFilter>();

            config.Uploaders.Register(upl);
            config.FilterCollection.Add(filter);
            filter.Invoke(Arg.Do((ReportFilterContext context) => context.CanSubmitReport = false));


            var processor = new ExceptionProcessor(config);

            processor.Process(new Exception());

            upl.Report.Should().BeNull("because report should have been filtered away");
        }
Beispiel #3
0
        public IHttpActionResult AddPlayerToMatch(string name, int matchId = 1)
        {
            using (var db = new HereAndThereDbContext())
            {
                try
                {
                    var player = new Player {
                        name = name, playerTypeId = Utils.DefaultPlayerType.id
                    };
                    player.SetAuditable();

                    var existingPlayer =
                        db.players.FirstOrDefault(x => x.name.ToLower() == player.name.ToLower());
                    if (existingPlayer != null)
                    {
                        player = existingPlayer;
                    }
                    else
                    {
                        db.players.Add(player);
                    }


                    //Todo: check whether the match has ended
                    var match = db.matches.FirstOrDefault(x => x.id == matchId);
                    if (match == null)
                    {
                        return(BadRequest(string.Format("No Such match with id: {0}", matchId)));
                    }

                    if (!match.players.Contains(player))
                    {
                        match.players.Add(player);
                    }


                    db.SaveChanges();
                    return(Ok(new { playerId = player.id }));
                }
                catch (Exception ex)
                {
                    return(BadRequest(ExceptionProcessor.Process(ex)));
                }
            }
        }
Beispiel #4
0
        public void Should_unpack_collections_that_are_attached_to_the_exception()
        {
            var upl    = new TestUploader();
            var config = new CoderrConfiguration();

            config.Uploaders.Register(upl);
            var json =
                @"{""$type"":""System.Collections.Generic.List`1[[Coderr.Client.Contracts.ContextCollectionDTO, Coderr.Client]], mscorlib"",""$values"":[{""Name"":""SqlCommand"",""Properties"":{""CommandText"":""WaitFor Delay '00:00:05'"",""CommandTimeout"":""3"",""ExecutionTime"":""00:00:03.0313327"",""OtherCommand[0]"":""select * from accounts where id=@id""}},{""Name"":""DbConnection"",""Properties"":{""ConnectionString"":""Data Source=.;Initial Catalog=OneTrueError;Integrated Security=True;Connect Timeout=30;multipleactiveresultsets=true"",""DataSource"":""."",""Database"":""OneTrueError"",""RunTime"":""00:00:03.0681702"",""State"":""Open"",""IsDisposed"":""False"",""ServerVersion"":""12.00.5207""}}]}";
            var ex = new InvalidOperationException();

            ex.Data["ErrCollections"] = json;

            var processor = new ExceptionProcessor(config);

            processor.Process(ex);

            upl.Report.ContextCollections.Should().Contain(x => x.Name == "SqlCommand");
        }
Beispiel #5
0
        public BankUser Get()
        {
            try
            {
                using (BankContext db = new BankContext())
                {
                    string userId     = RequestContext.Principal.Identity.GetUserId();
                    var    findedUser = db.BankUsers.FirstOrDefault(u => u.UserIdentityId == userId);
                    return(findedUser);
                }
            }
            catch (Exception e)
            {
                ExceptionProcessor.ProcessException(e);
            }

            return(null);
        }
Beispiel #6
0
 public IHttpActionResult Delete(int id)
 {
     try
     {
         using (BankContext db = new BankContext())
         {
             var userForDelete = db.BankUsers.FirstOrDefault(u => u.Id == id);
             db.BankUsers.Remove(userForDelete);
             db.SaveChanges();
         }
         return(Ok());
     }
     catch (Exception e)
     {
         ExceptionProcessor.ProcessException(e);
     }
     return(InternalServerError());
 }
Beispiel #7
0
 //TODO test
 protected void DetachDBInternal(ExternalDatastore externalDB)
 {
     lock (PersistentConnectionSyncLock)
     {
         var connection = PersistentConnection;
         if (connection != null)
         {
             var commandText = "DETACH DATABASE \"" + externalDB.Alias + "\";";
             try
             {
                 connection.ExecuteNonQuery(commandText, (object[])null, CurrentTransaction);
             }
             catch (Exception e)
             {
                 throw ExceptionProcessor.ProcessException(e, connection, commandText, CurrentTransaction);
             }
         }
     }
 }
        public void Should_include_partitions_in_reports()
        {
            var upl    = new TestUploader();
            var config = new CoderrConfiguration();
            var ex     = new Exception("hello");
            var ctx    = new ErrorReporterContext(this, ex);

            config.Uploaders.Register(upl);
            config.AddPartition(x =>
            {
                x.AddPartition("Id", "42");
            });

            var processor = new ExceptionProcessor(config);

            processor.Process(ctx);

            upl.Report.GetCollectionProperty("CoderrData", "ErrPartition.Id").Should().Be("42");
        }
        public async Task<IActionResult> Index(PaginationRequestViewModel paginationRequestViewModel)
        {
            var pagedTenantsViewModel = PagedResultsViewModel<TenantViewModel>.InitEmpty();
            
            try
            {
                paginationRequestViewModel.PageSize ??= HttpContext.TryGetPageSizeFromCookie();
                var pagination = _mapper.Map<Pagination>(paginationRequestViewModel);
                var pagedTenants = await _internalApiClient.GetTenants(pagination);
                pagedTenantsViewModel = _mapper.Map<PagedResultsViewModel<TenantViewModel>>(pagedTenants);
                _mapper.Map(pagination, pagedTenantsViewModel);
            }
            catch (BasicWebAppException ex)
            {
                ExceptionProcessor.ProcessError(LoggingEvents.ReadItemsFailed, _logger, HttpContext, ex);
            }

            return View(pagedTenantsViewModel);
        }
        public void Should_ignore_reports_that_have_already_been_reported_since_same_frameworks_have_multiple_injection_points_which_would_Report_the_same_exception()
        {
            var upl    = new TestUploader();
            var config = new CoderrConfiguration();
            var ex     = new Exception("hello");
            var ctx    = new ErrorReporterContext(this, ex);

            config.Uploaders.Register(upl);
            config.AddPartition(x =>
            {
                x.AddPartition("Id", "42");
            });

            var processor = new ExceptionProcessor(config);

            processor.Process(ctx);

            upl.Report.GetCollectionProperty("ErrPartitions", "Id").Should().Be("42");
        }
Beispiel #11
0
        public CardInfo Get(int id)
        {
            CardInfo retCard = null;

            try
            {
                using (BankContext db = new BankContext())
                {
                    retCard = db.BankUsers
                              .Include(u => u.Cards)
                              .FirstOrDefault(u => u.UserIdentityId == RequestContext.Principal.Identity.GetUserId())?.Cards
                              .FirstOrDefault(c => c.Id == id && c.IsActive);
                }
            }
            catch (Exception e)
            {
                ExceptionProcessor.ProcessException(e);
            }
            return(retCard);
        }
Beispiel #12
0
        public PayInfo Get(int id)
        {
            PayInfo userPay = null;

            try
            {
                using (BankContext db = new BankContext())
                {
                    userPay = db.BankUsers.Include(u => u.Pays).FirstOrDefault(u =>
                                                                               u.UserIdentityId == UserId)?.Pays.FirstOrDefault(p => p.Id == id);
                }
            }
            catch (Exception e)
            {
                ExceptionProcessor.ProcessException(e);
            }


            return(userPay);
        }
Beispiel #13
0
        public IHttpActionResult GetMatchPlayers(int matchId)
        {
            try
            {
                using (var db = new HereAndThereDbContext())
                {
                    var match = db.matches.FirstOrDefault(x => x.id == matchId);
                    if (match == null)
                    {
                        return(BadRequest(string.Format("No Such match with id: {0}", matchId)));
                    }

                    return(Ok(match.players.Select(x => new { x.id, x.name }).ToList()));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ExceptionProcessor.Process(ex)));
            }
        }
Beispiel #14
0
 public void Delete(int id)
 {
     try
     {
         using (BankContext db = new BankContext())
         {
             var currentUser = db.BankUsers.Include(c => c.Cards).FirstOrDefault(u =>
                                                                                 u.UserIdentityId == UserId && u.Cards.Any(c => c.Id == id));
             if (currentUser != null)
             {
                 //currentUser.Cards.Remove(currentUser.Cards.FirstOrDefault(c => c.Id == id));
                 currentUser.Cards.FirstOrDefault(c => c.Id == id).IsActive = false;
                 db.SaveChanges();
             }
         }
     }
     catch (Exception e)
     {
         ExceptionProcessor.ProcessException(e);
     }
 }
Beispiel #15
0
 /// <summary>
 ///     Gets an ongoing Match. you can use GetMatchInfo, if you have the matchId
 /// </summary>
 /// <returns>
 ///     Ongoing Match Info example
 ///     {"id":1,"startTime":"2016-11-07T21:00:29","endTime":"2016-11-10T09:51:28.78","playerCount":3,"players":[{"name":"karri","score":0.0,"id":1},{"name":"test2","score":0.0,"id":4},{"name":"k","score":0.0,"id":5}],"boundaries":[{"name":"lowerLeft","latitude":65.0519270000,"longitude":25.4474250000},{"name":"upperRight","latitude":65.0640070000,"longitude":25.4756460000}]}
 /// </returns>
 public IHttpActionResult GetOnGoingMatch()
 {
     try
     {
         using (var db = new HereAndThereDbContext())
         {
             var match = db.matches.Where(x => (x.endTime != null) && (x.endTime.Value > DateTime.Now))
                         .OrderByDescending(x => x.startTime)
                         .FirstOrDefault();
             if (match == null)
             {
                 return(BadRequest("No Ongoing Match"));
             }
             return(GetMatchInfo((int)match.id));
         }
     }
     catch (Exception ex)
     {
         return(BadRequest(ExceptionProcessor.Process(ex)));
     }
 }
        public ActionResult DeleteBlogItem(int blogItemId)
        {
            try
            {
                Repository <BlogEntity> blogRepository = new Repository <BlogEntity>();
                BlogEntity blogEntity = blogRepository.GetList().First(b => b.Id == blogItemId);

                if (blogEntity != null)
                {
                    blogRepository.Delete(blogEntity.Id);
                    return(Json(new { result = "Success" }, JsonRequestBehavior.AllowGet));
                }

                return(Json(new { result = "Fail" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ExceptionProcessor exceptionProcessor = new ExceptionProcessor();
                exceptionProcessor.process(ex);
                return(Json(new { result = "Fail" }, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #17
0
        public IEnumerable <CardInfo> Get()
        {
            IList <CardInfo> userCards = new List <CardInfo>();

            try
            {
                using (BankContext db = new BankContext())
                {
                    userCards = db.BankUsers
                                .Include(u => u.Cards)
                                .FirstOrDefault(u => u.UserIdentityId == UserId)
                                ?.Cards.Where(c => c.IsActive)
                                .ToList();
                }
            }
            catch (Exception e)
            {
                ExceptionProcessor.ProcessException(e);
            }

            return(userCards);
        }
        public async Task<IActionResult> Delete(Guid id, EditTenantViewModel editTenantViewModel)
        {
            if (!ModelState.IsValid)
            {
                _logger.LogWarning(LoggingEvents.DeleteItemBadData, "Delete tenant model is not valid. {ErrorMessages}", ModelState.GetModelStateErrorMessages());
                
                return View(nameof(Update), editTenantViewModel);
            }
            
            try
            {
                await _internalApiClient.DeleteTenant(id);

                return RedirectToAction("index");
            }
            catch (BasicWebAppException ex)
            {
                ExceptionProcessor.ProcessError(LoggingEvents.DeleteItemFailed, _logger, HttpContext, ex, id);
            }
            
            return View(nameof(Update), editTenantViewModel);
        }
Beispiel #19
0
        private static void Run(Func <object> func)
        {
            var oldSyncContext = SynchronizationContext.Current;

            try
            {
                var asyncSyncContext = new AsyncTestSyncContext();
                SetSynchronizationContext(asyncSyncContext);
                var result = func();
                var task   = result as Task;
                if (task != null)
                {
                    try
                    {
                        task.Wait();
                    }
                    catch (AggregateException ae)
                    {
                        var innerException = ae.InnerException;
                        ExceptionProcessor.PreserveStackTrace(innerException);
                        throw innerException;
                    }
                }
                else
                {
                    var ex = asyncSyncContext.WaitForCompletion();
                    if (ex != null)
                    {
                        ExceptionProcessor.PreserveStackTrace(ex);
                        throw ex;
                    }
                }
            }
            finally
            {
                SetSynchronizationContext(oldSyncContext);
            }
        }
Beispiel #20
0
        private List <string> ValidateCard(CardInfo cardInfo)
        {
            var results = new List <string>();

            try
            {
                using (BankContext db = new BankContext())
                {
                    if (db.BankUsers
                        .Include(u => u.Cards)
                        .Any(u => u.UserIdentityId != UserId &&
                             u.Cards.Any(c => c.CardNumber == cardInfo.CardNumber)))
                    {
                        results.Add("This card is not yours");
                    }
                }
            }
            catch (Exception e)
            {
                ExceptionProcessor.ProcessException(e);
            }
            return(results);
        }
Beispiel #21
0
        static Err()
        {
            _exceptionProcessor = new ExceptionProcessor(Configuration);
            try
            {
                var value = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
                            ?? Environment.GetEnvironmentVariable("APPLICATION_ENVIRONMENT");
                if (!string.IsNullOrWhiteSpace(value))
                {
                    Configuration.EnvironmentName = value;
                    return;
                }

                if (Debugger.IsAttached)
                {
                    Configuration.EnvironmentName = "Development";
                }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch
            {
            }
        }
Beispiel #22
0
        /// <summary>
        /// End a match
        /// </summary>
        /// <param name="matchId"></param>
        /// <returns></returns>
        public IHttpActionResult EndMatch(int matchId)
        {
            try
            {
                using (var db = new HereAndThereDbContext())
                {
                    var match = db.matches.FirstOrDefault(x => x.id == matchId);
                    if (match == null)
                    {
                        return(BadRequest(string.Format("No Such Match with id: {0}", matchId)));
                    }

                    var endTime = DateTime.Now;
                    match.endTime = endTime;
                    db.SaveChanges();
                    return(Ok(string.Format("Match Ended successfully @ {0}", endTime)));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ExceptionProcessor.Process(ex)));
            }
        }
Beispiel #23
0
        public IList <BankBranch> Get()
        {
            IList <BankBranch> retValues = new List <BankBranch>();

            try
            {
                using (BankContext db = new BankContext())
                {
                    retValues = db.BankBranches.ToList();
                    if (!retValues.Any())
                    {
                        CreateFirstData(db);
                        retValues = db.BankBranches.ToList();
                    }
                }
            }
            catch (Exception e)
            {
                ExceptionProcessor.ProcessException(e);
            }


            return(retValues);
        }
Beispiel #24
0
 public IHttpActionResult Put(int id, [FromBody] BankUser value)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     try
     {
         using (BankContext db = new BankContext())
         {
             string userId        = RequestContext.Principal.Identity.GetUserId();
             var    userForModify = db.BankUsers.FirstOrDefault(u => u.Id == id && u.UserIdentityId == userId);
             if (userForModify != null)
             {
                 foreach (PropertyInfo propertyInfo in userForModify.GetType().GetProperties()
                          .Where(p => p.Name != nameof(BankUser.Id)))
                 {
                     if (propertyInfo.GetValue(value, null) == null)
                     {
                         propertyInfo.SetValue(value, propertyInfo.GetValue(userForModify, null), null);
                     }
                 }
                 db.Entry(userForModify).CurrentValues.SetValues(value);
                 db.Entry(userForModify).State = EntityState.Modified;
                 db.SaveChanges();
                 var createdUser = db.BankUsers.FirstOrDefault(u => u.UserIdentityId == userId);
                 return(Ok(createdUser));
             }
         }
     }
     catch (Exception e)
     {
         ExceptionProcessor.ProcessException(e);
     }
     return(BadRequest());
 }
        public async Task<IActionResult> Update(Guid id, EditTenantViewModel editTenantViewModel)
        {
            if (!ModelState.IsValid)
            {
                _logger.LogWarning(LoggingEvents.UpdateItemBadData, "Edit tenant model is not valid. {ErrorMessages}", ModelState.GetModelStateErrorMessages());
                
                return View(editTenantViewModel);
            }            
            
            try
            {
                var editTenantContract = _mapper.Map<EditTenantContract>(editTenantViewModel);
                
                await _internalApiClient.EditTenant(id, editTenantContract);

                return RedirectToAction(nameof(Index));
            }
            catch (BasicWebAppException ex)
            {
                ExceptionProcessor.ProcessError(LoggingEvents.UpdateItemFailed, _logger, HttpContext, ex, id);
            }

            return View(editTenantViewModel);
        }
        public async Task<IActionResult> Create(NewTenantViewModel newTenantViewModel)
        {
            if (!ModelState.IsValid)
            {
                _logger.LogWarning(LoggingEvents.CreateItemBadData, "Empty tenant cannot be created. {ErrorMessages}", ModelState.GetModelStateErrorMessages());
                
                return View(newTenantViewModel);
            }

            try
            {
                var newTenantApiContract = _mapper.Map<NewTenantContract>(newTenantViewModel);

                var newTenantGuid = await _internalApiClient.CreateNewTenant(newTenantApiContract);

                return RedirectToAction(nameof(Details), new { Id = newTenantGuid });
            }
            catch (BasicWebAppException ex)
            {
                ExceptionProcessor.ProcessError(LoggingEvents.CreateItemFailed, _logger, HttpContext, ex, newTenantViewModel.Name);
            }

            return View(newTenantViewModel);
        }
Beispiel #27
0
 /// <summary>
 ///     Gets all  currently visible Player locations of a Match
 /// </summary>
 /// <param name="matchId"></param>
 /// <returns></returns>
 public IHttpActionResult GetAllPlayerLocations(int matchId)
 {
     try
     {
         using (var db = new HereAndThereDbContext())
         {
             var match = db.matches.FirstOrDefault(x => x.id == matchId);
             if (match == null)
             {
                 return(BadRequest(string.Format("No Such match with id: {0}", matchId)));
             }
             var movements =
                 db.locations.Where(x => (x.movement.matchId == matchId) && x.isVisible)
                 .Select(
                     x =>
                     new
             {
                 locationId = x.id,
                 x.movement.playerId,
                 playerName = x.movement.player.name,
                 x.latitude,
                 x.longitude,
                 x.isActual,
                 x.isVisible,
                 x.movement.isMoving,
                 x.timeStamp
             })
                 .ToList();
             return(Ok(movements));
         }
     }
     catch (Exception ex)
     {
         return(BadRequest(ExceptionProcessor.Process(ex)));
     }
 }
Beispiel #28
0
        public async Task <IActionResult> Create(NewTenantContract newTenantContract)
        {
            if (newTenantContract == null)
            {
                _logger.LogWarning(LoggingEvents.CreateItemBadData, "Empty tenant cannot be created");
                return(BadRequest());
            }

            try
            {
                _logger.LogInformation(LoggingEvents.CreateItem, "Creating new tenant with name {Name}", newTenantContract.Name);

                var newTenant = _mapper.Map <Tenant>(newTenantContract);
                newTenant.Guid = await _tenantLogic.Create(newTenant);

                return(Ok(newTenant.Guid));
            }
            catch (BasicWebAppException ex)
            {
                ExceptionProcessor.Process(LoggingEvents.CreateItemFailed, _logger, ex, newTenantContract.Name);
            }

            return(StatusCode(StatusCodes.Status500InternalServerError));
        }
Beispiel #29
0
 static Err()
 {
     _exceptionProcessor = new ExceptionProcessor(Configuration);
 }
Beispiel #30
0
 public ScenarioBuilder(object fixture, IntegrationContext integrationContext, ExceptionProcessor exceptionProcessor, Action <IScenarioResult> onScenarioFinished)
 {
     _context = new RunnableScenarioContext(
         integrationContext,
         exceptionProcessor,
         onScenarioFinished,
         integrationContext.ScenarioProgressNotifierProvider.Invoke(fixture),
         ProvideSteps);
 }