static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Enable debugging output to a logfile with the date and time of launch in the current directory Assembly _assembly = typeof(MainForm).Assembly; DateTime _now = DateTime.Now; logPath = Path.GetDirectoryName(_assembly.Location) + "\\" + _now.Year + "-" + _now.Month + "-" + _now.Day + "_" + _now.Hour + "-" + _now.Minute + "-" + _now.Second + ".log"; Debug.WriteLine("[LogListener] Setting up Listener for log file " + logPath); TextWriterTraceListener logListener = new TextWriterTraceListener(logPath); Debug.Listeners.Add(logListener); Debug.WriteLine("[LogListener] Log file " + logPath + " created"); // and start evetything Debug.WriteLine("[Program] Starting new MainForm"); Application.Run(new MainForm()); Debug.WriteLine("[Program] Returned from MainForm, cleaning up"); logListener.Flush(); logListener.Dispose(); }
public static async Task CorrelationIdTestAsync(Sts sts) { SetCredential(sts); var context = new AuthenticationContextProxy(sts.Authority, sts.ValidateAuthority); Guid correlationId = Guid.NewGuid(); AuthenticationResultProxy result = null; MemoryStream stream = new MemoryStream(); using (var listener = new TextWriterTraceListener(stream)) { Trace.Listeners.Add(listener); context.SetCorrelationId(correlationId); result = context.AcquireToken(sts.ValidResource, sts.ValidClientId, sts.ValidDefaultRedirectUri, PromptBehaviorProxy.Auto, sts.ValidUserId); VerifySuccessResult(sts, result); listener.Flush(); string trace = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Position); Verify.IsTrue(trace.Contains(correlationId.ToString())); Trace.Listeners.Remove(listener); } stream = new MemoryStream(); using (var listener = new TextWriterTraceListener(stream)) { Trace.Listeners.Add(listener); context.SetCorrelationId(Guid.Empty); AuthenticationResultProxy result2 = await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, sts.ValidClientId); Verify.IsNotNull(result2.AccessToken); listener.Flush(); string trace = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Position); Verify.IsFalse(trace.Contains(correlationId.ToString())); Verify.IsTrue(trace.Contains("Correlation ID")); Trace.Listeners.Remove(listener); } }
static void Main(string[] args) { var directory = args.Length == 0 ? "." : args[0]; directory = directory.EndsWith("\\") ? directory : directory + "\\"; TextWriterTraceListener log = null; try { using (var filestream = new FileStream(directory + "log.csv", FileMode.Create, FileAccess.Write, FileShare.Read)) { log = new TextWriterTraceListener(filestream); foreach (var file in new DirectoryInfo(directory).GetFiles().Select(file => file.Name)) { var begin = DateTime.Now; using (var source = new Bitmap(Image.FromFile(file))) { using (var bm = ConvertToGrayscale(source)) { bm.Save(string.Format("{0}{1}.{2}", directory, "gray", file)); } } var end = DateTime.Now; log.WriteLine(string.Format("{0},gray.{0},{1}", file, end - begin)); log.Flush(); } } } catch (Exception ex) { log.WriteLine(ex.Message); log.WriteLine(ex.StackTrace); } }
public override void Flush() { if (!enabled) { return; } tw.Flush(); }
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(); }
public static IDisposable Enable(string path) { var listener = new TextWriterTraceListener(path); _logging.Value.Sources.ForEach(s => s.Listeners.Add(listener)); return new DisposableAction(() => { listener.Flush(); _logging.Value.Sources.ForEach(s => s.Listeners.Remove(listener)); listener.Close(); }); }
//寫入檔案 private static void WriteLineToFile(DateTime msgTime, CategoryFilterMode msglvl, int threadid, string threadName, string msg) { try { //換天時執行 if (DateTime.Today > _todayDateTime) { SetLogFile(m_FilePath, m_FileName, m_FileExp, m_ReserveDay); } string message; //DateTime msgtime = DateTime.Now; //if (threadName == null) //{ // string messageId = string.Format("<{0}.{1}>{2}", m_ProcessId, threadid, Enum.Format(typeof(CategoryFilterMode), msglvl, "G")); // message = string.Format("{0}-{1}-{2}-{3}", messageId, msglvl, msgtime.ToString(), msg); //} //else //{ // string messageId = string.Format("<{0}.{1}.{2}>{3}", m_ProcessId, threadid, threadName, Enum.Format(typeof(CategoryFilterMode), msglvl, "G")); // message = string.Format("{0}-{1}-{2}", messageId, msgtime.ToString(), msg); //} string msgtime = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss.fff"); message = string.Format("{0} | {1} | {2} | {3} | {4}", msgtime, msglvl, GetMemoryLoad(), GetThreadPoolTaskNumber(), msg); //message = string.Format("{0} | {1} | {2} | {3}", msgtime, msglvl, GetThreadPoolTaskNumber(), msg); lock (objKey2) { if (myListener == null) { SetLogFilePath(string.Format(@"{0}\{1}", Application.StartupPath, "DefaultLog.log")); } myListener.WriteLine(message); myListener.Flush(); } } catch (Exception ex) { Log.Exception(ex); } }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi("*****@*****.**", "secret", "https://sandbox.rallydev.com", "v2.0"); DynamicJsonObject user = restApi.GetCurrentUser(); String userRef = user["_ref"]; String workspaceRef = "/workspace/12352608129"; //use valid workspace OID in your Rally String projectRef = "/project/14018981229"; //use valid project OID in your Rally System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener("log.log", "myListener"); try { //create story DynamicJsonObject myStory = new DynamicJsonObject(); myStory["Name"] = "my story " + DateTime.Now; myStory["Project"] = projectRef; myStory["Owner"] = userRef; CreateResult createStory = restApi.Create(workspaceRef, "HierarchicalRequirement", myStory); myStory = restApi.GetByReference(createStory.Reference, "FormattedID", "Owner", "Project"); myListener.WriteLine(DateTime.Now + "___________\r\n" + myStory["FormattedID"] + " Owner: " + myStory["Owner"]._refObjectName + " Project: " + myStory["Project"]._refObjectName); //update story myStory["Description"] = "updated " + DateTime.Now; //create tasks for (int i = 1; i <= 3; i++) { DynamicJsonObject myTask = new DynamicJsonObject(); myTask["Name"] = "task " + i + DateTime.Now; myTask["Owner"] = userRef; myTask["State"] = "In-Progress"; myTask["WorkProduct"] = myStory["_ref"]; CreateResult createTask = restApi.Create(workspaceRef, "Task", myTask); myTask = restApi.GetByReference(createTask.Reference, "FormattedID", "Owner", "State"); myListener.WriteLine(myTask["FormattedID"] + " State: " + myTask["StateX"]); } } catch (Exception e) { myListener.WriteLine(e); } myListener.Flush(); }
static void Main(string[] args) { RallyRestApi restApi = new RallyRestApi("*****@*****.**", "secret", "https://sandbox.rallydev.com", "v2.0"); DynamicJsonObject user = restApi.GetCurrentUser(); String userRef = user["_ref"]; String workspaceRef = "/workspace/12352608129"; //use valid workspace OID in your Rally String projectRef = "/project/14018981229"; //use valid project OID in your Rally System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener("log.log", "myListener"); try { //create story DynamicJsonObject myStory = new DynamicJsonObject(); myStory["Name"] = "my story " + DateTime.Now; myStory["Project"] = projectRef; myStory["Owner"] = userRef; CreateResult createStory = restApi.Create(workspaceRef, "HierarchicalRequirement", myStory); myStory = restApi.GetByReference(createStory.Reference, "FormattedID", "Owner", "Project"); myListener.WriteLine(DateTime.Now + "___________\r\n" + myStory["FormattedID"] + " Owner: " + myStory["Owner"]._refObjectName + " Project: " + myStory["Project"]._refObjectName); //update story myStory["Description"] = "updated " + DateTime.Now; //create tasks for (int i = 1; i <= 3; i++) { DynamicJsonObject myTask = new DynamicJsonObject(); myTask["Name"] = "task " + i + DateTime.Now; myTask["Owner"] = userRef; myTask["State"] = "In-Progress"; myTask["WorkProduct"] = myStory["_ref"]; CreateResult createTask = restApi.Create(workspaceRef, "Task", myTask); myTask = restApi.GetByReference(createTask.Reference, "FormattedID", "Owner", "State"); myListener.WriteLine(myTask["FormattedID"] + " State: " + myTask["StateX"]); } } catch(Exception e) { myListener.WriteLine(e); } myListener.Flush(); }
static void LaunchExample(string type) { try { if (File.Exists("debug.log")) File.Delete("debug.log"); if (File.Exists("trace.log")) File.Delete("trace.log"); } catch (Exception e) { Trace.WriteLine(String.Format("Could not access debug.log", e.ToString())); } using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log")) using (OpenTK.Toolkit.Init()) { Trace.Listeners.Add(dbg); try { var example = Type.GetType(type); if (example != null) { example.InvokeMember("Main", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, null, null); } } catch (Exception e) { Trace.WriteLine(String.Format("Exception occured in example {0}: {1}", type, e.ToString())); } Trace.Listeners.Remove(dbg); dbg.Flush(); dbg.Close(); } }
public static void LogToFile(LogFileType logType, string logMessage) { //string LogPath = Environment.CurrentDirectory; var logPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);//@"C:\VNPT-BHXH"; var logDirectory = logPath + @"\" + DateTime.Today.ToString("yyyyMMdd"); string filePath; if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); switch (logType) { case LogFileType.Trace: filePath = logDirectory + @"\TRACE.0.log"; break; case LogFileType.Message: filePath = logDirectory + @"\MESSAGE.0.log"; break; case LogFileType.Exception: filePath = logDirectory + @"\EXCEPTION.0.log"; break; default: filePath = logDirectory + @"\TRACE.0.log"; break; } } else { var filePaths = Directory.GetFiles(logDirectory, "*.log"); if (filePaths.Length == 0) { switch (logType) { case LogFileType.Trace: filePath = logDirectory + @"\TRACE.0.log"; break; case LogFileType.Message: filePath = logDirectory + @"\MESSAGE.0.log"; break; case LogFileType.Exception: filePath = logDirectory + @"\EXCEPTION.0.log"; break; default: filePath = logDirectory + @"\TRACE.0.log"; break; } } else { var fileList = new List<string>(); foreach (var fPath in filePaths) { var file = new FileInfo(fPath); var parts = file.Name.Split('.'); if (parts[0].ToUpper() == logType.ToString().ToUpper()) { fileList.Add(fPath); } } var lastestIndex = int.MinValue; var lastestFilePath = ""; if (fileList.Count <= 0) { filePath = logDirectory + @"\" + logType.ToString().ToUpper() + ".0.log"; } else { foreach (var fPath in fileList) { var file = new FileInfo(fPath); var parts = file.Name.Split('.'); //fPath.Split('.'); if (Convert.ToInt32(parts[1]) >= lastestIndex) { lastestIndex = Convert.ToInt32(parts[1]); lastestFilePath = fPath; } } filePath = lastestFilePath; } if (File.Exists(filePath)) { var lastestFile = new FileInfo(filePath); // check if file size be larger than 5MB then create new one if (((lastestFile.Length / 1024f) / 1024f) > 5) { lastestIndex++; filePath = logDirectory + @"\" + logType.ToString().ToUpper() + "." + lastestIndex + ".log"; } } } } logMessage = DateTime.Now.ToString("HH:mm:ss") + " " + logMessage; var listener = new TextWriterTraceListener(filePath); listener.WriteLine(logMessage); listener.Flush(); listener.Close(); }
static void LaunchExample(string type) { try { if (File.Exists("debug.log")) File.Delete("debug.log"); if (File.Exists("trace.log")) File.Delete("trace.log"); } catch (Exception e) { Trace.WriteLine(String.Format("Could not access debug.log", e.ToString())); } ToolkitOptions options = ToolkitOptions.Default; if (type.Contains("GLControl") || type.Contains("Form")) { // SDL does not currently support embedding in foreign windows // such as GLControl. We need to use a native OpenTK.Platform // backend in that case. This hack is specific to the example-browser // architecture - you do not need to do anything like this in your // own code (it will just work). options = new ToolkitOptions { Backend = PlatformBackend.PreferNative }; } using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log")) using (Toolkit.Init(options)) { Trace.Listeners.Add(dbg); try { var example = Type.GetType(type); if (example != null) { example.InvokeMember("Main", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, null, null); } } catch (Exception e) { Trace.WriteLine(String.Format("Exception occured in example {0}: {1}", type, e.ToString())); } Trace.Listeners.Remove(dbg); dbg.Flush(); dbg.Close(); } }
public void when_tracing_activity_then_can_render_activity_as_string() { var writer = new StringWriter(); var text = new TextWriterTraceListener(writer); manager.AddListener("*", text); manager.SetTracingLevel("*", SourceLevels.All); var tracer = Tracer.Get("Foo"); using (tracer.StartActivity("Outer")) { tracer.Info("Hello info from outer"); using (tracer.StartActivity("Inner")) { tracer.Warn("Warn from inner"); Tracer.Get("Foo.Bar").Error("Something failed on another class!"); } } System.Threading.Thread.Sleep(1000); text.Flush(); Console.WriteLine(writer.ToString()); }
private void PROCESS() { // Add listener string logFileName = string.Format("{0}-detect and download from the-game-db.txt", DateTime.Now.ToLocalTime().ToString()); logFileName = logFileName.Replace(":", ""); logFileName = logFileName.Replace("/", "-"); Directory.CreateDirectory("Logs"); logPath = Path.Combine("Logs", logFileName); listner = new TextWriterTraceListener(HelperTools.GetFullPath(logPath)); Trace.Listeners.Add(listner); // Start Trace.WriteLine(string.Format("Detect and download from the-game-db.for started at {0}", DateTime.Now.ToLocalTime()), "Detect And Download From TheGamesDB.net"); int step_index = 0; int steps_count = 4; #region 1 Getting all platform entries from the internet Trace.WriteLine("Getting entries for selected platform ...", "Detect And Download From TheGamesDB.net"); status_master = "Getting entries for selected platform ..."; progress_master = 100 / (steps_count - step_index); // Get database content Platform selectedPlatform = GamesDB.GetPlatform(_db_selected_platform_id); List<GameSearchResult> databaseEntries = new List<GameSearchResult>(GamesDB.GetPlatformGames(_db_selected_platform_id)); Trace.WriteLine("Platform entries done, total of " + databaseEntries.Count + " entries found.", "Detect And Download From TheGamesDB.net"); #endregion #region 2 Get the games step_index++; Trace.WriteLine("Collecting the roms ...", "Detect And Download From TheGamesDB.net"); status_master = "Collecting the roms ..."; progress_master = 100 / (steps_count - step_index); DataSet set = MyNesDB.GetDataSet("GAMES"); Trace.WriteLine("Roms collected, total of " + set.Tables[0].Rows.Count + " entries", "Detect And Download From TheGamesDB.net"); // Clear detected files first ? if (_clear_info_table) MyNesDB.DeleteDetects("INFOS"); if (_clear_snaps_table) MyNesDB.DeleteDetects("SNAPS"); if (_clear_covers_table) MyNesDB.DeleteDetects("COVERS"); #endregion #region 3 Compare and apply stuff step_index++; Trace.WriteLine("Comparing and applying naming", "Detect And Download From TheGamesDB.net"); status_master = "Comparing ..."; progress_master = 100 / (steps_count - step_index); int gameEntriesCount = set.Tables[0].Rows.Count; int matchedCount = 0; List<string> matchedRomNames = new List<string>(); List<string> notMatchedRomNames = new List<string>(); for (int game_index = 0; game_index < gameEntriesCount; game_index++) { string id = set.Tables[0].Rows[game_index]["Id"].ToString(); string entryName = set.Tables[0].Rows[game_index]["Name"].ToString().Replace("'", "'"); string entryPath = set.Tables[0].Rows[game_index]["Path"].ToString().Replace("'", "'"); status_sub_sub = ""; // Loop through database entries looking for a match for (int entry_index = 0; entry_index < databaseEntries.Count; entry_index++) { if (FilterSearch(entryName, entryPath, databaseEntries[entry_index].Title)) { Trace.WriteLine("GAME MATCHED [" + id + "] (" + entryName + ")", "Detect And Download From TheGamesDB.net"); matchedRomNames.Add(entryName); // Apply ApplyRom(entryName, id, GamesDB.GetGame(databaseEntries[entry_index].ID)); Trace.WriteLine("ROM DATA UPDATED.", "Detect And Download From TheGamesDB.net"); matchedCount++; if (_turbo_speed) databaseEntries.RemoveAt(entry_index); break; } } // Progress progress_sub = (game_index * 100) / gameEntriesCount; status_sub = string.Format("{0} {1} / {2} ({3} MATCHED) ... {4} %", Program.ResourceManager.GetString("Status_ApplyingDatabase"), (game_index + 1).ToString(), gameEntriesCount, matchedCount.ToString(), progress_sub); } #endregion #region 4 Update log with matched and not found roms step_index++; Trace.WriteLine("Finishing", "Detect And Download From TheGamesDB.net"); status_master = "Finishing ..."; progress_master = 100 / (steps_count - step_index); Trace.WriteLine("----------------------------"); Trace.WriteLine("MATCHED ROMS ( total of " + matchedRomNames.Count + " rom(s) )"); Trace.WriteLine("------------"); for (int i = 0; i < matchedRomNames.Count; i++) Trace.WriteLine((i + 1).ToString("D8") + "." + matchedRomNames[i]); Trace.WriteLine("----------------------------"); Trace.WriteLine("ROMS NOT FOUND ( total of " + notMatchedRomNames.Count + " rom(s) )"); Trace.WriteLine("--------------"); for (int i = 0; i < notMatchedRomNames.Count; i++) Trace.WriteLine((i + 1).ToString("D8") + "." + notMatchedRomNames[i]); Trace.WriteLine("----------------------------"); Trace.WriteLine(string.Format("Detect And Download From TheGamesDB.net finished at {0}.", DateTime.Now.ToLocalTime()), "Detect And Download From TheGamesDB.net"); listner.Flush(); Trace.Listeners.Remove(listner); CloseAfterFinish(); #endregion }
private void CreateLog(string activityLog, string errorLog, long logSize, int bufferSize, bool relativePath) { string logDirectory; try { if (errorLog == "") logError = false; if (relativePath) { //Path relativo -> Utilizo el path de la aplicación _LogActivity = AppPath() + "\\" + activityLog; _LogError = AppPath() + "\\" + errorLog; } else { //Path absoluto _LogActivity = activityLog; _LogError = errorLog; } logDirectory = Path.GetDirectoryName(_LogActivity); if (!Directory.Exists(logDirectory)) Directory.CreateDirectory(logDirectory); _LogSize = logSize; _BufferSize = bufferSize; string fecha = String.Format("{0:00}", DateTime.Now.Day) + "-" + String.Format("{0:00}", DateTime.Now.Month) + "-" + String.Format("{0:0000}", DateTime.Now.Year) + " a las " + String.Format("{0:00}", DateTime.Now.Hour) + ":" + String.Format("{0:00}", DateTime.Now.Minute) + ":" + String.Format("{0:00}", DateTime.Now.Second); string initLog = "**********************************************************\n" + "* Session del log iniciada (" + fecha + ") *\n" + "**********************************************************"; FileStreamWithBackup fileActivity = new FileStreamWithBackup(_LogActivity, _LogSize * 1024, FileMode.Append, FileShare.Read, bufferSize * 1024); fileActivity.CanSplitData = false; activityLogger = new TextWriterTraceListener(fileActivity); activityLogger.WriteLine(initLog); activityLogger.Flush(); if (logError) { FileStreamWithBackup fileError = new FileStreamWithBackup(_LogError, _LogSize * 1024, FileMode.Append, FileShare.Read, bufferSize * 1024); fileError.CanSplitData = false; errorLogger = new TextWriterTraceListener(fileError); errorLogger.WriteLine(initLog); errorLogger.Flush(); } } catch (Exception ex) { throw ex; } }
public void TestTraceLogger() { var stream = new MemoryStream(); var listener = new TextWriterTraceListener(stream); Trace.Listeners.Add(listener); var logger = new TraceLogFactory().GetLogger("logger"); var logMsg = TestSupport.RandomString(); logger.Finest(logMsg); logger.Info(logMsg); logger.Warning(logMsg); logger.Severe(logMsg); listener.Flush(); stream.Seek(0, SeekOrigin.Begin); var log = new StreamReader(stream).ReadToEnd(); Assert.That(log, Is.StringContaining("Information: 0 : " + logMsg)); Assert.That(log, Is.StringContaining("Warning: 0 : " + logMsg)); Assert.That(log, Is.StringContaining("Error: 0 : " + logMsg)); }
/// <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(); }
// static Crc16 _crc16; static void Main(string[] args) { Boolean done; TextWriterTraceListener tl = new TextWriterTraceListener(@"C:\roombalog.txt"); Trace.Listeners.Add(tl); ConsoleKeyInfo cki; //string name; //string message; StringComparer stringComparer = StringComparer.OrdinalIgnoreCase; Thread readThread = new Thread(Read); // Create a new SerialPort object with default settings. _serialPort = new SerialPort(); // Allow the user to set the appropriate properties. _serialPort.PortName = SetPortName(_serialPort.PortName); //_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate); //_serialPort.Parity = SetPortParity(_serialPort.Parity); //_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits); //_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits); //_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake); // Set the read/write timeouts _serialPort.ReadTimeout = 500; _serialPort.WriteTimeout = 500; _serialPort.Open(); _continue = true; readThread.Start(); _serialPort.WriteLine("h"); _serialPort.WriteLine("m"); _serialPort.WriteLine("s"); _serialPort.WriteLine("c15"); _serialPort.WriteLine("m"); // _serialPort.WriteLine(""); // Retrieve the device list from the local machine IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return; } // Print the list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) Console.WriteLine(" (" + device.Description + ")"); else Console.WriteLine(" (No description available)"); } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); // Take the selected adapter PacketDevice selectedDevice = allDevices[deviceIndex - 1]; // Open the device using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { Console.WriteLine("Listening on " + selectedDevice.Description + "..."); Trace.WriteLine("Listening on " + selectedDevice.Description + "..."); // start the capture done = false; do { communicator.ReceivePackets(1, PacketHandler); if (Console.KeyAvailable) { cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.Escape) done = true; } } while (done == false); } tl.Flush(); tl.Close(); readThread.Join(); _serialPort.Close(); }
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()); } }