public async void WithProxy() { var writer = new StringWriter(); var printer = Proxy.CreateProxy<HelloWorldPrinter>(async invocation => { await writer.WriteAsync("John says, \""); await invocation.Proceed(); await writer.WriteAsync("\""); return null; }); await printer.SayHello(writer); Assert.AreEqual("John says, \"Hello World!\"", writer.ToString()); }
public static async Task MiscWritesAsync() { var sw = new StringWriter(); await sw.WriteAsync('H'); await sw.WriteAsync(new char[] { 'e', 'l', 'l', 'o', ' ' }); await sw.WriteAsync("World!"); Assert.Equal("Hello World!", sw.ToString()); }
/// <summary> /// Formats the contents of an HTTP request or response body into a string. /// </summary> /// <param name="bodyStream"></param> /// <returns> /// The request or response body stream to use (must replace the current stream). /// </returns> private async Task<string> FormatBodyStreamAsync(Stream bodyStream) { if ((bodyStream == null) || !bodyStream.CanRead || !bodyStream.CanSeek) { return string.Empty; } // Creo un vettore di caratteri usato come buffer temporaneo. var buffer = new char[512]; // E' fondamentale che lo stream del body rimanga aperto. using (var bodyReader = new StreamReader(bodyStream, PortableEncoding.UTF8WithoutBOM, false, buffer.Length, true)) using (var psb = _stringBuilderPool.GetObject()) using (var stringWriter = new StringWriter(psb.StringBuilder, CultureInfo.InvariantCulture)) { // Riporto all'inizio la posizione dello stream per poterlo copiare in una stringa. bodyStream.Position = 0; // Avvio il ciclo di lettura a blocchi. var readIndex = 0; var readChars = 0; do { // Leggo un blocco di caratteri dallo stream. readChars = await bodyReader.ReadBlockAsync(buffer, 0, buffer.Length); readIndex += readChars; // Scrivo i caratteri letti. await stringWriter.WriteAsync(buffer, 0, readChars); } while (readChars == buffer.Length && readIndex < _settings.MaxLoggedBodyLength); // Riporto all'inizio la posizione dello stream per consentire agli altri di leggerlo. bodyStream.Position = 0; return stringWriter.ToString(); } }