Пример #1
0
        /// <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);
            }
        }
        private async void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            using var fs = new System.IO.FileStream($"{DateTime.Now:yyyy-MM-dd_HH+mm+ss}.log", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Read);
            using var sw = new System.IO.StreamWriter(fs);
            await sw.WriteLineAsync(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms"));

            await sw.WriteLineAsync(e.Exception.ToString());

            MessageBox.Show($"异常信息: {e.Exception}", "内部错误");
        }
Пример #3
0
        static StackObject *WriteLineAsync_16(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.WriteLineAsync(@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));
        }
Пример #4
0
 private async void saveUsToolStripMenuItem_Click(object sender, EventArgs e)
 {
     using (SaveFileDialog sfd = new SaveFileDialog()
     {
         Filter = "JEPG Document|*.Jpeg", ValidateNames = true
     })
     {
         if (sfd.ShowDialog() == DialogResult.OK)
         {
             try
             {
                 s = sfd.FileName;
                 using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName))
                 {
                     await sw.WriteLineAsync(s);
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
     }
     surface.Save(s);
     s += i;
     i++;
 }
        private async Task TestAsyncOperationSwitchToPoolInner(StaticThreadPool testInst)
        {
            Assert.IsFalse(testInst.IsThreadPoolThread);

            System.IO.StreamWriter writer = null;
            string fileName = Guid.NewGuid().ToString().Replace('-', '_');

            try
            {
                writer = new System.IO.StreamWriter(new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, 128, true));

                await testInst.SwitchToPool();

                Assert.IsTrue(testInst.IsThreadPoolThread);

                string longString = "test test test test test test test test test test test test";
                for (int i = 0; i < 10; i++)
                {
                    longString += longString;
                }

                await writer.WriteLineAsync(longString);

                Assert.IsTrue(testInst.IsThreadPoolThread);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }

                System.IO.File.Delete(fileName);
            }
        }
Пример #6
0
        public static async Task <bool> WriteToFileAsync(string filePath, string contents, bool supressLogMessage = true)
        {
            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));

                using (System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Write, 4096, true))
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(stream))
                    {
                        await sw.WriteLineAsync(contents);

                        if (!supressLogMessage)
                        {
                            Log.Here().Activity("Saved file: {0}", filePath);
                        }
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                Log.Here().Error("Error saving file at {0} - {1}", filePath, e.ToString());
                return(false);
            }
        }
Пример #7
0
        public async static Task <string> Flush()
        {
            if (Trace.Length > 0)
            {
                if (EnableDebugingLog)
                {
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(DebugLogPath, true))
                    {
                        await writer.WriteLineAsync(Trace.ToString());
                    }
                }
                else
                {
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(ErrorLogPath, true))
                    {
                        await writer.WriteLineAsync(Trace.ToString());
                    }
                }
            }

            string result = Trace.ToString();

            Trace.Clear();

            return(await Task.FromResult(result));
        }
Пример #8
0
 private void WriteToOutFile(string data)
 {
     if (null != _outFile)
     {
         _outFile.WriteLineAsync(data);
     }
 }
Пример #9
0
        public static async Task <bool> WriteToFileAsync(List <Task <string> > CList)
        {
            //var task = Task.Run(async() =>
            //{

            System.IO.StreamWriter sw = new System.IO.StreamWriter("OutPut.txt", true, Encoding.UTF8);
            try
            {
                foreach (var tk in CList)
                {
                    Console.WriteLine($"Begin reading ThreadID:{System.Threading.Thread.CurrentThread.ManagedThreadId}");
                    string str = await tk;
                    await sw.WriteLineAsync(str);
                }
            }
            catch (Exception ex)
            {
                log4net.LogManager.GetLogger(typeof(Program)).Error("Write To File Error.", ex);
                return(false);
            }
            finally
            {
                sw.Flush();
                sw.Close();
            }
            return(true);
            //});
            //return await task;
        }
Пример #10
0
        /// <summary>
        /// Sends an EOL-terminated message to the server (\n is appended by this method)
        /// </summary>
        /// <param name="format">Format of message to send</param>
        /// <param name="formatParameters">Format parameters</param>
        /// <returns></returns>
        public async Task <bool> SendRawMessage(String message)
        {
            try
            {
                await _streamSemaphore.WaitAsync();

                await streamWriter.WriteLineAsync(message);

                await streamWriter.FlushAsync();
            }
            catch (Exception e)
            {
                Exception = e;
                if (OnException != null)
                {
                    foreach (var d in OnException.GetInvocationList())
                    {
                        var task = Task.Run(() => d.DynamicInvoke(this, e));
                    }
                }
                return(false);
            }
            finally { _streamSemaphore.Release(); }

            if (OnRawMessageSent != null)
            {
                foreach (var d in OnRawMessageSent.GetInvocationList())
                {
                    var task = Task.Run(() => d.DynamicInvoke(this, message));
                }
            }

            return(true);
        }
Пример #11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            ///Скрываем исключения от пользовател
            app.UseExceptionHandler(appBuilder
                                    => appBuilder.Run(async context =>
            {
                var errorFeature       = context.Features.Get <IExceptionHandlerFeature>();
                var unhandledException = errorFeature?.Error;

                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                this._exceptionLog.WriteLn("----->ERROR Не обработканная ошибка: {" + (int)HttpStatusCode.InternalServerError + "} " + unhandledException.Message, unhandledException);

                using (var streamWriter = new System.IO.StreamWriter(context.Response.Body))
                {
                    await streamWriter.WriteLineAsync(unhandledException?.Message ?? string.Empty);
                }
            }));


            if (!env.IsDevelopment())
            {
                app.UseHsts();
            }

            //TODO нет пока HTTPS
            //добавляет для проекта переадресацию на тот же ресурс только по протоколу https
            //app.UseHttpsRedirection();
            // чтобы приложение могло бы отдавать статические файлы клиенту
            app.UseStaticFiles();
            app.UseSpaStaticFiles();


            app.UseAuthentication(); // система аутентификации
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
            app.UseSignalR(routes =>
            {
                routes.MapHub <Hubs.DataImport.DataImportHub>("/dataimport/hub");
                routes.MapHub <Hubs.Files.FilesHub>("/files/hub");
            });

            app.UseCors("SiteCorsPolicy"); // это тоже для нескольких портов(см. выше)
            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
Пример #12
0
 // Main entry point in the escalation where it will perform its custom operations
 public override async Task RunAsync(EscalationProperties properties)
 {
     // Implement custom escalation details here. Send notifications, update services, etc
     using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\temp\HelloWorld.txt", true))
     {
         await file.WriteLineAsync(DateTime.Now.ToString());
     }
 }
        public static void Log(Exception ex, string source)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~/Log.txt"));

            string logText = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + " | Message: " + ex.Message + " | Source: " + source;

            file.WriteLineAsync(logText);
        }
Пример #14
0
 // 创建用户
 public async Task CreateAsync(UserIdentity user)
 {
     user.Id = Guid.NewGuid().ToString();
     using (var stream = new System.IO.StreamWriter(_filePath, true, Encoding.UTF8))
     {
         await stream.WriteLineAsync(user.ToString());
     }
 }
Пример #15
0
        //Button Speichern
        private async void Button_speichern_Click(object sender, RoutedEventArgs e)
        {
            speicherpfad = await savepath();

            progressBar_Lade.Value = 0;

            if (listBox_Daten.Items.Count == 0)
            {
                //Ausgabe, sollte Liste noch leer sein
                label_TextAusgabe.Content = "keine Daten vorhanden";
                return;
            }

            if (speicherpfad == string.Empty)
            {
                return;
            }

            writer = new System.IO.StreamWriter(speicherpfad);
            List <string> liste = new List <string>();

            //Daten in Listbox werden in Liste gespeichert (zum Sortieren)
            foreach (string str in listBox_Daten.Items)
            {
                liste.Add(str);
            }

            //Liste wird sortiert
            liste.Sort();
            //Sortierung auf absteigend
            liste.Reverse();

            progressBar_Lade.Maximum  = listBox_Daten.Items.Count;
            label_TextAusgabe.Content = "wird gespeichert...";

            try
            {
                //Daten werden gespeichert
                foreach (string text in liste)
                {
                    await writer.WriteLineAsync(text);

                    progressBar_Lade.Value++;
                }
            }
            catch (Exception ex)
            {
                label_TextAusgabe.Content = ex.Message;
            }
            //nach dem Speichern wird die Liste geleert
            finally
            {
                writer.Close();
                label_TextAusgabe.Content  = "Daten gespeichert in " + speicherpfad;
                button_speichern.IsEnabled = false;
                liste.Clear();
            }
        }
Пример #16
0
        private void SaveTofile(string username)
        {
            var backingFile = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "userdata.txt");

            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(backingFile, true))
            {
                writer.WriteLineAsync(username.ToString());
            }
        }
Пример #17
0
        // 创建用户
        public async Task CreateAsync(IdentityUser user)
        {

            user.Id = Guid.NewGuid().ToString();
            using (var stream = new System.IO.StreamWriter(_filePath, true, Encoding.UTF8))
            {
                await stream.WriteLineAsync(user.ToString());
            }
        }
Пример #18
0
        public async Task Handler(EventFromMicroserviceA _event)
        {
            string eventReceive = JsonConvert.SerializeObject(_event);

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"..\MicroserviceB\EventMessage.txt", true))
            {
                await file.WriteLineAsync(eventReceive);
            }
        }
Пример #19
0
 public async Task WriteLineAsync(string filePath, List <string> list)
 {
     using (var writer = new System.IO.StreamWriter(filePath))
     {
         foreach (var line in list)
         {
             await writer.WriteLineAsync(line);
         }
     }
 }
Пример #20
0
 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();
     }
 }
Пример #21
0
 public static async void createList(List <User> usr)
 {
     using (System.IO.StreamWriter sw = System.IO.File.CreateText(Environment.CurrentDirectory + $@"\Scraped_Users_{DateTime.Now.ToShortDateString().Replace('/', '-')}.txt"))
     {
         sw.AutoFlush = true;
         for (int i = 0; i < usr.Count; i++)
         {
             await sw.WriteLineAsync(usr[i].Username);
         }
     }
 }
Пример #22
0
 private async Task SaveToJson(IList <Artikel> artikels)
 {
     using (System.IO.StreamWriter file =
                new System.IO.StreamWriter(@"C:\temp\IreckonuData.json", true))
     {
         foreach (var artikel in artikels)
         {
             await file.WriteLineAsync(Newtonsoft.Json.JsonConvert.SerializeObject(artikel));
         }
     }
 }
Пример #23
0
 private async void SaveResult_Click(object sender, EventArgs e)
 {
     using (System.IO.StreamWriter MHA_write = new System.IO.StreamWriter("MHA_training", true))
     {
         List <TextBox> textBoxes = new List <TextBox> {
             Squats_textBox, PushUps_textBox, PullUps_textBox, HangingLeg_textBox, InnerBiceps_textBox, Press_textBox
         };
         string my_training = DateTime.Now.ToString();
         textBoxes.ForEach(delegate(TextBox textBox) { my_training += "$" + textBox.Text; });
         await MHA_write.WriteLineAsync(my_training);
     }
 }
Пример #24
0
        public async Task <bool> ImageMonitor(MiraiHttpSession session, IGroupMessageEventArgs e)
        {
            var chain = e.Chain;

            foreach (var msg in chain)
            {
                if (msg is ImageMessage image)
                {
                    await using var file = new System.IO.StreamWriter("ImageMonitor.txt", true);
                    await file.WriteLineAsync($"{DateTime.Now.ToLongTimeString()} {e.Sender.Group.Id} {e.Sender.Id} {e.Sender.Name} {image.Url}");
                }
            }
            return(false);
        }
Пример #25
0
 /// <summary>
 /// Appends lines to a file, and then closes the file.
 /// </summary>
 /// <param name="file">The file to write to</param>
 /// <param name="contents">The content to write to the file</param>
 /// <returns>A task which completes when the write operation finishes</returns>
 ///
 public static async Task AppendAllLinesAsync(this IFile file, IEnumerable <string> contents)
 {
     using (var stream = await file.OpenAsync(FileAccess.ReadAndWrite).ConfigureAwait(false))
     {
         stream.Seek(stream.Length, System.IO.SeekOrigin.Begin);
         using (var sw = new System.IO.StreamWriter(stream))
         {
             foreach (var content in contents)
             {
                 await sw.WriteLineAsync(content).ConfigureAwait(false);
             }
         }
     }
 }
Пример #26
0
        public async Task ToLogFile(System.IO.Stream output)
        {
            await FileUploadsFinished;
            var   fileLogEntries   = AllFileResults.Select(file => new { Time = file.ProcessedAt, LogLine = file.ToLogString() });
            var   folderLogEntries = AllFolderResults.Select(folder => new { Time = folder.ProcessedAt, LogLine = folder.ToLogString() });
            var   sorted           = fileLogEntries.Concat(folderLogEntries).OrderBy(logEntry => logEntry.Time);

            using (var wr = new System.IO.StreamWriter(output))
            {
                foreach (string line in sorted.Select(logEntry => logEntry.LogLine))
                {
                    await wr.WriteLineAsync(line);
                }
            }
        }
Пример #27
0
 private async Task SaveLogMessageToFile(string message)
 {
     System.IO.Directory.CreateDirectory(PathConstans.TRACE_FILTER_LOG_PATH);
     using (System.IO.StreamWriter file = System.IO.File.AppendText(string.Format("{0}\\{1}.txt", PathConstans.TRACE_FILTER_LOG_PATH, DateTime.Now.Date.ToShortDateString())))
     {
         try
         {
             await file.WriteLineAsync(message);
         }
         finally //Clean resource after write text
         {
             file.Close();
         }
     }
 }
Пример #28
0
        private static async System.Threading.Tasks.Task fileLogAsync(string message, string entryType = "DEBUG")
        {
            if (CurrentLogLevel == LogLevel.Debug)
            {
                using (IsolatedStorageFile isoFile = GetIsolatedStorageFile()) {
                    await logFileLock.WaitAsync();

                    try {
                        //IsolatedStorage will be something like: C:\WINDOWS\system32\config\systemprofile\AppData\Local\IsolatedStorage\arpzpldm.neh\4hq14imw.y2b\Publisher.5yo4swcgiijiq5te00ddqtmrsgfhvrp4\AssemFiles\
                        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(ApplicationName + ".log", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read, isoFile)) {
                            //stream.Seek(0, System.IO.SeekOrigin.End);

                            if (debugLogEventCount == 0)
                            {
                                try {
                                    string path = stream.GetType().GetField("m_FullPath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(stream).ToString();
                                    if (logToEventLog && eventLogWriteEntryAction != null)
                                    {
                                        await System.Threading.Tasks.Task.Run(() => eventLogWriteEntryAction("Saving debug log to " + path, EventLogEntryType.Information));
                                    }
                                    else
                                    {
                                        await ConsoleLogAsync("Saving debug log to " + path, EventLogEntryType.Information);
                                    }
                                }
                                catch { }
                            }
                            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream)) {
                                await writer.WriteLineAsync(DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) + "\t[" + entryType + "]\t" + message);
                            }
                        }
                    }
                    catch (System.IO.IOException e) {
                        if (debugLogEventCount == 0 && eventLogWriteEntryAction != null)
                        {
                            await System.Threading.Tasks.Task.Run(() => eventLogWriteEntryAction(e.Message, EventLogEntryType.Error));
                        }
                    }
                    catch (System.NullReferenceException) {
                        LogToFile = false;
                    }
                    finally {
                        logFileLock.Release();
                        System.Threading.Interlocked.Increment(ref debugLogEventCount);
                    }
                }
            }
        }
Пример #29
0
 public async Task PutAsync(string Id, IAppointment Document)
 {
     try
     {
         string fn = Filename(Id);
         using (var writer = new System.IO.StreamWriter(fn))
         {
             string docSer = Newtonsoft.Json.JsonConvert.SerializeObject(Document);
             await writer.WriteLineAsync(docSer);
         }
     }
     catch (Exception ex)
     {
         mko.TraceHlp.ThrowEx("Schreiben des Terminsmit der ID " + Id + " fehlgeschlagen. Termin: " + Document, ex);
     }
 }
Пример #30
0
 private async Task WriteLineAsync(string text, bool append = true)
 {
     try
     {
         using (System.IO.StreamWriter writer = new System.IO.StreamWriter(logFilename, append, Encoding.UTF8))
         {
             if (!string.IsNullOrEmpty(text))
             {
                 await writer.WriteLineAsync(text);
             }
         }
     }
     catch
     {
         throw;
     }
 }
Пример #31
0
        /// <summary>
        /// Opens a file, appends the specified string to the file, and then closes the file.
        /// </summary>
        /// <param name="file">The file to write to</param>
        /// <param name="contents">The content to write to the file</param>
        /// <returns>A task which completes when the write operation finishes</returns>

        public static async Task AppendAllTextAsync(this IFile file, string contents)
        {
            try
            {
                using (var stream = await file.OpenAsync(FileAccess.ReadAndWrite).ConfigureAwait(false))
                {
                    stream.Seek(stream.Length, System.IO.SeekOrigin.Begin);
                    using (var sw = new System.IO.StreamWriter(stream))
                    {
                        //await sw.WriteAsync(contents).ConfigureAwait(false);
                        await sw.WriteLineAsync(contents).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception)
            {
            }
        }
 public override async System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, System.Net.TransportContext transportContext)
 {
     var agents = value as IEnumerable<Agent>;
     using (var writer = new System.IO.StreamWriter(writeStream))
     {
         // Write the CSV header
         writer.WriteLine("First name,Last name,Link");
         if (agents != null)
         {
             UrlHelper url = _request.GetUrlHelper();
             // Write the CSV content
             foreach (var agent in agents)
             {
                 string agentUrl = url.Link("DefaultApi", new { id = agent.AgentID });
                 await writer.WriteLineAsync(string.Format("{0},{1},{2}", agent.FirstName, agent.LastName, agentUrl));
             }
         }
     }
 }