WriteAsync() public method

public WriteAsync ( char value ) : System.Threading.Tasks.Task
value char
return System.Threading.Tasks.Task
Esempio n. 1
0
		protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
		{
			using (var writer = new StreamWriter(stream))
			{
                await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
				await writer.FlushAsync();
							
				while (Connected)
				{
					try
					{
						var result = await manualResetEvent.WaitAsync(5000);
						if (Connected == false)
							return;

						if (result == false)
						{
                            await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
							await writer.FlushAsync();

                            if (lastMessageEnqueuedAndNotSent != null)
                            {
								await SendMessage(lastMessageEnqueuedAndNotSent, writer);
                            }
							continue;
						}

						manualResetEvent.Reset();

						object message;
						while (msgs.TryDequeue(out message))
						{
							if (CoolDownWithDataLossInMiliseconds > 0 && Environment.TickCount - lastMessageSentTick < CoolDownWithDataLossInMiliseconds)
                            {
                                lastMessageEnqueuedAndNotSent = message;
                                continue;
                            }

							await SendMessage(message, writer);
						}
					}
					catch (Exception e)
					{
						Connected = false;
						log.DebugException("Error when using events transport", e);
						Disconnected();
						try
						{
							writer.WriteLine(e.ToString());
						}
						catch (Exception)
						{
							// try to send the information to the client, okay if they don't get it
							// because they might have already disconnected
						}

					}
				}
			}
		}
Esempio n. 2
0
        public static async void ExportData(ADatabase db, List<int> experiments, bool showMessagebox = true)
        {
            try
            {
                List<int> test = ADatabaseWorker.GetAllParametersIDs(db);
                foreach (int experiment in experiments)
                {
                    List<string> writeData = ADatabaseWorker.GetAllDataForExport(db, experiment, test);
                    if (!Directory.Exists("export"))
                        Directory.CreateDirectory("export");
                    using (StreamWriter outfile = new StreamWriter("export\\ExperimentID" + experiment.ToString() + ".csv", false, Encoding.UTF8))
                    {
                        string header = "experimentID; Дата; ";
                        foreach (string parameterName in ADatabase.Parameters)
                        {
                            header += parameterName + "; ";
                        }
                        await outfile.WriteAsync(header + Environment.NewLine);

                        foreach (string line in writeData)
                            await outfile.WriteAsync(line);
                    }
                    if (showMessagebox)
                        MessageBox.Show("Export complete!");
                }
            }
            catch (Exception ex)
            {
            }

        }
Esempio n. 3
0
		private async Task SendMessage(object message, StreamWriter writer)
		{
            var o = JsonExtensions.ToJObject(message);        
            await writer.WriteAsync("data: ");
            await writer.WriteAsync(o.ToString(Formatting.None));
            await writer.WriteAsync("\r\n\r\n");
            await writer.FlushAsync();
		}
Esempio n. 4
0
 private void writeCSVHeader()
 {
     using (System.IO.StreamWriter sw = new System.IO.StreamWriter(saveFile, true))
     {
         sw.WriteAsync("Time");
         for (int i = 0; i < valueLables.Count(); i++)
         {
             sw.WriteAsync("," + valueLables[i]);
         }
         sw.WriteAsync(Environment.NewLine);
     }
 }
 public async Task Invoke(IDictionary<string, object> environment)
 {
     var response = environment["owin.ResponseBody"] as Stream;
     using (var writer = new StreamWriter(response))
     {
         if (_options.IncludeTimestamp)
         {
             await writer.WriteAsync(DateTime.Now.ToLongTimeString());
         }
         await writer.WriteAsync("Hello, " + _options.Name + "!");
     }
 }
		protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
		{
			using (var writer = new StreamWriter(stream))
			{
                await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
				await writer.FlushAsync();
							
				while (Connected)
				{
					try
					{
						var result = await manualResetEvent.WaitAsync(5000);
						if (Connected == false)
							return;

						if (result == false)
						{
                            await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
							await writer.FlushAsync();
							continue;
						}
						manualResetEvent.Reset();
						object message;
						while (msgs.TryDequeue(out message))
						{
							var obj = JsonConvert.SerializeObject(message, Formatting.None, new EtagJsonConverter());
							await writer.WriteAsync("data: ");
							await writer.WriteAsync(obj);
							await writer.WriteAsync("\r\n\r\n");
							await writer.FlushAsync();
						}
					}
					catch (Exception e)
					{
						Connected = false;
						log.DebugException("Error when using events transport", e);
						Disconnected();
						try
						{
							writer.WriteLine(e.ToString());
						}
						catch (Exception)
						{
							// try to send the information to the client, okay if they don't get it
							// because they might have already disconnected
						}

					}
				}
			}
		}
Esempio n. 7
0
 private void writeCSVline()
 {
     using (System.IO.StreamWriter sw = new System.IO.StreamWriter(saveFile, true))
     {
         sw.WriteAsync(DateTime.Now.ToString());
         foreach (float value in collectedValues)
         {
             //sw.WriteAsync(DateTime.Now.ToString());
             sw.WriteAsync("," + value);
         }
         sw.WriteAsync(Environment.NewLine);
         //collectedValues.Clear();
     }
 }
Esempio n. 8
0
 static void WriteFullyQualifiedName()
 {
     //var personRepo = Factories.RepositoryFactory.GetRepository<IRepository<Person>>();
     var type = typeof(IRepository<Person>);
     var assemblyQualifiedName = typeof(SQLRepository.SQLRepository<Person>);
     var path = PathHelper.GetProjectDirectory();
     var finalPath = Path.Combine(path, "AssemblyNames.txt");
     using (var writer = new StreamWriter(finalPath,true))
     {
         writer.WriteAsync(type.ToString());
         writer.WriteAsync('\n');
         writer.WriteAsync(assemblyQualifiedName.AssemblyQualifiedName);
     }
 }
		public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
		{
			var values = value as IEnumerable;
			using (var writer = new StreamWriter(writeStream))
			{
				await writer.WriteAsync("<!DOCTYPE html><html><head></head><body>");
				foreach (object line in values)
				{
					await writer.WriteAsync(line + "<br />");
				}
				await writer.WriteAsync("</body></html>");
			}
			writeStream.Close();
		}
        public async Task Invoke(HttpContext context)
        {
            var cache = connection.GetDatabase();

            // Get this from the context in whatever way the user supplies it
            var consumerKey = Guid.NewGuid().ToString();

            var consumerCacheKey = $"consumer.throttle#{consumerKey}";

            var cacheResult = cache.HashIncrement(consumerCacheKey, 1);

            if (cacheResult == 1)
            {
                cache.KeyExpire($"consumer.throttle#{consumerKey}", TimeSpan.FromSeconds(15), CommandFlags.FireAndForget);
            }
            else if (cacheResult > requestsPerMinuteThreshold)
            {
                context.Response.StatusCode = 429;

                using (var writer = new StreamWriter(context.Response.Body))
                {
                    await writer.WriteAsync("You are making too many requests.");
                }

                return;
            }

            await next(context);
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            string zipPath = @"C:\\Users\\rainaldo crosbourne\\Documents\\GitHub\\Zippy\\zippy_files\\test.zip";

            string outputFile = @"C:\\Users\\rainaldo crosbourne\\Documents\\GitHub\\Zippy\\zippy_files\\t2.txt";
            //Create the zip archive
            //ZipFile.CreateFromDirectory(Path.GetDirectoryName(zipPath), zipPath);
            //Add entries to the archive
            //Close the archive
            //using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            //{

            //}
            //Creates a new, blank zip file to work with - the file will be
            //finalized when the using statement completes
            using (ZipArchive newFile = ZipFile.Open(zipPath, ZipArchiveMode.Create))
            {
                ZipArchiveEntry readmeEntry = newFile.CreateEntry(Path.GetFileName(outputFile),CompressionLevel.Fastest);
                using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                {
                    writer.WriteAsync("This is a test file writen and stream and added to zip file");
                }
                //using (System.IO.StreamWriter outFile = new System.IO.StreamWriter(outputFile))
                //{
                    //Output file name
                //    outFile.Write(string.Format("The test file\n"));
                //    //Iterate through Report dictionary
               // }
                //newFile.CreateEntryFromFile(outputFile, Path.GetFileName(outputFile), CompressionLevel.Fastest);
            }
            Console.ReadKey();
        }
 public async Task InsertRecordAsync(HttpEntry record)
 {
     var path = Path.Combine(_location, record.LoggingId.ToString("d"));
     using (var stream = File.OpenWrite(path))
     using (var writer = new StreamWriter(stream))
         await writer.WriteAsync(JsonConvert.SerializeObject(record));
 }
Esempio n. 13
0
        SaveAsync
        (
            string format = "json"
        )
        {
            string content = null;

            switch (format)
            {
            case "json":
            default:
                content = GoogleMavenData.SerializeToJSON_Newtonsoft(this);
                break;
            }

            string type_name = this.GetType().Name;
            string timestamp = DateTime.Now.ToString("yyyyMMdd-HHmm");
            string filename  = $"{type_name}-{timestamp}.{format}";

            //System.IO.File.WriteAllText(filename, content);
            using (System.IO.StreamWriter writer = System.IO.File.CreateText(filename))
            {
                await writer.WriteAsync(content);
            }

            return;
        }
Esempio n. 14
0
        public async Task Invoke(IDictionary<string, object> environment)
        {
            var path = (string)environment["owin.RequestPath"];

            OminifyPackage package;
            if (!packages.TryGetValue(path, out package))
            {
                await next(environment);
                return;
            }

            var responseHeaders = (IDictionary<string, string[]>)environment["owin.ResponseHeaders"];
            var responseBody = (Stream)environment["owin.ResponseBody"];

            responseHeaders["Content-Type"] = new[] { package.GetContentType() };
            responseHeaders["Access-Control-Allow-Origin"] = new[] { "*" };
            responseHeaders["Cache-Control"] = new[] { TimeSpan.FromDays(1).TotalSeconds.ToString(CultureInfo.InvariantCulture) };
            responseHeaders["Expires"] = new[] { DateTime.UtcNow.AddYears(1).ToString("R") };
            responseHeaders["Last-Modified"] = new[] { package.GetLastModifiedUtc(options).ToString("R") };

            using (var writer = new StreamWriter(responseBody))
            {
                await writer.WriteAsync(package.GetContent(options));
            }
        }
Esempio n. 15
0
        public async Task<VenueSearchResponse> SearchAsync(VenueSearchRequest searchRequest)
        {
            if (searchRequest == null)
            {
                throw new NoNullAllowedException("A valid search request is required.");
            }
            var request = WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/json";

            var data = JsonConvert.SerializeObject(searchRequest);
            using (var stream = await request.GetRequestStreamAsync())
            {
                using (var writer = new StreamWriter(stream))
                {
                    await writer.WriteAsync(data);
                }
            }

            request.ContentLength = data.Length;
            var response = await request.GetResponseAsync();
            using (var stream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    return JsonConvert.DeserializeObject<VenueSearchResponse>(reader.ReadToEnd());
                }
            }
        }
Esempio n. 16
0
		private async Task SendMessage(LogEventInfo message, StreamWriter writer)
		{
            var o = JsonExtensions.ToJObject(new LogEventInfoFormatted(message));        
            await writer.WriteAsync("data: ");
            await writer.WriteAsync(o.ToString(Formatting.None));
            await writer.WriteAsync("\r\n\r\n");
		}
        public static async Task <bool> PrintToZPLByIP(string printIP, string zplString)
        {
            int port = 9100; //6101

            try
            {
                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(printIP, port);

                // Write ZPL String to connection
                System.IO.StreamWriter writer =
                    new System.IO.StreamWriter(client.GetStream());
                await writer.WriteAsync(zplString);

                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();

                return(true);
            }
            catch
            {
                return(false);
                // Catch Exception
            }
        }
        private static async Task ReadHtmlWithAsyncAwait()
        {
            var httpClient = new HttpClient();
            try
            {
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
                HttpResponseMessage message = await httpClient.GetAsync("http://codevalue.net");
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

                Console.WriteLine($"response code is {message.StatusCode}");
                var html = await message.Content.ReadAsStringAsync();
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

                using (var file = File.Open(@"c:\codevalue.html",FileMode.OpenOrCreate))
                using (var writer=new StreamWriter(file))
                {
                    await writer.WriteAsync(html);
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

                }
                Console.WriteLine(html);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
           
        }
Esempio n. 19
0
 protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
 {
     string jsonString = await JsonConvert.SerializeObjectAsync(this.JsonObject);
     StreamWriter writer = new StreamWriter(stream);
     await writer.WriteAsync(jsonString);
     await writer.FlushAsync();
 }
Esempio n. 20
0
        private async void btnSave_Click(object sender, EventArgs e)
        {
            if (tbData.Text.Length <= 0)
            {
                MessageBox.Show(@"No text entered", @"Error!", MessageBoxButtons.OK);
                return;
            }

            try
            {
                //create dir if it does not exists
                while (!Directory.Exists(PathToFile))
                {
                    Directory.CreateDirectory(PathToFile);
                }

                using (StreamWriter fs = new StreamWriter(Path.Combine(PathToFile, FileName), false))
                {
                    await fs.WriteAsync(tbData.Text);
                }
            }
            catch (IOException ex)
            {
                //catch error
                MessageBox.Show(ex.Message, @"Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 21
0
 internal static async Task WriteAsync(String path, String content)
 {
     var local = IsolatedStorageFile.GetUserStoreForApplication();
     var filePath = String.Format(PathFormat, path);
     if (local.FileExists(filePath))
     {
         using (var isoStoreFile = new IsolatedStorageFileStream(filePath, FileMode.Truncate, FileAccess.Write, local))
         {
             using (var isoStreamWriter = new StreamWriter(isoStoreFile))
             {
                 await isoStreamWriter.WriteAsync(content);
             }
         }
     }
     else
     {
         using (var isoStoreFile = new IsolatedStorageFileStream(filePath, FileMode.Create, FileAccess.Write, local))
         {
             using (var isoStreamWriter = new StreamWriter(isoStoreFile))
             {
                 await isoStreamWriter.WriteAsync(content);
             }
         }
     }
 }
        public async Task<bool> InsertOrUpdate(KeyVaultConfiguration keyVaultConfiguration)
        {
            var writeToFile = JsonConvert.SerializeObject(keyVaultConfiguration);
            var filePath = Path.Combine(
                ConfigurationPath,
                keyVaultConfiguration.VaultName,
                string.Format(ConfigurationFileFormat, keyVaultConfiguration.VaultName));
            
            var directoryPath = Path.Combine(ConfigurationPath, keyVaultConfiguration.VaultName);
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            using (var file = File.Create(filePath))
            {
                using (var streamWriter = new StreamWriter(file))
                {
                    await streamWriter.WriteAsync(writeToFile);
                    await streamWriter.FlushAsync();
                    this.allConfigurations.Remove(keyVaultConfiguration);
                    this.allConfigurations.Add(keyVaultConfiguration);
                    return true;
                }
            }
        }
Esempio n. 23
0
        private async void Save_OnClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txt.Text))
            {
                return;
            }

            try
            {
                StorageFolder sf = ApplicationData.Current.LocalFolder;
                StorageFolder cacheFolder = await sf.CreateFolderAsync("cache", CreationCollisionOption.OpenIfExists);
                var file = await cacheFolder.CreateFileAsync("txt", CreationCollisionOption.ReplaceExisting);
                using (var stream = await file.OpenStreamForWriteAsync())
                {
                    using (StreamWriter sw = new StreamWriter(stream))
                    {
                        await sw.WriteAsync(txt.Text);
                        throw new Exception("xxx");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Save_OnClick");
                Debug.WriteLine(ex);
            }
            
        }
Esempio n. 24
0
 public async Task Save()
 {
     var roaming = ApplicationData.Current.RoamingFolder;
     if (Session != null)
     {
         var data = JsonConvert.SerializeObject(Session);
         var file = await roaming.CreateFileAsync("settings.json", CreationCollisionOption.ReplaceExisting);
         using (var stream = await file.OpenStreamForWriteAsync())
         using (var writer = new StreamWriter(stream))
         {
             await writer.WriteAsync(data);
             await writer.FlushAsync();
         }
     }
     else
     {
         try
         {
             var file = await roaming.GetFileAsync("settings.json");
             await file.DeleteAsync();
         }
         catch (Exception ex)
         {
             Debug.WriteLine(ex.ToString());
         }
     }
 }
Esempio n. 25
0
        private async void doShipping(Order order)
        {
            try
            {
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                char seperator = Path.DirectorySeparatorChar;
                FileStream file = await Task.Run<FileStream>(() => File.Create(path + seperator + "dispatch-" + order.OrderID.ToString() + ".txt"));

                if (file != null)
                {
                    string dispatchNote = "Order Summary: " + 
                                          "\r\nOrder ID: " + order.OrderID +
                                          "\r\nOrder Total: " + String.Format("{0:C}", order.TotalValue);

                    StreamWriter writer = new StreamWriter(file);
                    await writer.WriteAsync(dispatchNote);
                    await Task.Run(() => writer.Close());
                }
                else
                {
                    MessageBox.Show(String.Format("Unable to save to file: {0}", file.Name), "Not saved");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception");
            }
        }
        private static async Task<TokenResponse> RedeemRefreshTokenInternalAsync(OAuthAccount account)
        {
            HttpWebRequest request = WebRequest.CreateHttp(account.TokenService);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            var requestStream = await request.GetRequestStreamAsync();
            var writer = new StreamWriter(requestStream);

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("client_id={0}", Uri.EscapeDataString(account.ClientId));
            sb.AppendFormat("&redirect_uri={0}", Uri.EscapeDataString(account.RedirectUri));
            sb.AppendFormat("&client_secret={0}", Uri.EscapeDataString(account.ClientSecret));
            sb.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(account.RefreshToken));
            sb.Append("&grant_type=refresh_token");
            if (null != account.Resource)
                sb.AppendFormat("&resource={0}", Uri.EscapeDataString(account.Resource));

            var content = sb.ToString();
            await writer.WriteAsync(content);
            await writer.FlushAsync();

            var response = await request.GetResponseAsync() as HttpWebResponse;
            if (null != response && response.StatusCode == HttpStatusCode.OK)
            {
                var responseStream = response.GetResponseStream();
                if (null != responseStream)
                {
                    var reader = new StreamReader(responseStream);
                    return JsonConvert.DeserializeObject<TokenResponse>(await reader.ReadToEndAsync());
                }
            }
            return null;
        }
Esempio n. 27
0
 private async void writeJson(string json, string filename)
 {
     using (StreamWriter outputFile = new StreamWriter(filename))
     {
         await outputFile.WriteAsync(json);
     }
 }
		internal static async Task WriteAsync(this Stream stream, string value)
		{
			using (var writer = new StreamWriter(stream))
			{
				await writer.WriteAsync(value);
			}
		}
Esempio n. 29
0
        /// <summary>
        /// Async method, return Response xmlDocument
        /// </summary>
        /// <param name="xmlRequest">xml request document</param>
        /// <returns></returns>
        public static async Task<XmlDocument> SendRequestXmlDocumentAsync(XmlDocument xmlRequest)
        {

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.novaposhta.ua/v2.0/xml/");
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.ContentType = @"application/x-www-form-urlencoded";
            ServicePointManager.DefaultConnectionLimit = 2000;
         
            var streamOut = new StreamWriter(await httpWebRequest.GetRequestStreamAsync());
            await streamOut.WriteAsync(xmlRequest.InnerXml);

            //streamOut.Flush();
            streamOut.Close();

            //In Stream
            var response = (await httpWebRequest.GetResponseAsync()).GetResponseStream();

            if (response == null)
                return null;

            var streamIn = new StreamReader(response);

            string strResponse = await streamIn.ReadToEndAsync();
            streamIn.Close();
            response.Close();

            //Load XML data to XmlDocument
            var xmlResponse = new XmlDocument();
            xmlResponse.LoadXml(strResponse);

            return xmlResponse;
        }
Esempio n. 30
0
 public async Task AssignPin(string pin)
 {
     using (var writer = new StreamWriter(GpioPath.ExportPath(pin), false))
     {
         await writer.WriteAsync(pin);
     }
 }
Esempio n. 31
0
 public async Task WriteAsync(OutputFormatterWriteContext context)
 {
     using (var responceStream = new StreamWriter(context.HttpContext.Response.Body, Encoding.UTF8))
     {
         await responceStream.WriteAsync(JsonConvert.SerializeObject(context.Object, SerializerSettings));
     }
 }
Esempio n. 32
0
 public async Task<ActionResult> Index(List<Race> races)
 {
     StringBuilder sb = new StringBuilder();
     if (races == null)
     {
         return View();
     }
     foreach (var race in races)
     {
         sb.AppendLine(
             string.Format(
                 "insert into races(id, name, description, date, place, type, category, categoryFull, url, tags, lng, lat) values({0},'{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}');",
                 race.Id, 
                 race.Name.Replace("'", "''"), 
                 !string.IsNullOrEmpty(race.Description) ? race.Description.Replace("'", "''") : string.Empty, 
                 race.Date,
                 !string.IsNullOrEmpty(race.Place) ? race.Place.Replace("'", "''") : string.Empty, 
                 !string.IsNullOrEmpty(race.Type) ? race.Type.Replace("'", "''") : string.Empty, 
                 !string.IsNullOrEmpty(race.Category) ? race.Category.Replace("'", "''") : string.Empty, 
                 !string.IsNullOrEmpty(race.CategoryFull) ? race.CategoryFull.Replace("'", "''") : string.Empty, 
                 !string.IsNullOrEmpty(race.Url) ? race.Url.Replace("'", "''") : string.Empty,
                 !string.IsNullOrEmpty(race.Tags) ? race.Tags.Replace("'", "''") : string.Empty, 
                 race.Lng.Replace(",", "."), 
                 race.Lat.Replace(",", ".")));
         
     }
     var content = sb.ToString();
     using (StreamWriter outfile = new StreamWriter(string.Format(@"C:\Users\terehin\YandexDisk\ahotu\ahotu-{0}.sql", races[0].Category), true))
     {
         await outfile.WriteAsync(content);
     }
     return View();
 }
 public Task Invoke(IDictionary<string, object> environment)
 {
     // Get response stream and write to it
     var response = (Stream)environment["owin.ResponseBody"];
     using (var writer = new StreamWriter(response))
         return writer.WriteAsync("Hello from Owin!");
 }
Esempio n. 34
0
		private static async Task ServeDirectoryListingAsync(DirectoryInfo root, DirectoryInfo directory, HttpListenerResponse response)
		{
			StringBuilder listBuilder = new StringBuilder();

			foreach (FileInfo file in directory.EnumerateFiles())
			{
				String target = directory.IsSameDirectory(root) ? file.Name
				                                                : Path.Combine(directory.Name, file.Name);
				listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, file.Name);
			}

			foreach (DirectoryInfo subDirectory in directory.EnumerateDirectories())
			{
				String target = directory.IsSameDirectory(root) ? subDirectory.Name
				                                                : Path.Combine(directory.Name, subDirectory.Name);
				listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, subDirectory.Name);
			}

			String htmlResponse = String.Format("<ul>{0}</ul>", listBuilder.ToString());

			response.ContentType = "text/html";
			response.ContentLength64 = htmlResponse.Length;
			response.AddHeader("Date", DateTime.Now.ToString("r"));

			response.StatusCode = (Int32)HttpStatusCode.OK; // Must be set before writing to OutputStream.

			using (StreamWriter writer = new StreamWriter(response.OutputStream))
			{
				await writer.WriteAsync(htmlResponse).ConfigureAwait(false);
			}
		}
Esempio n. 35
0
 private static async Task SetData(string content)
 {
     // deserialize JSON directly from a file
     using (System.IO.StreamWriter file = new System.IO.StreamWriter(StorageFilePath, false))
     {
         await file.WriteAsync(content);
     }
 }
Esempio n. 36
0
        public async void SaveJson()
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(NameFile))
            {
                string output = JsonConvert.SerializeObject(Config);
                await file.WriteAsync(output);

                string date = DateTime.Now.ToLocalTime().ToString();
                Debug.WriteLine($"[{date}] Сохранение конфигурации.\n => {NameFile}");
            }
        }
Esempio n. 37
0
        private async Task _saveNeuronAsync(string filename, int x, int y, int z)
        {
            //_logger.LogInformation(1111, "NNet _saveNeuronTask save {filename} {state} {id}", filename, Neurons[z][y][x].State, Thread.CurrentThread.ManagedThreadId);
            //Thread.Sleep(_rand.Next(2000, 5000));
            var f = System.IO.File.Create(filename);

            using (var Writer = new System.IO.StreamWriter(f))
                await Writer.WriteAsync(JsonConvert.SerializeObject(
                                            Neurons[z][y][x]
                                            , Formatting.Indented
                                            ));
            //_logger.LogInformation(1111, "NNet _saveNeuronTask saved {filename} {state}", filename, Neurons[z][y][x].State);
        }
Esempio n. 38
0
 public async void saveAllWeight()
 {
     System.IO.StreamWriter weightTxt = new System.IO.StreamWriter(path);
     for (int i = 0; i < net.Count(); i++)
     {
         foreach (double w in net[i].weight)
         {
             await weightTxt.WriteAsync(w + " ");
         }
         weightTxt.WriteLine();
     }
     weightTxt.Close();
 }
    static int WriteAsync(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes <char>(L, 2))
            {
                System.IO.StreamWriter obj = (System.IO.StreamWriter)ToLua.CheckObject <System.IO.StreamWriter>(L, 1);
                char arg0 = (char)LuaDLL.lua_tonumber(L, 2);
                System.Threading.Tasks.Task o = obj.WriteAsync(arg0);
                ToLua.PushObject(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <string>(L, 2))
            {
                System.IO.StreamWriter obj = (System.IO.StreamWriter)ToLua.CheckObject <System.IO.StreamWriter>(L, 1);
                string arg0 = ToLua.ToString(L, 2);
                System.Threading.Tasks.Task o = obj.WriteAsync(arg0);
                ToLua.PushObject(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <char[]>(L, 2))
            {
                System.IO.StreamWriter obj = (System.IO.StreamWriter)ToLua.CheckObject <System.IO.StreamWriter>(L, 1);
                char[] arg0 = ToLua.CheckCharBuffer(L, 2);
                System.Threading.Tasks.Task o = obj.WriteAsync(arg0);
                ToLua.PushObject(L, o);
                return(1);
            }
            else if (count == 4)
            {
                System.IO.StreamWriter obj = (System.IO.StreamWriter)ToLua.CheckObject <System.IO.StreamWriter>(L, 1);
                char[] arg0 = ToLua.CheckCharBuffer(L, 2);
                int    arg1 = (int)LuaDLL.luaL_checknumber(L, 3);
                int    arg2 = (int)LuaDLL.luaL_checknumber(L, 4);
                System.Threading.Tasks.Task o = obj.WriteAsync(arg0, arg1, arg2);
                ToLua.PushObject(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: System.IO.StreamWriter.WriteAsync"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Esempio n. 40
0
        //Save order description
        public static string save_description_txt(string order_id, string description)
        {
            string filePath = System.Windows.Forms.Application.StartupPath + "\\Order description";

            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }

            string fileName = filePath + "\\" + order_id + ".txt";

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName))
            {
                sw.WriteAsync(description);
            }
            return(fileName);
        }
Esempio n. 41
0
        static void Main(string[] args)
        {
            string     data;
            FileStream fs = new FileStream("F:\\Bizruntime\\Workspace\\File IO\\f2.txt", FileMode.Open, FileAccess.ReadWrite);

            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
            sw.Write("hello to all");
            sw.WriteAsync("hello mitsian");
            using (StreamReader sr = new StreamReader(fs))
            {
                data = sr.ReadToEnd();
            }
            Console.WriteLine(data);
            sw.Close();
            fs.Close();
            Console.Read();
        }
        public static async void WriteFileToPath(string input_path, string linestowrite)
        {
            string path = input_path;

            // This text is added only once to the file.
            try
            {
                using (System.IO.StreamWriter file =
                           new System.IO.StreamWriter(path, true))
                {
                    await file.WriteAsync(linestowrite);
                }
            }
            catch (Exception ex)
            {
                GlobalClass.Log("ERROR @ WriteFileToPath" + ex.ToString());
            }
        }
        public async Task SaveConfgurationAsync(ConfigurationModel config, string name = "./Configuration/appsettings.json")
        {
            try
            {
                using (var file = new System.IO.StreamWriter(name, false))
                {
                    var json = config.ToJson();
                    await file.WriteAsync(json);

                    Configuration = config;
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, "the config file could not be read.");
                throw;
            }
        }
Esempio n. 44
0
        public async Task WriteStateAsync(string grainType,
                                          GrainReference grainRef,
                                          IGrainState grainState)
        {
            var storedData = JsonConvert.SerializeObject(grainState.State, _jsonSettings);

            var collectionName = grainState.GetType().Name;
            var key            = grainRef.ToKeyString();

            var fName = key + "." + collectionName;
            var path  = System.IO.Path.Combine(RootDirectory, fName);

            var fileInfo = new System.IO.FileInfo(path);

            using (var stream = new System.IO.StreamWriter(
                       fileInfo.Open(System.IO.FileMode.Create,
                                     System.IO.FileAccess.Write)))
            {
                await stream.WriteAsync(storedData);
            }
        }
Esempio n. 45
0
        static async void TestReadingUsingStreamReaderAndLinq()
        {
            DateTime jobEnd;
            DateTime jobStart = DateTime.Now;

            Console.WriteLine(" [Test Case] TestReadingUsingStreamReaderAndLinq");
            Console.WriteLine("Reading file: " + logfile);
            Console.WriteLine("Job Start Time: " + jobStart.ToLongTimeString());

            try
            {
                using (StreamReader sr = File.OpenText(logfile))
                {
                    string   line        = "";
                    long     total       = 0;
                    long     matchlines  = 0;
                    string[] toSearchFor = new string[] { "xslF345X02/primary_doc.xml", "725363", "3537" };

                    StringBuilder sb = new StringBuilder();
                    while ((line = sr.ReadLine()) != null)
                    {
                        // 使用Linq 查詢字串是否包含特色字串
                        if (ContainsAll(line, toSearchFor))
                        {
                            if (DisplayLine)
                            {
                                sb.AppendLine(string.Format("Line({0}) : {1}", total, line));
                                // Console.WriteLine(string.Format("Line({0}) : {1}", total, line));
                            }
                            matchlines++;
                        }
                        total++;
                    }

                    // 非同步寫入符合的記錄
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputfile))
                    {
                        // Can write either a string or char array
                        await file.WriteAsync(sb.ToString());
                    }

                    Console.WriteLine("Match Lines: " + matchlines);
                    Console.WriteLine("Total Lines: " + total);
                }
            }
            catch (OutOfMemoryException)
            {
                Console.WriteLine("Not enough memory. Couldn't perform this test.");
                Console.WriteLine();
            }
            catch (Exception)
            {
                Console.WriteLine("EXCEPTION. Couldn't perform this test.");
                Console.WriteLine();
            }
            jobEnd = DateTime.Now;
            Console.WriteLine("Job End Time: " + jobEnd.ToLongTimeString());
            Console.WriteLine("Job During: " + (jobEnd - jobStart));
            Console.WriteLine("====================================================");

            GC.Collect();
        }
Esempio n. 46
0
        public static void CreateCSV(string writepath, List <TestLimit> limits)
        {
            string        delimeter     = ",";
            List <string> headercolumns = new List <string>();

            headercolumns.Add("Product" + "," + Header.DeviceName.ToString());
            headercolumns.Add("Revision" + "," + Header.DeviceName.ToString());
            headercolumns.Add("Start Time" + "," + string.Format("{0:yyyy/MM/dd HH:mm:ss}", Header.START_T));
            headercolumns.Add("End Time" + "," + string.Format("{0:yyyy/MM/dd HH:mm:ss}", Header.FINISH_T));
            headercolumns.Add("Comment" + "," + "Where are the comments?");
            headercolumns.Add("Operator ID" + "," + Header.OperatorID.ToString());
            headercolumns.Add("Tester ID" + "," + Header.TesterID.ToString());
            headercolumns.Add("Lot ID" + "," + Header.CustomerLotNo.ToString());
            headercolumns.Add("Session ID" + "," + "Where is Session ID?");
            headercolumns.Add("Test Program Name" + "," + Header.ProgramName.ToString());
            headercolumns.Add("Test Type" + "," + Header.ModeCode.ToString());
            headercolumns.Add("# of sites" + "," + "Hard coded 4");
            headercolumns.Add("# of devices tested" + "," + Summary.Count.ToString());
            headercolumns.Add("# of pass devices" + "," + "Have not pulled passed items yet");
            headercolumns.Add("Yield" + "," + "Have not pulled yield items yet");

            int length = headercolumns.Count; using (System.IO.TextWriter writer = File.CreateText(writepath))
            {
                foreach (string item in headercolumns)
                {
                    writer.WriteLine(string.Join(delimeter, item));
                }
                writer.WriteLine();
            }

            StringBuilder headers = new StringBuilder();

            headers.Append("," + "Site" + "," + "X-coordinate" + "," + "Y-Coordinate" + "," + "Pass Fail" + "," + "Hard Bin" + "," + "Soft Bin" + "," + "Test Time" + "," + "Test Number");
            File.AppendAllText(writepath, headers.ToString());

            //var testresults = Summary.First().TestResults;
            StringBuilder TestNumber = new StringBuilder();
            StringBuilder TestName   = new StringBuilder();
            StringBuilder Units      = new StringBuilder();
            StringBuilder LowerLimit = new StringBuilder();
            StringBuilder UpperLimit = new StringBuilder();

            foreach (var limit in limits)
            {
                if (limit.TestNumber == "-1")
                {
                    continue;
                }

                TestNumber.Append("," + limit.TestNumber);
                TestName.Append("," + limit.TestName);
                Units.Append("," + limit.Units);
                LowerLimit.Append("," + limit.FTLower);
                UpperLimit.Append("," + limit.FTUpper);
            }

            File.AppendAllText(writepath, TestNumber.ToString());

            StringBuilder tn    = new StringBuilder();
            StringBuilder units = new StringBuilder();
            StringBuilder ll    = new StringBuilder();
            StringBuilder ul    = new StringBuilder();

            using (TextWriter writer2 = File.AppendText(writepath))
            {
                writer2.WriteLine();
            }
            tn.Append("," + "," + "," + "," + "," + "," + "," + "," + "Test Name");
            units.Append("," + "," + "," + "," + "," + "," + "," + "," + "Units");
            ll.Append("," + "," + "," + "," + "," + "," + "," + "," + "Lower Limit");
            ul.Append("Device #" + "," + "," + "," + "," + "," + "," + "," + "," + "Upper Limit");

            File.AppendAllText(writepath, tn.ToString());
            File.AppendAllText(writepath, TestName.ToString());

            using (TextWriter writer2 = File.AppendText(writepath))
            {
                writer2.WriteLine();
            }
            File.AppendAllText(writepath, units.ToString());
            File.AppendAllText(writepath, Units.ToString());
            using (TextWriter writer2 = File.AppendText(writepath))
            {
                writer2.WriteLine();
            }
            File.AppendAllText(writepath, ll.ToString());
            File.AppendAllText(writepath, LowerLimit.ToString());
            using (TextWriter writer2 = File.AppendText(writepath))
            {
                writer2.WriteLine();
            }
            File.AppendAllText(writepath, ul.ToString());
            File.AppendAllText(writepath, UpperLimit.ToString());

            ////using (TextWriter writer2 = File.AppendText(writepath))
            ////{
            ////    writer2.WriteLine();
            ////}
            ////File.AppendAllText(writepath, TestResults.ToString());

            using (TextWriter writer2 = File.AppendText(writepath))
            {
                writer2.WriteLine();
            }

            {
                int length3 = Summary.Count; using (System.IO.StreamWriter writer = File.AppendText(writepath))
                //int length3 = Summary.Count; using (System.IO.TextWriter writer = File.(writepath))
                {
                    writer.WriteLine();
                    int x = 1;
                    foreach (PartResult device in Summary)
                    {
                        writer.WriteAsync(x.ToString() + "," + device.SiteNumber.ToString() + "," + "Xcor" + "," + "Ycor" + "," + (device.isSuccess == false ? "Fail" : "Pass") +
                                          "," + device.HardBin.BinNum.ToString() + "," + device.SoftBin.BinNum.ToString() + "," + device.Duration.ToString() + ","
                                          );

                        x++;
                        foreach (TestResult result in device.TestResults)
                        {
                            writer.Write("," + result.Result.ToString());
                        }
                        writer.WriteLine();

                        writer.Flush();
                    }
                }

                //////int length3 = Summary.Count; using (System.IO.StreamWriter writer = File.AppendText(writepath))
                //////{
                //////    writer.WriteLine();
                //////    int x = 1;
                //////    foreach (PartResult device in Summary)
                //////    {
                //////        writer.Write(x.ToString() + "," + device.SiteNumber.ToString() + "," + "Xcor" + "," + "Ycor" + "," +
                //////        device.isSuccess.ToString() + "," + device.HardBin.BinNum.ToString() + "," + device.SoftBin.BinNum.ToString() + "," +
                //////        device.Duration.ToString());
                //////        writer.WriteLine();
                //////        x++;
                //////    }
                //////}

                //int length4 = Summary.Count; using (System.IO.StreamWriter writer = File.AppendText(writepath))
                //{
                //    writer.WriteLine();
                //    foreach (PartResult device in Summary)
                //    {
                //        foreach(TestResult result in device.TestResults)
                //        {
                //            result.
                //        }
                //        writer.Write(x.ToString() + "," + device.SiteNumber.ToString() + "," + "Xcor" + "," + "Ycor" + "," +
                //        device.isSuccess.ToString() + "," + device.HardBin.BinNum.ToString() + "," + device.SoftBin.BinNum.ToString() + "," +
                //        device.Duration.ToString());
                //        writer.WriteLine();
                //        x++;
                //    }
                //}
            }
        }
Esempio n. 47
0
 public static Task WriteAsync(this StreamWriter writer, char[] buffer)
 {
     return(writer.WriteAsync(buffer, 0, buffer.Length));
 }
Esempio n. 48
0
 static async Task w(string c, string f)
 {
     using (w r = new w(f)){ await r.WriteAsync(c); }
 }