public FlushAsync ( ) : System.Threading.Tasks.Task | ||
return | System.Threading.Tasks.Task |
public override async Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext) { using (stream) { Encoding encoding = SelectCharacterEncoding(content.Headers); using (var writer = new StreamWriter(stream, encoding)) { var individuals = value as IEnumerable<Individual>; if (individuals != null) { foreach (var individu in individuals) { await writer.WriteLineAsync(String.Format("{0,-10};{1,-10};{2,-10}", individu.Id, individu.FirstName, individu.LastName)); } await writer.FlushAsync(); } var individual = value as Individual; if (individual != null) { await writer.WriteLineAsync(String.Format("{0,-10};{1,-10};{2,-10}", individual.Id, individual.FirstName, individual.LastName)); await writer.FlushAsync(); } } } }
public async Task DoSomethingWithClientAsync() { try { using (var stream = _client.GetStream()) { using (var sr = new StreamReader(stream)) using (var sw = new StreamWriter(stream)) { await sw.WriteLineAsync("Hi. This is x2 TCP/IP easy-to-use server").ConfigureAwait(false); await sw.FlushAsync().ConfigureAwait(false); var data = default(string); while (!((data = await sr.ReadLineAsync().ConfigureAwait(false)).Equals("exit", StringComparison.OrdinalIgnoreCase))) { await sw.WriteLineAsync(data).ConfigureAwait(false); await sw.FlushAsync().ConfigureAwait(false); } } } } finally { if (_ownsClient && _client != null) { (_client as IDisposable).Dispose(); _client = null; } } }
private async void ClientWork(object state) { int clientId = (int)state; using (var channel = this.connection.ConnectChannel()) { using (StreamWriter writer = new StreamWriter(channel)) { using (StreamReader reader = new StreamReader(channel)) { string request = string.Format("Hello from {0}", clientId); string response; await writer.WriteLineAsync(request); await writer.FlushAsync(); response = await reader.ReadLineAsync(); await writer.WriteLineAsync(request); await writer.FlushAsync(); response = await reader.ReadLineAsync(); await channel.StopSendingAsync(); await channel.FlushAsync(); if (reader.EndOfStream) { Console.WriteLine("Client feel right!"); } } } } if (Interlocked.Decrement(ref pendingCount) == 0) { lock (termLock) { Monitor.Pulse(termLock); } } }
private static async Task WorkAsync(Channel channel) { using (channel) { using (var reader = new StreamReader(channel)) { using (var writer = new StreamWriter(channel)) { string request = await reader.ReadLineAsync(); await writer.WriteLineAsync(request); await writer.FlushAsync(); request = await reader.ReadLineAsync(); await writer.WriteLineAsync(request); await writer.FlushAsync(); Console.WriteLine("Server waiting for close"); if (reader.EndOfStream) { Console.WriteLine("Server feel right!"); } await channel.StopSendingAsync(); await channel.FlushAsync(); } } } }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { using (var writer = new StreamWriter(stream)) { await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n"); await writer.FlushAsync(); while (Connected) { try { var result = await manualResetEvent.WaitAsync(5000); if (Connected == false) return; if (result == false) { await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n"); await writer.FlushAsync(); if (lastMessageEnqueuedAndNotSent != null) { await SendMessage(lastMessageEnqueuedAndNotSent, writer); } continue; } manualResetEvent.Reset(); object message; while (msgs.TryDequeue(out message)) { if (CoolDownWithDataLossInMiliseconds > 0 && Environment.TickCount - lastMessageSentTick < CoolDownWithDataLossInMiliseconds) { lastMessageEnqueuedAndNotSent = message; continue; } await SendMessage(message, writer); } } catch (Exception e) { Connected = false; log.DebugException("Error when using events transport", e); Disconnected(); try { writer.WriteLine(e.ToString()); } catch (Exception) { // try to send the information to the client, okay if they don't get it // because they might have already disconnected } } } } }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { using (var writer = new StreamWriter(stream)) { await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n"); await writer.FlushAsync(); while (Connected) { try { var result = await manualResetEvent.WaitAsync(5000); if (Connected == false) return; if (result == false) { await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n"); await writer.FlushAsync(); continue; } manualResetEvent.Reset(); object message; while (msgs.TryDequeue(out message)) { var obj = JsonConvert.SerializeObject(message, Formatting.None, new EtagJsonConverter()); await writer.WriteAsync("data: "); await writer.WriteAsync(obj); await writer.WriteAsync("\r\n\r\n"); await writer.FlushAsync(); } } catch (Exception e) { Connected = false; log.DebugException("Error when using events transport", e); Disconnected(); try { writer.WriteLine(e.ToString()); } catch (Exception) { // try to send the information to the client, okay if they don't get it // because they might have already disconnected } } } } }
protected async Task Listen(Socket socket) { Stream ioStream = socket.GetStream(); StreamReader reader = new StreamReader(ioStream); StreamWriter writer = new StreamWriter(ioStream); await writer.WriteLineAsync(FtpResponse.PositiveCompletionReply.ServiceReady.ToString()); await writer.FlushAsync(); string command; while (true) { string result = await RunCommand(await reader.ReadLineAsync()); await writer.WriteLineAsync(result); await writer.FlushAsync(); } }
public HttpResponseMessage Get() { var resp = new HttpResponseMessage { Content = new PushStreamContent(async (respStream, content, context) => { try { var wordsToSend = Lipsum.Split(' '); using (var writer = new StreamWriter(respStream)) { foreach (var word in wordsToSend) { await writer.WriteLineAsync(word); await writer.FlushAsync(); await Task.Delay(millisecondsDelay: 250); } } } catch (Exception ex) { return; } finally { respStream.Close(); } }, "text/plain") }; return resp; }
public async Task WriteBody(StreamWriter writer) { _memoryStream.Position = 0; await writer.FlushAsync().ConfigureAwait(false); await _memoryStream.CopyToAsync(writer.BaseStream).ConfigureAwait(false); }
public override async Task Invoke(IOwinContext context) { // process response var owinResponse = new OwinResponse(context.Environment) { ContentType = "text/plain" }; var owinRequest = new OwinRequest(context.Environment); var writer = new StreamWriter(owinResponse.Body); switch (owinRequest.Path.Value) { case "/root/10mbTest.txt": writer.Write(TestHelpers.FileContent5bTest); owinResponse.ContentLength = TestHelpers.FileContent5bTest.Length; break; case "/root/simpleTest.txt": writer.Write(TestHelpers.FileContentSimpleTest); owinResponse.ContentLength = TestHelpers.FileContentSimpleTest.Length; break; case "/root/index.html": writer.Write(TestHelpers.FileContentIndex); owinResponse.ContentLength = TestHelpers.FileContentIndex.Length; break; case "/root/emptyFile.txt": writer.Write(TestHelpers.FileContentEmptyFile); owinResponse.ContentLength = TestHelpers.FileContentEmptyFile.Length; break; default: writer.Write(TestHelpers.FileContentAnyFile); owinResponse.ContentLength = TestHelpers.FileContentAnyFile.Length; break; } await writer.FlushAsync(); }
async Task<string> SendRPCAsync(string methodName, params object[] args) { var jsonArgs = new List<string>(); foreach(var arg in args) { if(arg is string) { jsonArgs.Add(String.Format("\"{0}\"", arg)); } else { jsonArgs.Add(arg.ToString()); } } var rpc = String.Format("{{\"id\": 1, \"method\": \"{0}\", \"params\": [{1}]}}", methodName, String.Join(", ", jsonArgs)); await ClientLock.WaitAsync(); try { var writer = new StreamWriter(ClientStream); await writer.WriteLineAsync(rpc); await writer.FlushAsync(); var reader = new StreamReader(ClientStream); return await reader.ReadLineAsync(); } finally { ClientLock.Release(); } }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { string jsonString = await JsonConvert.SerializeObjectAsync(this.JsonObject); StreamWriter writer = new StreamWriter(stream); await writer.WriteAsync(jsonString); await writer.FlushAsync(); }
public static async Task<bool> WriteTextIntoFileAsync(string text, StorageFile file) { try { if (file != null) { using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false)) { using (var writer = new StreamWriter(fileStream)) { fileStream.SetLength(0); // avoid leaving crap at the end if overwriting a file that was longer fileStream.Seek(0, SeekOrigin.Begin); await writer.WriteAsync(text).ConfigureAwait(false); await fileStream.FlushAsync(); await writer.FlushAsync(); return true; } } } } catch (Exception ex) { await Logger.AddAsync(ex.ToString(), Logger.FileErrorLogFilename).ConfigureAwait(false); } return false; }
private async Task SendServiceMessage(Message packet) { var command = packet.Json; try { using (var tcpClient = new TcpClient()) { await tcpClient.ConnectAsync(IPAddress.Loopback, 22005); using (var stream = tcpClient.GetStream()) using (var sw = new StreamWriter(stream, Encoding.UTF8)) { if (tcpClient.Connected) { await sw.WriteLineAsync(command); await sw.FlushAsync(); } } } } catch (Exception e) { Console.WriteLine(e.Message); } }
private static async Task<TokenResponse> RedeemRefreshTokenInternalAsync(OAuthAccount account) { HttpWebRequest request = WebRequest.CreateHttp(account.TokenService); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; var requestStream = await request.GetRequestStreamAsync(); var writer = new StreamWriter(requestStream); StringBuilder sb = new StringBuilder(); sb.AppendFormat("client_id={0}", Uri.EscapeDataString(account.ClientId)); sb.AppendFormat("&redirect_uri={0}", Uri.EscapeDataString(account.RedirectUri)); sb.AppendFormat("&client_secret={0}", Uri.EscapeDataString(account.ClientSecret)); sb.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(account.RefreshToken)); sb.Append("&grant_type=refresh_token"); if (null != account.Resource) sb.AppendFormat("&resource={0}", Uri.EscapeDataString(account.Resource)); var content = sb.ToString(); await writer.WriteAsync(content); await writer.FlushAsync(); var response = await request.GetResponseAsync() as HttpWebResponse; if (null != response && response.StatusCode == HttpStatusCode.OK) { var responseStream = response.GetResponseStream(); if (null != responseStream) { var reader = new StreamReader(responseStream); return JsonConvert.DeserializeObject<TokenResponse>(await reader.ReadToEndAsync()); } } return null; }
/// <summary> /// Показать ошибку на экране. /// </summary> /// <param name="ex">Ошибка.</param> /// <returns>Результат.</returns> public static async Task ShowError(Exception ex) { #if DEBUG #if LOG_ERROR_DEBUG try { if (ex != null) { var fld = await ApplicationData.Current.LocalFolder.CreateFolderAsync("error_log", CreationCollisionOption.OpenIfExists); var f = await fld.CreateFileAsync(Guid.NewGuid() + ".error"); using (var str = await f.OpenStreamForWriteAsync()) { using (var wr = new StreamWriter(str, Encoding.UTF8)) { await wr.WriteAsync(ex.ToString()); await wr.FlushAsync(); } } } } catch { } #endif #endif var dialog = new MessageDialog(ex?.Message ?? "", AppConstants.ErrorTitle); dialog.Commands.Add(new UICommand(AppConstants.OkButtonLabel, command => { })); dialog.Commands.Add(new UICommand(AppConstants.MoreInfoButtonLabel, async command => { await ShowFullError(ex); })); dialog.DefaultCommandIndex = 0; dialog.CancelCommandIndex = 0; await dialog.ShowAsync(); }
public async Task Save() { var roaming = ApplicationData.Current.RoamingFolder; if (Session != null) { var data = JsonConvert.SerializeObject(Session); var file = await roaming.CreateFileAsync("settings.json", CreationCollisionOption.ReplaceExisting); using (var stream = await file.OpenStreamForWriteAsync()) using (var writer = new StreamWriter(stream)) { await writer.WriteAsync(data); await writer.FlushAsync(); } } else { try { var file = await roaming.GetFileAsync("settings.json"); await file.DeleteAsync(); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } } }
public async Task<bool> InsertOrUpdate(KeyVaultConfiguration keyVaultConfiguration) { var writeToFile = JsonConvert.SerializeObject(keyVaultConfiguration); var filePath = Path.Combine( ConfigurationPath, keyVaultConfiguration.VaultName, string.Format(ConfigurationFileFormat, keyVaultConfiguration.VaultName)); var directoryPath = Path.Combine(ConfigurationPath, keyVaultConfiguration.VaultName); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } using (var file = File.Create(filePath)) { using (var streamWriter = new StreamWriter(file)) { await streamWriter.WriteAsync(writeToFile); await streamWriter.FlushAsync(); this.allConfigurations.Remove(keyVaultConfiguration); this.allConfigurations.Add(keyVaultConfiguration); return true; } } }
public static async Task SaveFileStringContentsAsync(string path, string contents) { using (StreamWriter writer = new StreamWriter(path, false)) { await writer.WriteAsync(contents); await writer.FlushAsync(); } }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { var json = JsonConvert.SerializeObject(_value, Formatting.Indented, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}); var writer = new StreamWriter(stream); writer.Write(json); await writer.FlushAsync(); }
private async Task SendMessage(object message, StreamWriter writer) { var o = JsonExtensions.ToJObject(message); await writer.WriteAsync("data: "); await writer.WriteAsync(o.ToString(Formatting.None)); await writer.WriteAsync("\r\n\r\n"); await writer.FlushAsync(); }
public static async Task WriteStringAsync(this WebSocket ws, String data, CancellationToken cancel) { using (var msg = ws.CreateMessageWriter(WebSocketMessageType.Text)) using (var writer = new StreamWriter(msg, Encoding.UTF8)) { writer.Write(data); await writer.FlushAsync().ConfigureAwait(false); } }
public async Task SendData(TcpClient client, string message) { NetworkStream stream = client.GetStream(); StreamWriter writer = new StreamWriter(stream); await writer.WriteLineAsync(message); await writer.FlushAsync(); Trace.TraceInformation("Sent data to client {0}: {1}", client.Client.RemoteEndPoint.ToString(), message); }
public async override Task WriteResponseBodyAsync(OutputFormatterContext context) { var itemType = context.DeclaredType.GetElementType() ?? context.DeclaredType.GetGenericArguments()[0]; using (var stringWriter = new StringWriter()) { stringWriter.WriteLine( string.Join<string>( ",", itemType.GetProperties().Select(x => x.Name) ) ); foreach (var obj in (IEnumerable<object>) context.Object) { var vals = obj.GetType().GetProperties().Select( pi => new { Value = pi.GetValue(obj, null) } ); var valueLine = string.Empty; string _val; foreach (var val in vals) { if (val.Value != null) { _val = val.Value.ToString(); //Check if the value contans a comma and place it in quotes if so if (_val.Contains(",")) _val = string.Concat("\"", _val, "\""); //Replace any \r or \n special characters from a new line with a space if (_val.Contains("\r")) _val = _val.Replace("\r", " "); if (_val.Contains("\n")) _val = _val.Replace("\n", " "); valueLine = string.Concat(valueLine, _val, ","); } else { valueLine = string.Concat(valueLine, ","); } } stringWriter.WriteLine(valueLine.TrimEnd(',')); } var writer = new StreamWriter(context.HttpContext.Response.Body); await writer.WriteAsync(stringWriter.ToString()); await writer.FlushAsync(); } }
public override async Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) { var json = _formatter.GetContext(_request, value); var writer = new StreamWriter(stream); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); content.Headers.TryAddWithoutValidation("x-template", _view); await writer.WriteAsync(json); await writer.FlushAsync(); return; }
// BCL Tcp Client public static async Task BclClient() { using (var client = new TcpClient()) { await client.ConnectAsync(Default.IPEndPoint); var stream = client.GetStream(); var sw = new StreamWriter(stream); await sw.WriteAsync("Hello World from BCL!"); await sw.FlushAsync(); } }
public async Task<ScriptResult> EvaluateAsync(string script, TimeSpan timeoutDuration) { if (string.IsNullOrWhiteSpace(script)) return null; var unusableName = _unusable.ExtractFirst(script); if (unusableName != null) { return new ScriptResult( state: ScriptState.Unusable, output: $"{unusableName} is unusable."); } using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms)) { Console.SetOut(sw); var watch = Stopwatch.StartNew(); var state = ScriptState.Failure; try { var returned = await EvaluateBaseAsync(script, timeoutDuration); if (returned != null) returned.Dump(); state = ScriptState.Success; } catch (OperationCanceledException ex) { Console.WriteLine(ex.Message); state = ScriptState.Timeout; } catch (Exception ex) { Console.WriteLine(ex.Message); } watch.Stop(); await sw.FlushAsync(); var output = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length).Trim(); if (string.IsNullOrEmpty(output)) { state = ScriptState.NoOutput; output = "Completed but no output."; } return new ScriptResult( state: state, output: output, elapsed: watch.Elapsed); } }
async Task WriteIFrameDataToStreamAsync(Stream writeStream, object value) { value = value ?? new object(); var writer = new StreamWriter(writeStream); await writer.WriteAsync( "<!DOCTYPE html>\n<html><body>" + JsonConvert.SerializeObject(value) + "</body></html>" ); await writer.FlushAsync(); }
static async Task IoBoundMethod(string path) { using (var stream = new FileStream(path, FileMode.OpenOrCreate)) using (var writer = new StreamWriter(stream)) { await writer.WriteLineAsync("Yehaa " + DateTime.Now); await writer.FlushAsync(); writer.Close(); stream.Close(); } }
private async void Send(string message) { if (socket == null || !socket.Connected) { return; } var writer = new StreamWriter(socket.GetStream()); await writer.WriteLineAsync(message); await writer.FlushAsync(); }
static int FlushAsync(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); System.IO.StreamWriter obj = (System.IO.StreamWriter)ToLua.CheckObject <System.IO.StreamWriter>(L, 1); System.Threading.Tasks.Task o = obj.FlushAsync(); ToLua.PushObject(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public async Task <byte[]> ToCsvAsync() { using var memoryStream = new System.IO.MemoryStream(); using var writer = new System.IO.StreamWriter(memoryStream); using var csv = new CsvHelper.CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture)); await csv .WriteRecordsAsync(await _schoolService.GetForExportAsync()); await csv.FlushAsync(); await writer.FlushAsync(); await memoryStream.FlushAsync(); return(memoryStream.ToArray()); }
public async Task SaveSvg(GraphicCanvas canvas, string name) { var path = GetPath(name, ".svg"); using (var s = OpenStream(path)) { if (s == null) { using (var ss = await Platforms.Current.OpenFileStreamForWritingAsync(path)) { using (var w = new System.IO.StreamWriter(ss)) { canvas.Graphic.WriteSvg(w); } } } else { var w = new System.IO.StreamWriter(s); canvas.Graphic.WriteSvg(w); await w.FlushAsync(); await CloseStream(s); } } }
private static async Task <U> MakeRequestAsync <T, U, EX>( string method, AuthenticationDetails auth, string path, NameValueCollection queryArguments, T payload, string baseUri, string contentType) where T : class where EX : ErrorResult { try { JsonSerializerSettings serialiserSettings = new JsonSerializerSettings(); serialiserSettings.NullValueHandling = NullValueHandling.Ignore; serialiserSettings.MissingMemberHandling = MissingMemberHandling.Ignore; serialiserSettings.Converters.Add(new EmailAddressConverter()); string uri = baseUri + path + NameValueCollectionExtension.ToQueryString(queryArguments); HttpClientHandler handler = new HttpClientHandler(); handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip; HttpClient client = new HttpClient(handler); if (auth != null) { if (auth is OAuthAuthenticationDetails) { OAuthAuthenticationDetails oauthDetails = auth as OAuthAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthDetails.AccessToken); } else if (auth is ApiKeyAuthenticationDetails) { ApiKeyAuthenticationDetails apiKeyDetails = auth as ApiKeyAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String( Encoding.GetEncoding(0).GetBytes(apiKeyDetails.ApiKey + ":x"))); } else if (auth is BasicAuthAuthenticationDetails) { BasicAuthAuthenticationDetails basicDetails = auth as BasicAuthAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String( Encoding.GetEncoding(0).GetBytes(basicDetails.Username + ":" + basicDetails.Password))); } } HttpContent content = null; HttpResponseMessage response = null; if (method != "GET") { Stream s = new MemoryStream(); Stream requestStream = new MemoryStream(); if (payload != null) { using (System.IO.StreamWriter os = new System.IO.StreamWriter(s)) { if (contentType == APPLICATION_FORM_URLENCODED_CONTENT_TYPE) { os.Write(payload); } else { string json = JsonConvert.SerializeObject(payload, Formatting.None, serialiserSettings); os.Write(json); } await os.FlushAsync(); s.Seek(0, SeekOrigin.Begin); await s.CopyToAsync(requestStream); os.Dispose(); } requestStream.Seek(0, SeekOrigin.Begin); content = new StreamContent(requestStream); response = await client.PostAsync(uri, content); } else { response = await client.PostAsync(uri, null); } } else { response = await client.GetAsync(uri); } if (response.IsSuccessStatusCode) { var resp = await response.Content.ReadAsStreamAsync(); if (resp == null) { return(default(U)); } { using (var sr = new System.IO.StreamReader(resp)) { var type = typeof(U); if (type.GetGenericTypeDefinition() == typeof(RateLimited <>)) { var responseType = type.GenericTypeArguments[0]; var result = JsonConvert.DeserializeObject(sr.ReadToEnd().Trim(), responseType, serialiserSettings); var status = new RateLimitStatus { Credit = response.Headers.Contains("X-RateLimit-Limit") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Limit").First()) : 0, Remaining = response.Headers.Contains("X-RateLimit-Remaining") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Remaining").First()) : 0, Reset = response.Headers.Contains("X-RateLimit-Reset") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Reset").First()) : 0 }; return((U)Activator.CreateInstance(type, result, status)); } return(JsonConvert.DeserializeObject <U>(sr.ReadToEnd().Trim(), serialiserSettings)); } } } else { switch (response.StatusCode) { case System.Net.HttpStatusCode.BadRequest: case System.Net.HttpStatusCode.Unauthorized: throw ThrowReworkedCustomException <EX>(response); case System.Net.HttpStatusCode.NotFound: default: throw new HttpRequestException(response.Content.ReadAsStringAsync().Result); } } } catch (Exception ex) { throw; } }