Ejemplo n.º 1
0
        public async Task ElTestoAsync()
        {
            var request = new SomeOperationRequest();

            var validateApiKey = GetApiKey().ToValidation(new ValidationFailure("ApiKey", "API Key is missing in headers"));

            var v = from v1 in validateApiKey
                    from v2 in Validate(request)
                    select v1 + v2;

            var appCode = from key in v.ToOption()
                          from code in GetAppCode(key)
                          select code;

            TryAsync <Result <SomeOperationResult> > bloo = from req in TryAsync(request)
                                                            from code in appCode.ToTryAsync()
                                                            select StartPaymentAsync(req, code);

            string message = await bloo.Match(
                Succ : tryRes => tryRes.Match(
                    Succ: payRes => $"Payment succeeded! PaymentID = {payRes.PaymentId}",
                    Fail: ex => ex.Message),
                Fail : ex => ex.Message);

            message.Should().Contain("42");
        }
Ejemplo n.º 2
0
        public async Task Handle(DocumentSentForApprovalEventDto notification, CancellationToken cancellationToken)
        {
            TryAsync <Unit> handle = async() =>
                                     await _updateDocumentStatus(notification.Id, DocumentStatus.WaitingForApproval.ToString()).ToUnit();

            await handle.Match(
                Succ : u => { },
                Fail : ex => _logger.LogError($"Error while handling {nameof(DocumentSentForApprovalEventDto)}: {ex}"));
        }
        public async Task Handle(DocumentUpdatedEventDto notification, CancellationToken cancellationToken)
        {
            TryAsync <Unit> handle = async() =>
                                     await _updateDocument(notification.Id, notification.Number, notification.Description).ToUnit();

            await handle.Match(
                Succ : u => { },
                Fail : ex => _logger.LogError($"Error while handling {nameof(DocumentUpdatedEventDto)}: {ex}"));
        }
        public async Task Handle(UserCreatedEventDto notification, CancellationToken cancellationToken)
        {
            TryAsync <Unit> handle = async() =>
                                     await _addUser(notification.Id, notification.Email, notification.FirebaseId)
                                     .ToUnit();

            await handle.Match(
                Succ : _ => { },
                Fail : ex => _logger.LogError($"Error while handling {nameof(UserCreatedEventDto)}: {ex}"));
        }
        public async Task Handle(FileAddedEventDto notification, CancellationToken cancellationToken)
        {
            TryAsync <Unit> handle = async() =>
                                     await _addFile(notification.FileId, notification.Id, notification.FileName,
                                                    notification.FileDescription).ToUnit();

            await handle.Match(
                Succ : u => { },
                Fail : ex => _logger.LogError($"Error while handling {nameof(FileAddedEventDto)}: {ex}"));
        }
Ejemplo n.º 6
0
        public async Task Handle(DocumentApprovedEventDto notification, CancellationToken cancellationToken)
        {
            TryAsync <Unit> handle = async() =>
                                     await _approveDocument(notification.Id, DocumentStatus.Approved.ToString(), notification.Comment)
                                     .ToUnit();

            await handle.Match(
                Succ : u => { },
                Fail : ex => _logger.LogError($"Error while handling {nameof(DocumentApprovedEventDto)}: {ex}"));
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> Get()
        {
            TryAsync <Lst <Contract.DTO.Chat.Channel> > svcResult = async() => await _chatService.GetAllChannels();

            var result = svcResult.Match <Lst <Contract.DTO.Chat.Channel>, IActionResult>(
                Succ: model => Ok(model.Select(p => p.Name).ToList()),
                Fail: ex => StatusCode(500, ex)
                );

            return(await result);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> Post([FromBody] Channel channel)
        {
            var             model     = _mapper.Map <Channel, Contract.DTO.Chat.Channel>(channel);
            TryAsync <Unit> svcResult = async() => await _chatService.AddChannel(model);

            var result = svcResult.Match <Unit, IActionResult>(
                Succ: unit => NoContent(),
                Fail: ex => StatusCode(500, ex)
                );

            return(await result);
        }
Ejemplo n.º 9
0
        private OptionAsync <Config> LoadAkkaConfig()
        {
            TryAsync <Config> tryLoadAkkaConfig =
                async() => ConfigurationFactory.ParseString(await File.ReadAllTextAsync("hocon.txt"));

            return(tryLoadAkkaConfig.Match(
                       akkaConfig => akkaConfig,
                       ex =>
            {
                _logger.LogError("Failed to load akka config");
                return (Config)null;
            }));
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Post([FromBody] Message message, int channelId)
        {
            message.ChannelId = channelId;
            var model = _mapper.Map <Message, Contract.DTO.Chat.Message>(message);

            TryAsync <Unit> svcResult = async() => await _chatService.AddMessage(model);

            var result = svcResult.Match <Unit, IActionResult>(
                Succ: unit => NoContent(),
                Fail: ex => StatusCode(500, ex)
                );

            return(await result);
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> Get(int channelId)
        {
            TryAsync <Lst <Contract.DTO.Chat.Message> > svcResult = async() => await _chatService.GetAllMessagesInChannel(channelId);

            var result = svcResult.Match <Lst <Contract.DTO.Chat.Message>, IActionResult>(
                Succ: model =>
            {
                var messages = model.Select(p => p.Content).ToList();
                return(Ok(messages));
            },
                Fail: ex => StatusCode(500, ex)
                );

            return(await result);
        }
Ejemplo n.º 12
0
 public static Task <Either <L, A> > ToEither <A, L>(this TryAsync <A> self, Func <Exception, L> Fail) =>
 self.Match(
     Succ: v => Either <L, A> .Right(v),
     Fail: x => Either <L, A> .Left(Fail(x)));
Ejemplo n.º 13
0
 public static Task <Either <Exception, A> > ToEither <A>(this TryAsync <A> self) =>
 self.Match(
     Succ: v => Either <Exception, A> .Right(v),
     Fail: x => Either <Exception, A> .Left(x));
Ejemplo n.º 14
0
 public static Task <OptionUnsafe <A> > ToOptionUnsafe <A>(this TryAsync <A> self) =>
 self.Match(
     Succ: v => OptionUnsafe <A> .Some(v),
     Fail: _ => OptionUnsafe <A> .None);
Ejemplo n.º 15
0
 public static Task <Validation <FAIL, A> > ToValidation <A, FAIL>(this TryAsync <A> self, Func <Exception, FAIL> Fail) =>
 self.Match(
     Succ: v => Success <FAIL, A>(v),
     Fail: e => Fail <FAIL, A>(Fail(e)));
Ejemplo n.º 16
0
 public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> self, Func <T, IActionResult> succ = null, Func <Exception, IActionResult> fail = null) =>
 self.Match(Succ: succ ?? GetGenericSuccessResult, Fail: fail ?? GetGenericErrorResult);
Ejemplo n.º 17
0
 /// <summary>
 /// Success case is converted to 200 OK.
 /// Exception is converted to 500 Server Error.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="try"></param>
 /// <returns></returns>
 public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> @try) =>
 @try.Match(Ok, ServerError);
Ejemplo n.º 18
0
 public static Task <R> match <T, R>(TryAsync <T> self, Func <T, R> Succ, R Fail) =>
 self.Match(Succ, Fail);
Ejemplo n.º 19
0
 /// <summary>
 /// Pattern matches the two possible states of the TryAsync computation
 /// </summary>
 /// <typeparam name="T">Type of the bound value</typeparam>
 /// <param name="self">TryAsync computation</param>
 /// <param name="Succ">Delegate to invoke if the TryAsync computation completes successfully</param>
 /// <param name="Fail">Delegate to invoke if the TryAsync computation fails</param>
 public static Task <Unit> match <T>(TryAsync <T> self, Action <T> Succ, Action <Exception> Fail) =>
 self.Match(Succ, Fail);
Ejemplo n.º 20
0
 public TryAsync <B> Map(TryAsync <A> ma, Func <A, B> f) => () =>
 ma.Match(
     Succ: x => new Result <B>(f(x)),
     Fail: e => new Result <B>(e));
 /// <summary>
 /// Converts a <see cref="TryAsync{A}"/> to an <see cref="IActionResult"/>.
 /// Default success case conversion will convert units to NoContent and all other values to Ok.
 /// Default failure case conversion will convert exceptions to an InternalServerError.
 /// </summary>
 /// <typeparam name="A">The <see cref="TryAsync{A}"/> parameter type.</typeparam>
 /// <param name="this">The <see cref="TryAsync{A}"/> to convert to an <see cref="IActionResult"/>.</param>
 /// <param name="Succ">Optionally, a custom conversion for the success case.</param>
 /// <param name="Fail">Optionally, a custom conversion for the failure case.</param>
 /// <returns>An <see cref="IActionResult"/> which can be returned from a controller.</returns>
 public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> @this, Func <T, IActionResult> Succ = null, Func <Exception, IActionResult> Fail = null) =>
 @this.Match(Succ: Succ ?? GetGenericSuccessResult, Fail: Fail ?? GetGenericErrorResult);
Ejemplo n.º 22
0
 public static Task <Validation <Exception, A> > ToValidation <A>(this TryAsync <A> self) =>
 self.Match(
     Succ: v => Success <Exception, A>(v),
     Fail: e => Fail <Exception, A>(e));
Ejemplo n.º 23
0
 /// <summary>
 /// By default, Success case is converted to 200 OK and an Exception is converted to 500 Server Error.
 /// Optionally, provide mapping functions for Success and Exception.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="try"></param>
 /// <param name="success"></param>
 /// <param name="fail"></param>
 /// <returns></returns>
 public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> @try, Func <T, IActionResult> success = null, Func <Exception, IActionResult> fail = null) =>
 @try.Match(success ?? Ok, fail ?? ServerError);
Ejemplo n.º 24
0
 public static Task <IEnumerable <A> > AsEnumerable <A>(this TryAsync <A> self) =>
 self.Match(
     Succ: v => new A[1] {
     v
 }.AsEnumerable(),
     Fail: x => new A[0].AsEnumerable());
Ejemplo n.º 25
0
 public static Task <Seq <A> > AsEnumerable <A>(this TryAsync <A> self) =>
 self.Match(
     Succ: v => v.Cons(Empty),
     Fail: x => Empty);
Ejemplo n.º 26
0
 public Task <Unit> Fail(Action <Exception> f) =>
 value.Match(succHandler, f);
Ejemplo n.º 27
0
 public static Task <string> AsString <A>(this TryAsync <A> self) =>
 self.Match(
     Succ: v => isnull(v)
                   ? "Succ(null)"
                   : $"Succ({v})",
     Fail: ex => $"Fail({ex.Message})");
Ejemplo n.º 28
0
 public Task <B> Fail(Func <Exception, B> f) =>
 value.Match(succHandler, f);
Ejemplo n.º 29
0
 public TryAsync <B> BiMap(TryAsync <A> ma, Func <A, B> fa, Func <Unit, B> fb) => () =>
 ma.Match(
     Succ: x => new Result <B>(fa(x)),
     Fail: _ => new Result <B>(fb(unit)));
Ejemplo n.º 30
0
 /// <summary>
 /// By default, Success case is converted to 200 OK and an Exception is converted to 500 Server Error.
 ///
 /// Optional: provide mapping function for Success.
 /// Optional: provide action for Exception logging. Returns 500 Status Code with empty body.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="try"></param>
 /// <param name="success"></param>
 /// <param name="fail"></param>
 /// <returns></returns>
 public static Task <IActionResult> ToActionResult <T>(this TryAsync <T> @try, Func <T, IActionResult> success = null, Action <Exception> fail = null) =>
 @try.Match(success ?? Ok,
            Fail: e => ServerErrorWithLogging(e, fail));