Exemplo n.º 1
0
 public void Constructor_2_OK()
 {
     var ex =
         new ServiceException(
         "x",
         new Exception());
 }
        public void ShouldBeSerializable()
        {
            Exception innerException = new Exception("Inner Error Message");
            const string message = "Error message";
            ServiceException exception = new ServiceException(message, innerException);

            SerializationHelper helper = new SerializationHelper();
            ServiceException deserialized = helper.Roundtrip(exception);

            Assert.AreEqual(message, deserialized.Message, "The message was not serialized.");
            Assert.AreEqual(innerException.Message, deserialized.InnerException.Message, "The inner exception was not serialized.");
        }
 public List<Entities.iDirectReports.ReportEntry> GetReport(DateTime startPeriod, DateTime endPeriod, List<uint> terminalIds)
 {
     try
     {
         return _iDirectReportDataSource.GetReport(startPeriod, endPeriod, terminalIds);
     }
     catch (Exception exception)
     {
         string additionalInfo = "Ошибка получения Networks";
         ServiceException serviceException = new ServiceException(additionalInfo, exception);
         ServicesHelper.WriteErrorToDisk(typeof(iDirectReportService), serviceException);
         throw serviceException;
     }
 }
        public void TestCaptureException()
        {
            ServiceException service = new ServiceException("Failed to invoke service.", new ServiceException("Failed to invoke other service."));
            CapturedExceptionCollection<CapturedException> exceptions = ExceptionFormatter.CaptureException(service);

            Assert.IsNotNull(exceptions);
            Assert.IsNotEmpty(exceptions.GetEntities());

            foreach (CapturedException exception in exceptions)
            {
                Assert.IsNotNull(exception);
                Console.WriteLine(exception);
            }
        }
 public List<Network> GetTerminalsTree()
 {
     try
     {
         return _iDirectReportDataSource.GetTerminalsTree();
     }
     catch (Exception exception)
     {
         string additionalInfo = "Ошибка получения Networks";
         ServiceException serviceException = new ServiceException(additionalInfo, exception);
         ServicesHelper.WriteErrorToDisk(typeof(iDirectReportService), serviceException);
         throw serviceException;
     }
 }
Exemplo n.º 6
0
        public void GetSportTeamsNotFoundTest()
        {
            //Arrange.
            Exception internalEx = new SportNotFoundException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND);

            teamsRepo.Setup(r => r.GetSportTeams(It.IsAny <string>())).Throws(toThrow);

            //Act.
            IActionResult        result   = controllerToTest.GetTeams("Dummy");
            NotFoundObjectResult notFound = result as NotFoundObjectResult;
            ErrorModelOut        error    = notFound.Value as ErrorModelOut;

            //Assert.
            teamsRepo.Verify(r => r.GetSportTeams(It.IsAny <string>()), Times.Once);
            Assert.IsNotNull(result);
            Assert.IsNotNull(notFound);
            Assert.AreEqual(404, notFound.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(toThrow.Message, error.ErrorMessage);
        }
Exemplo n.º 7
0
        public async void AddAsync_Throw_Exception_If_Regulation_Does_Not_Exist()
        {
            // arrange
            const string regulationId = "ID";

            var rule = new WelcomeRegulationRule
            {
                RegulationId = regulationId
            };

            _regulationRepositoryMock.Setup(o => o.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult <IRegulation>(null));

            // act
            Task task = _service.AddAsync(rule);

            // assert
            ServiceException exception = await Assert.ThrowsAsync <ServiceException>(async() => await task);

            Assert.Equal("Regulation not found.", exception.Message);
        }
        public void PutNoDataAccessTest()
        {
            //Arrange.
            Exception internalEx = new DataInaccessibleException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.DATA_INACCESSIBLE);

            teamsService.Setup(r => r.Modify(It.IsAny <TeamDto>())).Throws(toThrow);
            TeamModelIn input = CreateTeamModelIn();

            //Act.
            IActionResult result = controller.Put(2, input);
            ObjectResult  noData = result as ObjectResult;
            ErrorModelOut error  = noData.Value as ErrorModelOut;

            //Assert.
            Assert.IsNotNull(result);
            Assert.IsNotNull(noData);
            Assert.AreEqual(500, noData.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(toThrow.Message, error.ErrorMessage);
        }
Exemplo n.º 9
0
        public async Task ExceedMaxRedirectsShouldThrowsException()
        {
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://example.org/foo");

            var _response1 = new HttpResponseMessage(HttpStatusCode.Redirect);

            _response1.Headers.Location = new Uri("http://example.org/bar");

            var _response2 = new HttpResponseMessage(HttpStatusCode.Redirect);

            _response2.Headers.Location = new Uri("http://example.org/foo");

            this.testHttpMessageHandler.SetHttpResponse(_response1, _response2);

            ServiceException exception = await Assert.ThrowsAsync <ServiceException> (async() => await this.invoker.SendAsync(
                                                                                          httpRequestMessage, CancellationToken.None));

            Assert.True(exception.IsMatch(ErrorConstants.Codes.TooManyRedirects));
            Assert.Equal(String.Format(ErrorConstants.Messages.TooManyRedirectsFormatString, 5), exception.Error.Message);
            Assert.IsType(typeof(ServiceException), exception);
        }
        public void DeleteByIdNotExistentTest()
        {
            //Arrange.
            Exception internalEx = new TeamNotFoundException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND);

            teamsService.Setup(r => r.DeleteTeam(It.IsAny <int>())).Throws(toThrow);

            //Act.
            IActionResult        result   = controller.Delete(2);
            NotFoundObjectResult notFound = result as NotFoundObjectResult;
            ErrorModelOut        error    = notFound.Value as ErrorModelOut;

            //Assert.
            teamsService.Verify(r => r.DeleteTeam(2), Times.Once);
            Assert.IsNotNull(result);
            Assert.IsNotNull(notFound);
            Assert.AreEqual(404, notFound.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(toThrow.Message, error.ErrorMessage);
        }
Exemplo n.º 11
0
        public async Task SendAsync_ThrowsServiceExceptionWithEmptyMessageOnHTTPNotFoundWithoutErrorBody()
        {
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "https://localhost"))
                using (var stringContent = new StringContent("test"))
                    using (var httpResponseMessage = new HttpResponseMessage())
                    {
                        httpResponseMessage.Content    = stringContent;
                        httpResponseMessage.StatusCode = HttpStatusCode.NotFound;

                        this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage);
                        this.serializer.Setup(
                            mySerializer => mySerializer.DeserializeObject <ErrorResponse>(
                                It.IsAny <Stream>()))
                        .Returns((ErrorResponse)null);

                        ServiceException exception = await Assert.ThrowsAsync <ServiceException>(async() => await this.simpleHttpProvider.SendAsync(httpRequestMessage));

                        Assert.True(exception.IsMatch(ErrorConstants.Codes.ItemNotFound));
                        Assert.True(string.IsNullOrEmpty(exception.Error.Message));
                    }
        }
Exemplo n.º 12
0
        public void CreateUserNoDataAccessTest()
        {
            //Arrange.
            Exception internalEx = new DataInaccessibleException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.DATA_INACCESSIBLE);

            service.Setup(us => us.AddUser(It.IsAny <UserDto>())).Throws(toThrow);


            //Act.
            IActionResult result = controller.Post(input);
            ObjectResult  noData = result as ObjectResult;
            ErrorModelOut error  = noData.Value as ErrorModelOut;

            //Assert.
            Assert.IsNotNull(result);
            Assert.IsNotNull(noData);
            Assert.AreEqual(500, noData.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(toThrow.Message, error.ErrorMessage);
        }
Exemplo n.º 13
0
        public async Task SendRequest_UnauthorizedWithNoAuthenticationProvider()
        {
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, "https://example.com/bar");

            httpRequestMessage.Content = new StringContent("Hello World");

            var unauthorizedResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            var okResponse           = new HttpResponseMessage(HttpStatusCode.OK);

            testHttpMessageHandler.SetHttpResponse(unauthorizedResponse, okResponse);

            IList <DelegatingHandler> handlersWithNoAuthProvider = GraphClientFactory.CreateDefaultHandlers(null);

            using (HttpClient client = GraphClientFactory.Create(handlers: handlersWithNoAuthProvider, finalHandler: this.testHttpMessageHandler))
            {
                ServiceException ex = await Assert.ThrowsAsync <ServiceException>(() => client.SendAsync(httpRequestMessage, new CancellationToken()));

                Assert.Equal(ErrorConstants.Codes.InvalidRequest, ex.Error.Code);
                Assert.Equal(ErrorConstants.Messages.AuthenticationProviderMissing, ex.Error.Message);
            }
        }
        public async Task Get_CallBatchByUserIdsSevice_ThrowsServiceException()
        {
            // Arrange
            var activityInstance = this.GetDataStreamFacadeInstance();

            this.sentNotificationDataRepository
            .Setup(x => x.GetStreamsAsync(this.notificationId, null))
            .Returns(this.sentNotificationDataList.ToAsyncEnumerable());
            var serviceException = new ServiceException(null, null, HttpStatusCode.Unauthorized);

            this.usersService
            .Setup(x => x.GetBatchByUserIds(It.IsAny <IEnumerable <IEnumerable <string> > >()))
            .ThrowsAsync(serviceException);

            // Act
            var         userDataStream = activityInstance.GetUserDataStreamAsync(this.notificationId, this.notificationStatus);
            Func <Task> task           = async() => await userDataStream.ForEachAsync(x => x.ToList());

            // Assert
            await task.Should().ThrowAsync <ServiceException>();
        }
Exemplo n.º 15
0
        public void CreateAlreadyExistentUserTest()
        {
            //Arrange.
            Exception internalEx = new UserAlreadyExistsException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_ALREADY_EXISTS);

            service.Setup(us => us.AddUser(It.IsAny <UserDto>())).Throws(toThrow);

            //Act.
            IActionResult          result     = controller.Post(input);
            BadRequestObjectResult badRequest = result as BadRequestObjectResult;
            ErrorModelOut          error      = badRequest.Value as ErrorModelOut;

            //Assert.
            service.Verify(us => us.AddUser(It.IsAny <UserDto>()), Times.Once);
            Assert.IsNotNull(result);
            Assert.IsNotNull(badRequest);
            Assert.AreEqual(400, badRequest.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(error.ErrorMessage, toThrow.Message);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Get bookmark collection in word
        /// </summary>
        /// <returns>Dictionary with key is bookmark name and value is bookmark text</returns>
        public void GetBookmarkCollection(string key)
        {
            try
            {
                ContentServiceProfile contentProfile = Wkl.MainCtrl.ServiceCtrl.GetProfile(key).ContentService;

                Dictionary <string, string> bookmarks = new Dictionary <string, string>();

                Bookmarks bms = Wkl.MainCtrl.CommonCtrl.CommonProfile.Bookmarks;

                foreach (Bookmark bookmark in bms)
                {
                    if (bookmark.Name.Contains(ProntoMarkup.KeyImage))
                    {
                        bookmarks.Add(bookmark.Name, MarkupUtilities.GetBizNameOfBookmarkImage(bookmark.Name,
                                                                                               Wkl.MainCtrl.CommonCtrl.CommonProfile.ActiveDoc.InlineShapes));
                    }
                    else
                    {
                        bookmarks.Add(bookmark.Name, MarkupUtilities.GetRangeText(bookmark.Range));
                    }
                }

                contentProfile.GetBookmarks_OListBM = bookmarks;
            }
            catch (BaseException srvExp)
            {
                Services.ServiceException newSrvExp = new Services.ServiceException(ErrorCode.ipe_GetWordBookmarksError);
                newSrvExp.Errors.Add(srvExp);

                throw newSrvExp;
            }
            catch (Exception ex)
            {
                ServiceException srvExp = new ServiceException(ErrorCode.ipe_GetWordBookmarksError,
                                                               MessageUtils.Expand(Properties.Resources.ipe_GetWordBookmarksError, ex.Message), ex.StackTrace);

                throw srvExp;
            }
        }
Exemplo n.º 17
0
        public bool IsProntoDoc()
        {
            try
            {
                ProntoDoc.Framework.CoreObject.PdwxObjects.ChecksumInfo checksum = mainService.PropertyService.GetChecksum();

                return(IsProntoDoc(checksum));
            }
            catch (BaseException srvExp)
            {
                Services.ServiceException newSrvExp = new Services.ServiceException(ErrorCode.ipe_ValidateChecksumError);
                newSrvExp.Errors.Add(srvExp);

                throw newSrvExp;
            }
            catch (System.Exception ex)
            {
                ServiceException srvExp = new ServiceException(Core.ErrorCode.ipe_ValidateChecksumError,
                                                               Core.MessageUtils.Expand(Properties.Resources.ipe_ValidateChecksumError, ex.Message), ex.StackTrace);
                throw srvExp;
            }
        }
Exemplo n.º 18
0
        public async void UpdateAsync_Throw_Exception_If_Rule_Does_Not_Exist()
        {
            // arrange
            const string regulationRuleId = "ID";

            _regulationRepositoryMock.Setup(o => o.GetAsync(It.IsAny <string>()))
            .ReturnsAsync(new Core.Domain.Regulation());

            _welcomeRegulationRuleRepositoryMock.Setup(o => o.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult <IWelcomeRegulationRule>(null));

            // act
            Task task = _service.UpdateAsync(new WelcomeRegulationRule
            {
                RegulationId = regulationRuleId
            });

            // assert
            ServiceException exception = await Assert.ThrowsAsync <ServiceException>(async() => await task);

            Assert.Equal("Regulation rule not found.", exception.Message);
        }
Exemplo n.º 19
0
        public void SaveSelectedDomainToFile(UserData userData)
        {
            try
            {
                string dataSerialize = ProntoDoc.Framework.Utils.ObjectSerializeHelper.SerializeToString(userData);
                FileAdapter.SaveUserData(dataSerialize);
            }
            catch (BaseException srvExp)
            {
                Services.ServiceException newSrvExp = new Services.ServiceException(ErrorCode.ipe_SaveFileError);
                newSrvExp.Errors.Add(srvExp);

                throw newSrvExp;
            }
            catch (Exception ex)
            {
                ServiceException srvExp = new ServiceException(Core.ErrorCode.ipe_SaveFileError,
                                                               Core.MessageUtils.Expand(Properties.Resources.ipe_SaveFileError, ex.Message), ex.StackTrace);

                throw srvExp;
            }
        }
Exemplo n.º 20
0
        public async Task SyncAllUsers_ExpiredDeltaLink_ThrowsInvalidOperationException()
        {
            // Arrange
            var    activityContext = this.GetSyncAllUsersActivity();
            string deltaLink       = "expiredDeltaLink";
            IEnumerable <UserDataEntity> userDataResponse = new List <UserDataEntity>()
            {
                new UserDataEntity()
                {
                    Name = string.Empty
                },
            };
            NotificationDataEntity notification = new NotificationDataEntity()
            {
                Id = "notificationId1",
            };

            this.userDataRepository
            .Setup(x => x.GetDeltaLinkAsync())
            .ReturnsAsync(deltaLink);

            this.userDataRepository
            .Setup(x => x.SetDeltaLinkAsync(It.IsAny <string>()))
            .Returns(Task.CompletedTask);
            this.userDataRepository
            .Setup(x => x.GetAllAsync(It.IsAny <string>(), null))
            .ReturnsAsync(userDataResponse);

            var serviceException = new ServiceException(null, null, HttpStatusCode.BadRequest);

            this.userService.Setup(x => x.GetAllUsersAsync(It.IsAny <string>())).ThrowsAsync(serviceException);

            Func <Task> task = async() => await activityContext.RunAsync(notification, this.logger.Object);

            // Assert
            await task.Should().ThrowAsync <InvalidOperationException>();

            this.userService.Verify(x => x.GetAllUsersAsync(It.IsAny <string>()), Times.Exactly(2));
        }
Exemplo n.º 21
0
        public async Task SendAsync_CopyClientRequestIdHeader_AddClientRequestIdToError()
        {
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost"))
                using (var stringContent = new StringContent("test"))
                    using (var httpResponseMessage = new HttpResponseMessage())
                    {
                        httpResponseMessage.Content = stringContent;

                        const string clientRequestId = "3c9c5bc6-42d2-49ac-a99c-49c10513339a";

                        httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
                        httpResponseMessage.Headers.Add(CoreConstants.Headers.ClientRequestId, clientRequestId);
                        httpResponseMessage.RequestMessage = httpRequestMessage;

                        this.testHttpMessageHandler.AddResponseMapping(httpRequestMessage.RequestUri.ToString(), httpResponseMessage);

                        ServiceException exception = await Assert.ThrowsAsync <ServiceException>(async() => await this.simpleHttpProvider.SendAsync(httpRequestMessage));

                        Assert.NotNull(exception.Error);
                        Assert.Equal(clientRequestId, exception.Error.ClientRequestId);
                    }
        }
        public async void AddAsync_Throw_Exception_If_Regulation_Already_Exists()
        {
            // arrange
            const string regulationId = "ID";

            _regulationRepositoryMock.Setup(o => o.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult <IRegulation>(new Core.Domain.Regulation
            {
                Id = regulationId
            }));

            // act
            Task task = _service.AddAsync(new Core.Domain.Regulation
            {
                Id = regulationId
            });

            // assert
            ServiceException exception = await Assert.ThrowsAsync <ServiceException>(async() => await task);

            Assert.Equal("Regulation already exists.", exception.Message);
        }
Exemplo n.º 23
0
        public void UnfollowTeamNotFoundTest()
        {
            //Arrange.
            TeamModelIn input      = GetTeamModelIn();
            Exception   internalEx = new TeamNotFoundException();
            Exception   toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND);

            service.Setup(us => us.UnFollowTeam(It.IsAny <string>(), It.IsAny <int>())).Throws(toThrow);

            //Act.
            IActionResult        result   = controller.UnFollowTeam(3);
            NotFoundObjectResult notFound = result as NotFoundObjectResult;
            ErrorModelOut        error    = notFound.Value as ErrorModelOut;

            //Assert.
            service.Verify(us => us.UnFollowTeam(It.IsAny <string>(), It.IsAny <int>()), Times.Once);
            Assert.IsNotNull(result);
            Assert.IsNotNull(notFound);
            Assert.AreEqual(404, notFound.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(error.ErrorMessage, toThrow.Message);
        }
Exemplo n.º 24
0
        public async Task Get_ForbiddenGraphPermission_ReturnsAdminConsentError()
        {
            // Arrange
            var activityInstance = this.GetDataStreamFacadeInstance();
            var userDataList     = new List <User>();
            var error            = new Graph.Error()
            {
                Code    = HttpStatusCode.Forbidden.ToString(),
                Message = "UnAuthorized",
            };
            var forbiddenException = new ServiceException(error, null, HttpStatusCode.Forbidden);

            this.sentNotificationDataRepository
            .Setup(x => x.GetStreamsAsync(this.notificationId, null))
            .Returns(this.sentNotificationDataWithErrorList.ToAsyncEnumerable());
            this.userDataRepository
            .Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(new UserDataEntity());
            var sendNotificationData = this.sentNotificationDataWithErrorList.Select(x => x.Where(y => y.RowKey == "RowKey").FirstOrDefault()).FirstOrDefault();

            this.usersService
            .Setup(x => x.GetBatchByUserIds(It.IsAny <IEnumerable <IEnumerable <string> > >()))
            .ThrowsAsync(forbiddenException);
            string adminConsentError = "AdminConsentError";
            var    localizedString   = new LocalizedString(adminConsentError, adminConsentError);

            this.localizer.Setup(_ => _[adminConsentError]).Returns(localizedString);

            // Act
            var userDataStream = await activityInstance.GetUserDataStreamAsync(this.notificationId).ToListAsync();

            var userData = userDataStream.Select(x => x.Where(y => y.Id == "RowKey").FirstOrDefault()).FirstOrDefault();

            // Assert
            Assert.Equal(userData.Name, adminConsentError);
            Assert.Equal(userData.Upn, adminConsentError);
            Assert.Equal(userData.UserType, adminConsentError);
        }
        public static SkillException HandleGraphAPIException(ServiceException ex)
        {
            var skillExceptionType = SkillExceptionType.Other;

            if (ex.Message.Contains(APIErrorAccessDenied, StringComparison.InvariantCultureIgnoreCase))
            {
                skillExceptionType = SkillExceptionType.APIAccessDenied;
            }
            else if (ex.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                skillExceptionType = SkillExceptionType.APIUnauthorized;
            }
            else if (ex.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                skillExceptionType = SkillExceptionType.APIForbidden;
            }
            else if (ex.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                skillExceptionType = SkillExceptionType.APIBadRequest;
            }

            return(new SkillException(skillExceptionType, ex.Message, ex));
        }
Exemplo n.º 26
0
        public async Task <ActionResult> Schedule(int teamId = 0)
        {
            IEnumerable <Game> games = new List <Game>();
            ServiceException   error = null;

            try
            {
                games = await resultService.GetScheduleAsync(teamId);
            }
            catch (ServiceException e)
            {
                error = e;
            }

            var viewModel = new GamesViewModel(games, error);

            if (Request.IsAjaxRequest())
            {
                return(PartialView(viewModel));
            }

            return(View(viewModel));
        }
Exemplo n.º 27
0
        public void LoginNotFoundTest()
        {
            //Arrange.
            Exception internalEx = new UserNotFoundException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND);

            loginService.Setup(l => l.Login("otherUsername", "aPassword")).Throws(toThrow);

            //Act.
            LoginModelIn credentials = new LoginModelIn()
            {
                Username = "******", Password = "******"
            };
            IActionResult          result           = controllerToTest.Authenticate(credentials);
            BadRequestObjectResult badRequestResult = result as BadRequestObjectResult;
            ErrorModelOut          error            = badRequestResult.Value as ErrorModelOut;

            //Assert.
            loginService.VerifyAll();
            Assert.IsNotNull(badRequestResult);
            Assert.IsNotNull(error);
            Assert.AreEqual(toThrow.Message, error.ErrorMessage);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Gen check sum
        /// </summary>
        /// <param name="srvPro"></param>
        /// <param name="lstJParam">List JParameter just buit with select (-> has new order)</param>
        private void GetCheckSum(ServicesProfile srvPro, List <ChecksumInfoItem> checksumItems, string dscColor, bool hasDsc)
        {
            try
            {
                GenChecksumHelper genChkHelper = new GenChecksumHelper();
                srvPro.PdwInfo.ChecksumString = genChkHelper.GenChecksum(
                    srvPro.PdwInfo.OsqlString, checksumItems, srvPro.TemplateType, dscColor, hasDsc, srvPro.FullDocName);
            }
            catch (BaseException srvExp)
            {
                Services.ServiceException newSrvExp = new Services.ServiceException(ErrorCode.ipe_GenChecksumError);
                newSrvExp.Errors.Add(srvExp);

                throw newSrvExp;
            }
            catch (Exception ex)
            {
                ServiceException srvExp = new ServiceException(
                    ErrorCode.ipe_GenChecksumError,
                    MessageUtils.Expand(Properties.Resources.ipe_GenChecksumError, ex.Message), ex.StackTrace);
                throw srvExp;
            }
        }
        public async void DeleteAsync_Can_Not_Delete_If_Regulation_Assigned_With_Client()
        {
            // arrange
            const string regulationId = "ID";

            _regulationRepositoryMock.Setup(o => o.GetAsync(It.IsAny <string>()))
            .ReturnsAsync(new Core.Domain.Regulation());

            _clientRegulationRepositoryMock
            .Setup(o => o.GetByRegulationIdAsync(It.IsAny <string>()))
            .ReturnsAsync(new List <ClientRegulation>
            {
                new ClientRegulation()
            });

            // act
            Task task = _service.DeleteAsync(regulationId);

            // assert
            ServiceException exception = await Assert.ThrowsAsync <ServiceException>(async() => await task);

            Assert.Equal("Can not delete regulation associated with one or more clients.", exception.Message);
        }
Exemplo n.º 30
0
        public async Task <ActionResult> Team(int teamId)
        {
            Group            group = null;
            ServiceException error = null;

            try
            {
                group = await resultService.GetGroupForTeam(teamId);
            }
            catch (ServiceException e)
            {
                error = e;
            }

            var viewModel = new GroupViewModel(group, error);

            if (Request.IsAjaxRequest())
            {
                return(PartialView(viewModel));
            }

            return(View(viewModel));
        }
Exemplo n.º 31
0
        public async Task Get_ForbiddenGraphPermission_ReturnsAdminConsentError()
        {
            // Arrange
            var getMetadataActivityInstance = this.GetMetadataActivity();
            var notificationDataEntity      = this.GetNotificationDataEntity();
            var exportDataEntity            = this.GetExportDataEntity();
            var user = this.GetUser();

            string key             = "AdminConsentError";
            var    localizedString = new LocalizedString(key, key);

            this.localizer.Setup(_ => _[key]).Returns(localizedString);
            var serviceException = new ServiceException(null, null, HttpStatusCode.Forbidden);

            this.usersService.Setup(x => x.GetUserAsync(It.IsAny <string>())).ThrowsAsync(serviceException);

            // Act
            var result = await getMetadataActivityInstance.GetMetadataActivityAsync((notificationDataEntity, exportDataEntity));

            // Assert
            Assert.NotNull(result);
            Assert.Equal(result.ExportedBy, key);
        }
Exemplo n.º 32
0
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                HttpStatusCode code;
                ODataError     report = null;

                if (context.Exception is HttpResponseException)
                {
                    return;
                }
                else if (context.Exception is ServiceException)
                {
                    var e = (ServiceException)context.Exception.GetLastInnerException();

                    report = e.Error;
                    code   = e.StatusCode;
                }
                else if (context.Exception is ModelStateException)
                {
                    var e = new ServiceException((ModelStateException)context.Exception);
                    report = e.Error;
                    code   = e.StatusCode;
                }
                else
                {
                    report            = CommunicationErrors.InternalServerError;
                    report.InnerError = new ODataInnerError(context.Exception.GetLastInnerException());

                    code = HttpStatusCode.InternalServerError;
                }

                LogException(context, code, report);

                context.Exception = new HttpResponseException(context.Request.CreateResponse(code, report));
            }
        }
        public static async Task <bool> ShouldContinue(ServiceException mgsex, int currentRetry)
        {
            int waitForMilliSeconds;

            switch (mgsex.StatusCode)
            {
            case System.Net.HttpStatusCode.TooManyRequests:
                waitForMilliSeconds = 1000 * currentRetry * currentRetry;
                break;

            case System.Net.HttpStatusCode.Unauthorized:
                waitForMilliSeconds = 1000 * currentRetry * currentRetry;
                break;

            case System.Net.HttpStatusCode.BadGateway:
                waitForMilliSeconds = 1000 * currentRetry * currentRetry;
                break;

            case System.Net.HttpStatusCode.Forbidden:
                return(false);

            case System.Net.HttpStatusCode.NotFound:
            case System.Net.HttpStatusCode.BadRequest:
            default:
                return(false);
            }
            if (currentRetry == MaxRetry)
            {
                return(false);
            }
            else
            {
                await Task.Delay(waitForMilliSeconds);
            }

            return(true);
        }
Exemplo n.º 34
0
        private static void ExceptionSerializationTest()
        {
            var formatter = new XmlFormatter();
            var ms        = new MemoryStream();

            try
            {
                formatter.Serialize(ms, new NotImplementedException("test ex 23432"), typeof(Exception));
            }
            catch (Exception ex)
            {
            }

            try
            {
                var exObject = new ServiceException("test ex 234234");
                var type     = exObject.GetType();
                formatter.Serialize(ms, exObject, type);
                ms.Position = 0;
                var dexObj = formatter.Deserialize(ms, type);
            }
            catch (Exception ex)
            {
            }

            try
            {
                var exObject = new NotImplementedException("test ex 23432");
                var type     = exObject.GetType();
                formatter.Serialize(ms, exObject, type);
                ms.Position = 0;
                var dexObj = formatter.Deserialize(ms, type);
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// Processes the specified action and wraps it with common error handling logic.
        /// </summary>
        /// <remarks>
        /// If any exception is thrown, the <see cref="ArgumentException"/>, <see cref="ConfigurationException"/>,
        /// and <see cref="ServiceException"/> exceptions will be simply re-thrown.
        /// All other exceptions will be wrapped in <see cref="ServiceException"/> and thrown.
        /// </remarks>
        /// <param name="action">The action to process.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="methodDescription">The short description of what the source method does.</param>
        /// <param name="methodName">The full method name.</param>
        private static void Process(Action action, ILog logger, string methodDescription, string methodName)
        {
            Exception thrownException = null;

            try
            {
                action();
            }
            catch (ArgumentException ex)
            {
                thrownException = ex;
                throw;
            }
            catch (ConfigurationException ex)
            {
                thrownException = ex;
                throw;
            }
            catch (ServiceException ex)
            {
                thrownException = ex;
                throw;
            }
            catch (Exception ex)
            {
                string errorMessage = $"Error occurred while {methodDescription}.";
                thrownException = new ServiceException(errorMessage, ex);
                throw thrownException;
            }
            finally
            {
                if (thrownException != null)
                {
                    LogException(logger, methodName, thrownException);
                }
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Handles a message routed to the service by the MessageBroker.
        /// </summary>
        /// <param name="message">The message that should be handled by the service.</param>
        /// <returns>The result of the message processing.</returns>
		public override object ServiceMessage(IMessage message)
		{
			CommandMessage commandMessage = message as CommandMessage;
			MessageDestination messageDestination = GetDestination(message) as MessageDestination;
			if( commandMessage != null )
			{
				string clientId = commandMessage.clientId as string;
                MessageClient messageClient = messageDestination.SubscriptionManager.GetSubscriber(clientId);
                AcknowledgeMessage acknowledgeMessage = null;
                switch (commandMessage.operation)
                {
                    case CommandMessage.SubscribeOperation:
                        if (messageClient == null)
                        {
                            if (clientId == null)
                                clientId = Guid.NewGuid().ToString("D");

                            if (log.IsDebugEnabled)
                                log.Debug(__Res.GetString(__Res.MessageServiceSubscribe, messageDestination.Id, clientId));

                            string endpointId = commandMessage.GetHeader(MessageBase.EndpointHeader) as string;
                            if (_messageBroker.GetEndpoint(endpointId) == null)
                            {
                                ServiceException serviceException = new ServiceException("Endpoint was not specified");
                                serviceException.FaultCode = "Server.Processing.MissingEndpoint";
                                throw serviceException;
                            }
                            commandMessage.clientId = clientId;

                            if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions)
                            {
                                try
                                {
                                    acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage;
                                }
                                catch (MessageException me)
                                {
                                    acknowledgeMessage = me.GetErrorMessage();
                                    //Leave, do not subscribe
                                    return acknowledgeMessage;
                                }
                                catch (Exception ex)
                                {
                                    //Guard against service adapter failure
                                    acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex);
                                    if (log.IsErrorEnabled)
                                        log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
                                    //Leave, do not subscribe
                                    return acknowledgeMessage;
                                }
                            }

                            Subtopic subtopic = null;
                            Selector selector = null;
                            if (commandMessage.headers != null)
                            {
                                if (commandMessage.headers.ContainsKey(CommandMessage.SelectorHeader))
                                {
                                    selector = Selector.CreateSelector(commandMessage.headers[CommandMessage.SelectorHeader] as string);
                                }
                                if (commandMessage.headers.ContainsKey(AsyncMessage.SubtopicHeader))
                                {
                                    subtopic = new Subtopic(commandMessage.headers[AsyncMessage.SubtopicHeader] as string);
                                }
                            }
                            IClient client = FluorineContext.Current.Client;
                            client.Renew();
                            messageClient = messageDestination.SubscriptionManager.AddSubscriber(clientId, endpointId, subtopic, selector);
                            if (acknowledgeMessage == null)
                                acknowledgeMessage = new AcknowledgeMessage();
                            acknowledgeMessage.clientId = clientId;
                        }
                        else
                        {
                            acknowledgeMessage = new AcknowledgeMessage();
                            acknowledgeMessage.clientId = clientId;
                        }
                        return acknowledgeMessage;
                    case CommandMessage.UnsubscribeOperation:
                        if (log.IsDebugEnabled)
                            log.Debug(__Res.GetString(__Res.MessageServiceUnsubscribe, messageDestination.Id, clientId));

                        if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions)
                        {
                            try
                            {
                                acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage;
                            }
                            catch (MessageException me)
                            {
                                acknowledgeMessage = me.GetErrorMessage();
                            }
                            catch (Exception ex)
                            {
                                //Guard against service adapter failure
                                acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex);
                                if (log.IsErrorEnabled)
                                    log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
                            }
                        }
                        if (messageClient != null)
                            messageDestination.SubscriptionManager.RemoveSubscriber(messageClient);
                        if (acknowledgeMessage == null)
                            acknowledgeMessage = new AcknowledgeMessage();
                        return acknowledgeMessage;
                    case CommandMessage.PollOperation:
                        {
                            if (messageClient == null)
                            {
                                ServiceException serviceException = new ServiceException(string.Format("MessageClient is not subscribed to {0}", commandMessage.destination));
                                serviceException.FaultCode = "Server.Processing.NotSubscribed";
                                throw serviceException;
                            }
                            IClient client = FluorineContext.Current.Client;
                            client.Renew();
                            try
                            {
                                acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage;
                            }
                            catch (MessageException me)
                            {
                                acknowledgeMessage = me.GetErrorMessage();
                            }
                            catch (Exception ex)
                            {
                                //Guard against service adapter failure
                                acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex);
                                if (log.IsErrorEnabled)
                                    log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
                            }
                            if (acknowledgeMessage == null)
                                acknowledgeMessage = new AcknowledgeMessage();
                            return acknowledgeMessage;
                        }
                    case CommandMessage.ClientPingOperation:
                        if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions)
                        {
                            try
                            {
                                messageDestination.ServiceAdapter.Manage(commandMessage);
                            }
                            catch (MessageException)
                            {
                                return false;
                            }
                            catch (Exception ex)
                            {
                                //Guard against service adapter failure
                                if (log.IsErrorEnabled)
                                    log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
                                return false;
                            }
                        }
                        return true;
                    default:
                        if (log.IsDebugEnabled)
                            log.Debug(__Res.GetString(__Res.MessageServiceUnknown, commandMessage.operation, messageDestination.Id));
                        try
                        {
                            acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage;
                        }
                        catch (MessageException me)
                        {
                            acknowledgeMessage = me.GetErrorMessage();
                        }
                        catch (Exception ex)
                        {
                            //Guard against service adapter failure
                            acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex);
                            if (log.IsErrorEnabled)
                                log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex);
                        }
                        if (acknowledgeMessage == null)
                            acknowledgeMessage = new AcknowledgeMessage();
                        return acknowledgeMessage;
                }
			}
			else
			{
				if (log.IsDebugEnabled)
					log.Debug(__Res.GetString(__Res.MessageServiceRoute, messageDestination.Id, message.clientId));

                if (FluorineContext.Current != null && FluorineContext.Current.Client != null)//Not set when user code initiates push
                {
                    IClient client = FluorineContext.Current.Client;
                    client.Renew();
                }
                object result = messageDestination.ServiceAdapter.Invoke(message);
				return result;
			}
		}
Exemplo n.º 37
0
 public void Constructor_0_OK()
 {
     var ex = new ServiceException();
 }
 public void ShouldStoreMessagePassedToConstructor()
 {
     const string message = "Error Message";
     ServiceException exception = new ServiceException(message);
     Assert.AreEqual(message, exception.Message);
 }
 public void ShouldProvideDefaultMessage()
 {
     ServiceException serviceException = new ServiceException();
     Assert.AreEqual("Exception of type 'ServiceInterfaces.ServiceException' was thrown.", serviceException.Message);
 }
        private UploadChunkResult SetupGetChunkResponseTest(ServiceException serviceException = null, bool failsOnce = true, bool verifyTrackedExceptions = true)
        {
            var chunkSize = 320 * 1024;
            var bytesToUpload = new byte[] { 4, 8, 15, 16 };
            var trackedExceptions = new List<Exception>();
            this.uploadSession.Object.NextExpectedRanges = new[] { "0-" };
            var stream = new MemoryStream(bytesToUpload.Length);
            stream.Write(bytesToUpload, 0, bytesToUpload.Length);
            stream.Seek(0, SeekOrigin.Begin);

            var provider = new ChunkedUploadProvider(
                this.uploadSession.Object,
                this.client.Object,
                stream,
                chunkSize);

            var mockRequest = new Mock<UploadChunkRequest>(
                this.uploadSession.Object.UploadUrl,
                this.client.Object,
                null,
                0,
                bytesToUpload.Length - 1,
                bytesToUpload.Length);

            if (serviceException != null && failsOnce)
            {
                mockRequest.SetupSequence(r => r.PutAsync(
                    It.IsAny<Stream>(),
                    It.IsAny<CancellationToken>()))
                    .Throws(serviceException)
                    .Returns(Task.FromResult(new UploadChunkResult() { ItemResponse = new Item()}));
            }
            else if (serviceException != null)
            {
                mockRequest.Setup(r => r.PutAsync(
                    It.IsAny<Stream>(),
                    It.IsAny<CancellationToken>()))
                    .Throws(serviceException);
            }
            else
            {
                mockRequest.Setup(r => r.PutAsync(
                    It.IsAny<Stream>(),
                    It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult(new UploadChunkResult { ItemResponse = new Item()}));
            }

            var task = provider.GetChunkRequestResponseAsync(mockRequest.Object, bytesToUpload, trackedExceptions);
            try
            {
                task.Wait();
            }
            catch (AggregateException exception)
            {
                throw exception.InnerException;
            }

            if (verifyTrackedExceptions)
            {
                Assert.IsTrue(trackedExceptions.Contains(serviceException), "Expected ServiceException in TrackedException list");
            }

            return task.Result;
        }
 internal ServiceFailedEventArgs(ServiceException error, object userToken)
     : base(userToken)
 {
     Error = error;
 }
 public void GetChunkRequestResponseTest_Fail()
 {
     var exception = new ServiceException(new Error { Code = "Timeout" });
     var result = this.SetupGetChunkResponseTest(exception, failsOnce: false);
 }
        public void GetChunkRequestResponseTest_InvalidRange()
        {
            var exception = new ServiceException(new Error { Code = "InvalidRange" });
            var result = this.SetupGetChunkResponseTest(exception, verifyTrackedExceptions: false);

            Assert.IsNull(result.ItemResponse, "Expected no Item in ItemResponse");
            Assert.IsNull(result.UploadSession, "Expected no UploadSession in response");
        }
        public void GetChunkRequestResponseTest_SuccessAfterOneException()
        {
            var exception = new ServiceException(new Error {Code = "GeneralException"});
            var result = this.SetupGetChunkResponseTest(exception);

            Assert.IsNotNull(result.ItemResponse, "Expected Item in ItemResponse");
            Assert.IsTrue(result.UploadSucceeded);
        }
Exemplo n.º 45
0
 public ErrorDetails(string MethodName, string DateTime, ServiceException ExceptionType)
 {
     this.MethodName = MethodName;
     this.DateTime = DateTime;
     this.ExceptionType = ExceptionType;
 }
 public List<HughesSpeedTest> GetHughesSpeedTests(HughesSpeedTest filter, int pageNumber, int pageSize)
 {
     try
     {
         _hughesSpeedTestDataSource.AdditionalQueryParameters = filter;
         _hughesSpeedTestDataSource.CurrentPage = pageNumber;
         _hughesSpeedTestDataSource.PageSize = pageSize;
         return _hughesSpeedTestDataSource.PageData;
     }
     catch (Exception exception)
     {
         ServiceException serviceException = new ServiceException(exception);
         ServicesHelper.WriteErrorToDisk(typeof(HughesSpeedTestService), serviceException);
         throw serviceException;
     }
 }
 /// <summary>
 /// Получить подробную статистику для теста скорости
 /// </summary>
 /// <param name="testId">Id теста</param>
 /// <returns></returns>
 public List<HughesSpeedTestDetail> GetHughesSpeedTestDetails(int testId)
 {
     try
     {
         return _hughesSpeedTestDataSource.GetHughesSpeedTestDetails(testId);
     }
     catch (Exception exception)
     {
         string additionalInfo = string.Format("Ошибка получения HughesSpeedTestDetail для теста с testId = {0}", testId);
         ServiceException serviceException = new ServiceException(additionalInfo, exception);
         ServicesHelper.WriteErrorToDisk(typeof(ContractService), serviceException);
         throw serviceException;
     }
 }
 public int GetHughesSpeedTestsCount(
     HughesSpeedTest filter,
     DateTime startPeriod, 
     DateTime endPeriod)
 {
     try
     {
         _hughesSpeedTestDataSource.StartPeriod = startPeriod;
         _hughesSpeedTestDataSource.EndPeriod = endPeriod;
         _hughesSpeedTestDataSource.AdditionalQueryParameters = filter;
         return _hughesSpeedTestDataSource.TotalRecordCount;
     }
     catch (Exception exception)
     {
         ServiceException serviceException = new ServiceException(exception);
         ServicesHelper.WriteErrorToDisk(typeof(HughesSpeedTestService), serviceException);
         throw serviceException;
     }
 }