コード例 #1
0
        public async Task ZeroByteRead_IssuesZeroByteReadOnUnderlyingStream(StreamConformanceTests.ReadWriteMode readMode, bool useSsl)
        {
            (Stream httpConnection, Stream server) = ConnectedStreams.CreateBidirectional(4096, int.MaxValue);
            try
            {
                var sawZeroByteRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);

                httpConnection = new ReadInterceptStream(httpConnection, read =>
                {
                    if (read == 0)
                    {
                        sawZeroByteRead.TrySetResult();
                    }
                });

                using var handler = new SocketsHttpHandler
                      {
                          ConnectCallback = delegate { return(ValueTask.FromResult(httpConnection)); }
                      };
                handler.SslOptions.RemoteCertificateValidationCallback = delegate { return(true); };

                using var client = new HttpClient(handler);

                Task <HttpResponseMessage> clientTask = client.GetAsync($"http{(useSsl ? "s" : "")}://doesntmatter", HttpCompletionOption.ResponseHeadersRead);

                if (useSsl)
                {
                    var sslStream = new SslStream(server, false, delegate { return(true); });
                    server = sslStream;

                    using (X509Certificate2 cert = Test.Common.Configuration.Certificates.GetServerCertificate())
                    {
                        await((SslStream)server).AuthenticateAsServerAsync(
                            cert,
                            clientCertificateRequired: true,
                            enabledSslProtocols: SslProtocols.Tls12,
                            checkCertificateRevocation: false).WaitAsync(TimeSpan.FromSeconds(10));
                    }
                }

                await ResponseConnectedStreamConformanceTests.ReadHeadersAsync(server).WaitAsync(TimeSpan.FromSeconds(10));

                await server.WriteAsync(Encoding.ASCII.GetBytes(GetResponseHeaders()));

                using HttpResponseMessage response = await clientTask.WaitAsync(TimeSpan.FromSeconds(10));

                using Stream clientStream = response.Content.ReadAsStream();
                Assert.False(sawZeroByteRead.Task.IsCompleted);

                Task <int> zeroByteReadTask = Task.Run(() => StreamConformanceTests.ReadAsync(readMode, clientStream, Array.Empty <byte>(), 0, 0, CancellationToken.None));
                Assert.False(zeroByteReadTask.IsCompleted);

                // The zero-byte read should block until data is actually available
                await sawZeroByteRead.Task.WaitAsync(TimeSpan.FromSeconds(10));

                Assert.False(zeroByteReadTask.IsCompleted);

                byte[] data = "Hello" u8.ToArray();
                await WriteAsync(server, data);

                await server.FlushAsync();

                Assert.Equal(0, await zeroByteReadTask.WaitAsync(TimeSpan.FromSeconds(10)));

                // Now that data is available, a zero-byte read should complete synchronously
                zeroByteReadTask = StreamConformanceTests.ReadAsync(readMode, clientStream, Array.Empty <byte>(), 0, 0, CancellationToken.None);
                Assert.True(zeroByteReadTask.IsCompleted);
                Assert.Equal(0, await zeroByteReadTask);

                var readBuffer = new byte[10];
                int read       = 0;
                while (read < data.Length)
                {
                    read += await StreamConformanceTests.ReadAsync(readMode, clientStream, readBuffer, read, readBuffer.Length - read, CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10));
                }

                Assert.Equal(data.Length, read);
                Assert.Equal(data, readBuffer.AsSpan(0, read).ToArray());
            }
            finally
            {
                httpConnection.Dispose();
                server.Dispose();
            }
        }
コード例 #2
0
        public static ValueTask <int> MudAddEventListenerAsync <T>(this ElementReference elementReference, DotNetObjectReference <T> dotnet, string @event, string callback, bool stopPropagation = false) where T : class
        {
            var parameters = dotnet?.Value.GetType().GetMethods().First(m => m.Name == callback).GetParameters().Select(p => p.ParameterType);

            if (parameters != null)
            {
                var parameterSpecs = new object[parameters.Count()];
                for (var i = 0; i < parameters.Count(); ++i)
                {
                    parameterSpecs[i] = GetSerializationSpec(parameters.ElementAt(i));
                }
                return(elementReference.GetJSRuntime()?.InvokeAsync <int>("mudElementRef.addEventListener", elementReference, dotnet, @event, callback, parameterSpecs, stopPropagation) ?? ValueTask.FromResult(0));
            }
            else
            {
                return(new ValueTask <int>(0));
            }
        }
コード例 #3
0
 public ValueTask <Pong> InvokeAsync(Ping request, CancellationToken cancellationToken = default)
 {
     cancellationToken.ThrowIfCancellationRequested();
     return(ValueTask.FromResult(new Pong(request.AnyValue + request.AnyValue)));
 }
コード例 #4
0
 public static async ValueTask <Optional <T> > Asynchronous <T>(Optional <ValueTask <T> > maybeTask)
 => await maybeTask.IfPresent(
     async task => Optional.Maybe(await task),
     () => ValueTask.FromResult(Optional <T> .Nothing));
コード例 #5
0
 /// <summary>
 /// Gets the client rect of the first child of the element.
 /// Useful when you want to know the dimensions of a render fragment and for that you wrap it into a div
 /// </summary>
 public static ValueTask <BoundingClientRect> MudGetClientRectFromFirstChildAsync(this ElementReference elementReference) =>
 elementReference.GetJSRuntime()?.InvokeAsync <BoundingClientRect>("mudElementRef.getClientRectFromFirstChild", elementReference) ?? ValueTask.FromResult(new BoundingClientRect());
コード例 #6
0
 private ValueTask <ItemsProviderResult <TItem> > EmptyItemsProvider <TItem>(ItemsProviderRequest request)
 => ValueTask.FromResult(new ItemsProviderResult <TItem>(Enumerable.Empty <TItem>(), 0));
コード例 #7
0
 public ValueTask <int> GetExecutedTimes()
 {
     return(ValueTask.FromResult(this.executedTimes));
 }
コード例 #8
0
#pragma warning disable CA1822 // Mark members as static
        public ValueTaskAwaiter <int> GetAwaiter() => ValueTask.FromResult <int>(0).GetAwaiter();
コード例 #9
0
 public ValueTask <Pong> InvokeAsync(Ping request, CancellationToken cancellationToken = default)
 {
     return(ValueTask.FromResult(new Pong(request.Value)));
 }
コード例 #10
0
 public ValueTask <List <AdminGrantedInTenant> > Handle(AdminAdded @event, CancellationToken ct) =>
 ValueTask.FromResult(AdminStorage.TenantNames
                      .Select(tenantName =>
                              new AdminGrantedInTenant(@event.FirstName, @event.LastName, tenantName)
                              )
                      .ToList());
コード例 #11
0
 public ValueTask <bool> HasReadAccessAsync(string accessId, IPathElement item) => ValueTask.FromResult(true);
コード例 #12
0
 public ValueTask <AdminAdded> Handle(UserAdded @event, CancellationToken ct) =>
 ValueTask.FromResult(new AdminAdded(@event.FirstName, @event.LastName));
コード例 #13
0
 public ValueTask <bool> Handle(UserAdded @event, CancellationToken ct) =>
 ValueTask.FromResult(@event.IsAdmin);
コード例 #14
0
 ValueTask <ClaimsIdentity> IAuthenticator.IssueAsync(object identifier, string scenario, IDictionary <string, object> parameters, CancellationToken cancellation)
 {
     return(identifier == null?ValueTask.FromResult <ClaimsIdentity>(null) : this.IssueAsync(identifier.ToString(), scenario, parameters, cancellation));
 }
コード例 #15
0
        public ValueTask <T> DeserializeAsync <T>(byte[] data, CancellationToken cancellationToken = default)
        {
            var json = Encoding.UTF8.GetString(data);

            return(ValueTask.FromResult(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(json, Settings)));
        }
コード例 #16
0
        public virtual ValueTask <IEnumerable <ActivityDisplayDescriptor> > GetDescriptorsAsync(CancellationToken cancellationToken = default)
        {
            var descriptors = GetDescriptors();

            return(ValueTask.FromResult(descriptors));
        }
コード例 #17
0
 public ValueTask <ReadOnlyMemory <byte> > ReadAsync(string path, long offset, int length)
 {
     return(ValueTask.FromResult(Read(path, offset, length)));
 }
コード例 #18
0
        public override ValueTask <RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
        {
            if (MixService.GetAppSetting <bool>(MixAppSettingKeywords.IsInit))
            {
                return(ValueTask.FromResult(values));
            }

            RouteValueDictionary result = values;

            var keys = values.Keys.ToList();

            var language = (string)values[keys[0]];
            var keyIndex = 1;

            if (!MixService.Instance.CheckValidCulture(language))
            {
                language  = MixService.GetAppSetting <string>(MixAppSettingKeywords.DefaultCulture);
                keyIndex -= 1;
            }

            var path = string.Join('/', values.Values.Skip(keyIndex));

            if (MixService.Instance.CheckValidAlias(language, path))
            {
                result["controller"] = "home";
                result["culture"]    = language;
                result["action"]     = "Index";
                result["seoName"]    = path;
                return(ValueTask.FromResult(result));
            }


            string notTransformPattern = @"^(.*)\.(xml|json|html|css|js|map|jpg|png|gif|jpeg|svg|map|ico|webmanifest|woff|woff2|ttf|eot)$";
            Regex  reg = new Regex(notTransformPattern);

            if (reg.IsMatch(httpContext.Request.Path.Value))
            {
                return(ValueTask.FromResult(values));
            }

            var currentController = GetRouteValue(values, keys, ref keyIndex);
            var controller        = MixService.Translate(currentController, language, currentController);

            if (!IsValidController(controller))
            {
                controller           = "home";
                keyIndex            -= 1;
                result["keyword"]    = keyIndex < keys.Count ? string.Join('/', values.Values.Skip(keyIndex + 1)) : string.Empty;
                result["seoName"]    = keys.Count > keyIndex ? (string)values[keys[keyIndex]] : string.Empty;
                result["culture"]    = language;
                result["action"]     = "Index";
                result["controller"] = controller;
            }
            else
            {
                if (keys.Count > 2)
                {
                    result["id"] = GetRouteValue(values, keys, ref keyIndex);
                }
                result["controller"] = controller;
                result["keyword"]    = GetRouteValue(values, keys, ref keyIndex);
            }
            result["action"] = "Index";

            return(ValueTask.FromResult(result));
        }
コード例 #19
0
 public ValueTask <SubSnapshot <long> > GetSnapshot()
 {
     return(ValueTask.FromResult(this.Snapshot));
 }
コード例 #20
0
 public ValueTask <string> LoadAsync(TemplateContext context, SourceSpan callerSpan, string templatePath)
 => ValueTask.FromResult(Load(context, callerSpan, templatePath));
コード例 #21
0
 public ValueTask <bool> IsConcurrentHandle()
 {
     return(ValueTask.FromResult(this.ConcurrentHandle));
 }
コード例 #22
0
        public ValueTask <IMultiplexedConnectionListener> BindAsync(EndPoint endpoint, IFeatureCollection features = null, CancellationToken cancellationToken = default)
        {
            OnBindAsync?.Invoke(endpoint, features);

            return(ValueTask.FromResult <IMultiplexedConnectionListener>(new MockMultiplexedConnectionListener(endpoint)));
        }
コード例 #23
0
ファイル: HelperMarshal.cs プロジェクト: pedrobsaila/runtime
 public static ValueTask <int> SynchronousValueTaskInt(int i)
 {
     return(ValueTask.FromResult(i));
 }
コード例 #24
0
 public ValueTask <MultiplexedConnectionContext> AcceptAsync(IFeatureCollection features = null, CancellationToken cancellationToken = default)
 {
     return(ValueTask.FromResult <MultiplexedConnectionContext>(null));
 }
コード例 #25
0
 /// <summary>
 /// Returns true if the element has an ancestor with style position == "fixed"
 /// </summary>
 /// <param name="elementReference"></param>
 public static ValueTask <bool> MudHasFixedAncestorsAsync(this ElementReference elementReference) =>
 elementReference.GetJSRuntime()?
 .InvokeAsync <bool>("mudElementRef.hasFixedAncestors", elementReference) ?? ValueTask.FromResult(false);
コード例 #26
0
    public void ShallowCopyHttpConnectionOptionsCopiesAllPublicProperties()
    {
        Func <HttpMessageHandler, HttpMessageHandler> handlerFactory = handler => handler;
        Func <Task <string> > tokenProvider = () => Task.FromResult("");
        Func <WebSocketConnectionContext, CancellationToken, ValueTask <WebSocket> > webSocketFactory = (context, token) => ValueTask.FromResult <WebSocket>(null);
        Action <ClientWebSocketOptions> webSocketConfig = options => { };

        var testValues = new Dictionary <string, object>
        {
            { $"{nameof(HttpConnectionOptions.HttpMessageHandlerFactory)}", handlerFactory },
            { $"{nameof(HttpConnectionOptions.Headers)}", new Dictionary <string, string>() },
            { $"{nameof(HttpConnectionOptions.ClientCertificates)}", new X509CertificateCollection() },
            { $"{nameof(HttpConnectionOptions.Cookies)}", new CookieContainer() },
            { $"{nameof(HttpConnectionOptions.Url)}", new Uri("https://example.com") },
            { $"{nameof(HttpConnectionOptions.Transports)}", HttpTransportType.ServerSentEvents },
            { $"{nameof(HttpConnectionOptions.SkipNegotiation)}", true },
            { $"{nameof(HttpConnectionOptions.AccessTokenProvider)}", tokenProvider },
            { $"{nameof(HttpConnectionOptions.CloseTimeout)}", TimeSpan.FromDays(1) },
            { $"{nameof(HttpConnectionOptions.Credentials)}", Mock.Of <ICredentials>() },
            { $"{nameof(HttpConnectionOptions.Proxy)}", Mock.Of <IWebProxy>() },
            { $"{nameof(HttpConnectionOptions.UseDefaultCredentials)}", true },
            { $"{nameof(HttpConnectionOptions.DefaultTransferFormat)}", TransferFormat.Text },
            { $"{nameof(HttpConnectionOptions.WebSocketConfiguration)}", webSocketConfig },
            { $"{nameof(HttpConnectionOptions.WebSocketFactory)}", webSocketFactory },
            { $"{nameof(HttpConnectionOptions.ApplicationMaxBufferSize)}", 1L * 1024 * 1024 },
            { $"{nameof(HttpConnectionOptions.TransportMaxBufferSize)}", 1L * 1024 * 1024 },
        };

        var options    = new HttpConnectionOptions();
        var properties = typeof(HttpConnectionOptions)
                         .GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var property in properties)
        {
            property.SetValue(options, testValues[property.Name]);
        }

        var shallowCopiedOptions = HttpConnectionFactory.ShallowCopyHttpConnectionOptions(options);

        foreach (var property in properties)
        {
            Assert.Equal(testValues[property.Name], property.GetValue(shallowCopiedOptions));
            testValues.Remove(property.Name);
        }

        Assert.Empty(testValues);
    }
コード例 #27
0
        public ValueTask <bool> CanProcessAsync(TargetInformation information)
        {
            var result = information.IsFlacFile() && information.HasFrontierLabsVorbisComment();

            return(ValueTask.FromResult(result));
        }
コード例 #28
0
        public ValueTask <byte[]> SerializeAsync <T>(T state, CancellationToken cancellationToken = default)
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(state, Settings);

            return(ValueTask.FromResult(Encoding.UTF8.GetBytes(json)));
        }
コード例 #29
0
 public ValueTask <DbDataReader> ReaderExecutedAsync(DbCommand command, CommandExecutedEventData eventData,
                                                     DbDataReader result,
                                                     CancellationToken cancellationToken = new CancellationToken())
 {
     return(ValueTask.FromResult(result));
 }
コード例 #30
0
 /// <inheritdoc />
 protected override ValueTask <PositiveTimeSpan> CalculateValueAsync()
 => TimeSpan
 .FromMilliseconds(2)
 .To(timespan => ValueTask.FromResult((PositiveTimeSpan)timespan));