public async Task <Result <UserViewModel> > HandleAsync(LoginCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (string.IsNullOrWhiteSpace(command.Username)) { throw new InvalidOperationException("username is null or whitespace"); } if (string.IsNullOrWhiteSpace(command.Password)) { throw new InvalidOperationException("password is null or whitespace"); } var user = await userRepository.FindByNameAsync(command.Username, cancellationToken); if (user == null) { return(FailureResult <UserViewModel> .Unauthorized()); } if (!user.ValidatePassword(command.Password)) { return(FailureResult <UserViewModel> .Unauthorized()); } return(SuccessResult <UserViewModel> .Create(UserViewModel.FromUser(user))); }
public static FailureResult GetFailure(int exitCode, TimeSpan timeElapsed, Exception ex, IEnumerable<string> outputTextLines, IEnumerable<string> warningTextLines, IEnumerable<string> errorTextLines) { if (outputTextLines == null) throw new ArgumentNullException("outputTextLines"); if (warningTextLines == null) throw new ArgumentNullException("warningTextLines"); if (errorTextLines == null) throw new ArgumentNullException("errorTextLines"); var result = new FailureResult(); result.IsSuccess = false; result.ExiteCode = exitCode; result.TimeElapsed = timeElapsed; result.Exception = ex; result.OutputTextLines = new List<string>(outputTextLines); result.ErrorTextLines = new List<string>(errorTextLines); result.WarningTextLines = new List<string>(warningTextLines); return result; }
public async Task <Result <bool> > HandleAsync(ChangeCuisineCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <bool> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <bool> .Forbidden()); } var cuisine = await cuisineRepository.FindByCuisineIdAsync(command.CuisineId, cancellationToken); if (cuisine == null) { return(FailureResult <bool> .Create(FailureResultCode.CuisineDoesNotExist)); } cuisine.Change(command.Name); await cuisineRepository.StoreAsync(cuisine, cancellationToken); return(SuccessResult <bool> .Create(true)); }
public async Task <Result <bool> > HandleAsync(RemoveUserCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <bool> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <bool> .Forbidden()); } if (command.UserId == currentUser.Id) { return(FailureResult <bool> .Create(FailureResultCode.CannotRemoveCurrentUser)); } await userRepository.RemoveAsync(command.UserId, cancellationToken); return(SuccessResult <bool> .Create(true)); }
public async Task <Result <ICollection <RestaurantViewModel> > > HandleAsync(SysAdminSearchForRestaurantsQuery query, User currentUser, CancellationToken cancellationToken = default) { if (query == null) { throw new ArgumentNullException(nameof(query)); } if (currentUser == null) { return(FailureResult <ICollection <RestaurantViewModel> > .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <ICollection <RestaurantViewModel> > .Forbidden()); } var paymentMethods = (await paymentMethodRepository.FindAllAsync(cancellationToken)) .ToDictionary(en => en.Id.Value, PaymentMethodViewModel.FromPaymentMethod); var restaurants = await restaurantRepository.SearchAsync(query.SearchPhrase, cancellationToken); return(SuccessResult <ICollection <RestaurantViewModel> > .Create(restaurants .Select(en => RestaurantViewModel.FromRestaurant(en, paymentMethods, userRepository)).ToList())); }
public async Task <Result <RestaurantViewModel> > HandleAsync(AddRestaurantCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <RestaurantViewModel> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <RestaurantViewModel> .Forbidden()); } var paymentMethods = (await paymentMethodRepository.FindAllAsync(cancellationToken)) .ToDictionary(en => en.Id.Value, PaymentMethodViewModel.FromPaymentMethod); var restaurant = restaurantFactory.CreateWithName(command.Name); await restaurantRepository.StoreAsync(restaurant, cancellationToken); return(SuccessResult <RestaurantViewModel> .Create(RestaurantViewModel.FromRestaurant(restaurant, paymentMethods, userRepository))); }
public async Task <Result <Guid> > HandleAsync(AddDishCategoryToRestaurantCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <Guid> .Unauthorized()); } if (currentUser.Role < Role.RestaurantAdmin) { return(FailureResult <Guid> .Forbidden()); } var restaurant = await restaurantRepository.FindByRestaurantIdAsync(command.RestaurantId, cancellationToken); if (restaurant == null) { return(FailureResult <Guid> .Create(FailureResultCode.RestaurantDoesNotExist)); } if (currentUser.Role == Role.RestaurantAdmin && !restaurant.HasAdministrator(currentUser.Id)) { return(FailureResult <Guid> .Forbidden()); } var dishCategory = new DishCategory(new DishCategoryId(Guid.NewGuid()), command.RestaurantId, command.Name); await dishCategoryRepository.StoreAsync(dishCategory, cancellationToken); return(SuccessResult <Guid> .Create(dishCategory.Id.Value)); }
public async Task <Result <bool> > HandleAsync(AddAdminToRestaurantCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <bool> .Unauthorized()); } if (currentUser.Role < Role.RestaurantAdmin) { return(FailureResult <bool> .Forbidden()); } var restaurant = await restaurantRepository.FindByRestaurantIdAsync(command.RestaurantId, cancellationToken); if (restaurant == null) { return(FailureResult <bool> .Create(FailureResultCode.RestaurantDoesNotExist)); } if (currentUser.Role == Role.RestaurantAdmin && !restaurant.HasAdministrator(currentUser.Id)) { return(FailureResult <bool> .Forbidden()); } restaurant.AddAdministrator(command.UserId); await restaurantRepository.StoreAsync(restaurant, cancellationToken); return(SuccessResult <bool> .Create(true)); }
public void Should_Throw_Exception_When_No_Async_Result() { var failure = "failure"; var failableAsyncResult = FailureResult <string, string> .CreateAsync(failure); Assert.ThrowsAsync <Exception>(async() => await failableAsyncResult.GetResultOrThrowExceptionAsync(f => new Exception())); }
public async Task <Result <bool> > HandleAsync(ChangeUserPasswordCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <bool> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <bool> .Forbidden()); } var user = await userRepository.FindByUserIdAsync(command.UserId, cancellationToken); if (user == null) { return(FailureResult <bool> .Create(FailureResultCode.UserDoesNotExist)); } user.ChangePassword(command.Password); await userRepository.StoreAsync(user, cancellationToken); return(SuccessResult <bool> .Create(true)); }
public async Task <Result <bool> > HandleAsync(RemoveRestaurantCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <bool> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <bool> .Forbidden()); } var dishCategories = await dishCategoryRepository.FindByRestaurantIdAsync(command.RestaurantId, cancellationToken); if (dishCategories != null && dishCategories.Count > 0) { return(FailureResult <bool> .Create(FailureResultCode.RestaurantContainsDishCategories)); } var dishes = await dishRepository.FindByRestaurantIdAsync(command.RestaurantId, cancellationToken); if (dishes != null && dishes.Count > 0) { return(FailureResult <bool> .Create(FailureResultCode.RestaurantContainsDishes)); } await restaurantRepository.RemoveAsync(command.RestaurantId, cancellationToken); return(SuccessResult <bool> .Create(true)); }
public async Task Should_Execute_Task_Continuation() { var successResult = SuccessResult <int, int> .Create(1); var failureResult = FailureResult <int, int> .Create(2); Assert.AreEqual( 2, await successResult .OnSuccessAsync(s => Task.FromResult(s * 2)) .OnFailureAsync(f => Task.FromResult(f * 5)) .GetResultOrThrowExceptionAsync(f => new Exception())); Assert.AreEqual( 2, await successResult .OnSuccessAsync(s => SuccessResult <int, int> .CreateAsync(s * 2)) .OnFailureAsync(f => FailureResult <int, int> .CreateAsync(f * 5)) .GetResultOrThrowExceptionAsync(f => new Exception())); Assert.AreEqual( 4, await failureResult .OnFailureAsync(f => Task.FromResult(f * 2)) .OnSuccessAsync(s => Task.FromResult(s * 5)) .HandleAsync(s => 0, f => f)); Assert.AreEqual( 4, await failureResult .OnFailureAsync(f => FailureResult <int, int> .CreateAsync(f * 2)) .OnSuccessAsync(s => SuccessResult <int, int> .CreateAsync(s * 5)) .HandleAsync(s => 0, f => f)); }
protected IResult <IReadOnlyCollection <T> > GetAll(string procedureName, Mapper <DataSet, T> mapper, IDictionary <string, object> values = null) { IReadOnlyCollection <T> entities = null; IResult <IReadOnlyCollection <T> > result = new NoneResult <IReadOnlyCollection <T> >(); try { using (var dataSet = _context.ExecuteProcedure(procedureName, values)) { if (this.CheckDataSet(dataSet)) { entities = mapper?.MapCollection(dataSet); } } } catch (UserException ex) { result = new FailureResult <IReadOnlyCollection <T> >(ex, ex.Message); } if (entities != null) { result = new SuccessResult <IReadOnlyCollection <T> >(entities); } return(result); }
protected IResult <T> Get(string procedureName, Mapper <DataSet, T> mapper, IDictionary <string, object> values = null) { T obj = default(T); IResult <T> result = new NoneResult <T>(); try { using (var dataSet = _context.ExecuteProcedure(procedureName, values)) { if (this.CheckDataSet(dataSet) && mapper != null) { obj = mapper.MapItem(dataSet); } } } catch (UserException ex) { result = new FailureResult <T>(ex, ex.Message); } if (obj != null) { result = new SuccessResult <T>(obj); } return(result); }
public void Execute_FactoryThrowsException_FailureResultReturned() { // arrange var commandBuilder = new CommandInput.Builder(1, "command"); var commandInput = commandBuilder.Build(); var parser = Substitute.For <IParser>(); parser.Parse(Arg.Any <string>()).Returns(new[] { commandInput }); var factory = Substitute.For <ICommandFactory>(); factory.Create(Arg.Any <CommandInput>()).Returns(x => { throw new Exception(); }); var binder = Substitute.For <ICommandParameterBinder>(); var sut = new Session(parser, factory, binder); FailureResult executionResult = null; // act sut.Execute("command", result => executionResult = result as FailureResult); // assert Assert.Equal(1, executionResult.SourceLine); }
public async Task <Result <UserViewModel> > HandleAsync(AddUserCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <UserViewModel> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <UserViewModel> .Forbidden()); } var user = await userRepository.FindByNameAsync(command.Name, cancellationToken); if (user != null) { return(FailureResult <UserViewModel> .Create(FailureResultCode.UserAlreadyExists)); } user = userFactory.Create(command.Name, command.Role, command.Email, command.Password); await userRepository.StoreAsync(user, cancellationToken); return(SuccessResult <UserViewModel> .Create(UserViewModel.FromUser(user))); }
public async Task <Result <bool> > HandleAsync(EnsureAdminUserCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <bool> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <bool> .Forbidden()); } var systemAdminUsers = await userRepository.FindByRoleAsync(Role.SystemAdmin); if (systemAdminUsers.Count != 0) { return(SuccessResult <bool> .Create(true)); } var adminUser = new User(new UserId(Guid.Parse("BDD00A34-F631-4BA1-94D9-C6C909475247")), "admin", Role.SystemAdmin, "*****@*****.**", null, null); adminUser.ChangePassword("admin"); await userRepository.StoreAsync(adminUser, cancellationToken); return(SuccessResult <bool> .Create(true)); }
public async Task <Result <bool> > HandleAsync(ChangePaymentMethodCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <bool> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <bool> .Forbidden()); } var paymentMethod = await paymentMethodRepository.FindByPaymentMethodIdAsync(command.PaymentMethodId, cancellationToken); if (paymentMethod == null) { return(FailureResult <bool> .Create(FailureResultCode.PaymentMethodDoesNotExist)); } paymentMethod.Change(command.Name, command.Description); await paymentMethodRepository.StoreAsync(paymentMethod, cancellationToken); return(SuccessResult <bool> .Create(true)); }
public void Should_Throw_Exception_When_No_Result() { var failure = "failure"; var failableResult = FailureResult <string, string> .Create(failure); Assert.Throws <Exception>(() => failableResult.GetResultOrThrowException(f => new Exception())); }
public async Task <Result <CuisineViewModel> > HandleAsync(AddCuisineCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <CuisineViewModel> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <CuisineViewModel> .Forbidden()); } var cuisine = await cuisineRepository.FindByNameAsync(command.Name, cancellationToken); if (cuisine != null) { return(FailureResult <CuisineViewModel> .Create(FailureResultCode.CuisineAlreadyExists)); } cuisine = cuisineFactory.Create(command.Name); await cuisineRepository.StoreAsync(cuisine, cancellationToken); return(SuccessResult <CuisineViewModel> .Create(CuisineViewModel.FromCuisine(cuisine))); }
public async Task <Result <PaymentMethodViewModel> > HandleAsync(AddPaymentMethodCommand command, User currentUser, CancellationToken cancellationToken = default) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (currentUser == null) { return(FailureResult <PaymentMethodViewModel> .Unauthorized()); } if (currentUser.Role < Role.SystemAdmin) { return(FailureResult <PaymentMethodViewModel> .Forbidden()); } var paymentMethod = await paymentMethodRepository.FindByNameAsync(command.Name, cancellationToken); if (paymentMethod != null) { return(FailureResult <PaymentMethodViewModel> .Create(FailureResultCode.PaymentMethodAlreadyExists)); } paymentMethod = paymentMethodFactory.Create(command.Name, command.Description); await paymentMethodRepository.StoreAsync(paymentMethod, cancellationToken); return(SuccessResult <PaymentMethodViewModel> .Create(PaymentMethodViewModel.FromPaymentMethod(paymentMethod))); }
public void Should_Throw_Exception_When_Handler_Not_Provided() { var failure = "failure"; var failureResult = FailureResult <bool, string> .Create(failure); Assert.Throws <ArgumentNullException>(() => failureResult.Handle(r => r, null)); }
public void Should_Not_Get_New_Result_On_Success_Failable_Result_When_Is_Failure() { var result = FailureResult <int, int> .Create(1) .OnSuccess(s => SuccessResult <int, int> .Create(s + 5)); Assert.AreEqual(1, result.Handle(s => s, f => f)); }
public void Matches_expected_message() { const string received = "What's the frequency, Kenneth?"; const string expected = "What's {0} {1}, Kenneth?"; var result = new FailureResult(received); result.AssertNotSuccess(expected); }
public void Should_Not_Get_New_Failure_Failable_Result_On_Failure_When_Is_Success() { var success = SuccessResult <int, int> .Create(2) .OnSuccess(s => s * 2) .OnFailure(f => FailureResult <int, int> .Create(f * 3)); Assert.AreEqual(4, success.Handle(s => s, f => f)); }
public void Should_Get_New_Failure_Failable_Result_When_On_Failure() { var failure = FailureResult <int, int> .Create(2) .OnSuccess(s => s * 2) .OnFailure(f => FailureResult <int, int> .Create(f * 3)); Assert.AreEqual(6, failure.Handle(s => s, f => f)); }
public static async Task <Result <TSuccessResult, FailureResult> > ExecuteAsync <TSuccessResult>( Func <Task <TSuccessResult> > action, Expression <Func <TSuccessResult, bool> > waitCondition, TimeSpan maxWaitTime, Func <int, TimeSpan> stepEngine, string timeoutMessage, IList <Type> notIgnoredExceptionType, Action <int, TimeSpan> callbackIfWaitSuccessful, bool continueOnCapturedContext = false) { var retryAttempt = 0; TSuccessResult? value = default; List <Exception> ex = new(); var wc = waitCondition.Compile(); var stopwatch = Stopwatch.StartNew(); do { try { value = await action().ConfigureAwait(continueOnCapturedContext); if (wc(value)) { callbackIfWaitSuccessful?.Invoke(retryAttempt, stopwatch.Elapsed); return(value); } } catch (Exception e) when(notIgnoredExceptionType.Any(x => x == e.GetType())) { throw; } catch (Exception e) { ex.Add(e); } if (retryAttempt < int.MaxValue) { retryAttempt++; } var sleep = stepEngine.Invoke(retryAttempt); var stopwatchElapsed = stopwatch.Elapsed; var canRetry = stopwatch.Elapsed < maxWaitTime; if (!canRetry) { var baseFailureResult = FailureResult.Create(retryAttempt, maxWaitTime, stopwatchElapsed, timeoutMessage); return(ex.Any() ? baseFailureResult.WhenExceptions(ex) : baseFailureResult.WhenNotExpectedValue(value, waitCondition !)); } await Task.Delay(sleep); } while (true); }
public async Task Should_Create_Failure_Async_Result_When_Factory_Method_Used() { var failure = "failure"; var failureAsyncResult = FailureResult <bool, string> .CreateAsync(failure); var failureResult = await failureAsyncResult; Assert.AreEqual(failure, (failureResult as FailureResult <bool, string>).Failure); }
public void Should_Create_Failure_Result_When_Factory_Method_Used() { var failure = "failure"; var failureResult = FailureResult <bool, string> .Create(failure); Assert.AreEqual( failure, failureResult.Handle(r => string.Empty, f => f)); Assert.AreEqual(failure, (failureResult as FailureResult <bool, string>).Failure); }
public void TryGetFailureResult_should_return_failure_result_if_api_task_result_is_failure() { var failureResult = new FailureResult(); var taskResult = ApiTaskResult <SuccessResult, FailureResult> .FailureResult(failureResult, Guid.NewGuid(), new Urn("nid", "nss")); var success = taskResult.TryGetFailureResult(out var result); success.Should().BeTrue(); result.Should().Be(failureResult); }
public void Should_Not_Get_New_Result_On_Success_When_Is_Failure() { var failure = "failure"; var FailableResult = FailureResult <string, string> .Create(failure); var newResult = 2; var newFailableResult = FailableResult.OnSuccess(r => newResult); Assert.AreEqual("failure", newFailableResult.Handle(s => string.Empty, f => f)); }
public async void Failure(FailureResult result) { var message = result.ErrorMessage; var title = string.Format("MobilePay Error {0}", (int)result.ErrorCode); #if SILVERLIGHT System.Windows.MessageBox.Show(message, title, System.Windows.MessageBoxButton.OK); #else var popup = new Windows.UI.Popups.MessageDialog(message, title); await popup.ShowAsync(); #endif }
public ITaskResult<IdentityWithResult[]> Execute(Layer layer, Func<Identity, TaskContext> contextFactory, ITaskInterceptor interceptor) { ITaskResult<IdentityWithResult[]> failure = null; var results = new ConcurrentBag<IdentityWithResult>(); var layerTasks = layer.Items.Select(item => SystemTask.Factory.StartNew(() => { Identity id = item.Id; TaskContext taskContext = contextFactory(id); if (interceptor != null) { interceptor.BeforeTaskExecute(id, item.Task, taskContext); } ITaskResult<object> result = item.Task.Execute(taskContext); if (interceptor != null) { interceptor.AfterTaskExecute(id, item.Task, taskContext, result); } if (result.IsSuccess) { results.Add(new IdentityWithResult(id, result.Data)); } else { failure = new FailureResult<IdentityWithResult[]>(result.Error); } })).ToArray(); SystemTask.WaitAll(layerTasks); if (failure != null) { return failure; } return new SuccessResult<IdentityWithResult[]>(results.ToArray()); }