public RequestHandler <TRep> MakeRequestHandler(Uri baseUri, Router <TRep> router)
        {
            return(async(request, modelBinder) =>
            {
                var requestUri = new Uri(request.Uri.PathAndQuery.ToString(), UriKind.Relative);

                var path = new BaseUrlRelativePath(requestUri.ToString().Substring(baseUri.ToString().Length));
                var target = router(path);

                OneOf <Resource <TRep>, None> oneOf = (await target);
                return await oneOf.Match(
                    resource => resource.GetMethodHandler(request.Method)
                    .Match(
                        async handler =>
                {
                    var bindResult = await modelBinder(handler.Parameters);
                    var response = await bindResult.Match(
                        failed => Task.FromResult <Response <TRep> >(new Response <TRep> .ModelBindingFailedResponse()),
                        async boundModel => (await handler.Invoke(boundModel)).Match(
                            representation =>
                            (Response <TRep>) new Response <TRep> .RepresentationResponse(representation.Representation)
                            ));
                    return response;
                },
                        none => Task.FromResult((Response <TRep>) new Response <TRep> .MethodNotAllowed())),
                    none => Task.FromResult((Response <TRep>) new Response <TRep> .NotFoundResponse()));
            });
        }
示例#2
0
 private OneOf <string, int> Convert(OneOf <string, int> source)
 {
     return(source.Match <OneOf <string, int> >(
                (str) => int.Parse(str),
                (num) => num.ToString()
                ));
 }
示例#3
0
 public static OneOf <TSuccessNew, TError> ContinueOnSuccessWith <TSuccessOriginal, TError, TSuccessNew>(
     this OneOf <TSuccessOriginal, TError> original,
     Func <TSuccessOriginal, OneOf <TSuccessNew, TError> > continuation)
 {
     return(original.Match(
                originalSuccess => continuation(originalSuccess).Match <OneOf <TSuccessNew, TError> >(newSuccess => newSuccess, newError => newError),
                originalError => originalError));
 }
示例#4
0
        public void ReturnsDefaultWhenNoMatch()
        {
            var oo = new OneOf <int, string>(123);

            var ret = oo.Match((string x) => FailIfCalled <string>())
                      .Else((object x) => "ELSE:" + x.ToString());

            Assert.AreEqual("ELSE:123", ret);
        }
示例#5
0
        static async Task <Block> GetBlockAsync(RpcClient rpcClient, OneOf <uint, UInt256> id)
        {
            var task = id.Match(
                index => rpcClient.GetBlockHexAsync($"{index}"),
                hash => rpcClient.GetBlockHexAsync($"{hash}"));
            var hex = await task.ConfigureAwait(false);

            return(Convert.FromBase64String(hex).AsSerializable <Block>());
        }
示例#6
0
        public void ReturnsValueWhenMatch()
        {
            var oo = new OneOf <int, string>(123);

            var ret = oo.Match((string x) => FailIfCalled <string>())
                      .Match((int x) => "OK:" + x.ToString());

            Assert.AreEqual("OK:123", ret);
        }
示例#7
0
        public void MatchActionSelectsFirstCorrectly(string testStr)
        {
            OneOf <string, int, float> strEither = new OneOf <string, int, float>(testStr);

            strEither.Match(
                (str) => Assert.Equal(testStr, str),
                (i) => Assert.True(false, "second is matched, but first was expected"),
                (f) => Assert.True(false, "third is matched, but first was expected")
                );
        }
示例#8
0
        public void MatchActionSelectsSecondCorrectly()
        {
            int testInt = 5;

            OneOf <string, int, float> intEither = new OneOf <string, int, float>(testInt);

            intEither.Match(
                (str) => Assert.True(false, "first is matched, but second was expected"),
                (i) => Assert.Equal(testInt, i),
                (f) => Assert.True(false, "third is matched, but second was expected")
                );
        }
示例#9
0
        public void MatchActionSelectsThirdCorrectly()
        {
            float testFloat = 5;

            OneOf <string, int, float> intEither = new OneOf <string, int, float>(testFloat);

            intEither.Match(
                (str) => Assert.True(false, "first is matched, but third was expected"),
                (i) => Assert.True(false, "second is matched, but third was expected"),
                (f) => Assert.Equal(testFloat, f)
                );
        }
示例#10
0
 public static OneOf <TResult, TError> SelectMany <TSuccess1, TSuccess2, TError, TResult>(
     this OneOf <TSuccess1, TError> source,
     Func <TSuccess1, OneOf <TSuccess2, TError> > selector,
     Func <TSuccess1, TSuccess2, TResult> resultSelector)
 {
     return(source.Match(
                sourceSuccess =>
                selector(sourceSuccess).Match <OneOf <TResult, TError> >(
                    secondSuccess => resultSelector(sourceSuccess, secondSuccess),
                    error => error),
                error => error));
 }
示例#11
0
        public void ThrowsExceptionWhenNoMatch()
        {
            var oo = new OneOf <int, string>(123);

            TestDelegate test = () =>
            {
                var ret = oo
                          .Match((string x) => FailIfCalled <string>())
                          .ElseThrow((object x) => new InvalidOperationException());
            };

            NUnit.Framework.Assert.Throws <InvalidOperationException>(test);
        }
示例#12
0
        public async Task ExecuteResultAsync(ActionContext context)
        {
            context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
            context.HttpContext.Response.Headers.Add(HeaderNames.ContentType, "text/csv");
            context.HttpContext.Response.Headers.Add(
                HeaderNames.ContentDisposition,
                new ContentDispositionHeaderValue("attachment")
            {
                FileName = _fileName
            }.ToString());

            await using (var stream = context.HttpContext.Response.Body)
                await using (var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)))
                    await using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
                    {
                        csvWriter.WriteHeader <T>();
                        await csvWriter.NextRecordAsync();

                        await writer.FlushAsync();

                        await _records.Match(
                            async records =>
                        {
                            foreach (var record in records)
                            {
                                await WriteRecord(record);
                            }
                        },
                            async records =>
                        {
                            await foreach (var record in records)
                            {
                                await WriteRecord(record);
                            }
                        });

                        async Task WriteRecord(T record)
                        {
                            csvWriter.WriteRecord(record);
                            await csvWriter.NextRecordAsync();

                            await writer.FlushAsync();
                        }
                    }
        }
示例#13
0
            public async ValueTask <bool> MoveNextAsync()
            {
                if (!_pageInfo.HasNextPage)
                {
                    return(false);
                }

                Current = await NyaaSiService.SearchAsync(_request);

                if (Current.Match((IAniListError error) => true)
                    .Match(data => data.PageInfo?.HasNextPage != true))
                {
                    return(false);
                }

                _request.PageNumber += 1;
                Current.Switch(result => _pageInfo.HasNextPage = result.PageInfo.HasNextPage = result.Data.Count >= 75);

                return(true);
            }
示例#14
0
        static void AtomicUpdate(ref TrackingMap trackingMap, byte[]?key, OneOf <byte[]?, None> value)
        {
            key = key == null?Array.Empty <byte>() : key.AsSpan().ToArray();

            var _value = value.Match <OneOf <ReadOnlyMemory <byte>, None> >(
                v => v == null ? default(ReadOnlyMemory <byte>) : v.AsSpan().ToArray(),
                n => n);

            var priorCollection = Volatile.Read(ref trackingMap);

            do
            {
                var updatedCollection = priorCollection.SetItem(key, _value);
                var interlockedResult = Interlocked.CompareExchange(ref trackingMap, updatedCollection, priorCollection);
                if (object.ReferenceEquals(priorCollection, interlockedResult))
                {
                    break;
                }
                priorCollection = interlockedResult;
            }while (true);
        }
示例#15
0
        public IActionResult Get(int id)
        {
            OneOf <Product, NotFound, SystemError> result = GetProject(id);

            return(result.Match <IActionResult>(
                       product =>
            {
                _logger.LogInformation("查询成功");
                return new JsonResult(product);
            },
                       notfound =>
            {
                _logger.LogInformation("没有查到");
                return new NotFoundResult();
            },
                       systemerror =>
            {
                _logger.LogError("查询成败");
                return new StatusCodeResult(500);
            }));
        }
            public async ValueTask <bool> MoveNextAsync()
            {
                if (_info.Remaining == false)
                {
                    return(false);
                }

                var pageResult = await _source._getPage(_info, default);

                Current = pageResult;

                if (Current.Match((IAniListError error) => true)
                    .Match(data => (data.PageInfo?.CurrentPage ?? 0) == 0))
                {
                    return(false);
                }

                _info.Page++;
                _info.Remaining = _source._nextPage(_info, Current);

                return(true);
            }
示例#17
0
 public static OneOf <TSuccessNew, TError> Select <TSuccessOriginal, TSuccessNew, TError>(
     this OneOf <TSuccessOriginal, TError> source,
     Func <TSuccessOriginal, TSuccessNew> projection)
 {
     return(source.Match <OneOf <TSuccessNew, TError> >(success => projection(success), error => error));
 }
示例#18
0
 public static OneOf <TSuccess, TErrorNew> SelectError <TSuccess, TErrorOriginal, TErrorNew>(
     this OneOf <TSuccess, TErrorOriginal> source,
     Func <TErrorOriginal, TErrorNew> projection)
 {
     return(source.Match <OneOf <TSuccess, TErrorNew> >(success => success, error => projection(error)));
 }
示例#19
0
 public static ExecutableAction From(OneOf <ActionDefinition, ContextActionDefinition, ContextDataActionDefinition> actionDefinition) =>
 actionDefinition.Match(From, From, From);
示例#20
0
 public static SubmissionResult Map(
     OneOf <int, IReadOnlyList <ChallengeResult>, IReadOnlyList <CompileErrorMessage> > o) =>
 o.Match(
     score => new SubmissionResult(score, null, null),
     runErrors => new SubmissionResult(null, null, runErrors),
     compileErrors => new SubmissionResult(null, compileErrors, null));
示例#21
0
 private static bool HasNextPage <T>(PagingInfo info, OneOf <IPagedData <T>, IAniListError> data) => data.Match((IAniListError error) => false)
 .Match(pagedData => pagedData?.PageInfo?.HasNextPage == true);
示例#22
0
 public T Match <T>(Func <TimeSpan, T> matchFunc, Func <string, T> matchFunc2, Func <T> defaultFunc)
 => _input3.Match(matchFunc, matchFunc2);
示例#23
0
 public T Match <T>(Func <int, T> matchFunc, Func <string, T> matchFunc2)
 => _input1.Match(matchFunc, matchFunc2);
示例#24
0
 public void DefaultConstructorSetsValueToDefaultValueOfT0()
 {
     var x      = new OneOf <int, bool>();
     var result = x.Match(n => n == default(int), n => false);
 }
示例#25
0
 public static OneOf <TSuccess, TError> Flatten <TSuccess, TError>(this OneOf <OneOf <TSuccess, TError>, TError> source)
 {
     return(source.Match(inner => inner.Match <OneOf <TSuccess, TError> >(success => success, error => error), error => error));
 }
示例#26
0
 public static T Bifold <T>(this OneOf <T, T> source)
 {
     return(source.Match(success => success, error => error));
 }
示例#27
0
 private static string ToString(OneOf <Result <MetaData>, Error> r)
 {
     return(r.Match(a => a.results.Single().provider.display_name, e => e.error));
 }