WriteLineAsync() public method

public WriteLineAsync ( ) : System.Threading.Tasks.Task
return System.Threading.Tasks.Task
        // чтение данных из текстового файла
        private void ReadDaysFromDatabase()
        {
            try
            {
                using (var reader = new StreamReader(Environment.CurrentDirectory + DataFile))
                {
                    uint allBudget, costsCount;
                    UInt32.TryParse(reader.ReadLine(), out allBudget);
                    UInt32.TryParse(reader.ReadLine(), out costsCount);
                    _allBudget = allBudget;
                    for (var i = 0; i < costsCount; i++)
                    {
                        var costsString = reader.ReadLine();
                        var date = reader.ReadLine();

                        uint costs;
                        UInt32.TryParse(costsString, out costs);
                        _days.Add(new Day(DateTime.Parse(date), costs));
                    }
                }
            }
            catch (Exception)
            {
                // файл с данными не существует - создадим его
                using (var writer = new StreamWriter(Environment.CurrentDirectory + DataFile))
                {
                    // бюждет - незвестен
                    // кол-во трат - неизвестно
                    writer.WriteLineAsync("0");
                    writer.WriteLineAsync("0");
                }
            }
        }
 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();
             }
         }
     }
 }
Example #3
0
        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();
                    }
                }
            }
        }
Example #4
0
        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);
                }
            }
        }
Example #5
0
        public static async Task ReadOutChannels(XmlTvReader reader, StreamWriter resultsFileStream)
        {
            var channels = reader.GetChannels().Distinct().ToList();

            resultsFileStream.Write(EntityExtensions.GetHeader("Channels"));

            foreach (var channel in channels)
            {
                System.Console.WriteLine("Retrieved Channel: {0} - {1}", channel.Id, channel.DisplayName);
                resultsFileStream.Write(channel.GetChannelDetail());
            }

            var totalProgrammeCount = 0;

            resultsFileStream.Write("\r\n");
            foreach (var channel in channels)
            {
                System.Console.WriteLine("Processing Channel: {0}", channel.DisplayName);

                resultsFileStream.Write(EntityExtensions.GetHeader("Programs for " + channel.DisplayName));
                var channelProgrammeCount = await ReadOutChannelProgrammes(reader, channel, resultsFileStream);

                totalProgrammeCount += channelProgrammeCount;
                await resultsFileStream.WriteLineAsync(String.Format("Total Programmes for {1}: {0}", channelProgrammeCount, channel.DisplayName));
            }

            await resultsFileStream.WriteLineAsync(String.Format("Total Programmes: {0}", totalProgrammeCount));
        }
        public async Task Save(string path, BlackHoleGameTable gameTable)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(path))
                {
                    // save the game status and details
                    writer.Write(gameTable.TableSize + " ");
                    await writer.WriteAsync(gameTable.GameStatus + " ");
                    await writer.WriteAsync(gameTable.CoordinatesOfChosenField.Item1 + " " + gameTable.CoordinatesOfChosenField.Item2 + " ");
                    await writer.WriteAsync(gameTable.IsGameActive + " ");
                    await writer.WriteAsync(gameTable.PlayerAScore + " ");
                    await writer.WriteAsync(gameTable.PlayerBScore + "");

                    // save the game table values
                    await writer.WriteLineAsync();
                    for (Int32 row = 0; row < gameTable.TableSize; ++row)
                    {
                        for (Int32 column = 0; column < gameTable.TableSize; ++column)
                        {
                            await writer.WriteAsync(gameTable[row, column] + " ");
                        }
                        await writer.WriteLineAsync();
                    }
                }
            }
            catch
            {
                throw new BlackHoleGameDataException("Save file path is wrong.");
            }
        }
	    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;
		            }
		        }
		}
        public static async Task WriteTo(IHttpHeaders headers, Stream stream)
        {
#if PCL && !ASYNC_PCL
            var writer = new StreamWriter(new NonDisposableStream(stream), Encoding.UTF8, 128);
#else
            var writer = new StreamWriter(stream, Encoding.UTF8, 128, true);
#endif
            try
            {
                writer.NewLine = "\r\n";

                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        await
                            writer.WriteLineAsync($"{header.Key}: {string.Join(", ", header.Value)}");
                    }
                }

                await writer.WriteLineAsync();
            }
            finally
            {
                writer.Dispose();
            }
        }
        private async Task ProcessQueue(string queue)
        {
            try
            {
                var events = MessageQueue.GetBatch<PerfEvent>(queue)
                    .ToList();

                // Group by hour
                var groups = events.GroupBy(e => new { e.TimestampUtc.Date, e.TimestampUtc.Hour });

                await Task.WhenAll(groups.Select(async group =>
                {
                    if (group.Any())
                    {
                        string dir = Path.Combine(LogDirectory, queue);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        // Determine the file name for the log
                        string fileName = Path.Combine(
                            dir,
                            String.Format("{0:yyyyMMdd}{1}.csv", group.Key.Date, group.Key.Hour));

                        // Append to the log
                        using (var strm = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None))
                        using (var writer = new StreamWriter(strm))
                        {
                            foreach (var evt in group)
                            {
                                var fields = evt.Fields.OrderBy(p => p.Key);
                                if (strm.Length == 0)
                                {
                                    await writer.WriteLineAsync(
                                        "Source,Timestamp,Duration," + String.Join(",", fields.Select(f => f.Key)));
                                    await writer.FlushAsync();
                                }
                                await writer.WriteLineAsync(
                                    CsvEscape(evt.Source) + "," +
                                    CsvEscape(evt.TimestampUtc.ToString("O")) + "," + 
                                    CsvEscape(evt.Duration.TotalMilliseconds.ToString("0.00")) + "," + 
                                    String.Join(",", fields.Select(f => CsvEscape(f.Value == null ? String.Empty : f.Value.ToString()))));
                            }
                        }
                    }
                }));
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #10
0
 public static async void LogUnhandledException(Exception e)
 {
     var logsFolder = await ApplicationData.Current.LocalFolder
         .CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists);
     var file = await logsFolder.CreateFileAsync(String.Format("{0}.log", DateTime.Now.Ticks));
     var stream = await file.OpenStreamForWriteAsync();
     using (var writer = new StreamWriter(stream))
     {
         await writer.WriteLineAsync(e.Message);
         if (e.StackTrace != null)
             await writer.WriteLineAsync(e.StackTrace);
     }
 }
Example #11
0
        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 async Task Invoke(IDictionary<string, object> environment)
 {
     var response = environment["owin.ResponseBody"] as Stream;
     using (var writer = new StreamWriter(response))
     {
         await writer.WriteLineAsync(string.Format("Demo Component!", _options.Name));
         foreach (var option in _options.MoreOptions)
         {
             _next.Invoke(environment);
             Console.WriteLine("I hope this works");
             await writer.WriteLineAsync(string.Format("Option: {0}", option));                    
         }
     }
 }
Example #13
0
 public static void LogError(string error)
 {
     string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
     if (appPath != null)
     {
         string configFile = Path.Combine(appPath, "errorlogs.txt");
         var file = new StreamWriter(configFile, true);
         file.WriteLineAsync("-----------------");
         file.WriteLine(error);
         file.WriteLineAsync("---------------------");
         file.Close();
         Console.WriteLine("Error=>{0}", error);
     }
 }
 public async Task Invoke(IDictionary<string, object> environment)
 {
     var response = environment["owin.ResponseBody"] as Stream;
     if (response != null)
         using (var writer = new StreamWriter(response))
         {
             await writer.WriteLineAsync(string.Format("Hello {0}!", _options.Name));
             foreach (var option in _options.MoreOptions)
             {
                 //_next.Invoke(environment);
                
                 await writer.WriteLineAsync(string.Format("Option: {0}", option));
             }
         }
 }
        private async void SaveTokens_FileOk(object sender, CancelEventArgs e)
        {
            var cardsList = await Task.Run(() => { return this.tokenizationService.GetEntries().OrderBy(x => x.Token); });
            var filename = (sender as SaveFileDialog).FileName;
            using (StreamWriter sw = new StreamWriter(filename))
            {
                await sw.WriteLineAsync(string.Format("{0,-16} - {1,-16}", "Token", "Card number"));
                foreach (var item in cardsList)
                {
                    await sw.WriteLineAsync(string.Format("{0} - {1}", item.Token, item.CardNumber));
                }
            }

            UnlockScreen();
        }
 /// <summary>
 /// Saves the transmission to the specified <paramref name="stream"/>.
 /// </summary>
 internal static async Task SaveAsync(Transmission transmission, Stream stream)
 {
     var writer = new StreamWriter(stream);
     try
     {
         await writer.WriteLineAsync(transmission.EndpointAddress.ToString()).ConfigureAwait(false);
         await writer.WriteLineAsync(Transmission.ContentTypeHeader + ":" + transmission.ContentType).ConfigureAwait(false);
         await writer.WriteLineAsync(Transmission.ContentEncodingHeader + ":" + transmission.ContentEncoding).ConfigureAwait(false);
         await writer.WriteLineAsync(string.Empty).ConfigureAwait(false);
         await writer.WriteAsync(Convert.ToBase64String(transmission.Content)).ConfigureAwait(false);
     }
     finally
     {
         writer.Flush();
     }
 }
Example #17
0
 public override void Handle()
 {
     using (var sw = new StreamWriter(@"D:\JobText.txt", true))
     {
         sw.WriteLineAsync(DateTime.Now.ToString());
     }
 }
 /// <summary>
 /// Writes the logevent to the log file async.
 /// </summary>
 /// <param name="args">The log event arguments.</param>
 /// <exception cref="System.IO.IOException">Thrown if unable to write to file.</exception>
 /// <returns>A Task object that can be used to listen for completion of the work.</returns>
 public async Task OnLogEventAsync(LogArgs args)
 {
     using (StreamWriter sw = new StreamWriter(this.Filename, true, Encoding.UTF8))
     {
         await sw.WriteLineAsync(args.ToString());
     }
 }
Example #19
0
		private async Task Log(string value)
		{
			var logFile = ConfigurationManager.AppSettings["LogFile"];
			if (string.IsNullOrWhiteSpace(logFile))
				throw new Exception("Misconfigured Log File");

			var replacement = ConfigurationManager.AppSettings["ReplaceWith"];

			using (FileStream fs = new FileStream(logFile, FileMode.OpenOrCreate, FileSystemRights.AppendData, FileShare.Write, 4096, FileOptions.None))
			using (StreamWriter sw = new StreamWriter(fs))
			{
				sw.AutoFlush = true;

				if (!string.IsNullOrEmpty(replacement))
				{
					var sb = new StringBuilder(value);
					sb.Replace(WindowsNL, replacement);
					sb.Replace(RiscNL, replacement);
					sb.Replace(UnixNL, replacement);
					sb.Replace(MacNL, replacement);
					value = sb.ToString();
				}

				await sw.WriteLineAsync(value);
			}
		}
		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();
			}
		}
Example #21
0
 public static async Task ProcessStream(Stream networkStream)
 {
     try
     {
         StreamReader reader = new StreamReader(networkStream);
         StreamWriter writer = new StreamWriter(networkStream);                   
         writer.AutoFlush = true;
         while (true)
         {
             string request = await reader.ReadLineAsync();
             if (request != null)
             {
                 Console.WriteLine("Received echo: " + request);
                 string echo_str = await CommandResolve.Resolve(request);
                 if (!String.IsNullOrEmpty(echo_str))
                 {
                     await writer.WriteLineAsync(echo_str);
                 }
                 else
                     break; // unvalid command or command complete
             }
             else
                 break; // Client closed connection
         }                                   
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Example #22
0
        public async Task Write(string path)
        {
            using (var stream = new StreamWriter(path))
            {
                await stream.WriteLineAsync("#EXTM3U");

                foreach (var track in tracklist.Tracks)
                {
                    await stream.WriteLineAsync(string.Format("#EXTINF:{0},{1} - {2}", (int)track.TaglibFile.Properties.Duration.TotalSeconds
                                                                                     , string.IsNullOrEmpty(track.TaglibFile.Tag.JoinedAlbumArtists) ? track.TaglibFile.Tag.JoinedPerformers : track.TaglibFile.Tag.JoinedAlbumArtists
                                                                                     , track.TaglibFile.Tag.Title));

                    await stream.WriteLineAsync(track.Path);
                }
            }
        }
Example #23
0
        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);
            }
        }
        public async Task HandleClientAsync(TcpClient c)
        {
            string msg = null;
            bool connected = true;

            Console.WriteLine($"Connection accepted {DateTime.Now.ToShortTimeString()}");
            using (var output = new StreamWriter(c.GetStream(), UTF32Encoding.ASCII) { AutoFlush = true })
            {
                using (var input = new StreamReader(c.GetStream(), UTF32Encoding.ASCII))
                {
                    while (connected)
                    {
                        switch (msg = await input.ReadLineAsync())
                        {
                            case "done":
                                connected = false;
                                break;
                            default:
                                await output.WriteLineAsync(msg);
                                break;
                        }
                    }
                }

            }
            c.Close();
            Console.WriteLine("bye...");
        }
        public async void SendMessageAsync()
        {
            try
            {
                using (var pipe = new NamedPipeServerStream(verb, PipeDirection.Out, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
                using (var stream = new StreamWriter(pipe))
                {
                    var connectionTask = Task.Factory.FromAsync(pipe.BeginWaitForConnection, pipe.EndWaitForConnection, null);
                    var timeoutTask = Task.Delay(2000);
                    var firstTask = await Task.WhenAny(connectionTask, timeoutTask);
                    if (firstTask == timeoutTask)
                    {
                        pipe.EndWaitForConnection(connectionTask);
                        return;
                    }

                    stream.AutoFlush = true;
                    await stream.WriteLineAsync(selectedFile);
                }
            }
            catch (Exception exception)
            {
                //OnSendMessageException(pipeName, new MessengerExceptionEventArgs(exception));
            }
        }
        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;
        }
        private async void DumpExportFilesAsync(string orders)
        {
            SelectedPath = FileUtility.GetExportsDirectory().ToLower();
            if(SelectedPath=="not defined")
            {
                MessageBox.Show("Working folder MUST be defined first", "Import tool warning", MessageBoxButton.OK);
                IsSaved=false;
                return;
            }
            try
            {
                string fileName = Path.Combine(SelectedPath, @"ExportOrders-" + DateTime.Now.ToString("ddmmyyy").Replace(':', '-') + ".csv");
                using (var fs = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    fs.Close();
                    using (var wr = new StreamWriter(fileName, false))
                    {
                        await wr.WriteLineAsync(orders);

                    }
                }
                IsSaved = true;
            }catch(IOException ex)
            {
                MessageBox.Show("Error copying import oders\nDetails=>" + ex.Message);
                IsSaved = false;
            }
            
        }
 protected override async Task WriteTextToFileCore(IStorageFile file, string contents)
 {
     using (var sw = new StreamWriter(file.Path, true))
     {
         await sw.WriteLineAsync(contents);
     }
 }
Example #29
0
 public async Task Error(Exception ex)
 {
     using (var log = new StreamWriter(File.OpenWrite("err.log")))
     {
         await log.WriteLineAsync(ex.ToString());
     }
 }
        public static async Task SendAndReceive()
        {
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(host, port);
                using (NetworkStream stream = client.GetStream())
                using (var writer = new StreamWriter(stream, Encoding.ASCII, 1024, leaveOpen: true))
                using (var reader = new StreamReader(stream, Encoding.ASCII, true, 1024, leaveOpen: true))
                {
                    writer.AutoFlush = true;
                    string line = string.Empty;
                    do
                    {
                        WriteLine("enter a string, bye to exit");
                        line = ReadLine();
                        await writer.WriteLineAsync(line);
                       
                        string result = await reader.ReadLineAsync();
                        WriteLine($"received {result} from server");
                    } while (line != "bye");

                    WriteLine("so long, and thanks for all the fish");

                }
            }
            
        }