WriteAsync() public method

public WriteAsync ( char value ) : System.Threading.Tasks.Task
value char
return System.Threading.Tasks.Task
Example #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
						}

					}
				}
			}
		}
Example #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)
            {
            }

        }
Example #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();
		}
 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
						}

					}
				}
			}
		}
Example #6
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();
		}
Example #8
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 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);
            }
           
        }
Example #10
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());
         }
     }
 }
 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!");
 }
        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;
                }
            }
        }
		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);
			}
		}
Example #14
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());
                }
            }
        }
        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;
        }
 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);
             }
         }
     }
 }
Example #17
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();
 }
        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);
        }
 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));
 }
Example #20
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();
        }
Example #21
0
 private async void writeJson(string json, string filename)
 {
     using (StreamWriter outputFile = new StreamWriter(filename))
     {
         await outputFile.WriteAsync(json);
     }
 }
Example #22
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));
            }
        }
        /// <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;
        }
Example #24
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");
		}
Example #25
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);
            }
            
        }
Example #26
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 async Task WriteAsync(OutputFormatterWriteContext context)
 {
     using (var responceStream = new StreamWriter(context.HttpContext.Response.Body, Encoding.UTF8))
     {
         await responceStream.WriteAsync(JsonConvert.SerializeObject(context.Object, SerializerSettings));
     }
 }
Example #28
0
 public async Task AssignPin(string pin)
 {
     using (var writer = new StreamWriter(GpioPath.ExportPath(pin), false))
     {
         await writer.WriteAsync(pin);
     }
 }
Example #29
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);
            }
        }
		internal static async Task WriteAsync(this Stream stream, string value)
		{
			using (var writer = new StreamWriter(stream))
			{
				await writer.WriteAsync(value);
			}
		}