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(); } }
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)); } }
public ValueTask <Pong> InvokeAsync(Ping request, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); return(ValueTask.FromResult(new Pong(request.AnyValue + request.AnyValue))); }
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));
/// <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());
private ValueTask <ItemsProviderResult <TItem> > EmptyItemsProvider <TItem>(ItemsProviderRequest request) => ValueTask.FromResult(new ItemsProviderResult <TItem>(Enumerable.Empty <TItem>(), 0));
public ValueTask <int> GetExecutedTimes() { return(ValueTask.FromResult(this.executedTimes)); }
#pragma warning disable CA1822 // Mark members as static public ValueTaskAwaiter <int> GetAwaiter() => ValueTask.FromResult <int>(0).GetAwaiter();
public ValueTask <Pong> InvokeAsync(Ping request, CancellationToken cancellationToken = default) { return(ValueTask.FromResult(new Pong(request.Value))); }
public ValueTask <List <AdminGrantedInTenant> > Handle(AdminAdded @event, CancellationToken ct) => ValueTask.FromResult(AdminStorage.TenantNames .Select(tenantName => new AdminGrantedInTenant(@event.FirstName, @event.LastName, tenantName) ) .ToList());
public ValueTask <bool> HasReadAccessAsync(string accessId, IPathElement item) => ValueTask.FromResult(true);
public ValueTask <AdminAdded> Handle(UserAdded @event, CancellationToken ct) => ValueTask.FromResult(new AdminAdded(@event.FirstName, @event.LastName));
public ValueTask <bool> Handle(UserAdded @event, CancellationToken ct) => ValueTask.FromResult(@event.IsAdmin);
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)); }
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))); }
public virtual ValueTask <IEnumerable <ActivityDisplayDescriptor> > GetDescriptorsAsync(CancellationToken cancellationToken = default) { var descriptors = GetDescriptors(); return(ValueTask.FromResult(descriptors)); }
public ValueTask <ReadOnlyMemory <byte> > ReadAsync(string path, long offset, int length) { return(ValueTask.FromResult(Read(path, offset, length))); }
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)); }
public ValueTask <SubSnapshot <long> > GetSnapshot() { return(ValueTask.FromResult(this.Snapshot)); }
public ValueTask <string> LoadAsync(TemplateContext context, SourceSpan callerSpan, string templatePath) => ValueTask.FromResult(Load(context, callerSpan, templatePath));
public ValueTask <bool> IsConcurrentHandle() { return(ValueTask.FromResult(this.ConcurrentHandle)); }
public ValueTask <IMultiplexedConnectionListener> BindAsync(EndPoint endpoint, IFeatureCollection features = null, CancellationToken cancellationToken = default) { OnBindAsync?.Invoke(endpoint, features); return(ValueTask.FromResult <IMultiplexedConnectionListener>(new MockMultiplexedConnectionListener(endpoint))); }
public static ValueTask <int> SynchronousValueTaskInt(int i) { return(ValueTask.FromResult(i)); }
public ValueTask <MultiplexedConnectionContext> AcceptAsync(IFeatureCollection features = null, CancellationToken cancellationToken = default) { return(ValueTask.FromResult <MultiplexedConnectionContext>(null)); }
/// <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);
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); }
public ValueTask <bool> CanProcessAsync(TargetInformation information) { var result = information.IsFlacFile() && information.HasFrontierLabsVorbisComment(); return(ValueTask.FromResult(result)); }
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))); }
public ValueTask <DbDataReader> ReaderExecutedAsync(DbCommand command, CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = new CancellationToken()) { return(ValueTask.FromResult(result)); }
/// <inheritdoc /> protected override ValueTask <PositiveTimeSpan> CalculateValueAsync() => TimeSpan .FromMilliseconds(2) .To(timespan => ValueTask.FromResult((PositiveTimeSpan)timespan));