System.IO.StreamReader.ReadLineAsync()

Here are the examples of the csharp api System.IO.StreamReader.ReadLineAsync() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

170 Examples 7

19 Source : EventSourceReader.cs
with MIT License
from 3ventic

private async Task ReaderAsync()
        {
            try
            {
                if (string.Empty != LastEventId)
                {
                    if (Hc.DefaultRequestHeaders.Contains("Last-Event-Id"))
                    {
                        Hc.DefaultRequestHeaders.Remove("Last-Event-Id");
                    }
                    
                    Hc.DefaultRequestHeaders.TryAddWithoutValidation("Last-Event-Id", LastEventId);
                }
                using (HttpResponseMessage response = await Hc.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();
                    if (response.Headers.TryGetValues("content-type", out IEnumerable<string> ctypes) || ctypes?.Contains("text/event-stream") == false)
                    {
                        throw new ArgumentException("Specified URI does not return server-sent events");
                    }

                    Stream = await response.Content.ReadreplacedtreamAsync();
                    using (var sr = new StreamReader(Stream))
                    {
                        string evt = DefaultEventType;
                        string id = string.Empty;
                        var data = new StringBuilder(string.Empty);

                        while (true)
                        {
                            string line = await sr.ReadLineAsync();
                            if (line == string.Empty)
                            {
                                // double newline, dispatch message and reset for next
                                if (data.Length > 0)
                                {
                                    MessageReceived?.Invoke(this, new EventSourceMessageEventArgs(data.ToString().Trim(), evt, id));
                                }
                                data.Clear();
                                id = string.Empty;
                                evt = DefaultEventType;
                                continue;
                            }
                            else if (line.First() == ':')
                            {
                                // Ignore comments
                                continue;
                            }

                            int dataIndex = line.IndexOf(':');
                            string field;
                            if (dataIndex == -1)
                            {
                                dataIndex = line.Length;
                                field = line;
                            }
                            else
                            {
                                field = line.Substring(0, dataIndex);
                                dataIndex += 1;
                            }

                            string value = line.Substring(dataIndex).Trim();

                            switch (field)
                            {
                                case "event":
                                    // Set event type
                                    evt = value;
                                    break;
                                case "data":
                                    // Append a line to data using a single \n as EOL
                                    data.Append($"{value}\n");
                                    break;
                                case "retry":
                                    // Set reconnect delay for next disconnect
                                    int.TryParse(value, out ReconnectDelay);
                                    break;
                                case "id":
                                    // Set ID
                                    LastEventId = value;
                                    id = LastEventId;
                                    break;
                                default:
                                    // Ignore other fields
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Disconnect(ex);
            }
        }

19 Source : Machine.cs
with MIT License
from 3RD-Dimension

private void Work()
        {
            try
            {
                StreamReader reader = new StreamReader(Connection);
                StreamWriter writer = new StreamWriter(Connection);

                int StatusPollInterval = Properties.Settings.Default.StatusPollInterval;

                int ControllerBufferSize = Properties.Settings.Default.ControllerBufferSize;
                BufferState = 0;

                TimeSpan WaitTime = TimeSpan.FromMilliseconds(0.5);
                DateTime LastStatusPoll = DateTime.Now + TimeSpan.FromSeconds(0.5);
                DateTime StartTime = DateTime.Now;

                DateTime LastFilePosUpdate = DateTime.Now;
                bool filePosChanged = false;

                bool SendMacroStatusReceived = false;

                writer.Write("\n$G\n");
                writer.Write("\n$#\n");
                writer.Flush();

                while (true)
                {
                    Task<string> lineTask = reader.ReadLineAsync();

                    while (!lineTask.IsCompleted)
                    {
                        if (!Connected)
                        {
                            return;
                        }

                        while (ToSendPriority.Count > 0)
                        {
                            writer.Write((char)ToSendPriority.Dequeue());
                            writer.Flush();
                        }
                        if (Mode == OperatingMode.SendFile)
                        {
                            if (File.Count > FilePosition && (File[FilePosition].Length + 1) < (ControllerBufferSize - BufferState))
                            {
                                string send_line = File[FilePosition].Replace(" ", ""); // don't send whitespace to machine

                                writer.Write(send_line);
                                writer.Write('\n');
                                writer.Flush();

                                RecordLog("> " + send_line);

                                RaiseEvent(UpdateStatus, send_line);
                                RaiseEvent(LineSent, send_line);

                                BufferState += send_line.Length + 1;

                                Sent.Enqueue(send_line);

                                if (PauseLines[FilePosition] && Properties.Settings.Default.PauseFileOnHold)
                                {
                                    Mode = OperatingMode.Manual;
                                }

                                if (++FilePosition >= File.Count)
                                {
                                    Mode = OperatingMode.Manual;
                                }

                                filePosChanged = true;
                            }
                        }
                        else if (Mode == OperatingMode.SendMacro)
                        {
                            switch (Status)
                            {
                                case "Idle":
                                    if (BufferState == 0 && SendMacroStatusReceived)
                                    {
                                        SendMacroStatusReceived = false;

                                        string send_line = (string)ToSendMacro.Dequeue();

                                        send_line = Calculator.Evaluate(send_line, out bool success);

                                        if (!success)
                                        {
                                            ReportError("Error while evaluating macro!");
                                            ReportError(send_line);

                                            ToSendMacro.Clear();
                                        }
                                        else
                                        {
                                            send_line = send_line.Replace(" ", "");

                                            writer.Write(send_line);
                                            writer.Write('\n');
                                            writer.Flush();

                                            RecordLog("> " + send_line);

                                            RaiseEvent(UpdateStatus, send_line);
                                            RaiseEvent(LineSent, send_line);

                                            BufferState += send_line.Length + 1;

                                            Sent.Enqueue(send_line);
                                        }
                                    }
                                    break;
                                case "Run":
                                case "Hold":
                                    break;
                                default:    // grbl is in some kind of alarm state
                                    ToSendMacro.Clear();
                                    break;
                            }

                            if (ToSendMacro.Count == 0)
                                Mode = OperatingMode.Manual;
                        }
                        else if (ToSend.Count > 0 && (((string)ToSend.Peek()).Length + 1) < (ControllerBufferSize - BufferState))
                        {
                            string send_line = ((string)ToSend.Dequeue()).Replace(" ", "");

                            writer.Write(send_line);
                            writer.Write('\n');
                            writer.Flush();

                            RecordLog("> " + send_line);

                            RaiseEvent(UpdateStatus, send_line);
                            RaiseEvent(LineSent, send_line);

                            BufferState += send_line.Length + 1;

                            Sent.Enqueue(send_line);
                        }


                        DateTime Now = DateTime.Now;

                        if ((Now - LastStatusPoll).TotalMilliseconds > StatusPollInterval)
                        {
                            writer.Write('?');
                            writer.Flush();
                            LastStatusPoll = Now;
                        }

                        //only update file pos every X ms
                        if (filePosChanged && (Now - LastFilePosUpdate).TotalMilliseconds > 500)
                        {
                            RaiseEvent(FilePositionChanged);
                            LastFilePosUpdate = Now;
                            filePosChanged = false;
                        }

                        Thread.Sleep(WaitTime);
                    }

                    string line = lineTask.Result;

                    RecordLog("< " + line);

                    if (line == "ok")
                    {
                        if (Sent.Count != 0)
                        {
                            BufferState -= ((string)Sent.Dequeue()).Length + 1;
                        }
                        else
                        {
                            MainWindow.Logger.Info("Received OK without anything in the Sent Buffer");
                            BufferState = 0;
                        }
                    }
                    else
                    {
                        if (line.StartsWith("error:"))
                        {
                            if (Sent.Count != 0)
                            {
                                string errorline = (string)Sent.Dequeue();

                                RaiseEvent(ReportError, $"{line}: {errorline}");
                                BufferState -= errorline.Length + 1;
                            }
                            else
                            {
                                if ((DateTime.Now - StartTime).TotalMilliseconds > 200)
                                    RaiseEvent(ReportError, $"Received <{line}> without anything in the Sent Buffer");

                                BufferState = 0;
                            }

                            Mode = OperatingMode.Manual;
                        }
                        else if (line.StartsWith("<"))
                        {
                            RaiseEvent(ParseStatus, line);
                            SendMacroStatusReceived = true;
                        }
                        else if (line.StartsWith("[PRB:"))
                        {
                            RaiseEvent(ParseProbe, line);
                            RaiseEvent(LineReceived, line);
                        }                      
                        else if (line.StartsWith("["))
                        {
                            RaiseEvent(UpdateStatus, line);
                            RaiseEvent(LineReceived, line);
                        }
                        else if (line.StartsWith("ALARM"))
                        {
                            RaiseEvent(ReportError, line);
                            Mode = OperatingMode.Manual;
                            ToSend.Clear();
                            ToSendMacro.Clear();
                        }
                        else if (line.Length > 0)
                            RaiseEvent(LineReceived, line);
                    }
                }
            }
            catch (Exception ex)
            {
                RaiseEvent(ReportError, $"Fatal Error in Work Loop: {ex.Message}");
                RaiseEvent(() => Disconnect());
            }
        }

19 Source : DockerSupport.cs
with Apache License 2.0
from akkadotnet

public async Task WaitForKafkaServerAsync()
        {
            // wait until Kafka is ready
            var logStream = await Client.Containers.GetContainerLogsAsync(
                _kafkaContainerName, 
                new ContainerLogsParameters
                {
                    Follow = true,
                    ShowStdout = true,
                    ShowStderr = true
                });

            string line = null;
            var timeoutInMilis = 60000;
            using (var reader = new StreamReader(logStream))
            {
                var stopwatch = Stopwatch.StartNew();
                while (stopwatch.ElapsedMilliseconds < timeoutInMilis && (line = await reader.ReadLineAsync()) != null)
                {
                    if (line.Contains("started (kafka.server.KafkaServer)"))
                    {
                        break;
                    }
                }
                stopwatch.Stop();
            }
#if NETFX
            logStream.Dispose();
#else
            await logStream.DisposeAsync();
#endif
            
            if (!(line?.Contains("started (kafka.server.KafkaServer)") ?? false))
            {
                await TearDownDockerAsync();
                Client = null;
                throw new Exception("Kafka docker image failed to run.");
            }
            Console.WriteLine("Kafka server started.");
        }

19 Source : JsonFormatterParser.cs
with MIT License
from Analogy-LogViewer

public async Task<IEnumerable<replacedogyLogMessage>> Process(string fileName, CancellationToken token,
            ILogMessageCreatedHandler messagesHandler)
        {
            //var formatter = new JsonFormatter();
            List<replacedogyLogMessage> parsedMessages = new List<replacedogyLogMessage>();
            try
            {
                using (var replacedogy = new LoggerConfiguration()
                    .MinimumLevel.Verbose()
                    .WriteTo.replacedogy()
                    .CreateLogger())
                {
                    using (var fileStream =
                        new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {

                        if (fileName.EndsWith(".gz", StringComparison.InvariantCultureIgnoreCase))
                        {
                            using (var gzStream = new GZipStream(fileStream, CompressionMode.Decompress))
                            {
                                using (var streamReader = new StreamReader(gzStream, encoding: Encoding.UTF8))
                                {
                                    string json;
                                    while ((json = await streamReader.ReadLineAsync()) != null)
                                    {

                                        var data = JsonConvert.DeserializeObject(json, JsonSerializerSettings);
                                        var jo = data as JObject;
                                        var evt = LogEventReader.ReadFromJObject(jo, messageFields);
                                        {
                                            replacedogy.Write(evt);
                                            replacedogyLogMessage m = CommonParser.ParseLogEventProperties(evt);
                                            m.RawText = jo.ToString(Formatting.None);
                                            m.RawTextType = replacedogyRowTextType.JSON;
                                            parsedMessages.Add(m);
                                        }
                                    }

                                }
                            }
                        }


                        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
                        {
                            string json;
                            while ((json = await streamReader.ReadLineAsync()) != null)
                            {
                                var data = JsonConvert.DeserializeObject(json);
                                var jo = data as JObject;
                                var evt = LogEventReader.ReadFromJObject(jo, messageFields);
                                {
                                    replacedogy.Write(evt);
                                    replacedogyLogMessage m = CommonParser.ParseLogEventProperties(evt);
                                    m.RawText = jo.ToString(Formatting.None);
                                    m.RawTextType = replacedogyRowTextType.JSON;
                                    parsedMessages.Add(m);
                                }
                            }
                        }

                    }

                    messagesHandler.AppendMessages(parsedMessages, fileName);
                    return parsedMessages;
                }
            }
            catch (Exception e)
            {
                replacedogyLogMessage empty = new replacedogyLogMessage($"Error reading file {fileName}: Error: {e.Message}",
                    replacedogyLogLevel.Error, replacedogyLogClreplaced.General, "replacedogy", "None");
                empty.Source = nameof(CompactJsonFormatParser);
                empty.Module = "replacedogy.LogViewer.Serilog";
                parsedMessages.Add(empty);
                messagesHandler.AppendMessages(parsedMessages, fileName);
                return parsedMessages;
            }
        }

19 Source : CloudbleedSiteChecker.cs
with MIT License
from andrew-schofield

private async Task<HashSet<string>> ExtractBreachesFromStream(Stream stream, IProgress<ProgressItem> progressIndicator)
        {
            var breaches = new HashSet<string>();
            using (var rd = new StreamReader(stream))
            {
                while (true)
                {
                    var line = await rd.ReadLineAsync();
                    if (line == null)
                        break;
                    if (!string.IsNullOrWhiteSpace(line))
                    {
                        breaches.Add(line.ToLower().Trim());
                    }
                }
            }

            return breaches;
        }

19 Source : HaveIBeenPwnedPasswordChecker.cs
with MIT License
from andrew-schofield

private async Task<List<HaveIBeenPwnedPreplacedwordEntry>> GetBreaches(IProgress<ProgressItem> progressIndicator, IEnumerable<PwEntry> entries, Func<bool> canContinue)
        {
            List<HaveIBeenPwnedPreplacedwordEntry> allBreaches = new List<HaveIBeenPwnedPreplacedwordEntry>();
            int counter = 0;
            SHA1 sha = new SHA1CryptoServiceProvider();

            Dictionary<string, bool> cache = new Dictionary<string, bool>();

            foreach (var entry in entries)
            {
                if (!canContinue())
                {
                    break;
                }

                counter++;
                progressIndicator.Report(new ProgressItem((uint)((double)counter / entries.Count() * 100), string.Format("Checking \"{0}\" for breaches", entry.Strings.ReadSafe(PwDefs.replacedleField))));
                if(entry.Strings.Get(PwDefs.PreplacedwordField) == null || string.IsNullOrWhiteSpace(entry.Strings.ReadSafe(PwDefs.PreplacedwordField)) || entry.Strings.ReadSafe(PwDefs.PreplacedwordField).StartsWith("{REF:")) continue;
                var preplacedwordHash = string.Join("", sha.ComputeHash(entry.Strings.Get(PwDefs.PreplacedwordField).ReadUtf8()).Select(x => x.ToString("x2"))).ToUpperInvariant();
                if (cache.ContainsKey(preplacedwordHash))
                {
                    if (cache[preplacedwordHash])
                    {
                        allBreaches.Add(new HaveIBeenPwnedPreplacedwordEntry(entry.Strings.ReadSafe(PwDefs.UserNameField), entry.GetUrlDomain(), entry));
                    }
                    continue;
                }
                var prefix = preplacedwordHash.Substring(0, 5);
                using (var response = await client.GetAsync(string.Format(API_URL, prefix)))
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        cache[preplacedwordHash] = false;
                        var stream = await response.Content.ReadreplacedtreamAsync();
                        using (var reader = new StreamReader(stream))
                        {
                            string line;
                            while ((line = await reader.ReadLineAsync()) != null)
                            {
                                var parts = line.Split(':');
                                var suffix = parts[0];
                                var count = int.Parse(parts[1]);
                                if (prefix + suffix == preplacedwordHash)
                                {
                                    allBreaches.Add(new HaveIBeenPwnedPreplacedwordEntry(entry.Strings.ReadSafe(PwDefs.UserNameField), entry.GetUrlDomain(), entry));
                                    cache[preplacedwordHash] = true;
                                }
                            }
                        }
                    }
                }
            }
            return allBreaches;
        }

19 Source : PwnedPasswordsClient.cs
with MIT License
from andrewlock

internal static async Task<long> Contains(HttpContent content, string sha1Suffix)
        {
            using (var streamReader = new StreamReader(await content.ReadreplacedtreamAsync()))
            {
                while (!streamReader.EndOfStream)
                {
                    var line = await streamReader.ReadLineAsync();
                    var segments = line.Split(':');
                    if (segments.Length == 2
                        && string.Equals(segments[0], sha1Suffix, StringComparison.OrdinalIgnoreCase)
                        && long.TryParse(segments[1], out var count))
                    {
                        return count;
                    }
                }
            }

            return 0;

        }

19 Source : PrinterResponseReader.cs
with MIT License
from andycb

public async Task<T> GerPrinterResponce<T>()
            where T : clreplaced, IPrinterResponce
        {
            // Responses from the printer will be in the format:
            // CMD Mxxx Received.
            // Some data
            // Some data.
            // ok

            string commandId = null;
            var data = new List<string>();
            while (true)
            {
                var line = await this.streamReader.ReadLineAsync().ConfigureAwait(false);
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue
;                }

                var match = this.cmdReceivedRegex.Match(line);
                if (match.Success)
                {
                    // Pull out the ID that the response is for
                    commandId = match.Groups["CommandId"].Value;
                }
                else if (string.Equals(line, "ok", StringComparison.InvariantCulture)
                    || string.Equals(line, "ok.", StringComparison.InvariantCulture))
                {
                    if (commandId != null)
                    {
                        // We have all the data, try and construct an responce object for it
                        return (T)this.GenerateResponce(commandId, data);
                    }

                    return null;
                }
                else if (line.EndsWith("error.", StringComparison.InvariantCulture))
                {
                    // The printer returned an error, pull out the error code
                    var errorCode = string.Empty;
                    var errorParts = line.Split(' ');
                    if (errorParts.Length == 2)
                    {
                        errorCode = errorParts[0];
                    }

                    throw new PrinterException(errorCode);
                }
                else
                {
                    // This is some data to preplaced to the response object to parse.
                    data.Add(line);
                }   
            }
        }

19 Source : HashiCorpVaultTestServer.cs
with MIT License
from arcus-azure

private async Task StartHashiCorpVaultAsync()
        {
            _logger.LogTrace("Starting HashiCorp Vault at '{listenAddress}'...", ListenAddress);

            if (!_process.Start())
            {
                throw new CouldNotStartHashiCorpVaultException(
                    $"Vault process did not start correctly, exit code: {_process.ExitCode}");
            }

            var isStarted = false;

            string line = await _process.StandardOutput.ReadLineAsync();
            while (line != null)
            {
                _logger.LogTrace(line);
                if (line?.StartsWith("==> Vault server started!") == true)
                {
                    isStarted = true;
                    break;
                }

                line = await _process.StandardOutput.ReadLineAsync();
            }

            if (!isStarted)
            {
                throw new CouldNotStartHashiCorpVaultException(
                    "Vault process wasn't configured correctly and could therefore not be started successfully");
            }

            _logger.LogInformation("HashiCorp Vault started at '{ListenAddress}'", ListenAddress);
        }

19 Source : FileBuilder.cs
with MIT License
from aschearer

public static async Task<List<Tuple<string, float>>> FromStream(Stream stream)
        {
            List<Tuple<string, float>> files;
            using (var reader = new StreamReader(stream))
            {
                // Step 1: Read the raw input data and convert it into a list of <file names, file size> tuples.
                files = new List<Tuple<string, float>>();
                var startProcessing = false;
                string line;
                while (!reader.EndOfStream)
                {
                    line = await reader.ReadLineAsync();

                    if (line.Trim() == Resource.LogStartWord)
                    {
                        // This is the line before the size breakdown
                        startProcessing = true;
                        continue;
                    }

                    if (!startProcessing)
                    {
                        continue;
                    }

                    Tuple<string, float> data;
                    if (GetPathAndMegabytesFrom(line, out data))
                    {
                        files.Add(data);
                    }
                    else
                    {
                        break;
                    }
                }

                // Step 2: Sort the list of files by file name.
                files.Sort(new PathAndSizeComparer());
            }

            return files;
        }

19 Source : AureliaCliDevelopmentServer.cs
with MIT License
from aurelia

private static async Task<int> FindTcpPortAsync(string sourcePath)
        {

            int FirstOpenPort()
            {
                var listener = new TcpListener(IPAddress.Loopback, 0);
                listener.Start();
                try
                {
                    return ((IPEndPoint)listener.LocalEndpoint).Port;
                }
                finally
                {
                    listener.Stop();
                }
            }

            using (var file = File.Open(Path.Combine(sourcePath, AureliaJsonFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var sr = new StreamReader(file))
            {
                while (!sr.EndOfStream)
                {
                    var line = await sr.ReadLineAsync();
                    if (line.Contains("port"))
                    {
                        var port = line.Replace(",", "").Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        if (port.Length == 2 && int.TryParse(port[1], out var portNumber))
                        {
                            var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
                            var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections().ToList();
                            if (!tcpConnInfoArray.Any(y => y.LocalEndPoint.Port == portNumber)) { return portNumber; }
                        }
                        // meh found the port section but broke
                        return FirstOpenPort();
                    }
                }
            }

            //didn't find squat
            return FirstOpenPort();


        }

19 Source : PackageInstaller.cs
with Apache License 2.0
from awslabs

private async Task PipeOutputAsync(Process process)
        {
            string output = await process.StandardOutput.ReadLineAsync();
            _logger?.LogInformation(output);
        }

19 Source : DomainBlacklist.cs
with MIT License
from bitbeans

public static async Task<string[]> ReadAllLinesAsync(string path, Encoding encoding)
	    {
		    var lines = new List<string>();
		    using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions))
		    using (var reader = new StreamReader(stream, encoding))
		    {
			    string line;
			    while ((line = await reader.ReadLineAsync()) != null)
			    {
				    lines.Add(line);
			    }
		    }
		    return lines.ToArray();
	    }

19 Source : CsvReader.cs
with MIT License
from bonsai-rx

IObservable<TResult> Generate<TSource, TResult>(IObservable<TSource> source, Func<string, TResult> parser)
        {
            return Observable.Using(
                async token =>
                {
                    var skipRows = SkipRows;
                    var reader = new StreamReader(FileName);
                    while (!reader.EndOfStream && skipRows > 0)
                    {
                        if (token.IsCancellationRequested) break;
                        await reader.ReadLineAsync();
                        skipRows--;
                    }
                    return reader;
                },
                (reader, token) =>
                {
                    if (token.IsCancellationRequested || reader.EndOfStream)
                    {
                        return Task.FromResult(Observable.Empty<TResult>());
                    }

                    return Task.FromResult(source.Select(input =>
                    {
                        var line = reader.ReadLine();
                        return parser(line);
                    }));
                });
        }

19 Source : CsvReader.cs
with MIT License
from bonsai-rx

IObservable<TResult> Generate<TResult>(Func<string, TResult> parser)
        {
            return Observable.Create<TResult>(async (observer, token) =>
            {
                try
                {
                    var skipRows = SkipRows;
                    using (var stream = File.OpenRead(FileName))
                    using (var reader = new StreamReader(stream))
                    {
                        while (!reader.EndOfStream)
                        {
                            if (token.IsCancellationRequested) break;
                            var line = await reader.ReadLineAsync();
                            if (skipRows > 0)
                            {
                                skipRows--;
                                continue;
                            }

                            observer.OnNext(parser(line));
                        }
                    }

                    observer.OnCompleted();
                }
                catch (Exception ex)
                {
                    observer.OnError(ex);
                }
            });
        }

19 Source : LndClient.cs
with MIT License
from btcpayserver

private async Task ListenLoop(HttpRequestMessage request)
            {
                try
                {
                    _Response = await _Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _Cts.Token);
                    _Body = await _Response.Content.ReadreplacedtreamAsync();
                    _Reader = new StreamReader(_Body);
                    while(!_Cts.IsCancellationRequested)
                    {
                        string line = await WithCancellation(_Reader.ReadLineAsync(), _Cts.Token);
                        if(line != null)
                        {
                            if(line.StartsWith("{\"result\":", StringComparison.OrdinalIgnoreCase))
                            {
                                var invoiceString = JObject.Parse(line)["result"].ToString();
                                LnrpcInvoice parsedInvoice = _Parent.Deserialize<LnrpcInvoice>(invoiceString);
                                await _Invoices.Writer.WriteAsync(ConvertLndInvoice(parsedInvoice), _Cts.Token);
                            }
                            else if(line.StartsWith("{\"error\":", StringComparison.OrdinalIgnoreCase))
                            {
                                var errorString = JObject.Parse(line)["error"].ToString();
                                var error = _Parent.Deserialize<LndError>(errorString);
                                throw new LndException(error);
                            }
                            else
                            {
                                throw new LndException("Unknown result from LND: " + line);
                            }
                        }
                    }
                }
                catch when(_Cts.IsCancellationRequested)
                {

                }
                catch(Exception ex)
                {
                    _Invoices.Writer.TryComplete(ex);
                }
                finally
                {
                    Dispose(false);
                }
            }

19 Source : DefaultFilteredAdapter.cs
with Apache License 2.0
from casbin

private async Task LoadFilteredPolicyFileAsync(Model.Model model, Filter filter, Action<string, Model.Model> handler)
        {
            var reader = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
            while (!reader.EndOfStream)
            {
                string line = (await reader.ReadLineAsync())?.Trim();
                if (string.IsNullOrWhiteSpace(line) || FilterLine(line, filter))
                {
                    return;
                }
                handler(line, model);
            }
        }

19 Source : DefaultFileAdapter.cs
with Apache License 2.0
from casbin

private async Task LoadPolicyDataAsync(Model.Model model, Helper.LoadPolicyLineHandler<string, Model.Model> handler, StreamReader inputStream)
        {
            while (!inputStream.EndOfStream)
            {
                string line = await inputStream.ReadLineAsync();
                handler(line, model);
            }
        }

19 Source : AdbDevice.cs
with MIT License
from CCRcmcpe

private static async Task KillConnectedProcesses(string targetSerial)
        {
            var netstat = new Process
            {
                StartInfo = new ProcessStartInfo("netstat", "-no")
                    {CreateNoWindow = true, RedirectStandardOutput = true}
            };

            netstat.Start();

            string? line;
            while ((line = await netstat.StandardOutput.ReadLineAsync()) != null)
            {
                string[] split = Regex.Split(line, @"\s+").Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
                if (split.Length != 5 || split[2] != targetSerial)
                {
                    continue;
                }

                int pid = int.Parse(split[4]);
                if (pid == 0)
                {
                    continue;
                }

                var process = Process.GetProcessById(pid);
                try
                {
                    process.Kill();
                }
                catch (Exception e)
                {
                    Log.Debug(e, "尝试杀死PID为{PID}的程序时出错", pid);
                }
            }

            var cts = new CancellationTokenSource(1000);
            await netstat.WaitForExitAsync(cts.Token);
        }

19 Source : Program.cs
with MIT License
from cemahseri

private static async Task RunFfmpegCommand(string command, bool getDuration = false)
        {
            var process = new Process
            {
                StartInfo =
                {
                    UseShellExecute = false,
                    CreateNoWindow = true, // For hiding the window that's going to be created.
                    WindowStyle = ProcessWindowStyle.Hidden, // For hiding the window that's going to be created.
                    FileName = "ffmpeg.exe",
                    Arguments = command
                }
            };

            if (getDuration)
            {
                process.StartInfo.RedirectStandardError = true; // Gotta redirect the error output for reading the output of target process.
            }

            process.Start();

            if (getDuration)
            {
                while (!process.StandardError.EndOfStream)
                {
                    var line = await process.StandardError.ReadLineAsync();
                    if (string.IsNullOrEmpty(line) || !line.StartsWith("  Duration: "))
                    {
                        continue;
                    }

                    var commaIndex = line.IndexOf(',');
                    _duration = line[12..commaIndex];
                }
            }

            await process.WaitForExitAsync();
        }

19 Source : FFmpeg.cs
with GNU General Public License v3.0
from Ch3shireDev

public static async Task ConvertToMp3(Track track)
#endif
        {
            CheckBinary();
            var filePath = track.filePath;
            if (string.IsNullOrWhiteSpace(filePath)) return;
            if (!File.Exists(filePath)) return;
            if (!string.Equals(Path.GetExtension(filePath), ".m4a", StringComparison.OrdinalIgnoreCase)) return;
            var f = TagLib.File.Create(filePath);
            var TotalDuration = f.Properties.Duration.TotalSeconds;

            var TemporaryOutput = Path.GetTempFileName();
            TemporaryOutput = Path.ChangeExtension(TemporaryOutput, ".mp3");

            var progressBar = YoutubeDL.CreateProgressBar(track);

            var process = new Process();
            var startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.FileName = ffmpegDir;
            startInfo.Arguments = "-i \"" + track.filePath + "\"";
            startInfo.Arguments += " -acodec libmp3lame -ab 128k -y ";
            startInfo.Arguments += "\"" + TemporaryOutput + "\"";
            process.StartInfo = startInfo;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.CreateNoWindow = true;
            process.Start();

            var reader = process.StandardError;

            while (!process.HasExited)
            {
#if DEBUG
                var str = reader.ReadLine();
#else
                var str = await reader.ReadLineAsync();
#endif
                if (string.IsNullOrWhiteSpace(str)) continue;
                var match = Regex.Match(str, @"time=(\d\d):(\d\d):(\d\d)");
                if (match.Success && match.Groups.Count == 4)
                {
                    var Hours = match.Groups[1].ToString();
                    var Minutes = match.Groups[2].ToString();
                    var Seconds = match.Groups[3].ToString();

                    var Duration = int.Parse(Hours) * 3600 + int.Parse(Minutes) * 60 + int.Parse(Seconds);
                    Debug.WriteLine(Duration + " " + TotalDuration);
                    var Percent = (int) (Duration * 100 / TotalDuration);
                    //YoutubeDL.UpdateProgressBar(track, Percent);
                    Debug.WriteLine("{0} {1} {2}", Hours, Minutes, Seconds);
                }
            }

            YoutubeDL.RemoveProgressBar(track);
            if (File.Exists(TemporaryOutput))
            {
                var finalOutput = Path.GetDirectoryName(track.filePath) + "\\" +
                                  Path.GetFileNameWithoutExtension(track.filePath) + ".mp3";
                if (File.Exists(finalOutput)) File.Delete(finalOutput);
                File.Move(TemporaryOutput, finalOutput);
                if (File.Exists(finalOutput))
                {
                    track.filePath = finalOutput;
                    track.UpdateItem();
                }
            }

            MainWindow.SavePlaylists();
        }

19 Source : YoutubeDl.cs
with GNU General Public License v3.0
from Ch3shireDev

public static async Task DownloadTrack(Track track)
#endif
        {
            if (track == null) return;
            if (!track.IsOnline) return;

#if !DEBUG
            DownloadManager.Counter++;
#endif

            CreateProgressBar(track);

            if (File.Exists(TemporaryPath(track))) File.Delete(TemporaryPath(track));
            ProcessStart(track, "-o " + TemporaryPath(track), out var process);
            var reader = process.StandardOutput;
            while (!process.HasExited)
            {
#if DEBUG
                var output = reader.ReadLine();
#else
                var output = await reader.ReadLineAsync();
#endif
                if (string.IsNullOrWhiteSpace(output)) continue;
                Debug.WriteLine(output);
                var r = new Regex(@"\[download]\s*([0-9.]*)%", RegexOptions.IgnoreCase);
                var m = r.Match(output);
                if (m.Success)
                {
                    var g = m.Groups[1].ToString();
                    var flag = double.TryParse(g, out var result);
                    if (flag) UpdateProgressBar(track, Convert.ToInt32(result));
                }
            }

            ProcessStart(track, "--get-filename", out var process2);

            string name;
            reader = process2.StandardOutput;
            {
#if DEBUG
                var output = reader.ReadToEnd();
#else
                var output = await reader.ReadToEndAsync();
#endif
                var str = output.Split('\n');
                name = str[0];
            }

            RemoveProgressBar(track);

            if (File.Exists(TemporaryPath(track)))
            {
                track.filePath = TemporaryPath(track);
                var outputDir = MainWindow.Instance.Options.DefaultDirectory + "\\" + name;
                if (File.Exists(outputDir))
                    try
                    {
                        File.Delete(outputDir);
                    }
                    catch
                    {
                        // ignored
                    }

                File.Move(TemporaryPath(track), outputDir);
                if (File.Exists(outputDir))
                    track.filePath = outputDir;
                track.OfflineToLocalData();
                track.UpdateItem();
            }
            else
            {
                track.MusicTab.PlaylistView.Items.Remove(track.Item);
                track.MusicTab.Tracks.Remove(track);
            }

#if !DEBUG
            DownloadManager.Counter--;
#endif
            MainWindow.SavePlaylists();
        }

19 Source : DotNetInteractiveProcessRunner.cs
with MIT License
from CodeConversations

protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Task.Run(async () =>
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    var output = await DotNetInteractiveProcess.StandardOutput.ReadLineAsync();

                    if (!string.IsNullOrEmpty(output))
                    {
                        logger.LogDebug(output);

                        var eventEnvelope = KernelEventEnvelope.Deserialize(output);

                        var token = eventEnvelope.Event.Command?.GetToken();

                        if (token != null && pendingRequests.TryGetValue(token, out var tracker))
                        {
                            tracker(eventEnvelope.Event);
                        }
                    }
                }
            }, stoppingToken);

            return Task.CompletedTask;
        }

19 Source : System_IO_StreamReader_Binding.cs
with MIT License
from CragonGame

static StackObject* ReadLineAsync_11(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject* ptr_of_this_method;
            StackObject* __ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.StreamReader instance_of_this_method = (System.IO.StreamReader)typeof(System.IO.StreamReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.ReadLineAsync();

            object obj_result_of_this_method = result_of_this_method;
            if(obj_result_of_this_method is CrossBindingAdaptorType)
            {    
                return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance);
            }
            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
        }

19 Source : AssetScriptReferenceRetargeter.cs
with MIT License
from cre8ivepark

private static async Task ProcessYamlFile(string filePath, string targetPath, Dictionary<string, Tuple<string, long>> remapDictionary)
        {
            int lineNum = 0;
            using (StreamReader reader = new StreamReader(filePath))
            using (StreamWriter writer = new StreamWriter(targetPath))
            {
                while (!reader.EndOfStream)
                {
                    string line = await reader.ReadLineAsync();
                    lineNum++;
                    if (line.Contains("m_Script") || (filePath.EndsWith(".anim") && line.Contains("script")))
                    {
                        if (!line.Contains('}'))
                        {
                            // Read the second line as well
                            line += await reader.ReadLineAsync();
                            lineNum++;

                            if (!line.Contains('}'))
                            {
                                throw new InvalidDataException($"Unexpected part of YAML line split over more than two lines, starting two lines: {line}");
                            }
                        }

                        if (line.Contains(ScriptFileIdConstant))
                        {
                            Match regexResults = Regex.Match(line, Utilities.MetaFileGuidRegex);
                            if (!regexResults.Success || regexResults.Groups.Count != 2 || !regexResults.Groups[1].Success || regexResults.Groups[1].Captures.Count != 1)
                            {
                                throw new InvalidDataException($"Failed to find the guid in line: {line}.");
                            }

                            string guid = regexResults.Groups[1].Captures[0].Value;
                            if (remapDictionary.TryGetValue(guid, out Tuple<string, long> tuple))
                            {
                                line = Regex.Replace(line, @"fileID: \d+, guid: \w+", $"fileID: {tuple.Item2}, guid: {tuple.Item1}");
                            }
                            else if (nonClreplacedDictionary.ContainsKey(guid))
                            {
                                throw new InvalidDataException($"A script without a clreplaced ({nonClreplacedDictionary[guid]}) is being processed.");
                            }
                            else
                            {
                                // Switch to error later
                                Debug.LogWarning($"Couldn't find a script remap for {guid} in file: '{filePath}' at line '{lineNum}'.");
                            }
                        }
                        // else this is not a script file reference
                    }
                    else if (line.Contains(ScriptFileIdConstant))
                    {
                        throw new InvalidDataException($"Line in file {filePath} contains script type but not m_Script: {line.Trim()}");
                    }
                    //{ fileID: 11500000, guid: 83d9acc7968244a8886f3af591305bcb, type: 3}

                    await writer.WriteLineAsync(line);
                }
            }
        }

19 Source : Corpus.Reuters.cs
with MIT License
from curiosity-ai

public static async Task<(IDoreplacedent[] trainDoreplacedents, IDoreplacedent[] testDoreplacedents)> GetAsync()
            {
                var path = GetDataPath();
                
                if (! await Storage.Current.ExistsAsync(path))
                {
                    await DownloadAsync();
                }

                var categories = new Dictionary<string, string[]>();
                var trainDocs = new List<IDoreplacedent>();
                var testDocs  = new List<IDoreplacedent>();

                using (var dest = await Storage.Current.OpenLockedStreamAsync(GetDataPath(), System.IO.FileAccess.Read))
                using (var zip = new ZipArchive(dest, ZipArchiveMode.Read))
                {
                    using (var cat = zip.GetEntry(@"reuters/cats.txt").Open())
                    using(var sr = new StreamReader(cat))
                    {
                        while(!sr.EndOfStream)
                        {
                            var line = await sr.ReadLineAsync();
                            var parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            categories.Add(parts[0], parts.Skip(1).ToArray());
                        }
                    }

                    foreach(var kv in categories)
                    {
                        IDoreplacedent doc;
                        using (var cat = zip.GetEntry(@"reuters/" + kv.Key).Open())
                        using (var sr = new StreamReader(cat))
                        {
                            var txt = await sr.ReadToEndAsync();
                            txt = txt.Replace('\n', ' ');
                            doc = new Doreplacedent(txt, Language.English);
                            doc.Labels.AddRange(kv.Value);
                        }

                        if (kv.Key.StartsWith("train"))
                        {
                            trainDocs.Add(doc);
                        }
                        else
                        {
                            testDocs.Add(doc);
                        }
                    }
                }

                return (trainDocs.ToArray(), testDocs.ToArray());
            }

19 Source : JsonRpcStreamsTests.cs
with Apache License 2.0
from CXuesong

[Fact]
        public async Task ServerHandlerTest()
        {
            var request = new RequestMessage(123, "add", JToken.FromObject(new {x = 20, y = 35}));
            (var ss, var cs) = FullDuplexStream.CreatePair();
            using (var clientReader = new StreamReader(cs))
            using (var clientWriter = new StreamWriter(cs))
            using (var serverReader = new ByLineTextMessageReader(ss))
            using (var serverWriter = new ByLineTextMessageWriter(ss))
            {
                async Task<ResponseMessage> WaitForResponse()
                {
                    var sw = Stopwatch.StartNew();
                    var content = await clientReader.ReadLineAsync();
                    Output.WriteLine($"Received response in {sw.Elapsed}.");
                    return (ResponseMessage) Message.LoadJson(content);
                }

                async Task<ResponseMessage> SendRequest(MessageId messageId)
                {
                    request.Id = messageId;
                    request.WriteJson(clientWriter);
                    clientWriter.WriteLine();
                    await clientWriter.FlushAsync();
                    var response = await WaitForResponse();
                    replacedert.Equal(messageId, response.Id);
                    replacedert.Null(response.Error);
                    replacedert.Equal(55, (int) response.Result);
                    return response;
                }

                using (var server = new ServerTestHelper(this, serverReader, serverWriter,
                    StreamRpcServerHandlerOptions.None))
                {
                    await SendRequest(123);
                    await SendRequest("abc");
                }
            }
        }

19 Source : DotnetCommandService.cs
with Apache License 2.0
from CycloneDX

private static async Task ConsumeStreamReaderAsync(StreamReader reader, StringBuilder lines)
        {
            await Task.Yield();

            string line;
            while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
            {
                lines.AppendLine(line);
            }
        }

19 Source : DocumentData.cs
with MIT License
from czh098tom

public static async Task<TreeNode> CreateNodeFromFileAsync(string fileName, DoreplacedentData target)
        {
            TreeNode root = null;
            TreeNode prev = null;
            TreeNode tempN = null;
            int prevLevel = -1;
            int i;
            int levelgrad;
            char[] temp;
            string des;
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(fileName, Encoding.UTF8);
                while (!sr.EndOfStream)
                {
                    temp = (await sr.ReadLineAsync()).ToCharArray();
                    i = 0;
                    while (temp[i] != ',')
                    {
                        i++;
                    }
                    des = new string(temp, i + 1, temp.Length - i - 1);
                    if (prevLevel != -1)
                    {
                        levelgrad = Convert.ToInt32(new string(temp, 0, i)) - prevLevel;
                        if (levelgrad <= 0)
                        {
                            for (int j = 0; j >= levelgrad; j--)
                            {
                                prev = prev.Parent;
                            }
                        }
                        tempN = (TreeNode)EditorSerializer.DeserializeTreeNode(des);
                        tempN.parentWorkSpace = target;
                        //tempN.FixAttrParent();
                        prev.AddChild(tempN);
                        prev = tempN;
                        prevLevel += levelgrad;
                    }
                    else
                    {
                        root = (TreeNode)EditorSerializer.DeserializeTreeNode(des);
                        //root.FixAttrParent();
                        root.parentWorkSpace = target;
                        prev = root;
                        prevLevel = 0;
                    }
                }
            }
            catch (System.Exception e)
            {
                System.Windows.MessageBox.Show(e.ToString());
            }
            finally
            {
                if (sr != null) sr.Close();
            }
            return root;
        }

19 Source : CpuUtil.cs
with GNU General Public License v3.0
from d8ahazard

private static async Task<float> GetTempOsx() {
			// bash command / opt / vc / bin / vc gen cmd measure_temp
			var temp = 0f;
			try {
				var process = new Process {
					StartInfo = new ProcessStartInfo {
						FileName = "sysctl",
						Arguments = "machdep.xcpm.cpu_thermal_level",
						RedirectStandardOutput = true,
						RedirectStandardError = true,
						UseShellExecute = false,
						CreateNoWindow = true
					}
				};
				process.Start();
				while (!process.StandardOutput.EndOfStream) {
					var res = await process.StandardOutput.ReadLineAsync();
					if (res != null && res.Contains("machdep.xcpm.cpu_thermal_level")) {
						var p1 = res.Replace("machdep.xcpm.cpu_thermal_level: ", "");
						if (!float.TryParse(p1, out temp)) {
							Log.Warning("Unable to parse line: " + res);
						}
					}
				}

				process.Dispose();
			} catch (Exception e) {
				Log.Warning("Exception: " + e.Message);
			}

			var sd = DataUtil.GetSystemData();
			if (sd.Units == DeviceUnits.Imperial) {
				temp = (float)Math.Round(temp * 1.8f + 32);
			}

			return temp;
		}

19 Source : CpuUtil.cs
with GNU General Public License v3.0
from d8ahazard

private static async Task<float> GetTempLinux() {
			// bash command / opt / vc / bin / vc gen cmd measure_temp
			var temp = 0f;
			try {
				var process = new Process {
					StartInfo = new ProcessStartInfo {
						FileName = "/bin/bash",
						Arguments = "-c \"sensors\"",
						RedirectStandardOutput = true,
						RedirectStandardError = true,
						UseShellExecute = false,
						CreateNoWindow = true
					}
				};
				process.Start();
				while (!process.StandardOutput.EndOfStream) {
					var res = await process.StandardOutput.ReadLineAsync();
					if (res == null || !res.Contains("temp")) {
						continue;
					}

					var splits = res.Split("+");
					if (splits.Length <= 1) {
						continue;
					}

					var p1 = splits[1];
					if (p1.Contains(" ")) {
						var splits2 = p1.Split(" ");
						if (splits2.Length > 0) {
							p1 = splits2[0];
						}
					}
					if (!float.TryParse(p1, out temp)) {
						Log.Warning("Unable to parse line: " + res);
					}
				}

				process.Dispose();
			} catch (Exception e) {
				Log.Warning("Exception: " + e.Message);
			}

			var sd = DataUtil.GetSystemData();
			if (sd.Units == DeviceUnits.Imperial) {
				temp = (float)Math.Round(temp * 1.8f + 32);
			}

			return temp;
		}

19 Source : CpuUtil.cs
with GNU General Public License v3.0
from d8ahazard

private static int GetMemoryUsageLinux() {
			var process = new Process {
				StartInfo = new ProcessStartInfo {
					FileName = "vmstat",
					RedirectStandardOutput = true,
					RedirectStandardError = true,
					UseShellExecute = false,
					CreateNoWindow = true,
					Arguments = "-s"
				}
			};
			process.Start();
			var used = -1f;
			var total = -1f;
			while (!process.StandardOutput.EndOfStream) {
				var data = process.StandardOutput.ReadLineAsync().Result;
				if (data == null) {
					continue;
				}

				if (data.Contains("total memory")) {
					var str = data.Replace(" used memory", "");
					if (float.TryParse(str.Split(" ")[0], out var foo)) {
						used = foo;
					}
				}

				if (data.Contains("used memory")) {
					var str = data.Replace(" total memory", "");
					if (float.TryParse(str.Split(" ")[0], out var foo)) {
						total = foo;
					}
				}
			}

			if (Math.Abs(used - -1) > float.MinValue && Math.Abs(total - -1f) > float.MinValue) {
				return (int)(used / total);
			}

			process.Dispose();
			return 0;
		}

19 Source : CpuUtil.cs
with GNU General Public License v3.0
from d8ahazard

private static int GetMemoryUsageOsx() {
			var process = new Process {
				StartInfo = new ProcessStartInfo {
					FileName = "vm_stat",
					RedirectStandardOutput = true,
					RedirectStandardError = true,
					UseShellExecute = false,
					CreateNoWindow = true
				}
			};
			process.Start();
			var free = 0;
			var active = 0;
			var spec = 0;
			var throttled = 0;
			var wired = 0;
			while (!process.StandardOutput.EndOfStream) {
				var data = process.StandardOutput.ReadLineAsync().Result;
				if (data == null) {
					continue;
				}

				string line;
				if (data.Contains("Pages free")) {
					line = data.Split(":")[1].Replace(".", "").Trim().TrimEnd();
					if (int.TryParse(line, out var foo)) {
						free = foo;
					}
				}

				if (data.Contains("Pages active")) {
					line = data.Split(":")[1].Replace(".", "").Trim().TrimEnd();
					if (int.TryParse(line, out var foo)) {
						active = foo;
					}
				}

				if (data.Contains("Pages speculative")) {
					line = data.Split(":")[1].Replace(".", "").Trim().TrimEnd();
					if (int.TryParse(line, out var foo)) {
						spec = foo;
					}
				}

				if (data.Contains("Pages throttled")) {
					line = data.Split(":")[1].Replace(".", "").Trim().TrimEnd();
					if (int.TryParse(line, out var foo)) {
						throttled = foo;
					}
				}

				if (data.Contains("Pages wired down")) {
					line = data.Split(":")[1].Replace(".", "").Trim().TrimEnd();
					if (int.TryParse(line, out var foo)) {
						wired = foo;
					}
				}
			}

			var total = free + active + spec + throttled + wired;
			process.Dispose();
			return total == 0 ? 0 : active / total;
		}

19 Source : CooperativeShutdown.cs
with Apache License 2.0
from damianh

internal async Task Listen()
            {
                while (!_stopListening.IsCancellationRequested)
                {
                    // message transmission mode is not supported on Unix
                    var pipe = new NamedPipeServerStream(_pipeName,
                        PipeDirection.InOut,
                        NamedPipeServerStream.MaxAllowedServerInstances,
                        PipeTransmissionMode.Byte,
                        PipeOptions.None);

                    _logger.LogInformation($"Listening on pipe '{_pipeName}'.");

                    await pipe
                        .WaitForConnectionAsync(_stopListening.Token)
                        .ConfigureAwait(false);

                    _logger.LogInformation($"Client connected to pipe '{_pipeName}'.");

                    try
                    {
                        using (var reader = new StreamReader(pipe))
                        {
                            using (var writer = new StreamWriter(pipe) { AutoFlush = true })
                            {
                                while (true)
                                {
                                    // a pipe can get disconnected after OS pipes enumeration as well
                                    if (!pipe.IsConnected)
                                    {
                                        _logger.LogDebug($"Pipe {_pipeName} connection is broken re-connecting");
                                        break;
                                    }

                                    var s = await reader.ReadLineAsync().WithCancellation(_stopListening.Token)
                                        .ConfigureAwait(false);

                                    if (s != "EXIT")
                                    {
                                        continue;
                                    }

                                    _logger.LogInformation($"Received command from server: {s}");

                                    await writer.WriteLineAsync("OK").ConfigureAwait(false);
                                    _logger.LogInformation("Responded with OK");

                                    _logger.LogInformation("Raising exit request...");
                                    _shutdownRequested();

                                    return;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        // As the pipe connection should be restored this exception should not be considered as terminating
                        _logger.LogDebug(ex, "Pipe connection failed");
                    }
                }
            }

19 Source : AsyncEnumerable.cs
with Apache License 2.0
from danielmarbach

async IAsyncEnumerable<int> ReadDelays([EnumeratorCancellation] CancellationToken token = default)
    {
        using (var stream = File.OpenRead("AsyncEnumerable.txt"))
        using (var reader = new StreamReader(stream))
        {
            string line;
            while ((line = await reader.ReadLineAsync()
                .ConfigureAwait(false)) != null && !token.IsCancellationRequested)
            {
                Console.WriteLine("  Read next line");
                yield return Convert.ToInt32(line);
            }
        }
        Console.WriteLine("  Done enumerating");
    }

19 Source : ValueTasksExtensions.cs
with Apache License 2.0
from danielmarbach

public static async Task<int> LoadFromFileAndCache(this ValueTasks runnable, string key)
    {
        using (var stream = File.OpenText(@"Values.txt"))
        {
            string line;
            while ((line = await stream.ReadLineAsync()) != null)
            {
                var splitted = line.Split(Convert.ToChar(";"));
                var k = splitted[0];
                var v = Convert.ToInt32(splitted[1]);

                if (k != key)
                {
                    continue;
                }

                runnable.cachedValues.TryAdd(k, v);
                return v;
            }
        }
        return 0;
    }

19 Source : ServiceRunner.cs
with GNU Affero General Public License v3.0
from devunt

private IAsyncEnumerator<byte[]> HandleHttpRequest(StreamReader reader)
        {
            return new AsyncEnumerator<byte[]>(async yield =>
            {
                while (true)
                {
                    var requestLine = await reader.ReadLineAsync();
                    if (string.IsNullOrWhiteSpace(requestLine))
                    {
                        yield.Break();
                    }

                    var request = new HttpRequest(requestLine);
                    while (true)
                    {

                        var line = await reader.ReadLineAsync();
                        if (string.IsNullOrEmpty(line))
                        {
                            if (request.Headers.TryGetValue("Content-Length", out string contentLength))
                            {
                                var length = int.Parse(contentLength);
                                var bytes = new List<char>(length);
                                while (bytes.Count < length)
                                {
                                    var buffer = new char[length];
                                    var readCount = await reader.ReadAsync(buffer, 0, length);
                                    bytes.AddRange(buffer.Take(readCount));
                                }

                                request.AddBody(bytes.Select(c => (byte) c));
                            }

                            break;
                        }

                        request.AddHeader(line);
                    }
                    Log.D($"[{Identifier}] {request.Method} {request.Path}");

                    var response = await ((IHttpHandler) Handler).HandleRequest(request);
                    await yield.ReturnAsync(response.ToBytes());

                    if (response.Headers.TryGetValue("Connection", out object connection))
                    {
                        if (connection.ToString().ToLower() == "close")
                        {
                            yield.Break();
                        }
                    }
                }
            });
        }

19 Source : ServiceRunner.cs
with GNU Affero General Public License v3.0
from devunt

private IAsyncEnumerator<byte[]> HandleWsRequest(StreamReader reader)
        {
            return new AsyncEnumerator<byte[]>(async yield =>
            {
                var requestLine = await reader.ReadLineAsync();
                if (string.IsNullOrWhiteSpace(requestLine))
                {
                    yield.Break();
                }

                var httpRequest = new HttpRequest(requestLine);
                while (true)
                {
                    var line = await reader.ReadLineAsync();
                    if (string.IsNullOrEmpty(line))
                    {
                        break;
                    }

                    httpRequest.AddHeader(line);
                }

                Log.D($"[{Identifier}] WS Handshake {httpRequest.Path}");

                var key = Encoding.ASCII.GetBytes(httpRequest.Headers["Sec-WebSocket-Key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");

                var httpResponse = new HttpResponse();
                httpResponse.StatusCode = HttpStatusCode.SwitchingProtocols;
                httpResponse.Headers["Connection"] = "Upgrade";
                httpResponse.Headers["Upgrade"] = "websocket";
                httpResponse.Headers["Sec-WebSocket-Accept"] = Convert.ToBase64String(SHA1.Create().ComputeHash(key));

                await yield.ReturnAsync(httpResponse.ToBytes());

                while (true)
                {
                    var request = new WsRequest();

                    while (true)
                    {
                        var buffer = new byte[1024];
                        var readCount = await reader.BaseStream.ReadAsync(buffer, 0, buffer.Length);

                        if (request.AddBytes(buffer.Take(readCount)))
                        {
                            break;
                        }
                    }

                    Log.D($"[{Identifier}] WS Message ({request.Opcode})");

                    switch (request.Opcode)
                    {
                        case WsOpcode.Text:
                        case WsOpcode.Binary:
                            var response = await ((IWsHandler)Handler).HandleRequest(request);
                            await yield.ReturnAsync(response.ToBytes());
                            break;
                        case WsOpcode.Close:
                            yield.Break();
                            break;
                        case WsOpcode.Ping:
                        case WsOpcode.Pong:
                            break;
                        default:
                            Log.B(request.RawContent);
                            break;
                    }
                }
            });
        }

19 Source : KubeResourceClient.cs
with MIT License
from DimensionDataResearch

protected IObservable<string> ObserveLines(HttpRequest request)
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));
            
            return
                Observable.Create<string>(async (subscriber, subscriptionCancellation) =>
                {
                    try
                    {
                        using (HttpResponseMessage responseMessage = await Http.GetStreamedAsync(request, subscriptionCancellation))
                        {
                            responseMessage.EnsureSuccessStatusCode();

                            using (Stream responseStream = await responseMessage.Content.ReadreplacedtreamAsync())
                            using (StreamReader responseReader = new StreamReader(responseStream))
                            {
                                string line = await responseReader.ReadLineAsync();
                                while (line != null)
                                {
                                    subscriber.OnNext(line);

                                    line = await responseReader.ReadLineAsync();
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException operationCanceled)
                    {
                        if (operationCanceled.CancellationToken == subscriptionCancellation)
                            return; // Not an error.

                        subscriber.OnError(operationCanceled);
                    }
                    catch (Exception exception)
                    {
                        subscriber.OnError(exception);
                    }
                    finally
                    {
                        subscriber.OnCompleted();
                    }
                })
                .Publish() // All subscribers share the same connection
                .RefCount(); // Connection is opened as the first client connects and closed as the last client disconnects.
        }

19 Source : FileEx.cs
with MIT License
from Dirkster99

public static async Task<List<string>> GetFileTextLinesAsync(string path)
		{
			var lines = new List<string>();

			// Open the FileStream with the same FileMode, FileAccess
			// and FileShare as a call to File.OpenText would've done.
			using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions))
			{
				var bom = new byte[4];               // Decode bom (if any) and continue to read text content
				await stream.ReadAsync(bom, 0, 4);
				stream.Seek(0, SeekOrigin.Begin);
				Encoding encoding = GetEncoding(bom);

				using (var reader = new StreamReader(stream, encoding))
				{
					string line;
					while ((line = await reader.ReadLineAsync()) != null)
					{
						lines.Add(line);
					}
				}
			}

			return lines;
		}

19 Source : CancelOnProcessTerminationTests.cs
with MIT License
from dotnet

[LinuxOnlyTheory]
        [InlineData(SIGINT, Skip = "https://github.com/dotnet/command-line-api/issues/1206")]  // Console.CancelKeyPress
        [InlineData(SIGTERM)] // AppDomain.CurrentDomain.ProcessExit
        public async Task CancelOnProcessTermination_cancels_on_process_termination(int signo)
        {
            const string ChildProcessWaiting = "Waiting for the command to be cancelled";
            const int CancelledExitCode = 42;

            Func<string[], Task<int>> childProgram = (string[] args) =>
            {
                var command = new Command("the-command")
                {
                    Handler = CommandHandler.Create<CancellationToken>(async ct =>
                    {
                        try
                        {
                            Console.WriteLine(ChildProcessWaiting);
                            await Task.Delay(int.MaxValue, ct);
                        }
                        catch (OperationCanceledException)
                        {
                            // For Process.Exit handling the event must remain blocked as long as the
                            // command is executed.
                            // We are currently blocking that event because CancellationTokenSource.Cancel
                            // is called from the event handler.
                            // We'll do an async Yield now. This means the Cancel call will return
                            // and we're no longer actively blocking the event.
                            // The event handler is responsible to continue blocking until the command
                            // has finished executing. If it doesn't we won't get the CancelledExitCode.
                            await Task.Yield();

                            return CancelledExitCode;
                        }

                        return 1;
                    })
                };
                return new CommandLineBuilder(new RootCommand
                       {
                           command
                       })
                       .CancelOnProcessTermination()
                       .Build()
                       .InvokeAsync("the-command");
            };

            using RemoteExecution program = RemoteExecutor.Execute(childProgram, psi: new ProcessStartInfo { RedirectStandardOutput = true });
            
            Process process = program.Process;

            // Wait for the child to be in the command handler.
            string childState = await process.StandardOutput.ReadLineAsync();
            childState.Should().Be(ChildProcessWaiting);

            // Request termination
            kill(process.Id, signo).Should().Be(0);

            // Verify the process terminates timely
            bool processExited = process.WaitForExit(10000);
            if (!processExited)
            {
                process.Kill();
                process.WaitForExit();
            }
            processExited.Should().Be(true);

            // Verify the process exit code
            process.ExitCode.Should().Be(CancelledExitCode);
        }

19 Source : HistoryAPI.cs
with MIT License
from dotnet-shell

public static async Task<string> ListenForSearchResultAsync(Action<int, string> onStartedListening)
        {
            var result = string.Empty;

            var r = new Random();
            var token = Guid.NewGuid().ToString();
            TcpListener listener;

            int port;
            while (true)
            {
                try
                {
                    var randomPortToTry = r.Next(1025, 65535);
                    listener = new TcpListener(IPAddress.Loopback, randomPortToTry);
                    listener.Start();
                    port = randomPortToTry;
                    break;
                }
                catch (SocketException)
                {

                }
            }

            onStartedListening?.Invoke(port, token);

            using (var client = await listener.AcceptTcpClientAsync())
            using (var sr = new StreamReader(client.GetStream()))
            {
                var clientToken = await sr.ReadLineAsync();
                if (clientToken != token)
                {
                    throw new InvalidDataException("Invalid token");
                }

                result = await sr.ReadLineAsync();
            }

            listener.Stop();
            return result;
        }

19 Source : DotNetRunner.cs
with MIT License
from dotnet-outdated

private static async Task ConsumeStreamReaderAsync(StreamReader reader, StringBuilder lines)
        {
            await Task.Yield();

            string line;
            while ((line = await reader.ReadLineAsync()) != null)
            {
                lines.AppendLine(line);
            }
        }

19 Source : FurnaceRecipeLoader.cs
with MIT License
from dotnetGame

public async Task LoadRecipes(StreamReader streamReader)
        {
            while (!streamReader.EndOfStream)
            {
                var line = await streamReader.ReadLineAsync();
                ParseLine(line);
            }
        }

19 Source : PlaylistTokenizer.cs
with GNU Lesser General Public License v3.0
from dotnettools

public async Task<PlaylistToken> ReadAsync()
        {
            while (!_reader.EndOfStream)
            {
                var content = await _reader.ReadLineAsync().ConfigureAwait(false);
                var token = ParseToken(content);
                if (token != null)
                    return token;
            }

            return null;
        }

19 Source : AssetScriptReferenceRetargeter.cs
with MIT License
from doughtmw

private static async Task ProcessYamlFile(string filePath, string targetPath, Dictionary<string, Tuple<string, long>> remapDictionary)
        {
            int lineNum = 0;
            using (StreamReader reader = new StreamReader(filePath))
            using (StreamWriter writer = new StreamWriter(targetPath))
            {
                while (!reader.EndOfStream)
                {
                    string line = await reader.ReadLineAsync();
                    lineNum++;
                    if (line.Contains("m_Script") || (filePath.EndsWith(".anim") && line.Contains("script")))
                    {
                        if (!line.Contains('}'))
                        {
                            // Read the second line as well
                            line += await reader.ReadLineAsync();
                            lineNum++;

                            if (!line.Contains('}'))
                            {
                                throw new InvalidDataException($"Unexpected part of YAML line split over more than two lines, starting two lines: {line}");
                            }
                        }

                        if (line.Contains(ScriptFileIdConstant))
                        {
                            Match regexResults = Regex.Match(line, Utilities.MetaFileGuidRegex);
                            if (!regexResults.Success || regexResults.Groups.Count != 2 || !regexResults.Groups[1].Success || regexResults.Groups[1].Captures.Count != 1)
                            {
                                throw new InvalidDataException($"Failed to find the guid in line: {line}.");
                            }

                            string guid = regexResults.Groups[1].Captures[0].Value;
                            if (remapDictionary.TryGetValue(guid, out Tuple<string, long> tuple))
                            {
                                line = Regex.Replace(line, @"fileID: \d+, guid: \w+", $"fileID: {tuple.Item2}, guid: {tuple.Item1}");
                            }
                            else if (nonClreplacedDictionary.ContainsKey(guid))
                            {
                                // this guid bypreplacedes throwing the exception. The reason for this is that there is currently an replacedet (OculusXRSDKDeviceManagerProfile.replacedet) that is reliant
                                // on Unity 2019+ specific code (OculusXRSDKDeviceManagerProfile.cs), which causes CI to fail since it's running on Unity 2018.
                                if (guid != "4f726b4cb3605994fac74d508110ec62")
                                {
                                    throw new InvalidDataException($"A script without a clreplaced ({nonClreplacedDictionary[guid]}) is being processed.");
                                }
                            }
                            else
                            {
                                // Switch to error later
                                Debug.LogWarning($"Couldn't find a script remap for {guid} in file: '{filePath}' at line '{lineNum}'.");
                            }
                        }
                        // else this is not a script file reference
                    }
                    else if (line.Contains(ScriptFileIdConstant))
                    {
                        throw new InvalidDataException($"Line in file {filePath} contains script type but not m_Script: {line.Trim()}");
                    }
                    // { fileID: 11500000, guid: 83d9acc7968244a8886f3af591305bcb, type: 3}

                    await writer.WriteLineAsync(line);
                }
            }
        }

19 Source : TickParser.cs
with MIT License
from dshe

internal static async Task<ITick[]> ToTicks<T>(this StreamReader streamReader) where T: ITick
        {
            HashSet<ITick> ticks = new();
            // read header
            await streamReader.ReadLineAsync().ConfigureAwait(false); 
            while (!streamReader.EndOfStream)
            {
                string? row = await streamReader.ReadLineAsync().ConfigureAwait(false);
                if (row == null)
                    continue;
				ITick? tick = GetTick<T>(row);
                if (tick == null)
                    continue;
                if (!ticks.Add(tick))
                    throw new InvalidDataException("Duplicate tick date: " + tick.ToString() + ".");
            }
            // occasionally, ticks are returned in seemingly random order!
            return ticks.OrderBy(x => x.Date).ToArray();
        }

19 Source : CommonFunc.cs
with MIT License
from EjiHuang

public static async Task<List<string>> ReadLineAsync(string filePath)
        {
            var list = new List<string>();

            using (var reader = new StreamReader(filePath))
            {
                string line;

                while ((line = await reader.ReadLineAsync()) != null)
                {
                    list.Add(line);
                }
            }
            return list;
        }

19 Source : CsvDataReader.cs
with Apache License 2.0
from elastic

public async Task<IEnumerable<HistoricalValue>> GetHistoricalQuotes(string symbol)
		{
			var retVal = new List<HistoricalValue>();
			symbol = symbol.Replace('.', '_');
			var logPath = _folderPath + Path.DirectorySeparatorChar + symbol + ".csv";
			var logFile = File.OpenRead(logPath);
			using (var logReader = new StreamReader(logFile))
			{
				string line;
				while ((line = await logReader.ReadLineAsync()) != null)
				{
					var items = line.Split(',');
					var date = items[0].Split('-');

					retVal.Add(new HistoricalValue
					{
						Date = new DateTime(int.Parse(date[0]), int.Parse(date[1]), int.Parse(date[2])),
						Close = decimal.Parse(items[1].Replace(',', '.'), CultureInfo.InvariantCulture),
						High = decimal.Parse(items[2].Replace(',', '.'), CultureInfo.InvariantCulture),
						Low = decimal.Parse(items[3].Replace(',', '.'), CultureInfo.InvariantCulture),
						Open = decimal.Parse(items[4].Replace(',', '.'), CultureInfo.InvariantCulture)
					});
				}
			}

			return retVal;
		}

19 Source : CmdRunner.cs
with MIT License
from emgarten

private static async Task ReadStreamAsync(StreamReader streamReader, StringBuilder lines)
        {
            await Task.Yield();

            while (true)
            {
                var currentLine = await streamReader.ReadLineAsync();

                if (currentLine == null)
                {
                    break;
                }

                lines.AppendLine(currentLine);
            };
        }

See More Examples