ReadLineAsync() public method

public ReadLineAsync ( ) : Task
return Task
Beispiel #1
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);
                }
            }
        }
 private async void Open_Stream_Click(object sender, RoutedEventArgs e)
 {
     (sender as Button).IsEnabled = false;
     string url = String.Format("https://api.particle.io/v1/devices/{0}/events/NeedCover?access_token={1}", PHOTON1DEVICEID, ACCESS_TOKEN);
     WebRequest request = WebRequest.Create(url);
     request.Method = "GET";
     using (WebResponse response = await request.GetResponseAsync())
     {
         using (Stream stream = response.GetResponseStream())
         {
             StreamReader reader = new StreamReader(stream);
             int blankRead = 0;
             while (blankRead <= 1)
             {
                 // Event comes streaming in 3 lines. blank line, 
                 // "event: NeedCover", 
                 // then a json line that starts with "data:",
                 // If more than a couple blank lines in a row then we're done with the stream.
                 var str = await reader.ReadLineAsync();
                 if (string.IsNullOrEmpty(str))
                 {
                     ++blankRead;
                 }
                 else if (str == "event: NeedCover")
                 {
                     blankRead = 0;
                     var data = await reader.ReadLineAsync();
                     var jsonData = JsonConvert.DeserializeObject<ParticleEvent>(data.Substring(data.IndexOf("data:") + 5));
                     streamResultTextBox.Text = jsonData.data;
                 }
             }
         }
     }
     (sender as Button).IsEnabled = true;
 }
Beispiel #3
0
        public async Task ResponseLimit()
        {
            var client = CreateClient();
            var url = BaseUrl + "/000/" + Guid.NewGuid().ToString();

            var request = new HttpRequestMessage(HttpMethod.Post, url + "/xhr_streaming");
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

            string msg = "\"" + new string('x', 128) + "\"";
            int nrOfMessages = 31;
            for (int i = 0; i < nrOfMessages; i++)
            {
                var sendResponse = await client.PostAsync(url + "/xhr_send", new StringContent("[" + msg + "]", Encoding.UTF8, "application/json"));
                Assert.Equal(HttpStatusCode.NoContent, sendResponse.StatusCode);
            }

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var contentStream = await response.Content.ReadAsStreamAsync();
            var reader = new StreamReader(contentStream);
            var prelude = await reader.ReadLineAsync();
            var open = await reader.ReadLineAsync();
            Assert.Equal(new string('h', 2048), prelude);
            Assert.Equal("o", open);
            var remaining = await reader.ReadToEndAsync();
            Assert.Equal(string.Concat(Enumerable.Repeat("a[" + msg + "]\n", nrOfMessages)), remaining);
        }
        public async Task<bool> HandshakeConnection(NetworkStream ClientStream)
        {
            StreamReader Reader = new StreamReader(ClientStream);
            StreamWriter Writer = new StreamWriter(ClientStream);

            TCPGetRequestHeader RequestHeader = new TCPGetRequestHeader();

            string message = await Reader.ReadLineAsync();
            while (message != Terminal)
            {
                this.ParseHeader(message, ref RequestHeader);
                message = await Reader.ReadLineAsync();
            }

            string accept = this.AcceptKey(RequestHeader.SocketKey);

            Writer.Write("HTTP/1.1 101 Switching Protocols\r\n");
            Writer.Write("Upgrade: websocket\r\n");
            Writer.Write("Connection: Upgrade\r\n");
            Writer.Write("Sec-WebSocket-Accept: " + accept + "\r\n");
            Writer.Write("\r\n");

            Writer.Flush();

            return true;
        }
Beispiel #5
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();
                    }
                }
            }
        }
Beispiel #6
0
        public async Task Transport()
        {
            var client = CreateClient();
            var url = BaseUrl + "/000/" + Guid.NewGuid().ToString();

            var request = new HttpRequestMessage(HttpMethod.Post, url + "/xhr_streaming");
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("UTF-8", response.Content.Headers.ContentType.CharSet);
            Assert.Equal("application/javascript", response.Content.Headers.ContentType.MediaType);
            AssertCors(response, null);

            var contentStream = await response.Content.ReadAsStreamAsync();
            var reader = new StreamReader(contentStream);
            var prelude = await reader.ReadLineAsync();
            var open = await reader.ReadLineAsync();
            Assert.Equal(new string('h', 2048), prelude);
            Assert.Equal("o", open);

            var sendResponse = await client.PostAsync(url + "/xhr_send", new StringContent("[\"x\"]", Encoding.UTF8, "application/json"));
            Assert.Equal(HttpStatusCode.NoContent, sendResponse.StatusCode);

            var message = await reader.ReadLineAsync();
            Assert.Equal("a[\"x\"]", message);

            client.Dispose();
        }
 public static async void InitLoadSet() {
   string fileContent;
   Uri uri = new Uri("ms-appx:///Data/Sets.txt");
   file = await StorageFile.GetFileFromApplicationUriAsync(uri);
   StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync());
   fileContent = await sRead.ReadLineAsync();
   KeyValuePair<int, object> res = Type(fileContent);
   ListWords currentListWords = new ListWords();
   while (res.Key != -1)
   {
     if (res.Key == 0)
     {
       currentListWords.Name = (string)res.Value;
       SetsNames.Add((string)res.Value);
     }
     if (res.Key == 1)
     {
       currentListWords.Add((Word)res.Value);
     }
     if (res.Key == 2)
     {
       SetsWords.Add(currentListWords.Name, currentListWords);
       currentListWords = new ListWords();
     }
     fileContent = sRead.ReadLineAsync().Result;
     res = Type(fileContent);
   }
   MainPage.CurrentListWords = SetsWords["None"];
   sRead.Dispose();
 }
Beispiel #8
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            #region 进度提示窗口设置
            ProgressForm progressForm = new ProgressForm();
            progressForm.Size = new Size(600, 80);
            progressForm.StartPosition = FormStartPosition.Manual;
            progressForm.Location = new Point(this.DesktopLocation.X + this.Width / 2 - progressForm.Size.Width / 2, this.DesktopLocation.Y + this.Height / 2 - progressForm.Size.Height / 2);
            progressForm.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            progressForm.progress.Maximum = 100;
            progressForm.progress.Minimum = 0;
            progressForm.progress.Value = 0;
            progressForm.Show(this);
            this.Enabled = false;
            #endregion

            using (StreamReader reader = new StreamReader("TitleUrl.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string title = await reader.ReadLineAsync();
                    string url = await reader.ReadLineAsync();

                    try
                    {
                        titleURL.Add(title, url);
                    }
                    catch (Exception)
                    {
                        // 异常:
                        //   T:System.ArgumentNullException:
                        //     key 为 null。
                        //
                        //   T:System.ArgumentException:
                        //     System.Collections.Generic.Dictionary`2 中已存在具有相同键的元素。
                    }

                    //更新进度条
                    if (progressForm.progress.Value < 90)
                    {
                        progressForm.progress.Value++;
                        progressForm.Text = "正在加载离线数据:" + progressForm.progress.Value + "%";                        
                    }

                }
            }

            progressForm.progress.Value = 100;
            progressForm.Text = "任务进度:" + progressForm.progress.Value + "%";
            progressForm.Close();
            this.Enabled = true;

        }
        /// <summary>
        /// Splits the file into the specified number of files.
        /// </summary>
        /// <param name="filePath">The file to split.</param>
        /// <param name="fileCount">The number of files to split the original file into.</param>
        /// <returns>The list of file names generated by splitting the original file.</returns>
        public async Task<List<string>> SplitAsync(string filePath, int fileCount)
        {
            List<string> filePaths = new List<string>();

            //Load the existing file.
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
            {
                using (StreamReader streamReader = new StreamReader(fileStream))
                {
                    //Count the total number of lines in the original file.
                    int lineCount = 0;
                    while (!streamReader.EndOfStream)
                    {
                        ++lineCount;
                        await streamReader.ReadLineAsync();
                    }

                    //Compute the number of lines per file.
                    int linesPerFile = lineCount / fileCount;

                    streamReader.BaseStream.Seek(0, SeekOrigin.Begin);

                    //Generate each output file.
                    for(int i = 0; i < fileCount; i++)
                    {
                        string fileName = Helpers.GetSplitFileName(i);
                        
                        filePaths.Add(fileName);

                        using (FileStream newFileStream = new FileStream(fileName, FileMode.Create))
                        {
                            using (StreamWriter streamWriter = new StreamWriter(newFileStream))
                            {
                                for (int linesInCurrentFile = 0; 
                                    linesInCurrentFile < linesPerFile ||
                                    (i == fileCount - 1 && !streamReader.EndOfStream); //Write any remaining lines (due to rounding) to the last file.
                                    linesInCurrentFile++)
                                {
                                    string line = await streamReader.ReadLineAsync();

                                    await streamWriter.WriteLineAsync(line);
                                }
                            }
                        }
                    }

                }
            }

            return filePaths;
        }
        private async void ServerStub(TcpClient client)
        {
            string ipClient = client.Client.RemoteEndPoint.ToString();
            Console.WriteLine("Подключился клиент: {0}", ipClient);

            NetworkStream ns = client.GetStream();
            StreamWriter sw = new StreamWriter(ns);
            StreamReader sr = new StreamReader(ns);

            try
            {
                string method = await sr.ReadLineAsync();
                int arg1 = int.Parse(await sr.ReadLineAsync());
                int arg2 = int.Parse(await sr.ReadLineAsync());
                int res = 0;

                switch (method)
                {
                    case "+":
                        res = add(arg1, arg2);
                        break;

                    case "-":
                        res = sub(arg1, arg2);
                        break;

                    case "*":
                        res = mul(arg1, arg2);
                        break;

                    default:
                        throw new Exception("Неверный код функции");
                }

                sw.WriteLine(res);

                Console.WriteLine("Клиент {0} присал сообщение: {1} {2} {3} | {4}", ipClient, method, arg1, arg2, res);
            }
            catch (Exception e)
            {
                Console.WriteLine("Ошибка при обработке пакета от клиента: {0}", ipClient);
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
            }
            finally
            {
                sw.Close();
                sr.Close();
                client.Close();
                Console.WriteLine("Клиент отключился: {0}", ipClient);
            }
        }
        protected override async Task HandleClient(TcpClient client) {
            using (var stream = client.GetStream())
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream)) {

                string line = await reader.ReadLineAsync().ConfigureAwait(false);

                while (line != null) {
                    writer.WriteLine(line);
                    writer.Flush();
                    line = await reader.ReadLineAsync().ConfigureAwait(false);
                }
            }
        }
Beispiel #12
0
 public Capitals()
 {
     foreach (var item in _fileNames)
     {
         using (StreamReader reader = new StreamReader(item, Encoding.GetEncoding("windows-1251")))
         {
             while (reader.Peek() > -1)
             {
                 Task<string> readText = reader.ReadLineAsync();
                 if (readText != null)
                 {
                     string[] cuntryAndCapital = readText.Result.Split(';');
                     cuntryAndCapital[0] = cuntryAndCapital[0].Trim();
                     cuntryAndCapital[1] = cuntryAndCapital[1].Trim();
                     Capital newOne = new Capital
                     {
                         NameCountry = cuntryAndCapital[0],
                         NameCapital = cuntryAndCapital[1]
                     };
                     _countriesWithCapitals.Add(newOne);
                 }
             }
         }
     }
 }
        private async Task ParseGroundTruthTxt(string path)
        {
            _groundTruthBoxs.Clear();
            using (StreamReader reader = new StreamReader(path))
            {
                while (!reader.EndOfStream)
                {
                    string line = await reader.ReadLineAsync();
                    
                    string[] points = line.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries);

                    GroundTruthBox groundTruthBox = new GroundTruthBox();
                    
                    groundTruthBox.DownLeft.X = double.Parse(points[0]);
                    groundTruthBox.DownLeft.Y = double.Parse(points[1]);
                    groundTruthBox.DownRight.X = double.Parse(points[2]);
                    groundTruthBox.DownRight.Y = double.Parse(points[3]);
                    groundTruthBox.UpRight.X = double.Parse(points[4]);
                    groundTruthBox.UpRight.Y = double.Parse(points[5]);
                    groundTruthBox.UpLeft.X = double.Parse(points[6]);
                    groundTruthBox.UpLeft.Y = double.Parse(points[7]);

                    _groundTruthBoxs.Add(groundTruthBox);
                }
            }
        }
        /// <summary>
        /// read data for week 3 task
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static async Task<List<Vertex>> ReadVertexArray(string fileName)
        {
            try
            {
                List<Vertex> vertices = new List<Vertex>();

                using (var stream = new StreamReader(fileName))
                {
                    while (!stream.EndOfStream)
                    {
                        var line = await stream.ReadLineAsync();
                        var values = line.Split(new char[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                        int n = Int32.Parse(values[0]);
                        List<int> edges = new List<int>();

                        for (int i = 1; i < values.Length; i++)
                        {
                            edges.Add(Int32.Parse(values[i]));
                        }

                        vertices.Add(new Vertex(n, edges));
                    }
                }

                return vertices;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
        public async Task<IEnumerable<FtpFileInfo>> GetFilesListAsync(string path)
        {
            var ftpRequest = PrepareRequest(path, WebRequestMethods.Ftp.ListDirectoryDetails);

            var result = new List<FtpFileInfo>();

            using (var responce = await ftpRequest.GetResponseAsync())
            using (var stream = responce.GetResponseStream())
            {
                if (stream == null)
                {
                    throw new FtpException();
                }

                using (var streamReader = new StreamReader(stream))
                {
                    var uri = new Uri(_baseUri, path);
                    while (streamReader.EndOfStream == false)
                    {
                        var nextLine = await streamReader.ReadLineAsync();
                        var fileInfo = FtpFileInfo.Parse(nextLine);
                        fileInfo.Uri = new Uri(uri, fileInfo.Name);
                        result.Add(fileInfo);
                    }
                }
            }
            return result;
        }
Beispiel #16
0
        public async Task ReceiveInput()
        {
            IsActive = true;
            _networkStream = _socket.GetStream();

            using (var reader = new StreamReader(_networkStream))
            {
                while (IsActive)
                {
                    try
                    {
                        var content = await reader.ReadLineAsync();

                        // If content is null, that means the connection has been gracefully disconnected
                        if (content == null)
                        {
                            MarkAsDisconnected();
                            return;
                        }

                        if (MessageReceived != null)
                            MessageReceived(this, content);
                    }

                    // If the tcp connection is ungracefully disconnected, it will throw an exception
                    catch (IOException)
                    {
                        MarkAsDisconnected();
                        return;
                    }
                }
            }
        }
Beispiel #17
0
        public async Task <IActionResult> UploadAndProcess(IFormFile file)
        {
            var content = new List <String>();

            if (file != null && file.Length > 0)
            {
                if (SystemConstants.AcceptedExtensions.Contains(Path.GetExtension(file.FileName).ToUpperInvariant()))
                {
                    using (var Reader = new System.IO.StreamReader(file.OpenReadStream()))
                    {
                        string inputLine = "";
                        while ((inputLine = await Reader.ReadLineAsync()) != null)
                        {
                            content.Add(inputLine);
                        }
                        Reader.Close();
                    }
                    //Upload
                    var res = await MdApi.PostPNLAsync(content);

                    return(PartialView("_PartialPassengerList", res));
                }
                else
                {
                    return(BadRequest(new { Result = false, Message = "please upload txt only" }));
                }
            }
            return(BadRequest(new { Result = false, Message = "Empty file" }));
        }
        private async Task <string> CheckResponse()
        {
            var answer = Console.ReadLine();

            using (var reader = new System.IO.StreamReader(ResponseFile, true))
            {
                while (!reader.EndOfStream)
                {
                    var line = await reader.ReadLineAsync();

                    if (line.StartsWith(answer))
                    {
                        Console.WriteLine(line.Substring(2));
                        Console.WriteLine("");
                        return(answer);
                    }
                }
            }

            var color = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("There is no answer response to this question");
            Console.ForegroundColor = color;
            return(null);
        }
Beispiel #19
0
        public async Task<IEnumerable<string>> LoadAsync()
        {
            List<string> feeds = new List<string>();

            try
            {
                using (FileStream fsAsync = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true))
                using (StreamReader sr = new StreamReader(fsAsync))
                {
                    string line = string.Empty;

                    while ((line = await sr.ReadLineAsync()) != null)
                    {
                        if (line.StartsWith("#") == false)
                        {
                            Uri tmp = null;
                            if (Uri.TryCreate(line, UriKind.Absolute, out tmp))
                            {
                                feeds.Add(line);
                            }
                        }
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Utils.LogException(e);
            }

            return feeds;
        }
        public async Task TestTcpTraceListener()
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);
            listener.Start();
            int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;


            var traceSource = new TraceSource("UnitTestLogger");
            traceSource.Listeners.Remove("Default");
            traceSource.Switch.Level = SourceLevels.All;
            traceSource.Listeners.Add(new TcpTraceListener(
                                            IPAddress.Loopback, port, 
                                            new ExponentialBackoffTcpReconnectionPolicy()));

            var listenerClient = await listener.AcceptTcpClientAsync();

            traceSource.TraceEvent(TraceEventType.Information, 100, "Boris");

            var receiverReader = new StreamReader(listenerClient.GetStream());
            var line = await receiverReader.ReadLineAsync();

            Assert.True(line.EndsWith("UnitTestLogger Information: 100 : Boris"));

            listenerClient.Close();
            listener.Stop();
            traceSource.Close();
        }
        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");

                }
            }
            
        }
        private async Task MainAsync()
        {
            var connStr = "mongodb://*****:*****@"handouts\homework_5_2";
            string inputFileName = "small_zips.json";
            string inputFilePath = Path.Combine(assignmentDir, inputFileName);

            using (var streamReader = new StreamReader(inputFilePath))
            {
                string line;
                while ((line = await streamReader.ReadLineAsync()) != null)
                {
                    var document = BsonSerializer.Deserialize<ZipEntry>(line);
                    await col.InsertOneAsync(document);
                }
            }

            var agg = col.Aggregate()
                .Match(x => new[] { "CA", "NY" }.Contains(x.State))
                .Group(x => x.City, g => new { Count = g.Count(), TotalPop = g.Sum(x => x.Population) })
                .Match(x => x.TotalPop > 25 * 1000)
                .Group(x => true, g => new { AvgPop = g.Average(x => x.TotalPop) })
                ;

            var cmd = String.Format("db.zips.{0}", agg.ToString());
            var results = await agg.ToListAsync();
        }
        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...");
        }
        /// <summary>
        /// Runs the mapper task.
        /// </summary>
        public async Task RunAsync()
        {
            CloudBlockBlob blob = new CloudBlockBlob(new Uri(this.blobSas));
            Console.WriteLine("Matches in blob: {0}/{1}", blob.Container.Name, blob.Name);

            using (Stream memoryStream = new MemoryStream())
            {
                //Download the blob.
                await blob.DownloadToStreamAsync(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);

                using (StreamReader streamReader = new StreamReader(memoryStream))
                {
                    Regex regex = new Regex(this.configurationSettings.RegularExpression);

                    int lineCount = 0;

                    //Read the file content.
                    while (!streamReader.EndOfStream)
                    {
                        ++lineCount;
                        string textLine = await streamReader.ReadLineAsync();

                        //If the line matches the search parameters, then print it out.
                        if (textLine.Length > 0)
                        {
                            if (regex.Match(textLine).Success)
                            {
                                Console.WriteLine("Match: \"{0}\" -- line: {1}", textLine, lineCount);
                            }
                        }
                    }
                }
            }
        }
Beispiel #25
0
        /* Loaders */

        // Load specified file (if exists).
        public async void LoadFile(String file)
        {
            try
            {
                using (StreamReader reader = new StreamReader(Path.GetFullPath(file)))
                {
                    // Read single line
                    String line;
                    while ((line = await reader.ReadLineAsync()) != null)
                    {
                        // Save raw line (could be useful)
                        rawItems.Add(line);

                        // Parse line by tabs
                        List<String> subitems = line.Split('\t').ToList();
                        parsedItems.Add(subitems);
                    }

                }
            }
            catch (Exception e)
            {
                logger.Error("Could not read file {0}: {1}", file, e.Message);
            }
        }
Beispiel #26
0
        public async override Task <ActionData> Action(string mapData)
        {
            try
            {
                writer.WriteLine(mapData);
                writer.Flush();
                // TODO どう書くのがいいのか
                var raw = await reader.ReadLineAsync();

                Console.WriteLine("RAW: " + Name + ": " + raw);
                string[] data = raw.Split(new char[] { ',' }, 3);
                if (data.Length == 3)
                {
                    return(new ActionData(this, data[0], bool.Parse(data[1]), data[2]));
                }
                else
                {
                    return(new ActionData(this, data[0], bool.Parse(data[1])));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                this.ch = '落';
                isAlive = false;
                return(new ActionData(this, "STAY", false));
            }
        }
        public async Task StartWaiting()
        {
            //SendHello
            var helloMessage = JsonConvert.SerializeObject(new MJsonMessageHello());
            SendMessageToClient(helloMessage);

            Debug.WriteLine(
                "Connect to Client ({0}:{1})" ,
                ( (IPEndPoint)tcpClient.Client.RemoteEndPoint ).Address ,
                ( (IPEndPoint)tcpClient.Client.RemoteEndPoint ).Port
                );

            try
            {
                NetworkStream stream = tcpClient.GetStream();
                StreamReader reader = new StreamReader(stream);

                while (tcpClient.Connected)
                {
                    string line = await reader.ReadLineAsync() + NetworkConstants.NewLineString;
                    //Debug.WriteLine("get:"+ line);
                    GetMessageFromClient(line);
                }
            }
            catch (IOException e)
            {
                Debug.Fail("error! : "+ e.Message);
                Disconnect();
                ClientConnectionBrokenHandler(this);
            }

        }
        public override async void GetRemoteMessage(TcpClient client)
        {
            string ipClient = client.Client.RemoteEndPoint.ToString();
            Console.WriteLine("Подключился клиент: {0}", ipClient);

            NetworkStream ns = client.GetStream();
            StreamWriter sw = new StreamWriter(ns);
            StreamReader sr = new StreamReader(ns);

            try
            {
                string message = "";
                while (message != "end")
                {
                    message = await sr.ReadLineAsync();
                    Console.WriteLine("Клиент {0} присал сообщение: {1}", ipClient, message);
                }
            }
            catch(Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
            finally
            {
                sw.Close();
                sr.Close();
                client.Close();
                Console.WriteLine("Клиент отключился: {0}", ipClient);
            }
        }
        private async void UploadData(string collectionName, string jsonFilePath)
        {
            try
            {
                await db.DropCollectionAsync(collectionName);
                var collection = db.GetCollection<Restaurant>(collectionName);
                using (var streamReader = new StreamReader(jsonFilePath))
                {
                    string line;
                    while ((line = await streamReader.ReadLineAsync()) != null)
                    {
                        using (var jsonReader = new JsonReader(line))
                        {
                            var context = BsonDeserializationContext.CreateRoot(jsonReader);
                            var document = collection.DocumentSerializer.Deserialize(context);
                            collection.InsertOneAsync(document);
                        }
                    }
                }

                Console.WriteLine("Successfully Uploaded Grades");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception \n\n");
                Console.WriteLine(ex.Message);
            }

        }
Beispiel #30
0
        public async Task<string[]> ReadAllLinesAsync(string path, Encoding encoding)
        {
            System.Diagnostics.Debug.WriteLine("Reading");
            var lines = new List<string>();
            char[] delimiterChars = { ',', ':', '\t' };

            using (var reader = new StreamReader(path, encoding))
            {
                string line;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    lines.Add(line);
                }
            }
            //Adds items to database based on the words in each line of the file.
            foreach (string item in lines)
            {
                string[] words = item.Split(delimiterChars);
                System.Diagnostics.Debug.WriteLine("Hello from the other side");
                DateTime date = new DateTime(2016, 6, 11);
                if (NewItem(Convert.ToInt32(words[0]), words[1], words[2], words[3], float.Parse(words[4]), Convert.ToInt32(words[5]), Convert.ToInt32(words[6]), Convert.ToInt32(words[7]), date))

                {
                    Console.WriteLine("Success");
                }
                else
                {
                    Console.WriteLine("Fail");
                }

            }
            //Deletes the file when done reading.
            File.Delete(path);
            return lines.ToArray();
        }
Beispiel #31
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);
     }
 }
        async void ReceiveData(TcpClient client)
        {
            NetworkStream stream = client.GetStream();
            StreamReader reader = new StreamReader(stream);

            while (true)
            {
                string message = await reader.ReadLineAsync();

                // If message is null then the client has disconnected
                if(message == null)
                {
                    clients.Remove(client);

                    Trace.TraceInformation("Disconnected from client {0}", client.Client.RemoteEndPoint.ToString());

                    return;
                }

                Trace.TraceInformation("Received data from client {0}: {1}", client.Client.RemoteEndPoint.ToString(), message);

                // Process data
                string[] words = message.Split(' ');
                if(words[0] == "GameResults")
                {
                    Game.RoundResults.Add(client.Client.RemoteEndPoint.ToString(), int.Parse(words[1]));
                }
            }
        }
Beispiel #33
0
        private static async Task<bool> ParseHeadingLineAsync(StreamReader reader,
            Action<string, string, string> onHeadingLine)
        {
            var line = await reader.ReadLineAsync();

            return RawParser.ParseHeadingLine(line, onHeadingLine);
        }
Beispiel #34
0
        async IAsyncEnumerable <string> GetLines(string filePath)
        {
            string       line;
            StreamReader file = new System.IO.StreamReader(filePath);

            while ((line = await file.ReadLineAsync()) != null)
            {
                await Task.Delay(300);

                yield return(line);
            }
        }
Beispiel #35
0
        /// <summary>
        /// For a given VHO #, add any new unique AltCodes into our member vho
        /// When completed a VHO, cache this in the DB
        /// </summary>
        /// <param name="vhoNumber"></param>
        public async Task <bool> AddUniqueFromVHOAsync(MongoDB.Driver.IMongoCollection <CatalogObject> collection)
        {
            Dictionary <string, CatalogObject> vho = new Dictionary <string, CatalogObject>();

            string path = GetTemplate(vhoNumber, "d:\\img\\img\\", new DateTime(2015, 7, 21));

            if (path != string.Empty)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Processing VHO : " + vhoNumber);
                Console.ForegroundColor = ConsoleColor.White;
                try
                {
                    String tempFile = Decompress(path);
                    using (StreamReader file = new System.IO.StreamReader(tempFile, Encoding.UTF8))
                    {
                        string line;
                        while ((line = await file.ReadLineAsync()) != null)
                        {
                            CatalogObject json = JsonConvert.DeserializeObject <CatalogObject>(line);

                            if ((json.AltCode == string.Empty))//blank AltCode, prob single screen
                            {
                                if (singleScreen)
                                {
                                    //Use the PID PAID since the AltCode is missing
                                    json.AltCode = json.ProviderID + ":" + json.ProviderAssetID.Substring(4);
                                    await AddMediaAsync(collection, json);
                                }
                            }
                            else if (multiScreen)
                            {
                                await AddMediaAsync(collection, json);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception caught opening file :" + ex.Message);
                }
            }
            //and Upsert the vho!
            //await collection.InsertManyAsync(vho.Values);
            return(true);
        }
Beispiel #36
0
 public async Task <IdentityUser> FindByIdAsync(string userId)
 {
     using (var stream = new IO.StreamReader(_filePath))
     {
         string       line;
         IdentityUser result = null;
         while ((line = await stream.ReadLineAsync()) != null)
         {
             var user = IdentityUser.FromString(line);
             if (user.Id == userId)
             {
                 result = user;
                 break;
             }
         }
         return(result);
     }
 }
Beispiel #37
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                endpoints.MapGrpcService <AccountGrpcService>();

                endpoints.MapGet("/_proto/", async ctx =>
                {
                    ctx.Response.ContentType = "text/plain";

                    using var fs = new System.IO.FileStream(System.IO.Path.Combine(env.ContentRootPath, "accounts.proto"), FileMode.Open, FileAccess.Read);
                    using var sr = new System.IO.StreamReader(fs);

                    while (!sr.EndOfStream)
                    {
                        var line = await sr.ReadLineAsync();
                        if (line != "/* >>" || line != "<< */")
                        {
                            await ctx.Response.WriteAsync(line);
                        }
                    }
                });
            });
        }
Beispiel #38
0
        public static async Task GetDataInsertDB(string resource, Action <double, uint> animatePbar)
        {
            CreateTables();
            UserDB dcon = new UserDB();
            var    db   = dcon.DbConn;


            int lineNum = 0;

            try

            {
                var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Verse)).Assembly;

                //foreach (var res in assembly.GetManifestResourceNames())
                //    info += "found resource: " + res;
                //Debug.WriteLine(info);
                Stream        stream = assembly.GetManifestResourceStream(resource);
                List <string> csv    = new List <string>();
                if (stream != null)
                {
                    using (var reader = new System.IO.StreamReader(stream))
                    {
                        while (-1 < reader.Peek())
                        {
                            csv.Add(await reader.ReadLineAsync());
                        }
                    }
                }
                else
                {
                    Debug.WriteLine("SHIT");
                }

                string strCurrentBook  = "";
                double dval            = 0;
                uint   length          = (uint)csv.Count;
                Regex  regexBook       = new Regex(@"[\d]* ?[A-z]+\b");
                Regex  regexChaptVerse = new Regex(@"\b[\d]+:[\d]+");
                bool   isOldTestament  = true;
                int    bookIndex       = 0;
                for (int i = 0; i < length; i++)
                {
                    //if (i == max)
                    //    break;
                    lineNum++;
                    string line       = csv[i];
                    string strRowBook = regexBook.Match(line).Value;
                    if (isOldTestament && strRowBook == "Matthew")
                    {
                        isOldTestament = false;
                    }
                    var    arrChapterVerse = regexChaptVerse.Match(line).Value.Split(':');
                    int    intRowChapter   = int.Parse(arrChapterVerse[0].Trim());
                    int    intVerseNum     = int.Parse(arrChapterVerse[1].Trim());
                    string strVerseContent = line.Substring(line.IndexOf(',') + 1);

                    if (strCurrentBook != strRowBook)
                    {
                        strCurrentBook = strRowBook;
                        bookIndex++;
                    }
                    var v = new Verse()
                    {
                        Text          = strVerseContent,
                        ChapterNumber = intRowChapter,
                        BookName      = strRowBook,
                        Testament     = isOldTestament ? "Old" : "New",
                        //Id = i+1,
                        LastRecited  = DateTime.Now.AddDays(-3000),
                        IsMemorized  = false,
                        VerseNumber  = intVerseNum,
                        BookPosition = bookIndex
                    };
                    db.Insert(v);
                    animatePbar?.Invoke(++dval, length);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("THIS LINE " + lineNum + "\n" + ex.ToString());
            }

            var vs = db.Table <Verse>().Count();
        }
Beispiel #39
0
        public async Task <bool> load()
        {
            try{
                string file_path = globals.models[uid].path;
                if (!globals.models.ContainsKey(uid) || globals.models[uid].class_type == null)
                {
                    Console.WriteLine("model not defined in load");
                    return(false);
                }
                stats.lines      = 0;
                stats.load_start = DateTime.Now.Ticks;
                string line;
                uint   index = 0;
                if (globals.debug)
                {
                    Console.WriteLine($"Reading: {file_path}");
                }
                if (!File.Exists(file_path))
                {
                    Console.WriteLine($"Data file does not exist: {file_path}");
                    return(false);
                }
                System.IO.StreamReader file = new System.IO.StreamReader(file_path);
                if (null == file)
                {
                    Console.WriteLine($"Cannot open file: {file_path}");
                    return(false);
                }

                bool has_key = !string.IsNullOrWhiteSpace(key);

                if (globals.debug)
                {
                    Console.WriteLine($"Key is '{key}' : {has_key}");
                }

                while ((line = await file.ReadLineAsync()) != null)
                {
                    index++;

                    record record = null;
                    try{
                        if (globals.models[uid].data_starts_on_line > index)
                        {
                            record = new record(uid, key, index, line, file_path, true);
                            Console.WriteLine(String.Format("Skipping Line: {0}", index));
                        }
                        else
                        {
                            record = new record(uid, key, index, line, file_path, false);
                        }
                    } catch (Exception ex) {
                        record = new record(uid, key, index, line, file_path, ex.Message, true);
                        errors.Add(ex.Message);
                        if (globals.debug)
                        {
                            //  if(errors.Count<debug_limit) {
                            Console.WriteLine("table parsing error: " + ex.Message);
                            //  }
                        }
                    }

                    /* TODO DUPE ERR
                     *  try{
                     *      if(has_key && record.is_data) {
                     *          int? hash=record.key_hash;
                     *          if(null==hash) {
                     *              //  throw new Exception(string.Format("Key '{0}': is null ",key));
                     *          }
                     *          if(null!=records && records.Count>0) {
                     *              record dupe=records.Find((r) =>r.key_hash==hash);
                     *              if(null!=dupe) {
                     *                  record.is_error=true;
                     *                  //  throw new Exception(string.Format("Duplicate record on key {0}:{1}",key,hash));
                     *              }
                     *          }
                     *      }
                     *  } catch (Exception ex) {
                     *      if(globals.debug) {
                     *      Console.WriteLine("table parsing error-dupe lookup: "+ex.Message);
                     *  }
                     */

                    records.Add(record);
                }
                //records.Sort((record x, record y) => x.line.CompareTo(y.line)); //order the list.. if usint parallel-ize
                is_loaded = true;
                file.Close();
                stats.lines = index;
                if (globals.debug)
                {
                    Console.WriteLine("Parsed");
                }
                stats.load_end = DateTime.Now.Ticks;
                return(true);
            } catch (Exception ex) {
                is_loaded      = false;
                stats.load_end = DateTime.Now.Ticks;
                Console.WriteLine("Loading data: " + ex.Message);
                return(false);
            }
        } //end load
Beispiel #40
0
        public static async Task <Tuple <string, Dictionary <string, byte[]> > > LoadToBytesAsync(Stream yfbfile)
        {
            string _name;
            Dictionary <string, byte[]> dic = new Dictionary <string, byte[]>();

            using (yfbfile)
            {
                long seek;
                using (var reader = new System.IO.StreamReader(yfbfile, System.Text.Encoding.UTF8, false, 128, true))
                {
                    string a = await reader.ReadLineAsync();

                    var b = a.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (b[0] == "yfb" && b[3] == "http://www.yinyue200.com/zh-cn/appList/yfxsrt/yfbfiles.aspx")
                    {
                        if (b[2] == "1.0.0.0" && b[1] == "smallpackage")
                        {
                            //文件符合格式要求
                            _name = await reader.ReadLineAsync();

                            seek = System.Text.Encoding.UTF8.GetByteCount(a + "\n" + _name + "\n");
                        }
                        else
                        {
                            throw new NotSupportedException();
                        }
                    }
                    else
                    {
                        throw new InvalidDataException();
                    }
                }
                yfbfile.Seek(seek, SeekOrigin.Begin);
                bool nextend = false;
                long nextpos = 0;

                string      name;
                List <byte> bytelist = new List <byte>();
re:
                int byt = yfbfile.ReadByte();
                if (byt == -1)
                {
                    return(new Tuple <string, Dictionary <string, byte[]> >(_name, dic));
                }
                else if (byt == 10)
                {
                    name = Encoding.UTF8.GetString(bytelist.ToArray());
                }
                else
                {
                    bytelist.Add((byte)byt);
                    goto re;
                }
                byte[] longbuffer = new byte[8];
                await yfbfile.ReadAsync(longbuffer, 0, longbuffer.Length);

                var startpos = BitConverter.ToInt64(longbuffer, 0);
                await yfbfile.ReadAsync(longbuffer, 0, longbuffer.Length);

                ulong startlens = BitConverter.ToUInt64(longbuffer, 0);
                long  nowpos    = yfbfile.Position;
                if (startpos == 0)
                {
                }
                else
                {
                    var fu = yfbfile.ReadByte();
                    if (fu == 1)
                    {
                        nextend = true;
                    }
                    else if (fu == 0)
                    {
                        await yfbfile.ReadAsync(longbuffer, 0, longbuffer.Length);

                        nextpos = BitConverter.ToInt64(longbuffer, 0);
                    }
                    yfbfile.Seek(startpos + nowpos, SeekOrigin.Begin);
                }
                byte[] content = new byte[startlens];
                yfbfile.Read(content, 0, content.Length);
                dic.Add(name, content);
                if (nextend)
                {
                    return(new Tuple <string, Dictionary <string, byte[]> >(_name, dic));
                }
                if (nextpos != 0)
                {
                    yfbfile.Seek(nextpos, SeekOrigin.Current);
                }
                bytelist = new List <byte>();
                goto re;
            }
        }
Beispiel #41
0
        public static async Task ExtractToDirectoryAsync(IStorageFolder folder, Stream yfbfile)
        {
            string _name;

            using (yfbfile)
            {
                long seek;
                using (var reader = new System.IO.StreamReader(yfbfile, System.Text.Encoding.UTF8, false, 128, true))
                {
                    string a = await reader.ReadLineAsync();

                    var b = a.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (b[0] == "yfb" && b[3] == "http://www.yinyue200.com/zh-cn/appList/yfxsrt/yfbfiles.aspx")
                    {
                        if (b[2] == "1.0.0.0" && b[1] == "smallpackage")
                        {
                            //文件符合格式要求
                            _name = await reader.ReadLineAsync();

                            seek = System.Text.Encoding.UTF8.GetByteCount(a + "\n" + _name + "\n");
                        }
                        else
                        {
                            throw new NotSupportedException();
                        }
                    }
                    else
                    {
                        throw new InvalidDataException();
                    }
                }
                yfbfile.Seek(seek, SeekOrigin.Begin);
                bool nextend = false;
                long nextpos = 0;

                string      name;
                List <byte> bytelist = new List <byte>();
re:
                int byt = yfbfile.ReadByte();
                if (byt == -1)
                {
                    return;
                }
                else if (byt == 10)
                {
                    name = Encoding.UTF8.GetString(bytelist.ToArray());
                }
                else
                {
                    bytelist.Add((byte)byt);
                    goto re;
                }
                byte[] longbuffer = new byte[8];
                await yfbfile.ReadAsync(longbuffer, 0, longbuffer.Length);

                var startpos = BitConverter.ToInt64(longbuffer, 0);
                await yfbfile.ReadAsync(longbuffer, 0, longbuffer.Length);

                ulong startlens = BitConverter.ToUInt64(longbuffer, 0);
                long  nowpos    = yfbfile.Position;
                if (startpos == 0)
                {
                }
                else
                {
                    var fu = yfbfile.ReadByte();
                    if (fu == 1)
                    {
                        nextend = true;
                    }
                    else if (fu == 0)
                    {
                        await yfbfile.ReadAsync(longbuffer, 0, longbuffer.Length);

                        nextpos = BitConverter.ToInt64(longbuffer, 0);
                    }
                    yfbfile.Seek(startpos + nowpos, SeekOrigin.Begin);
                }
                byte[] content = new byte[startlens];
                yfbfile.Read(content, 0, content.Length);
                using (var str = await(await folder.CreateFileAsync(name.Replace("/", "\\"), CreationCollisionOption.ReplaceExisting)).OpenTransactedWriteAsync())
                {
                    await str.Stream.WriteAsync(content.AsBuffer());

                    await str.CommitAsync();
                }
                if (nextend)
                {
                    return;
                }
                if (nextpos != 0)
                {
                    yfbfile.Seek(nextpos, SeekOrigin.Current);
                }
                bytelist = new List <byte>();
                goto re;
            }
        }