SaveAsync ( string format = "json" ) { string content = null; switch (format) { case "json": default: content = this.SerializeToJSON_Newtonsoft(); break; } string type_name = this.GetType().FullName; string timestamp = DateTime.Now.ToString("yyyyMMdd-HHmmss.ff"); 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; }
public static void CreateAccent(string name, Color highlight, Color accent) { using (var sw = new System.IO.StreamWriter(System.IO.File.Create(System.IO.Path.Combine(MeCore.DataDirectory, "Color", name + ".xaml")))) { string s = System.Windows.Markup.XamlWriter.Save(createResourceDictionary(highlight, accent)); System.Threading.Tasks.Task.WaitAll(sw.WriteAsync(s)); } }
/// <summary> /// Simple helper to write data to file /// </summary> /// <param name="data"></param> /// <param name="fileName"></param> /// <returns></returns> static async Task WriteDataToFile(string data, string fileName) { using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName)) { await file.WriteAsync(data); } }
//Metodo hace la copia de seguridad public void escribirMensaje() { int numFilas = dgvTabla.Rows.Count;//Cuenta el numero de filas que tiene la tabla String txtOrigen = ""; String txtDestino = ""; String texto = ""; //crea el fichero System.IO.StreamWriter file = new System.IO.StreamWriter(this.ruta, true); //Crear objeto StringBuilder para escribir un texto StringBuilder sb = new StringBuilder(); //Mientras la lista mensaje esta vacia while( !lmsg.Is_Empty()) { //devuelve el primer mensaje de la lista, con el origen,destino y el texto. Despues borra el msg de la lista Mensaje msg = lmsg.Get_First(); txtOrigen=msg.getOrigen(); txtDestino = msg.getDestino(); texto = msg.getMensaje(); lmsg.Remove_First(); //Agregar mensaje al objeto sb.AppendLine("Origen: " + txtOrigen + "#" + " Destino: " + txtDestino + "#" + " Texto: " + texto + "##"); } //escribe el mensaje en el fichero de texto file.WriteAsync(sb.ToString()); file.Close(); }
private async Task writeContent(string file, string content) { System.IO.Stream stream = null; System.IO.StreamWriter writer = null; Android.Net.Uri uri = Android.Net.Uri.Parse(file); try { stream = ContentResolver.OpenOutputStream(uri); writer = new System.IO.StreamWriter(stream, System.Text.Encoding.UTF8); await writer.WriteAsync(content); writer.Close(); stream.Close(); } finally { if (writer != null) { writer.Dispose(); } if (stream != null) { stream.Dispose(); } } }
/// <summary> /// Обеспечивает сохранение в файл тремя способами. /// </summary> /// <param name="path">Полный путь до файла для записи.</param> /// <param name="append">true для добавления данных в файл, false для перезаписи.</param> /// <param name="writeHeaders"></param> /// <returns>Задача, представляющая асинхронную операцию записи в файл.</returns> private async System.Threading.Tasks.Task Save(string path, bool append = false, bool writeHeaders = true) { if (fileOpened) { Cursor.Current = Cursors.WaitCursor; using (var writer = new System.IO.StreamWriter(path, append, System.Text.Encoding.Unicode)) { if (writeHeaders) { foreach (var header in Headers) { await writer.WriteAsync($"{header};"); } await writer.WriteLineAsync(); } foreach (var item in clinicSource) { await writer.WriteLineAsync(item.ToString()); } } Cursor.Current = Cursors.Default; } else { if (MessageBox.Show(Resources.StartForm_Save_File_Not_Opened__Openь_, Resources.StartForm_Save_Saving_Error, MessageBoxButtons.YesNo, MessageBoxIcon.Error) != DialogResult.Yes) { return; } OpenToolStripMenuItem_Click(this, EventArgs.Empty); } }
/// <summary> /// 写文件,如果文件不存在则创建,存在则追加 /// </summary> /// <param name="path">文件路径</param> /// <param name="strings">内容</param> /// <param name="charset">编码,默认utf-8</param> public static async Task AppendAsync(string path, string strings, string charset = "utf-8") { Create(path); await using System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true, System.Text.Encoding.GetEncoding(charset)); await f2.WriteAsync(strings); }
private static async Task Handler(PipeReadWrapper incomingRequestStream, PipeWriteWrapper outgoingResponseStream) { Console.WriteLine("Child process is handling a request on thread " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); byte[] theBytes = null; using (var memStream = new System.IO.MemoryStream()) { byte[] buffer = new byte[16 * 1024]; int read; while ((read = await incomingRequestStream.ReadAsync(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, read); } theBytes = memStream.ToArray(); } incomingRequestStream.Close(); var writer = new System.IO.StreamWriter(outgoingResponseStream); await writer.WriteAsync(string.Format("Hey, thanks for saying '{0}'.", System.Text.Encoding.UTF8.GetString(theBytes))); try { writer.Close(); } catch (System.IO.IOException) { Console.WriteLine("Got an IO exception. The parent process must've closed the pipe without waiting for a reply."); } Console.WriteLine("Child process finished handling a request."); }
//Metodo hace la copia de seguridad public void escribirMensaje() { int numFilas = dgvTabla.Rows.Count;//Cuenta el numero de filas que tiene la tabla String txtOrigen = ""; String txtDestino = ""; String texto = ""; //crea el fichero System.IO.StreamWriter file = new System.IO.StreamWriter(this.ruta, true); //Crear objeto StringBuilder para escribir un texto StringBuilder sb = new StringBuilder(); //Mientras la lista mensaje esta vacia while (!lmsg.Is_Empty()) { //devuelve el primer mensaje de la lista, con el origen,destino y el texto. Despues borra el msg de la lista Mensaje msg = lmsg.Get_First(); txtOrigen = msg.getOrigen(); txtDestino = msg.getDestino(); texto = msg.getMensaje(); lmsg.Remove_First(); //Agregar mensaje al objeto sb.AppendLine("Origen: " + txtOrigen + "#" + " Destino: " + txtDestino + "#" + " Texto: " + texto + "##"); } //escribe el mensaje en el fichero de texto file.WriteAsync(sb.ToString()); file.Close(); }
static StackObject *WriteAsync_12(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 4); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Int32 @count = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Int32 @index = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Char[] @buffer = (System.Char[]) typeof(System.Char[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 4); System.IO.StreamWriter instance_of_this_method = (System.IO.StreamWriter) typeof(System.IO.StreamWriter).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.WriteAsync(@buffer, @index, @count); object obj_result_of_this_method = result_of_this_method; if (obj_result_of_this_method is CrossBindingAdaptorType) { return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance)); } return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
public static async Task <T> LoadRemoteData <T>(string url, string localPath) { using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); var client = new System.Net.Http.HttpClient(); try { var str = await client.GetStringAsync(url); var result = await Helper.SerializationHelper.DeserializeAsync <T>(new System.IO.StringReader(str)); if (System.IO.File.Exists(localPath)) { System.IO.File.Delete(localPath); } using (var sw = new System.IO.StreamWriter(localPath)) { await sw.WriteAsync(str); } return(result); } catch { return(default(T)); } } }
public async Task RunAsyncMethod(bool isValid, bool isValidDevice, string submissionNumber, string userUuid) { // preparation var config = new Mock <IConfiguration>(); config.Setup(_ => _["SupportRegions"]).Returns("Region1,Region2"); var diagnosisRepo = new Mock <IDiagnosisRepository>(); diagnosisRepo.Setup(_ => _.SubmitDiagnosisAsync(It.IsAny <string>(), It.IsAny <DateTimeOffset>(), It.IsAny <string>(), It.IsAny <TemporaryExposureKeyModel[]>())) .Returns(Task.CompletedTask); var tekRepo = new Mock <ITemporaryExposureKeyRepository>(); var validation = new Mock <IValidationUserService>(); var validationResult = new IValidationUserService.ValidateResult() { IsValid = isValid }; validation.Setup(_ => _.ValidateAsync(It.IsAny <HttpRequest>(), It.IsAny <IUser>())).ReturnsAsync(validationResult); var deviceCheck = new Mock <IDeviceValidationService>(); deviceCheck.Setup(_ => _.Validation(It.IsAny <DiagnosisSubmissionParameter>())).ReturnsAsync(isValidDevice); var logger = new Mock.LoggerMock <Covid19Radar.Api.DiagnosisApi>(); var diagnosisApi = new DiagnosisApi(config.Object, diagnosisRepo.Object, tekRepo.Object, validation.Object, deviceCheck.Object, logger); var context = new Mock <HttpContext>(); var bodyJson = new DiagnosisSubmissionParameter() { SubmissionNumber = submissionNumber, UserUuid = userUuid, Keys = new DiagnosisSubmissionParameter.Key[] { new DiagnosisSubmissionParameter.Key() { KeyData = "", RollingPeriod = 1, RollingStartNumber = 1 } } }; var bodyString = Newtonsoft.Json.JsonConvert.SerializeObject(bodyJson); using var stream = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(stream, leaveOpen: true)) { await writer.WriteAsync(bodyString); await writer.FlushAsync(); } stream.Seek(0, System.IO.SeekOrigin.Begin); context.Setup(_ => _.Request.Body).Returns(stream); // action await diagnosisApi.RunAsync(context.Object.Request); // assert }
/// <summary> /// Save the value of content into a file. /// </summary> /// <param name="content">Data to save into a file</param> /// <param name="fileName">The file name to use, if not exist will be created</param> /// <param name="fileExtention">The extention of a file</param> /// <param name="Path">The path where the file is created</param> /// <param name="timeStampToken">If true insert the timestamp into file name</param> /// <param name="sessionIdInFileName">If true inset the sessionId into file name</param> /// <returns>The file name generated</returns> public string ToFile(object content, string fileName, string fileExtention, string Path, bool timeStampToken, bool sessionIdInFileName) { var encoder = new UTF8Encoding(); char[] contentToSave; var response = new ResponseObject(content, _sessionId); var responseType = response.Response.GetType(); string fullFileName; if (typeof(byte[]).GetTypeInfo().IsAssignableFrom(responseType)) { contentToSave = encoder.GetChars((byte[])response.Response); } else { if (typeof(string).GetTypeInfo().IsAssignableFrom(responseType)) { contentToSave = ((string)response.Response).ToCharArray(); } else { if (typeof(char[]).GetTypeInfo().IsAssignableFrom(responseType)) { contentToSave = (char[])response.Response; } else { throw new NotSupportedException("Response type not supported for ResponseToFileAttribute"); } } } fullFileName = $"{Path ?? ""}{fileName}"; if (sessionIdInFileName) { fullFileName += $"-{response.SessionId.ToString()}"; } if (timeStampToken) { fullFileName += $"-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}"; } if (!string.IsNullOrEmpty(fileExtention)) { fullFileName += $".{fileExtention}"; } var logFile = System.IO.File.Create(fullFileName); using (var logWriter = new System.IO.StreamWriter(logFile)) { var logTask = logWriter.WriteAsync(contentToSave); logTask.Wait(); logWriter.Flush(); } return(fullFileName); }
public async Task SendEmailAsync(string email, string subject, string htmlMessage) { //sending email logic here using (System.IO.StreamWriter file = new System.IO.StreamWriter($"identityEmail-{DateTime.UtcNow.Millisecond}.txt")) { await file.WriteAsync(htmlMessage); } }
public void Print(string message, Exception e) { Debug.WriteLine("{0} Error={0}:{1}", message, e.GetType(), e.Message); using (var sw = new System.IO.StreamWriter("./error.log")) { sw.WriteAsync(string.Format("\r\n{0}:{1}\r\n{2}rn", e.GetType(), e.Message, e.StackTrace)); } }
static async Task DebugAsync(string filePath, string text) { // filename is a string with the full path // true is to append using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, true)) { // Can write either a string or char array await file.WriteAsync(text + "\n"); } }
private void btn_Save_Click(object sender, EventArgs e) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filepath)) { sw.WriteAsync(tb_dcption.Text); tb_dcption.ReadOnly = true; btn_Edit.Enabled = true; btn_Save.Enabled = false; } }
/// <summary> /// Save the document syntax to the root file /// </summary> public static async Task SerializeAsync(DocumentSyntax documentSyntax, System.IO.Stream stream) { // Write out the entire root table var content = documentSyntax.ToString(); using (var writer = new System.IO.StreamWriter(stream)) { await writer.WriteAsync(content); } }
public async Task Write(string filename, object data) { var json = await Obj2Json(data); using (System.IO.StreamWriter file = new System.IO.StreamWriter( filename, false, System.Text.Encoding.GetEncoding("Shift_JIS"))) { await file.WriteAsync(json); } }
protected async Task <System.IO.Stream> GetStreamFromStringAsync(string inputString) { await using var stream = new System.IO.MemoryStream(); await using var writer = new System.IO.StreamWriter(stream); await writer.WriteAsync(inputString).ConfigureAwait(true); await writer.FlushAsync(); stream.Position = 0; return(stream); }
private static async Task SimpleHandler(System.IO.StreamReader incomingRequestReader, System.IO.StreamWriter outgoingResponseWriter) { Console.WriteLine("Child process is handling a request on thread " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); var requestString = await incomingRequestReader.ReadToEndAsync(); await outgoingResponseWriter.WriteAsync("Hey, thanks for saying '" + requestString + "'."); Console.WriteLine("Child process finished handling a request."); }
public override async Task Execute(IHttpRequestResponseContext context) { SetStatus(context); context.Response.ContentLength64 = response.Length; context.Response.SendChunked = false; context.Response.ContentType = "text/html"; using (context.Response.OutputStream) using (var tw = new System.IO.StreamWriter(context.Response.OutputStream, UTF8.WithoutBOM, 65536, true)) await tw.WriteAsync(response); }
/// <summary> /// Registra a resposta. /// </summary> /// <param name="viewPath"></param> /// <param name="model"></param> /// <returns></returns> protected async Task WriteResponse(string viewPath, object model) { if (!System.IO.File.Exists(viewPath)) { throw new Exception("View not found. Path: " + viewPath); } using (var writer = new System.IO.StreamWriter((System.IO.Stream) this.Environment["owin.ResponseBody"])) { await writer.WriteAsync(RazorEngine.Razor.Parse(new System.IO.StreamReader(viewPath).ReadToEnd(), model)); } }
public static void SaveGrid(this Grid grid, string path) { using (var saver = new System.IO.StreamWriter(path + @"\SavedGame.txt", true)) { saver.WriteLineAsync($"Time: {DateTime.Now}"); foreach (var cell in grid.Cells) { if (cell.Digit == null) { saver.WriteAsync('.'); } else { var digit = (char)((int)cell.Digit + '1'); saver.WriteAsync(digit); } } saver.WriteLineAsync(); } }
public static async Task <bool> SendMail(string to, string subject, string body, bool isHtmlFormatted = false) { var process = new Process() { StartInfo = new ProcessStartInfo { FileName = "/usr/sbin/sendmail", Arguments = "-t", RedirectStandardInput = true, UseShellExecute = false, CreateNoWindow = false, } }; await Task.Factory.StartNew(() => process.Start()); System.IO.StreamWriter stdin = process.StandardInput; await stdin.WriteAsync($"To: {to}\n"); if (isHtmlFormatted) { await stdin.WriteAsync("Content-Type: text/html\n"); } await stdin.WriteAsync($"Subject: {subject.Replace('\n', ' ')}\n"); await stdin.WriteAsync("\n"); await stdin.WriteAsync(body.Replace("\n.\n", "\n.-\n")); await stdin.WriteAsync("\n.\n"); await Task.Factory.StartNew(() => process.WaitForExit()); return(process.ExitCode == 0); }
protected void SubmitButton_Click(object sender, EventArgs e) { submitButton.Enabled = false; string date = Datebox.Text; string name = namebox.Text; string project = projectname.SelectedValue; string collegename = universityname.SelectedValue; string quantity = quantitybox.Text; int totalAmount = 0; resultLable.Text = "Thank you!!!"; Int32.TryParse(quantity, out int numQuantity); string[] lastname = name.Split(null); string nameForCode; if (lastname.Length > 1) { nameForCode = lastname[1]; } else { nameForCode = lastname[0]; } string uniqueCode = "Unique Code : " + collegename + project + nameForCode + date.Replace("-", ""); string fileloc = System.AppDomain.CurrentDomain.BaseDirectory + "\\result.txt"; if (project == "B") { totalAmount = numQuantity * 35; } else if (project == "P") { totalAmount = numQuantity * 40; } //System.IO.File.WriteAllText(fileloc, name); //System.IO.File.WriteAllText(fileloc, "Project" + project); using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileloc, true)) { file.WriteLine("Date : " + date); file.WriteLine("Name : " + name); file.WriteAsync("College : " + collegename); file.WriteLine("Project : " + project); file.WriteLine(uniqueCode); file.WriteLine("Amount : " + totalAmount); } }
public async Task RunAsyncMethod(string title, string message, System.Type ResultType) { // preparation var result = new Mock <ItemResponse <NotificationMessageModel> >(); result.SetupGet(_ => _.Resource) .Returns(new NotificationMessageModel() { Message = message }); var cosmosNotification = new Mock <Container>(); cosmosNotification.Setup(_ => _.CreateItemAsync(It.IsAny <NotificationMessageModel>(), It.IsAny <PartitionKey?>(), It.IsAny <ItemRequestOptions>(), It.IsAny <CancellationToken>())) .ReturnsAsync(result.Object); var cosmos = new Mock <ICosmos>(); cosmos.SetupGet(_ => _.Notification) .Returns(cosmosNotification.Object); var notification = new Mock <INotificationService>(); var logger = new Mock.LoggerMock <Covid19Radar.Api.External.NotificationCreateApi>(); var notificationCreateApi = new Covid19Radar.Api.External.NotificationCreateApi(cosmos.Object, notification.Object, logger); var context = new Mock.HttpContextMock(); var param = new Api.External.Models.NotificationCreateParameter() { Title = title, Message = message }; var bodyString = Newtonsoft.Json.JsonConvert.SerializeObject(param); using var stream = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(stream, leaveOpen: true)) { await writer.WriteAsync(bodyString); await writer.FlushAsync(); } stream.Seek(0, System.IO.SeekOrigin.Begin); context._Request.Body = stream; // action var actual = await notificationCreateApi.RunAsync(context.Request); // assert Assert.IsInstanceOfType(actual, ResultType); }
public static async Task <bool> WriteFileAsync(string path, string content) { try { using (System.IO.StreamWriter outputFile = new System.IO.StreamWriter(path)) { await outputFile.WriteAsync(content); } return(true); } catch (Exception ex) { DivinityApp.Log($"Error writing file: {ex.ToString()}"); return(false); } }
/// <summary> /// Http Get Request to OpenWeatherApi /// </summary> /// <param name="City"></param> /// <returns></returns> private async Task <WeatherResponse> GetAsync(string City) { try { if (TimeSinceLastRefresh.Hours < 1 && System.IO.File.Exists("weather.tmp")) { String weatherSaved = ""; using (var file = new System.IO.StreamReader("weather.tmp")) { weatherSaved = await file.ReadToEndAsync(); } if (!string.IsNullOrEmpty(weatherSaved)) { Task t = Task.Run(() => { Weather = JsonConvert.DeserializeObject <WeatherResponse>(weatherSaved); }); t.Wait(); } else { throw new ApplicationException("Failed to read content of the weather.tmp"); } } else { var fullPath = _path + City + "&lang=pl&units=metric&APPID=" + _token; _httpClient.DefaultRequestHeaders.Clear(); var response = await _httpClient.GetAsync(fullPath); var content = await response.Content.ReadAsStringAsync(); using (var file = new System.IO.StreamWriter("weather.tmp")) { await file.WriteAsync(content); Task t = Task.Run(() => { Weather = JsonConvert.DeserializeObject <WeatherResponse>(content); }); t.Wait(); } LastRefresh = DateTime.Now; } return(Weather); } catch (Exception ex) { logger.Error(ex.Message, "Failed to get weather"); return(null); } }
public static void Main(string[] args) { var app = new CommandLineApplication { Name = "Random People Generator", Description = "Creates lists of randomised people for testing purposes" }; app.HelpOption(); var formatOption = app.Option("-f|--format <Format>", "Output format (csv|json)", CommandOptionType.SingleValue); var outputOption = app.Option("-o|--output <Filename>", "Output filename", CommandOptionType.SingleValue); var numberOption = app.Option <int>("-n|--number <Count>", "Number of people to generate", CommandOptionType.SingleValue); var randomOption = app.Option("-r|--random", "Creates random list, or seeded list (same each time)", CommandOptionType.NoValue); app.OnExecuteAsync(async(token) => { var numPeople = numberOption.HasValue() ? numberOption.ParsedValue : 10; var format = formatOption.HasValue() ? formatOption.Value() : "json"; var random = randomOption.HasValue() ? true : false; var filename = outputOption.HasValue() ? outputOption.Value() : $"{AppDomain.CurrentDomain.BaseDirectory}people.{format}"; var people = RandomPersonFactory.GetPeople(numPeople, random); using (System.IO.StreamWriter file = new System.IO.StreamWriter($"{filename}")) { if (format == "json") { await file.WriteAsync(JsonConvert.SerializeObject(people)); } else { file.WriteLine(new PersonalDetails().HeaderRow); people.ForEach(p => file.WriteLine(p.ToCSV())); await file.FlushAsync(); } } Console.WriteLine($"Wrote {numPeople} {(random ? "random" : "seeded")} people to {filename}"); return(0); }); app.Execute(args); }
private async Task SaveDB() { var sb = new System.Text.StringBuilder(); foreach (var kvp in _db) { sb.AppendLine($"@@@{kvp.Key}@@@"); foreach (var p in kvp.Value) { sb.AppendLine(p.ToString()); } } using (var fw = new System.IO.FileStream(dbfilename, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) using (var sw = new System.IO.StreamWriter(fw)) { await sw.WriteAsync(sb.ToString()); } }
} // End Constructor async System.Threading.Tasks.Task Microsoft.AspNetCore.Mvc.IActionResult.ExecuteResultAsync( Microsoft.AspNetCore.Mvc.ActionContext context) { if (context == null) { throw new System.ArgumentNullException("context"); } if (XmlRequestBehavior == XmlRequestBehavior_t.DenyGet && string.Equals(context.HttpContext.Request.Method, "GET", System.StringComparison.OrdinalIgnoreCase)) { throw new System.InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); } Microsoft.AspNetCore.Http.HttpResponse response = context.HttpContext.Response; // https://stackoverflow.com/questions/9254891/what-does-content-type-application-json-charset-utf-8-really-mean if (this.m_sql == null) { response.StatusCode = 500; response.ContentType = this.ContentType + "; charset=" + this.ContentEncoding.WebName; using (System.IO.StreamWriter output = new System.IO.StreamWriter(response.Body, this.ContentEncoding)) { await output.WriteAsync("{ error: true, msg: \"SQL-command is NULL or empty\"}"); } return; } // End if (this.m_sql == null) using (System.Data.Common.DbConnection con = this.m_factory.Connection) { await OnlineYournal.SqlServiceXmlHelper.AnyDataReaderToXml( con , this.m_sql , this.m_parameters , "dbo" , "T_BlogPost" , this.ContentEncoding , this.m_renderType , context.HttpContext ); } // End Using con } // End Task ExecuteResultAsync
public async Task<HttpProgressInfo> ExecuteRequestAsync(string url, Dictionary<string,string> headers = null, string method = "GET", JToken body = null) { var pi = new HttpProgressInfo(); pi.Url = new Uri(url); pi.Method = method; pi.RequestHeaders = new WebHeaderCollection(); var req = WebRequest.CreateHttp(url); req.Method = method; if (headers != null) { foreach (var i in headers) { req.Headers.Add(i.Key, i.Value); pi.RequestHeaders.Add(i.Key, i.Value); } } pi.RequestBody = body == null ? null : body.DeepClone(); pi.RequestStarted = DateTime.UtcNow; pi.State = HttpTransactionState.Started; OnProgress(pi); if (body != null) { using (var rs = await req.GetRequestStreamAsync()) using (var sw = new System.IO.StreamWriter(rs)) { await sw.WriteAsync(body.ToString(Formatting.None)); } } pi.RequestCompleted = DateTime.UtcNow; pi.State = HttpTransactionState.RequestSent; OnProgress(pi); var res = (HttpWebResponse)await req.GetResponseAsync(); pi.State = HttpTransactionState.HeadersReceived; pi.ResponseStarted = DateTime.UtcNow; pi.ResponseStatus = res.StatusCode; pi.ResponseStatusDescription = res.StatusDescription; pi.ResponseHeaders = res.Headers; OnProgress(pi); using (var rs = res.GetResponseStream()) using (var sr = new System.IO.StreamReader(rs, Encoding.UTF8)) { var dataText = await sr.ReadToEndAsync(); pi.State = HttpTransactionState.Complete; pi.ResponseCompleted = DateTime.UtcNow; if (!string.IsNullOrWhiteSpace(dataText)) { var tok = JToken.Parse(dataText); pi.ResponseBody = tok; } } OnProgress(pi); return pi; }