public void ProceedToFail()
            {
                var exceptionService = new ExceptionService();
                var value = string.Empty;

                exceptionService.Register<ArgumentException>(exception => { value = exception.Message; });
                exceptionService.Process<string>(() => { throw new ArgumentOutOfRangeException("achieved"); });

                Assert.AreNotEqual("achieved", value);
            }
            public void ProceedToSucceed()
            {
                var exceptionService = new ExceptionService();
                var value = string.Empty;

                exceptionService.Register<ArgumentException>(exception => { value = exception.Message; });
                value = exceptionService.Process(() => (1 + 1).ToString(CultureInfo.InvariantCulture));

                Assert.AreEqual("2", value);

                exceptionService.Process<string>(() => { throw new ArgumentException("achieved"); });

                Assert.AreEqual("achieved", value);
            }
 public IEnumerable <VMRol> ObtenerRolesUsuario(string usuario)
 {
     try
     {
         return(new NegocioUsuario().ObtenerRolesUsuario(usuario));
     }
     catch (Exception ex)
     {
         ExceptionService exception = new ExceptionService()
         {
             Mensaje   = ex.Message,
             Operacion = "Roles de usuario."
         };
         throw new FaultException <ExceptionService>(exception);
     }
 }
Beispiel #4
0
            public void ShouldNotRetryWhenNotAnyExceptionIsThrown()
            {
                var attemptsCount = 0;

                var exceptionService = new ExceptionService();

                exceptionService.RetryingAction += (sender, args) => attemptsCount++;

                exceptionService
                .Register <DivideByZeroException>(exception => { })
                .OnErrorRetryImmediately(3);

                exceptionService.ProcessWithRetry(() => { });

                Assert.AreEqual(0, attemptsCount);
            }
Beispiel #5
0
            public void ShouldNotRetryWhenAnotherExceptionTypeIsThrown()
            {
                var exceptionService = new ExceptionService();

                exceptionService
                .Register <DivideByZeroException>(exception => { })
                .OnErrorRetryImmediately(3);

                var attemptsCount = 0;

                ExceptionTester.CallMethodAndExpectException <ArgumentException>(() => exceptionService.ProcessWithRetry(() =>
                {
                    attemptsCount++;
                    throw new ArgumentException();
                }));
            }
Beispiel #6
0
 public RespuestaSesion ValidarAcceso(string url, string usuario)
 {
     try
     {
         return(new NegocioSistema().ValidarAcceso(url, usuario));
     }
     catch (Exception ex)
     {
         ExceptionService exception = new ExceptionService()
         {
             Mensaje   = ex.Message,
             Operacion = "Validar acceso."
         };
         throw new FaultException <ExceptionService>(exception);
     }
 }
Beispiel #7
0
 /// <summary>
 /// user list changed
 /// </summary>
 /// <param name="roomId"></param>
 /// <param name="conversationId"></param>
 protected void userListChanged(int roomId, long conversationId)
 {
     try
     {
         Clients.Others.userListChanged(new
         {
             UserList       = _hub.GetFollowerListByUserID(CurrentUser.UserID),
             RoomId         = roomId,
             ConversationId = conversationId
         });
     }
     catch (Exception ex)
     {
         ExceptionService.LogError("Error getting followers list", ex);
     }
 }
Beispiel #8
0
 public void CerrarSesion(string usuario)
 {
     try
     {
         new NegocioSistema().CerrarSesion(usuario);
     }
     catch (Exception ex)
     {
         ExceptionService exception = new ExceptionService()
         {
             Mensaje   = ex.Message,
             Operacion = "Cerrar sesión."
         };
         throw new FaultException <ExceptionService>(exception);
     }
 }
 public VMRol RegistrarNuevoRol(string nombre, string descripcion, int idPais)
 {
     try
     {
         return(new NegocioUsuario().RegistrarRol(nombre, descripcion, idPais));
     }
     catch (Exception ex)
     {
         ExceptionService exception = new ExceptionService()
         {
             Mensaje   = ex.Message,
             Operacion = "Nuevo rol."
         };
         throw new FaultException <ExceptionService>(exception);
     }
 }
Beispiel #10
0
 public RespuestaSesion ValidarToken(string token)
 {
     try
     {
         return(new NegocioSistema().ValidarToken(token));
     }
     catch (Exception ex)
     {
         ExceptionService exception = new ExceptionService()
         {
             Mensaje   = ex.Message,
             Operacion = "Validar token."
         };
         throw new FaultException <ExceptionService>(exception);
     }
 }
Beispiel #11
0
        public MainViewModel(IParkenDdClient client,
                             VoiceCommandService voiceCommandService,
                             JumpListService jumpList,
                             ParkingLotListFilterService filterService,
                             SettingsService settings,
                             StorageService storage,
                             GeolocationService geo,
                             TrackingService tracking,
                             ExceptionService exceptionService)
        {
            _client           = client;
            _voiceCommands    = voiceCommandService;
            _jumpList         = jumpList;
            _filterService    = filterService;
            _settings         = settings;
            _storage          = storage;
            _geo              = geo;
            _tracking         = tracking;
            _exceptionService = exceptionService;

            Messenger.Default.Register(this, (SettingChangedMessage msg) =>
            {
                if (msg.IsSetting(nameof(_settings.ShowExperimentalCities)))
                {
                    var temp      = SelectedCity;
                    _selectedCity = null;
                    RaisePropertyChanged(() => SelectedCity);
                    RaisePropertyChanged(() => MetaDataCities);
                    _selectedCity = temp;
                    RaisePropertyChanged(() => SelectedCity);
                }
            });

            PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == nameof(MetaDataCities))
                {
                    UpdateServiceData();
                }
            };

            NetworkInformation.NetworkStatusChanged += sender =>
            {
                UpdateInternetAvailability();
            };
            UpdateInternetAvailability();
        }
        /// <summary>
        /// Handles the transformation exception.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="messageToTransform">The <see cref="ReceivedMessage"/> that must be transformed by the transformer.</param>
        /// <returns></returns>
        public async Task <MessagingContext> HandleTransformationException(Exception exception, ReceivedMessage messageToTransform)
        {
            Logger.Error(exception.Message);
            Logger.Trace(exception.StackTrace);

            using (DatastoreContext db = _createContext())
            {
                var repository = new DatastoreRepository(db);
                var service    = new ExceptionService(_configuration, repository, _bodyStore);

                await service.InsertIncomingExceptionAsync(exception, messageToTransform.UnderlyingStream);

                await db.SaveChangesAsync();
            }

            return(new MessagingContext(exception));
        }
Beispiel #13
0
        public TModel GetModelFromString(string JSON_Content)
        {
            try
            {
                JsonSerializerSettings settings = new JsonSerializerSettings {
                    TypeNameHandling = TypeNameHandling.All
                };
                _Model = JsonConvert.DeserializeObject <TModel>(JSON_Content, settings);

                return(_Model);
            }
            catch (Exception error)
            {
                ExceptionService.WriteLine(error);
                return(null);
            }
        }
Beispiel #14
0
        public bool Delete(int id)
        {
            try
            {
                var entity = repository.Get(id);
                repository.Update(entity);

                entity.IsDelete = true;
                unitOfWork.Save();
                return(true);
            }
            catch (Exception ex)
            {
                ExceptionService.WriteException(ex, section, SysConstants.AppException_Classifier);
                throw new Exception(ex.Message);
            }
        }
Beispiel #15
0
            public void ShouldNotRetryAndReturnsResult()
            {
                var attemptsCount = 0;

                var exceptionService = new ExceptionService();

                exceptionService.RetryingAction += (sender, args) => attemptsCount++;

                exceptionService
                .Register <DivideByZeroException>(exception => { }, null)
                .OnErrorRetryImmediately(3);

                var result = exceptionService.ProcessWithRetry(() => 1 + 1);

                Assert.AreEqual(0, attemptsCount);
                Assert.AreEqual(2, result);
            }
        private async Task UpdateUnreadAsync()
        {
            try
            {
                var unreadChatMessages = await _chatService.GetUnreadAsync(ApiPriority.Background);

                SendUnreadChatMessagesUpdate(unreadChatMessages.Count);

                var unreadNotifications = await _notificationService.GetNumberUnreadAsync();

                SendUnreadNotificationsUpdate(unreadNotifications);
            }
            catch (Exception ex)
            {
                ExceptionService.HandleException(ex);
            }
        }
Beispiel #17
0
        //public VMSistema RegistrarModulo(int idSistema,string nombre, string urlIcono,
        //    string urlDestino, string dbCadConexion ,bool estatus )
        //{
        //    return new NegocioModulosAcceso()
        //        .RegistrarSistema( nombre,  logo,  urlhome,  sistemaEmbebido,  estatus);
        //}

        #endregion

        #region ServiceAccesos

        public string IniciarSesion(string usuario, string llave, string ip, string sistema, bool cerrarSesiones = false)
        {
            try
            {
                return(new NegocioSistema().IniciarSesion(usuario, llave, ip, sistema, cerrarSesiones));
            }
            catch (Exception ex)
            {
                ExceptionService exception = new ExceptionService()
                {
                    Mensaje   = ex.Message,
                    Operacion = "Inicio de sesión.",
                    ErrorCode = ex.Data["code"].ToString()
                };
                throw new FaultException <ExceptionService>(exception);
            }
        }
Beispiel #18
0
            public void Setup()
            {
                _exceptionService = new ExceptionService();

                _exceptionService.Register <Exception>(exception => { _exLevel0 = true; }, null);
                _exceptionService.Register <Level21Exception>(exception => { _exLevel21 = true; }, null);
                _exceptionService.Register <Level11Exception>(exception => { _exLevel11 = true; }, null);
                _exceptionService.Register <Level31Exception>(exception => { _exLevel31 = true; }, null);
                _exceptionService.Register <Level32Exception>(exception => { _exLevel32 = true; }, null);
                _exceptionService.Register <Level22Exception>(exception => { _exLevel22 = true; }, null);
                _exLevel0  = false;
                _exLevel21 = false;
                _exLevel11 = false;
                _exLevel31 = false;
                _exLevel32 = false;
                _exLevel22 = false;
            }
Beispiel #19
0
            public void ShouldRetryTwice()
            {
                var attemptsCount = 0;

                var exceptionService = new ExceptionService();

                exceptionService
                .Register <DivideByZeroException>(exception => { }, null)
                .OnErrorRetryImmediately(2);

                exceptionService.ProcessWithRetry(() =>
                {
                    attemptsCount++;
                    throw new DivideByZeroException();
                });

                Assert.AreEqual(2, attemptsCount);
            }
Beispiel #20
0
        public async Task Init()
        {
            List <IEvent> events;

            try
            {
                var firstFour = await _eventService.GetUpcomingAsync(ApiPriority.UserInitiated, 4);

                events = firstFour.Select(e => e.ToModel(_eventClosedText, _unattendButtonText, _attendButtonText, _peopleAttendingText, _eventInfoText, _eventDateText, _eventTimeLabel, _eventLocationLabel, _aboutHeaderLabel)).ToList();
            }
            catch (Exception ex)
            {
                ExceptionService.HandleException(ex);
                events = new List <IEvent>();
            }

            await BuildEventCategories(events);
        }
Beispiel #21
0
        public ClassifierOrganization GetById(int id)
        {
            try
            {
                ClassifierOrganization entity = null;

                if (id > 0)
                {
                    entity = repository.Get(id);
                }
                return(entity);
            }
            catch (Exception ex)
            {
                ExceptionService.WriteException(ex, section, SysConstants.AppException_Classifier);
                throw new Exception(ex.Message);
            }
        }
        public IEnumerable <UserProfile> Get(Func <UserProfile, bool> predicate)
        {
            try
            {
                IEnumerable <UserProfile> source = new List <UserProfile>();

                var ctx = unitOfWork.CityLifeDbContext;

                source = ctx.Set <UserProfile>().Where(predicate).ToList();

                return(source);
            }
            catch (Exception ex)
            {
                ExceptionService.WriteException(ex, section, SysConstants.AppException_UserProfile);
                throw new Exception(ex.Message);
            }
        }
Beispiel #23
0
        /// <summary>
        /// WEB应用程序异常捕捉
        /// </summary>
        private static void WebOnError(object sender, EventArgs e)
        {
            var httpApp = (HttpApplication)sender;
            var ex      = httpApp.Server.GetLastError();
            var ex0     = ExceptionBase.FindSourceException(ex);

            if (ex0 is FileNotFoundException)
            {
                return;
            }
            string message = null;

            if (ex != null)
            {
                message = ex.Message;
            }
            ExceptionService.Publish(new HttpWebException(message, ex, httpApp));
        }
Beispiel #24
0
 public VMUsuario RegistrarNuevoUsuario(string Nombre, string apellidoMaterno, string apellidoPaterno, string celular, string correo,
                                        string extension, int idEstatus, string password, string usuario_sistema)
 {
     try
     {
         return(new NegocioUsuario().RegistrarUsuario(Nombre, apellidoMaterno, apellidoPaterno, celular, correo,
                                                      extension, idEstatus, password, usuario_sistema));
     }
     catch (Exception ex)
     {
         ExceptionService exception = new ExceptionService()
         {
             Mensaje   = ex.Message,
             Operacion = "Registro de Usuario."
         };
         throw new FaultException <ExceptionService>(exception);
     }
 }
Beispiel #25
0
        /// <summary>
        /// Hub overriden methood while disconnecting
        /// </summary>
        /// <returns></returns>
        public System.Threading.Tasks.Task OnDisconnected()
        {
            try
            {
                CurrentUser.StatusID = 2;
                _hub.UpdateUserStatus(CurrentUser.UserID, Context.ConnectionId, Enums.BroadCastType.Web, Enums.UserStatus.OFL);
                IList <string> connectionIDs = new BusinessLogic.UserAccess()
                                               .GetFollowerListByConnectID(CurrentUser.UserID, Enums.PageType.Profile, Enums.FriendshipStatus.FA)
                                               .Where(x => x.ConnectedBy == (byte)Enums.BroadCastType.Web).Select(x => x.ConnectionID).ToList();

                Clients.Clients(connectionIDs).updateUserList(GetMyChatInfo(1));
            }
            catch (Exception ex)
            {
                ExceptionService.LogError("Error updating user status", ex);
            }

            return(base.OnDisconnected(false));
        }
 /// <summary>
 /// hide post to page
 /// </summary>
 /// <param name="post"></param>
 /// <returns></returns>
 public async Task <IHttpActionResult> HidePost(PostModel post)
 {
     if (ModelState.IsValid)
     {
         try
         {
             return(Ok(_post.HidePost(post)));
         }
         catch (Exception ex)
         {
             ExceptionService.LogError("Error hiding post to page", ex);
             return(BadRequest(ex.Message));
         }
     }
     else
     {
         return(BadRequest(ModelState.JsonValidation()));
     }
 }
Beispiel #27
0
        public static bool AddApplicationEvent(int selectedSiteID, ActionTaken actionTaken)
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var apiUrl = ConfigurationManager.AppSettings.Get("WebAPI");
                if (null == AppSession.AccessToken || string.IsNullOrEmpty(AppSession.AccessToken.Token))
                {
                    AppSession.AccessToken = EprodWebApi.GetAuthenticationToken(apiUrl,
                                                                                ConfigurationManager.AppSettings.Get("AppID"),
                                                                                ConfigurationManager.AppSettings.Get("AppPassword"));
                }
                ApplicationEvent appEvent = new ApplicationEvent()
                {
                    UserId       = (int)AppSession.UserID,
                    SiteId       = selectedSiteID,
                    ProgramId    = AppSession.SelectedProgramId,
                    EproductId   = (int)EProductType.Reports,
                    ActionTypeId = (int)actionTaken
                };

                return(EprodWebApi.ApplicationEvent(appEvent, apiUrl, AppSession.AccessToken.Token));
            }
            catch (Exception ex)
            {
                if (ex.Message.ToString() != "No Data" && ex.Message.ToString() != "Limit")
                {
                    ExceptionLog exceptionLog = new ExceptionLog
                    {
                        ExceptionText = "Reports: " + ex.Message,
                        PageName      = "WebApiMethods.cs",
                        MethodName    = "AddApplicationEvent",
                        UserID        = Convert.ToInt32(AppSession.UserID),
                        SiteId        = Convert.ToInt32(AppSession.SelectedSiteId),
                        TransSQL      = "",
                        HttpReferrer  = null
                    };
                    ExceptionService _exceptionService = new ExceptionService();
                    _exceptionService.LogException(exceptionLog);
                }
            }
            return(false);
        }
Beispiel #28
0
        /// <param name="timetable">Used to save results</param>
        public static async ValueTask <(Url?attendanceUrl, string?errorMessage)> GetAttendanceUrlAsync(Lesson lesson, TimetableInfo?timetable = null)
        {
            try
            {
                var lessonInfo = timetable?.GetAndAddLessonsInfo(lesson);
                if (lessonInfo?.DlNureInfo.AttendanceUrl != null)
                {
                    return(lessonInfo.DlNureInfo.AttendanceUrl, null);
                }

                int?lessonId = await GetLessonIdAsync(lesson, timetable);

                if (lessonId == null)
                {
                    return(null, LN.LessonNotFound);
                }

                CourseModule?attendance = (await new MoodleRepository()
                                           .GetCourseContentsAsync(lessonId.Value, new() { { GetCourseContentsOption.ModName, "attendance" } }))
                                          .FirstOrDefault()?
                                          .Modules
                                          .FirstOrDefault();
                if (attendance == null)
                {
                    return(null, LN.NoAttendanceModule);
                }

                Uri attendanceUrl = new(attendance.Url);
                if (timetable != null)
                {
                    lessonInfo !.DlNureInfo.AttendanceUrl = attendanceUrl;
                    await EventsRepository.UpdateLessonsInfo(timetable);
                }

                return(attendanceUrl, null);
            }
            catch (Exception ex)
            {
                EnrichException(ex, timetable?.Entity, lesson);
                ExceptionService.LogException(ex);
                return(null, ex.Message);
            }
        }
Beispiel #29
0
        public List <ClassifierOrganization> GetMatchNames(string name)
        {
            try
            {
                List <ClassifierOrganization> result = new List <ClassifierOrganization>();

                var query1 = repository.Get(x => x.Name.ToLower().Contains(name.ToLower()))
                             .ToList();

                result = query1;

                return(result);
            }
            catch (Exception ex)
            {
                ExceptionService.WriteException(ex, section, SysConstants.AppException_Classifier);
                throw new Exception(ex.Message);
            }
        }
Beispiel #30
0
 /// <summary>
 /// get left pane detail of users home page
 /// </summary>
 /// <param name="UserID"></param>
 /// <returns></returns>
 public async Task <IHttpActionResult> GetLeftHomeInfo(long UserID)
 {
     if (ModelState.IsValid)
     {
         try
         {
             return(Ok(_page.GetLeftHomeInfo(UserID)));
         }
         catch (Exception ex)
         {
             ExceptionService.LogError("Error fetching detail of home left pane", ex);
             return(BadRequest(ex.Message));
         }
     }
     else
     {
         return(BadRequest(ModelState.JsonValidation()));
     }
 }
        public bool Delete(int id)
        {
            try
            {
                var entity = orgrepository.Get(id);
                entity.IsDelete = true;
                entity.IsActive = false;
                orgrepository.Update(entity);

                unitOfWork.Save();

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionService.WriteException(ex, section, SysConstants.AppException_Organization);
                throw new Exception(ex.Message);
            }
        }
Beispiel #32
0
            public void MultipleExceptionsOfSameTypeThrownTooManyTimesProducesOnlyOneException()
            {
                var exceptionService = new ExceptionService();

                exceptionService.Register <DivideByZeroException>(exception => { }, null)
                .UsingTolerance(9, TimeSpan.FromSeconds(10.0));

                var index = 0;
                var exceptionHandledAt10Th = false;

                for (; index < 10; index++)
                {
                    ThreadHelper.Sleep(100);
                    exceptionHandledAt10Th = exceptionService.HandleException(new DivideByZeroException());
                }

                Assert.IsTrue(exceptionHandledAt10Th);
                Assert.AreEqual(10, index);
            }
Beispiel #33
0
 public void ThrowsArgumentNullExceptionForNullParameterInGeneric()
 {
     var exceptionService = new ExceptionService();
     ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => exceptionService.Process<int>(null));
 }
Beispiel #34
0
            public void ShouldNotRetryWhenNotAnyExceptionIsThrown()
            {
                var attemptsCount = 0;

                var exceptionService = new ExceptionService();

                exceptionService.RetryingAction += (sender, args) => attemptsCount++;

                exceptionService
                    .Register<DivideByZeroException>(exception => { })
                    .OnErrorRetryImmediately(3);

                exceptionService.ProcessWithRetry(() => { });

                Assert.AreEqual(0, attemptsCount);
            }
            public async Task ProceedTaskToFail()
#endif
            {
                var exceptionService = new ExceptionService();
                var value = string.Empty;

                exceptionService.Register<ArgumentException>(exception => { value = exception.Message; });
#if NET40 || SL5 || PCL
                exceptionService.ProcessAsync(() => { throw new ArgumentOutOfRangeException("achieved"); });
#else
                await exceptionService.ProcessAsync(async () => { throw new ArgumentOutOfRangeException("achieved"); });
#endif

                Assert.AreNotEqual("achieved", value);
            }
Beispiel #36
0
            public void ReturnsHandlerWhenRegisteredUsingGeneric()
            {
                var exceptionService = new ExceptionService();

                exceptionService.Register<Exception>(exception => { });

                exceptionService.Register<ArgumentNullException>(exception => { });

                var handler = exceptionService.GetHandler<Exception>();

                Assert.IsNotNull(handler);
                Assert.AreEqual(typeof (Exception), handler.ExceptionType);
            }
Beispiel #37
0
            public void UnregistersExceptionForDoubleUnregistration()
            {
                var exceptionService = new ExceptionService();

                exceptionService.Register<ArgumentException>(exception => { });

                Assert.IsTrue(exceptionService.ExceptionHandlers.ToList().Any(row => row.ExceptionType == typeof (ArgumentException)));
                Assert.AreEqual(exceptionService.ExceptionHandlers.Count(), 1);

                Assert.IsTrue(exceptionService.Unregister<ArgumentException>());
                Assert.IsFalse(exceptionService.ExceptionHandlers.ToList().Any(row => row.ExceptionType == typeof (ArgumentException)));
                Assert.AreEqual(exceptionService.ExceptionHandlers.Count(), 0);

                Assert.IsFalse(exceptionService.Unregister<ArgumentException>());
            }
Beispiel #38
0
            public void ChecksIfTheBufferedEventRegistrationWorks()
            {
                var buffercount = 0;

                var exceptionService = new ExceptionService();

                exceptionService.ExceptionBuffered += (sender, args) =>
                {
                    Assert.IsInstanceOfType(args.BufferedException, typeof (DivideByZeroException));
                    buffercount++;
                };

                exceptionService.Register<DivideByZeroException>(exception => { })
                    .UsingTolerance(9, TimeSpan.FromSeconds(10.0));

                var index = 0;
                var exceptionHandledAt10Th = false;

                for (; index < 10; index++)
                {
                    ThreadHelper.Sleep(100);
                    exceptionHandledAt10Th = exceptionService.HandleException(new DivideByZeroException());
                }

                Assert.IsTrue(exceptionHandledAt10Th);
                Assert.AreEqual(10, index);
                Assert.AreEqual(9, buffercount);
            }
Beispiel #39
0
 public void ChecksIfTheExceptionHandlersHasAnyItems()
 {
     var exceptionService = new ExceptionService();
     Assert.IsNotNull(exceptionService.ExceptionHandlers);
     Assert.IsFalse(exceptionService.ExceptionHandlers.Any());
 }
Beispiel #40
0
            public async Task ProceedTaskToSucceed()
            {
                var exceptionService = new ExceptionService();
                var value = string.Empty;

                exceptionService.Register<ArgumentException>(exception => { value = exception.Message; });
#pragma warning disable 1998
                value = await exceptionService.ProcessAsync(async () => (1 + 1).ToString(CultureInfo.InvariantCulture));
#pragma warning restore 1998

                Assert.AreEqual("2", value);

#pragma warning disable 1998
                await exceptionService.ProcessAsync<string>(async () => { throw new ArgumentException("achieved"); });
#pragma warning restore 1998

                Assert.AreEqual("achieved", value);
            }
Beispiel #41
0
            public void ReturnsTrueWhenRegistered()
            {
                var exceptionService = new ExceptionService();

                exceptionService.Register<Exception>(exception => { });

                exceptionService.Register<ArgumentNullException>(exception => { });

                Assert.IsTrue(exceptionService.IsExceptionRegistered(typeof (ArgumentNullException)));
            }
Beispiel #42
0
            public void ReturnsTrueWhenRegisteredUsingGeneric()
            {
                var exceptionService = new ExceptionService();

                exceptionService.Register<Exception>(exception => { });

                exceptionService.Register<ArgumentNullException>(exception => { });

                Assert.IsTrue(exceptionService.IsExceptionRegistered<Exception>());
            }
Beispiel #43
0
            public void ReturnsArgumentNullException()
            {
                var exceptionService = new ExceptionService();

                ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => exceptionService.IsExceptionRegistered(null));
            }
Beispiel #44
0
            public void PerformsHandleForNotRegisteredTypeViaInheritance()
            {
                var exceptionService = new ExceptionService();
                var originalException = new DivideByZeroException("achieved");
                var value = string.Empty;
                exceptionService.Register<Exception>(exception => { value = exception.Message; });

                Assert.IsTrue(exceptionService.HandleException(originalException));

                Assert.AreEqual("achieved", value);
            }
Beispiel #45
0
            public void ReturnsNullWhenNotRegistered()
            {
                var exceptionService = new ExceptionService();

                exceptionService.Register<ArgumentNullException>(exception => { });

                Assert.IsNull(exceptionService.GetHandler(typeof (Exception)));
            }
Beispiel #46
0
            public void ShouldNotRetryAndReturnsResult()
            {
                var attemptsCount = 0;

                var exceptionService = new ExceptionService();

                exceptionService.RetryingAction += (sender, args) => attemptsCount++;

                exceptionService
                    .Register<DivideByZeroException>(exception => { })
                    .OnErrorRetryImmediately(3);

                var result = exceptionService.ProcessWithRetry(() => 1 + 1);

                Assert.AreEqual(0, attemptsCount);
                Assert.AreEqual(2, result);
            }
Beispiel #47
0
            public async Task ProceedActionToSucceed()
            {
                var exceptionService = new ExceptionService();
                var value = string.Empty;

                exceptionService.Register<ArgumentException>(exception => { value = exception.Message; });
                await exceptionService.ProcessAsync(() => { throw new ArgumentException("achieved"); });

                Assert.AreEqual("achieved", value);
            }
Beispiel #48
0
            public void ShouldRetryWithDelay()
            {
                var interval = TimeSpan.FromMilliseconds(10);

                var exceptionService = new ExceptionService();

                exceptionService.RetryingAction += (sender, args) => Assert.AreEqual(interval, args.Delay);

                exceptionService
                    .Register<DivideByZeroException>(exception => { })
                    .OnErrorRetry(2, interval);

                exceptionService.ProcessWithRetry(() => { throw new DivideByZeroException(); });
            }
Beispiel #49
0
            public async Task ProceedTaskToFail()
            {
                var exceptionService = new ExceptionService();
                var value = string.Empty;

                exceptionService.Register<ArgumentException>(exception => { value = exception.Message; });
#pragma warning disable 1998
                await exceptionService.ProcessAsync(async () => { throw new ArgumentOutOfRangeException("achieved"); });
#pragma warning restore 1998

                Assert.AreNotEqual("achieved", value);
            }
Beispiel #50
0
            public void RegistersException()
            {
                var exceptionService = new ExceptionService();
                Assert.IsNotNull(exceptionService.ExceptionHandlers);
                Assert.AreEqual(exceptionService.ExceptionHandlers.Count(), 0);

                exceptionService.Register<ArgumentException>(exception => { });

                Assert.IsTrue(exceptionService.ExceptionHandlers.ToList().Any(row => row.ExceptionType == typeof (ArgumentException)));
                Assert.AreEqual(exceptionService.ExceptionHandlers.Count(), 1);
            }
Beispiel #51
0
            public void ChecksIfRetryActionEventRegistrationWorks()
            {
                const int attemptsCount = 1;

                var exceptionService = new ExceptionService();

                exceptionService.RetryingAction += (sender, args) => Assert.AreEqual(attemptsCount, args.CurrentRetryCount);

                exceptionService
                    .Register<DivideByZeroException>(exception => { })
                    .OnErrorRetryImmediately(attemptsCount);

                exceptionService.ProcessWithRetry(() => { throw new DivideByZeroException(); });
            }
Beispiel #52
0
            public void MultipleExceptionsOfSameTypeThrownTooManyTimesProducesOnlyOneException()
            {
                var exceptionService = new ExceptionService();

                exceptionService.Register<DivideByZeroException>(exception => { })
                    .UsingTolerance(9, TimeSpan.FromSeconds(10.0));

                var index = 0;
                var exceptionHandledAt10Th = false;

                for (; index < 10; index++)
                {
                    ThreadHelper.Sleep(100);
                    exceptionHandledAt10Th = exceptionService.HandleException(new DivideByZeroException());
                }

                Assert.IsTrue(exceptionHandledAt10Th);
                Assert.AreEqual(10, index);
            }
Beispiel #53
0
            public void ShouldRetryTwice()
            {
                var attemptsCount = 0;

                var exceptionService = new ExceptionService();

                exceptionService
                    .Register<DivideByZeroException>(exception => { })
                    .OnErrorRetryImmediately(2);

                exceptionService.ProcessWithRetry(() =>
                {
                    attemptsCount++;
                    throw new DivideByZeroException();
                });

                Assert.AreEqual(2, attemptsCount);
            }
            public async Task ProceedActionToSucceed()
#endif
            {
                var exceptionService = new ExceptionService();
                var value = string.Empty;

                exceptionService.Register<ArgumentException>(exception => { value = exception.Message; });
#if NET40 || SL5 || PCL
                value = "2";
                exceptionService.ProcessAsync(() => (1 + 1).ToString(CultureInfo.InvariantCulture))
                                .ContinueWith(task => Assert.AreEqual(value, task.Result));
#else
                value = await exceptionService.ProcessAsync(() => (1 + 1).ToString(CultureInfo.InvariantCulture));
                Assert.AreEqual("2", value);
#endif

#if NET40 || SL5 || PCL
                exceptionService.ProcessAsync<string>(() => { throw new ArgumentException("achieved"); });
#else
                await exceptionService.ProcessAsync<string>(() => { throw new ArgumentException("achieved"); });
#endif

                Assert.AreEqual("achieved", value);
            }
Beispiel #55
0
            public void ShouldNotRetryWhenAnotherExceptionTypeIsThrown()
            {
                var exceptionService = new ExceptionService();

                exceptionService
                    .Register<DivideByZeroException>(exception => { })
                    .OnErrorRetryImmediately(3);

                var attemptsCount = 0;

                ExceptionTester.CallMethodAndExpectException<ArgumentException>(() => exceptionService.ProcessWithRetry(() =>
                {
                    attemptsCount++;
                    throw new ArgumentException();
                }));
            }
Beispiel #56
0
 public void ThrowsArgumentNullExceptionForNullParameter()
 {
     var exceptionService = new ExceptionService();
     ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => exceptionService.HandleException(null));
 }
Beispiel #57
0
            public void ReturnsNullWhenNotRegisteredUsingGeneric()
            {
                var exceptionService = new ExceptionService();

                exceptionService.Register<ArgumentNullException>(exception => { });

                Assert.IsNull(exceptionService.GetHandler<Exception>());
            }