示例#1
0
        /// <summary>
        /// Ejecuta consulta de select
        /// </summary>
        /// <param name="query">La consulta</param>
        /// <returns>Datatable con el resultadao</returns>
        public System.Data.DataTable executeQuery(String query)
        {
            DataTable       table      = new DataTable();
            OleDbConnection connection = getConnectionString();

            using (connection)
            {
                try
                {
                    connection.Open();
                    OleDbCommand command = new OleDbCommand(query, connection);
                    table.Load(command.ExecuteReader());
                    return(table);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ocurrió un error durante la consulta a la base de datos " + ex.ToString());
                    myTraceListener.WriteLine("Ocurrió un error durante la consulta a la base de datos " + ex.ToString());
                    return(table);
                }
                finally
                {
                    myTraceListener.Flush();
                    myTraceListener.Dispose();
                }
            }
        }
        public JobOutcome Execute(IJobProcessorServices context, IJob job)
        {
            try
            {
                FileInfo mLogFileInfo = new FileInfo(System.IO.Path.Combine(
                                                         mLogDir, mLogFile));
                if (mLogFileInfo.Exists)
                {
                    mLogFileInfo.Delete();
                }
                mTrace.WriteLine("Starting Job...");

                //start step export
                mCreateExport(context, job);

                mTrace.IndentLevel = 0;
                mTrace.WriteLine("... successfully ending Job.");
                mTrace.Flush();
                mTrace.Close();

                return(JobOutcome.Success);
            }
            catch (Exception ex)
            {
                context.Log(ex, "Autodesk.STEP.ExportSampleJob failed: " + ex.ToString() + " ");

                mTrace.IndentLevel = 0;
                mTrace.WriteLine("... ending Job with failures.");
                mTrace.Flush();
                mTrace.Close();

                return(JobOutcome.Failure);
            }
        }
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            applicationListener.WriteLine($"Starting up: {DateTime.Now}");
            applicationListener.Flush();

            Application.ApplicationExit += Application_ApplicationExit;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            WatchOperations.Instance.TraceListener = applicationListener;
            WatchOperations.Instance.EnableWatch();


            //         using (var processIcon = new ProcessIcon())
            //{
            //	processIcon.Display();
            //	Application.Run();
            //}

            _processIcon = new ProcessIcon();
            _processIcon.Display();
            Application.Run();
        }
示例#4
0
        public static void EjecutarCmd(string comando)
        {
            try
            {
                Process cmd = new Process();
                cmd.StartInfo.FileName               = "cmd.exe";
                cmd.StartInfo.WorkingDirectory       = @"C:\tmp";
                cmd.StartInfo.RedirectStandardInput  = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.CreateNoWindow         = true;
                cmd.StartInfo.UseShellExecute        = false;
                cmd.Start();
                cmd.StandardInput.WriteLine(comando);
                cmd.StandardInput.Flush();
                cmd.StandardInput.Close();
                cmd.WaitForExit();
                Trace.WriteLine(comando);
                twl.Flush();

                // MessageBox.Show(cmd.StandardOutput.ReadToEnd());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
示例#5
0
        /**********************************************************************************************//**
        * Closes edit log file.
        *
        * \author  Ilan Hindy
        * \date    16/01/2017
        **************************************************************************************************/

        public static void CloseEditLogFile()
        {
            if (editTraceListener != null)
            {
                editTraceListener.Flush();
                Trace.Listeners.Remove(editTraceListener);
                editTraceListener.Close();
            }
        }
示例#6
0
        public void Flush()
        {
            if (_textWriterTraceListener == null)
            {
                return;
            }

            _textWriterTraceListener.Flush();
        }
示例#7
0
        public void resetTraceCounterToOne()
        {
            traceCounter = 1;

            traceLog.Flush(); // flush & close trace log file to be opened for review
            traceLog.Close();

            traceLog = new TextWriterTraceListener(System.IO.File.CreateText("trace.log"));
            Debug.Listeners.Add(traceLog);
        }
示例#8
0
 static void ConsoleListen()
 {
     Console.ReadLine();
     if (_iCWriter != null)
     {
         Thread.Sleep(3000);
         Trace.Flush();
         _iCListener.Flush();
         _iCWriter.Flush();
         _iCWriter.Flush();
     }
     System.Environment.Exit(0);
 }
示例#9
0
 static internal void FlushOutput()
 {
     if (_iCWriter != null)
     {
         Trace.Flush();
         Trace.Flush();
         _iCListener.Flush();
         _iCListener.Flush();
         _iCWriter.Flush();
         _iCWriter.Flush();
     }
     Console.Out.Flush();
     Console.Out.Flush();
 }
示例#10
0
        /// <summary>
        /// 保存异常日志
        /// </summary>
        /// <param name="exceptionMsg"></param>
        private void SaveExceptionInfo(string exceptionMsg)
        {
            if (!Directory.Exists(Path.GetDirectoryName(CommonInfo.ERRORLOGPATH)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(CommonInfo.ERRORLOGPATH));
            }
            string fileName = CommonInfo.ERRORLOGPATH + DateTime.Now.ToString("yy-MM-dd") + ".log";
            TextWriterTraceListener textWrite = new TextWriterTraceListener(fileName, "ExceptionLog");

            textWrite.Flush();
            textWrite.WriteLine(DateTime.Now.ToString() + "监控平台出现异常--------------------------------");
            textWrite.WriteLine(exceptionMsg);
            textWrite.Flush();
            textWrite.Close();
        }
示例#11
0
        public void FunctionExtention_TimeoutSafeInvoke_Should_Catch_Up_To_2_Timeouts()
        {
            StringWriter  sw       = new StringWriter();
            TraceListener listener = new TextWriterTraceListener(sw);

            Trace.Listeners.Add(listener);
            int        magicInt = 1234;
            int        tries    = 0;
            Func <int> f        = () => {
                if (tries++ < 2)
                {
                    throw new WebException("The operation has timed out", WebExceptionStatus.Timeout);
                }
                else
                {
                    return(magicInt);
                }
            };

            Assert.AreEqual(magicInt, f.TimeoutSafeInvoke(), "FunctionExtention.TimeoutSafeInvoke should invoke the specified function");
            Trace.Listeners.Remove(listener);
            listener.Flush();
            sw.Close();
            string trace = sw.ToString();

            Assert.IsTrue(trace.Contains("System.Net.WebException"), "FunctionExtention.TimeoutSafeInvoke should log a WebException to trace log");
        }
示例#12
0
        internal static void TraceLog(string message)
        {
            //format the message
            DateTime timeStamp     = DateTime.Now;
            string   timeStampInfo = string.Format(timeStampFormat,
                                                   timeStamp.Year,
                                                   timeStamp.Month,
                                                   timeStamp.Day,
                                                   timeStamp.Hour,
                                                   timeStamp.Minute,
                                                   timeStamp.Second,
                                                   timeStamp.Millisecond);

            string logMessage = string.Format("[PTF Internal Trace Log][{0}] {1}",
                                              timeStampInfo,
                                              message);

            //Write the message into trace listeners
            try
            {
                Trace.WriteLine(logMessage);

                if (textListener != null)
                {
                    textListener.Flush();
                }
            }
            catch (Exception)
            {
                //We shouldn't catch general exception, but application on internal
                //log should not prevent the PTF from executing.
            }
        }
示例#13
0
        public void ShouldRunAppDataActivity()
        {
            var projectDirectoryInfo = new DirectoryInfo(this._basePath);

            var shellDirectoryInfo = projectDirectoryInfo.Parent.GetDirectories("*.Shell").Single();

            var configuration = Program.LoadConfiguration(shellDirectoryInfo.FullName);

            using (var writer = new StringWriter())
                using (var listener = new TextWriterTraceListener(writer))
                {
                    Program.InitializeTraceSource(listener, configuration);

                    var metaSection = configuration.GetSection("meta")?.GetChildren();
                    Assert.True(metaSection.Any(), "The expected section is not here.");

                    var args = new[]
                    {
                        nameof(AppDataActivity),
                        ProgramArgs.BasePath, projectDirectoryInfo.FullName
                    };
                    var activitiesGetter = Program.GetActivitiesGetter(args);
                    var activity         = activitiesGetter
                                           .GetActivity()
                                           .WithConfiguration(configuration) as AppDataActivity;
                    Assert.NotNull(activity);

                    activity.Start(new ProgramArgs(args));

                    listener.Flush();

                    this._testOutputHelper.WriteLine(writer.ToString());
                }
        }
示例#14
0
        /**********************************************************************************************//**
        * Edit log init.
        *
        * \author  Ilan Hindy
        * \date    16/01/2017
        **************************************************************************************************/

        public static void EditLogInit()
        {
            string editLogFileName = Config.Instance[Config.Keys.EditLogFileName];
            string editLogFilePath = Config.Instance[Config.Keys.EditLogFilePath];

            CloseEditLogFile();

            string fileName = editLogFilePath + editLogFileName;

            //The log file operates by appending text so it has to be deleted at the beginning of the operation
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            //Create the file stream that the main log file will be written to
            editLogFile = new FileStream(fileName, FileMode.OpenOrCreate);

            // Creates the new trace listener.
            editTraceListener = new System.Diagnostics.TextWriterTraceListener(editLogFile);

            // Write the logs that where generated before opening the file
            foreach (string l in logsBeforeConfigLoad)
            {
                editTraceListener.WriteLine(l);
                editTraceListener.Flush();
            }
            logsBeforeConfigLoad = new List <string>();
        }
示例#15
0
        private static void DebugTrace()
        {
            Debug.Assert(File.Exists("app.log"));

            TextWriterTraceListener consoleListener =
                new TextWriterTraceListener(Console.Out);

            Debug.Listeners.Add(consoleListener);



            TextWriterTraceListener fileListener =
                new TextWriterTraceListener("app.log");

            Debug.Listeners.Add(fileListener);



            Debug.WriteLine("app started at:{0}", DateTime.Now);
            Trace.WriteLine(
                String.Format("app started at:{0}", DateTime.Now)
                );

            fileListener.Flush();
        }
示例#16
0
            public void Invoke()
            {
                try
                {
                    using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log"))
                    {
                        Trace.Listeners.Add(dbg);
                        Trace.Listeners.Add(new ConsoleTraceListener());

                        _main.Invoke(null, null);

                        dbg.Flush();
                        dbg.Close();
                    }
                }
                catch (TargetInvocationException expt)
                {
                    string ex_info;
                    if (expt.InnerException != null)
                    {
                        ex_info = expt.InnerException.ToString();
                    }
                    else
                    {
                        ex_info = expt.ToString();
                    }
                    //MessageBox.Show(ex_info, "An OpenTK example encountered an error.", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    Trace.WriteLine(ex_info.ToString());
                }
                catch (Exception expt)
                {
                    Trace.WriteLine(expt.ToString());
                }
            }
示例#17
0
        private static void TraceEvent(TraceEventType type, string message)
        {
            if (TraceFilePath != null)
            {
                var level = new SourceSwitch(SourceName)
                {
                    Level = Level
                };
                var trace = new TraceSource(SourceName)
                {
                    Switch = level
                };

                trace.Listeners.Clear();

                using (var file = new TextWriterTraceListener(TraceFilePath))
                {
                    trace.Listeners.Add(file);
                    trace.TraceEvent(type, 0, $"{DateTime.Now:HH:mm:ss.fff} {message}");
                    file.Flush();
                }

                trace.Close();
            }
        }
        private static void LogToFileLog(String message, LoggingLevel level)
        {
            try
            {
                UpdateLogFile();

                // Write to file and Output (Default listener) if Debug
                String dateAndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                String logMessage  = String.Format("{0} [{1}] {2}", dateAndTime, level.ToString(), message);

                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Trace.WriteLine(logMessage);
                }
                if (logListener != null)
                {
                    logListener.WriteLine(logMessage);
                    logListener.Flush();
                }
            }
            catch (Exception)
            {
                // Logging should not throw exception
            }
        }
示例#19
0
 public override void WillTerminate(NSNotification notification)
 {
     if (_traceListener != null)
     {
         _traceListener.Flush();
     }
 }
 private void Form_DetectAndDownloadFromTheGamesDB_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (!finished)
     {
         if (mainThread != null)
         {
             if (mainThread.IsAlive)
             {
                 ManagedMessageBoxResult result =
                     ManagedMessageBox.ShowQuestionMessage(
                         Program.ResourceManager.GetString("Message_AreYouSureYouWantToStopCurrentProgress"),
                         Program.ResourceManager.GetString("MessageCaption_DetectAndDownloadFromTheGamesDB"));
                 if (result.ClickedButtonIndex == 0)
                 {
                     client.CancelAsync();
                     mainThread.Abort();
                     mainThread = null;
                     Trace.WriteLine("Database import operation finished at " + DateTime.Now.ToLocalTime(), "Detect And Download From TheGamesDB.net");
                     listner.Flush();
                     Trace.Listeners.Remove(listner);
                     CloseAfterFinish();
                 }
                 else
                 {
                     e.Cancel = true;
                 }
             }
         }
     }
 }
示例#21
0
        public static void LogExceptionToFile(Exception ex)
        {
            var logPath      = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
            var logDirectory = logPath + @"\EXCEPTION";
            var filePath     = "";

            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
                filePath = logDirectory + @"\EXCEPTION.0.log";
            }
            else
            {
                var filePaths = Directory.GetFiles(logDirectory, "*.log");
                if (filePaths.Length == 0)
                {
                    filePath = logDirectory + @"\EXCEPTION.0.log";
                }
                else
                {
                    var fPath = filePaths[filePaths.Length - 1];
                    if (File.Exists(fPath))
                    {
                        var lastestFile = new FileInfo(fPath);
                        // > 2 MB
                        if (((lastestFile.Length / 1024f) / 1024f) > 2)
                        {
                            var file     = new FileInfo(fPath);
                            var fileName = file.Name.Split('.');
                            filePath = logDirectory + @"\EXCEPTION." + (int.Parse(fileName[1]) + 1) + @".log";
                        }
                        else
                        {
                            filePath = fPath;
                        }
                    }
                }
            }

            var a          = Environment.NewLine;
            var logMessage = string.Concat(new object[]
            {
                ex.Message,
                Environment.NewLine,
                ex.Source,
                Environment.NewLine,
                ex.StackTrace,
                Environment.NewLine,
                ex.TargetSite,
                Environment.NewLine,
                ex.InnerException
            });

            logMessage = DateTime.Now.ToString("HH:mm:ss") + " " + logMessage;
            var listener = new TextWriterTraceListener(filePath);

            listener.WriteLine(logMessage);
            listener.Flush();
            listener.Close();
        }
        static void Main(string[] args)
        {
            //Use TraceSource, not Trace, they are easier to turn off
            TraceSource trace = new TraceSource("app");
            //SourceSwitches allow you to turn the tracing on and off.
            SourceSwitch level = new SourceSwitch("app");

            //I assume you want to be dynamic, so probalby some user input would be here:
            if (args.Length > 0 && args[0] == "Off")
            {
                level.Level = SourceLevels.Off;
            }
            else
            {
                level.Level = SourceLevels.Verbose;
            }
            trace.Switch = level;
            //remove default listner to improve performance
            trace.Listeners.Clear();
            //Listeners implement IDisposable
            using (TextWriterTraceListener file = new TextWriterTraceListener("log.txt"))
                using (ConsoleTraceListener console = new ConsoleTraceListener())
                {
                    //The file will likely be in /bin/Debug/log.txt
                    trace.Listeners.Add(file);
                    //So you can see the results in screen
                    trace.Listeners.Add(console);
                    //Now trace, the console trace appears immediately.
                    trace.TraceInformation("Hello world");
                    //File buffers, it flushes on Dispose or when you say so.
                    file.Flush();
                }
            System.Console.ReadKey();
        }
        /// <summary>
        /// Gets lines of trace messages.
        /// </summary>
        /// <returns>Lines of trace messages in an array of strings.</returns>
        public string[] GetTraceMessages()
        {
            List <string> traceLogEntries = new List <string>(c_maxTraceEntries);

            m_listener.Flush();

            using (StreamReader sr = new StreamReader(m_blockingStream))
            {
                int    numLines = 0;
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Length >= MaxLineLength)
                    {
                        line = line.Substring(0, MaxLineLength - AbridgedNotes.Length) + AbridgedNotes;
                    }
                    traceLogEntries.Add(line);

                    if (++numLines >= c_maxTraceEntries)
                    {
                        break;
                    }
                }
            }

            return(traceLogEntries.ToArray());
        }
示例#24
0
        static void Main()
        {
            string        dirDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Gargoyle Strategic Investments\\SentoniClient";
            string        appDataPath = dirDataPath + "\\TraceListener.log";
            DirectoryInfo dInfo       = new DirectoryInfo(dirDataPath);

            if (!dInfo.Exists)
            {
                dInfo.Create();
            }

            TextWriterTraceListener trace = new TextWriterTraceListener(new StreamWriter(appDataPath, false));

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            catch (Exception ex)
            {
                trace.WriteLine(ex.ToString());
                trace.Flush();
            }
        }
        public void ShouldDownloadFeeds()
        {
            var projectDirectoryInfo = new DirectoryInfo(this._projectPath);

            var args = new [] { nameof(DownloadFeedsActivity), ProgramArgs.BasePath, projectDirectoryInfo.FullName };
            var shellProjectDirectoryInfo = projectDirectoryInfo.Parent.GetDirectories().Single(i => i.Name.EndsWith("Shell"));
            var configuration             = Shell.Program.LoadConfiguration(shellProjectDirectoryInfo.FullName);
            var activity = configuration.GetActivity(args) as DownloadFeedsActivity;

            Assert.NotNull(activity);

            var meta = activity.Configuration.ToFeedsMetadata();

            Assert.NotNull(meta);
            this._testOutputHelper.WriteLine(meta.ToString());

            using (var writer = new StringWriter())
                using (var listener = new TextWriterTraceListener(writer))
                {
                    Program.InitializeTraceSource(listener, configuration);

                    activity.DownloadFeeds(meta, meta.ToRootDirectory(new ProgramArgs(args)));

                    listener.Flush();
                    this._testOutputHelper.WriteLine(writer.ToString());
                }
        }
        public void ShouldUploadJson(string cloudStorageSetName, string connectionStringName)
        {
            var projectDirectoryInfo = new DirectoryInfo(this._projectPath);

            var args = new [] { nameof(StoreFeedsActivity) };
            var shellProjectDirectoryInfo = projectDirectoryInfo.Parent.GetDirectories().Single(i => i.Name.EndsWith("Shell"));
            var configuration             = Shell.Program.LoadConfiguration(shellProjectDirectoryInfo.FullName);
            var activity = configuration.GetActivity(args) as StoreFeedsActivity;

            Assert.NotNull(activity);

            var meta = activity.GetProgramMetadata();

            Assert.NotNull(meta);

            var account = meta.GetCloudStorageAccount(cloudStorageSetName, connectionStringName);

            Assert.NotNull(account);

            var feedsMeta = activity.Configuration.ToFeedsMetadata();

            feedsMeta.FeedsDirectory = projectDirectoryInfo.ToCombinedPath(feedsMeta.FeedsDirectory);

            using (var writer = new StringWriter())
                using (var listener = new TextWriterTraceListener(writer))
                {
                    Program.InitializeTraceSource(listener, configuration);

                    activity.UploadJson(account, feedsMeta, new ProgramArgs(args));

                    listener.Flush();
                    this._testOutputHelper.WriteLine(writer.ToString());
                }
        }
示例#27
0
        private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Trace.WriteLine("!!! Unhandled Exception !!!");
                Trace.WriteLine(e.ExceptionObject.ToString());

                if (service)
                {
                    svcTextListener.WriteLine(e.ExceptionObject.ToString());
                    svcTextListener.WriteLine("**** An error has occurred - please zip up the MXdiags folder and post it in the forum ****");
                    svcTextListener.Flush();
                }
                else
                {
                    Console.WriteLine(e.ExceptionObject.ToString());
                    Console.WriteLine("**** An error has occurred - please zip up the MXdiags folder and post it in the forum ****");
                    Console.WriteLine("Press Enter to terminate");
                    Console.ReadLine();
                }
                Thread.Sleep(1000);
                Environment.Exit(1);
            }
            catch (Exception)
            {
            }
        }
        public static void LogException(string category, Exception exc)
        {
            string absolute_path = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase), Properties.Settings.Default.LogPath);
            Uri    uri           = new Uri(absolute_path);
            string path          = Path.GetFullPath(uri.AbsolutePath);

            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }
            TextWriterTraceListener listener = new TextWriterTraceListener(path);

            Trace.Listeners.Add(listener);

            Trace.WriteLine("SNMP Manager Exception");
            Trace.Indent();
            Trace.WriteLine("ExceptionType: " + exc.GetType().ToString());
            Trace.WriteLine("Category: " + category);
            Trace.WriteLine("Timestamp: " + DateTime.Now.ToString());
            Trace.WriteLine("HResult" + exc.HResult);
            Trace.WriteLine("Message: " + exc.Message);
            Trace.WriteLine("StackTrace: " + exc.StackTrace);
            Trace.Unindent();
            Trace.WriteLine("End Exception SNMP Manager");
            Trace.WriteLine("----");
            listener.Flush();
            listener.Close();
        }
    public static void Main()
    {
        TextWriterTraceListener myWriter = new
                                           TextWriterTraceListener(System.Console.Out);

        Debug.Listeners.Add(myWriter);
        Debug.WriteLine("Test output 1 ");
        Stream myFile = File.Create("output.txt");
        TextWriterTraceListener myTextListener = new
                                                 TextWriterTraceListener(myFile);

        Debug.Listeners.Add(myTextListener);
        Debug.WriteLine("Test output 2 ");


        if (!EventLog.SourceExists("Demo"))
        {
            EventLog.CreateEventSource("Demo", "Demo");
        }


        Debug.Listeners.Add(new EventLogTraceListener("Demo"));
        Debug.WriteLine("Test output 3 ");
        myWriter.Flush();
        myWriter.Close();
        myFile.Flush();
        myFile.Close();
    }
示例#30
0
        public void Write(FormatterBase formatter, string logFileName)
        {
            TextWriterTraceListener listener = new TextWriterTraceListener(logFileName);

            listener.WriteLine(formatter.Message);
            listener.Flush();
            listener.Close();
        }
 public void TestFlush()
 {
     using (var target = new TextWriterTraceListener(_stream))
     {
         target.Write(TestMessage);
         target.Flush();
     }
 }
        public void TestWriteAfterDisposeShouldNotThrow()
        {
            var target = new TextWriterTraceListener(_stream);
            target.Dispose();

            target.WriteLine(TestMessage);
            target.Write(TestMessage);
            target.Flush();
        }