public static void _Main(string[] args) { Trace.WriteLine("start"); var logname = string.Format("{0}_{1}.{2}", "unhand", DateTime.Now.ToString("MMMdd-hhmmss-fffffff"), "log"); var listenerFile = new System.IO.FileInfo(logname); listenerWriter = listenerFile.CreateText(); listener = new TextWriterTraceListener(listenerWriter); Trace.Listeners.Add(listener); //Trace.Listeners.Add(new TextWriterTraceListener(Console.Error)); Trace.AutoFlush = true; AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(unhand_Handler); try { Trace.WriteLine("throw 1"); throw new Exception("1"); } catch (Exception e) { Trace.WriteLine($"Catch clause caught : {e.Message} \n"); } Trace.WriteLine("throw 2"); throw new Exception("2"); //Trace.WriteLine("end"); }
public MemoryTestHost(MemoryHost host, string logPath) { _host = host; _listener = new TextWriterTraceListener(logPath + ".transports.log"); Disposables = new List<IDisposable>(); ExtraData = new Dictionary<string, string>(); }
public void CanSendMetrics() { // set up a listener var log = new StringBuilder(); var writer = new StringWriter(log); var listener = new TextWriterTraceListener(writer); Trace.Listeners.Add(listener); var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, "my-test-appkey"); var metricsRecorder = new MetricsRecorder(rpcClient, new Uri("http://metrics.labs.cityindex.com/LogEvent.ashx")); metricsRecorder.Start(); rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword); var headlines = rpcClient.News.ListNewsHeadlinesWithSource("dj", "UK", 100); foreach (var item in headlines.Headlines) { rpcClient.News.GetNewsDetail("dj", item.StoryId.ToString()); } new AutoResetEvent(false).WaitOne(10000); rpcClient.LogOut(); metricsRecorder.Stop(); rpcClient.Dispose(); Trace.Listeners.Remove(listener); var logText = log.ToString(); Assert.IsTrue(logText.Contains("Latency message complete"), "did not find evidence of metrics being posted"); }
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); } }
/// <summary> /// Return a dataset list given the name of the dataset. /// </summary> /// <param name="dsname"></param> /// <returns></returns> private static FileInfo[] GetFileList(string dsname) { TraceListener listener = null; if (VerboseFileFetch) { listener = new TextWriterTraceListener(Console.Out); Trace.Listeners.Add(listener); } try { return GRIDJobs.FindJobFiles(JobName, JobVersionNumber, dsname, nFiles: NFiles, statusUpdate: l => Console.WriteLine(l), intelligentLocal: true); } finally { if (listener != null) { Trace.Listeners.Remove(listener); } } }
static WorkflowTrace() { runtime.Switch = new SourceSwitch("System.Workflow.Runtime", SourceLevels.Off.ToString()); tracking = new TraceSource("System.Workflow.Runtime.Tracking"); tracking.Switch = new SourceSwitch("System.Workflow.Runtime.Tracking", SourceLevels.Off.ToString()); host = new TraceSource("System.Workflow.Runtime.Hosting"); host.Switch = new SourceSwitch("System.Workflow.Runtime.Hosting", SourceLevels.Off.ToString()); BooleanSwitch switch2 = new BooleanSwitch("System.Workflow LogToFile", "Log traces to file"); if (switch2.Enabled) { TextWriterTraceListener listener = new TextWriterTraceListener("WorkflowTrace.log"); Trace.Listeners.Add(listener); runtime.Listeners.Add(listener); host.Listeners.Add(listener); } BooleanSwitch switch3 = new BooleanSwitch("System.Workflow LogToTraceListeners", "Trace to listeners in Trace.Listeners", "0"); if (switch3.Enabled) { foreach (TraceListener listener2 in Trace.Listeners) { if (!(listener2 is DefaultTraceListener)) { runtime.Listeners.Add(listener2); tracking.Listeners.Add(listener2); host.Listeners.Add(listener2); } } } }
public static void VisualLog(LogLevels loglevel, string type, String ex) { // create output to console TextWriterTraceListener console = new TextWriterTraceListener(); console.Writer = Console.Out; Trace.Listeners.Add(console); //output error if (System.Diagnostics.Trace.Listeners.Count > 0) { Trace.Write(new TraceData(loglevel, DateTime.Now, type, ex)); } //close streams console.Close(); if (!ApplicationType.GetApplicationType().Equals(ApplicationType.Type.Console)) { //messagebox MessageBoxIcon icon = MessageBoxIcon.None; switch (loglevel) { case LogLevels.Error: icon = MessageBoxIcon.Error; break; case LogLevels.Warning: icon = MessageBoxIcon.Warning; break; case LogLevels.Info: icon = MessageBoxIcon.Information; break; } MessageBox.Show(ex, type, MessageBoxButtons.OK, icon); } }
public static void AddTextWriterTL() { //RemoveAllTraceListeners(); Trace.AutoFlush = true; System.Diagnostics.TextWriterTraceListener tListener = new System.Diagnostics.TextWriterTraceListener("TWTrace.txt"); System.Diagnostics.Trace.Listeners.Add(tListener); }
public static void Main(string[] args) { var listener = new TextWriterTraceListener(Console.Out); Trace.Listeners.Add(listener); launchApp(); }
public void Initialize() { try { // service hosts need to be started in a particular order, before everything else //DatabaseNotificationManagerServiceHost.Instance.Start(); //LoggerWCFTraceListenerServiceHost.Instance.Start(); if (LicenseManager.Instance.LoggingEnabled) { Logger.TraceSwitch.Level = LicenseManager.Instance.TraceLevel; Trace.AutoFlush = true; var logFile = new FileInfo(Utility.LogFilePath); if (!logFile.Directory.Exists) logFile.Directory.Create(); var listener = new TextWriterTraceListener(Utility.LogFilePath) { Name = ServiceName + "Trace" }; //Trace.Listeners.Clear(); Trace.Listeners.Add(listener); } // create service agents Agents = new List<IServiceAgent> { new Converter.Agent.Agent(), new DlnaDownloader.Agent.Agent() }; } catch (Exception exception) { Utility.EmergencyWriteEventLog(exception.Message); Logger.TraceErr(exception); } }
public void DiagnosticsTraceWriterTest() { StringWriter sw = new StringWriter(); TextWriterTraceListener listener = new TextWriterTraceListener(sw); try { Trace.AutoFlush = true; Trace.Listeners.Add(listener); DiagnosticsTraceWriter traceWriter = new DiagnosticsTraceWriter(); traceWriter.Trace(TraceLevel.Verbose, "Verbose!", null); traceWriter.Trace(TraceLevel.Info, "Info!", null); traceWriter.Trace(TraceLevel.Warning, "Warning!", null); traceWriter.Trace(TraceLevel.Error, "Error!", null); traceWriter.Trace(TraceLevel.Off, "Off!", null); Assert.AreEqual(@"Newtonsoft.Json Verbose: 0 : Verbose! Newtonsoft.Json Information: 0 : Info! Newtonsoft.Json Warning: 0 : Warning! Newtonsoft.Json Error: 0 : Error! ", sw.ToString()); } finally { Trace.Listeners.Remove(listener); Trace.AutoFlush = false; } }
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); } }
/// <summary> /// 写日志 /// </summary> /// <param name="type"></param> /// <param name="id"></param> /// <param name="msg"></param> public static void WriteLog(TraceEventType type, int id, string msg) { string direct = HttpContext.Current.Server.MapPath("~/Log/Api/"); if (!Directory.Exists(direct)) Directory.CreateDirectory(direct); string file = direct + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; TextWriterTraceListener listen = new TextWriterTraceListener(file); listen.TraceOutputOptions = TraceOptions.ProcessId | TraceOptions.ThreadId | TraceOptions.Timestamp | TraceOptions.DateTime | TraceOptions.LogicalOperationStack; //TraceOptions.Callstack; Trace.Listeners.Add(listen); Trace.AutoFlush = false; //Trace.WriteLine("Test"); SourceSwitch sourceSwitch = new SourceSwitch("sourceSwitch"); sourceSwitch.Level = SourceLevels.Verbose; TraceSource traceSource = new TraceSource("traceSource"); traceSource.Switch = sourceSwitch; traceSource.Listeners.Add(listen); traceSource.TraceEvent(type, id, msg); Trace.Close(); }
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 void TraceTest01() { Refresh("TraceClassTests_TextWriterTraceListener1"); try { using (FileStream fs = File.Create("TraceClassTests_TextWriterTraceListener1")) { TextWriterTraceListener textTL = new TextWriterTraceListener(fs); Trace.Listeners.Add(textTL); Trace.WriteLine("Message start."); Trace.IndentSize = 2; Trace.IndentLevel = 2; Trace.Write("This message should be indented."); Trace.TraceError("This error not be indented."); Trace.TraceError("{0}", "This error is indendented"); Trace.TraceWarning("This warning is indented"); Trace.TraceWarning("{0}", "This warning is also indented"); Trace.TraceInformation("This information in indented"); Trace.TraceInformation("{0}", "This information is also indented"); Trace.IndentSize = 0; Trace.IndentLevel = 0; Trace.WriteLine("Message end."); textTL.Dispose(); Assert.True(HelperMethods.CheckStrings("TraceClassTests_TextWriterTraceListener1", String.Format("Message start.\r\n This message should be indented.{0} Error: 0 : This error not be indented.\r\n {0} Error: 0 : This error is indendented\r\n {0} Warning: 0 : This warning is indented\r\n {0} Warning: 0 : This warning is also indented\r\n {0} Information: 0 : This information in indented\r\n {0} Information: 0 : This information is also indented\r\nMessage end.\r\n", "DEFAULT_APPNAME"))); //DEFAULT_APPNAME this a bug which needs to be fixed. } } finally { Refresh("TraceClassTests_TextWriterTraceListener1"); } }
/// <summary> /// The main entry point for the application. /// </summary> private static void Main(string [] args) { var service = new RRLightService(); if (Environment.UserInteractive) { // Application runs as an independent program (e.g. from console), but not as Windows service. // As this project uses Windows Form application as the base, it cannot run as console application. // Instead, all messages will be redirected to log file in "Logs" subcirectory. DirectoryInfo currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory()); DirectoryInfo logsDirectory = currentDirectory.CreateSubdirectory("Logs"); var listner = new TextWriterTraceListener( Path.Combine(logsDirectory.FullName, string.Format("RRLightServiceDebug-{0:yy-MM-dd-HH-mm}.log", DateTime.UtcNow))); listner.TraceOutputOptions |= TraceOptions.DateTime; Trace.Listeners.Add(listner); Trace.AutoFlush = true; // Always enable verbose trace. TraceVerbose.Enabled = true; service.ManualRun(); } else { // Send trace messages to Event Log. var listner = new EventLogTraceListener("PanoptoRRLightService"); Trace.Listeners.Add(listner); // Enable verbose trace if config is set. TraceVerbose.Enabled = Properties.Settings.Default.EnableVerboseTrace; ServiceBase.Run(new ServiceBase[] { service }); } }
public CShapeLogger(string LogFileName) { __TraceSource = new TraceSource(__TRACE_LISTENER_NAME); if (__TraceListener != null) { traceListenerClose(__TraceListener); // 리스너가 이미 있으면 종료 } //로그파일 출력 리스너 할당 __TraceListener = new System.Diagnostics.TextWriterTraceListener(LogFileName); StreamWriter sw = __TraceListener.Writer as StreamWriter; sw.AutoFlush = true; //콘솔 출력 리스너 할당 var console = new System.Diagnostics.TextWriterTraceListener(Console.Out); console.Filter = new System.Diagnostics.EventTypeFilter(System.Diagnostics.SourceLevels.Information); // 리스너 추가 __TraceSource.Listeners.Clear(); traceSourceListenersAdd(__TraceSource, console); traceSourceListenersAdd(__TraceSource, __TraceListener); TraceSourceSwitchLevel(SourceLevels.All); }
public static int LogTextTraceWriter(string message) { string filename = "c:\\PGASurfLog.txt"; //string time = DateTime.Now.ToString(CultureInfo.InvariantCulture); if (!String.IsNullOrEmpty(message)) { message = string.Format("{0}\n", message); } // Create a file for output named TestFile.txt. if (myFile == null) { myFile = File.Create(filename, 4096, FileOptions.RandomAccess); } if (myTextListener == null) { /* Create a new text writer using the output stream, and add it to * the trace listeners. */ myTextListener = new SystemLogger.TextWriterTraceListener(myFile); SystemLogger.Trace.Listeners.Add(myTextListener); } // Write output to the file. SystemLogger.Trace.WriteLine(message); // Flush the output. SystemLogger.Trace.Flush(); return(0); }
/// <summary> /// Constructor /// </summary> static void Main(string[] args) { Debug.AutoFlush = true; Debug.IndentLevel = 0; // Write to CLI also TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out); Debug.Listeners.Add(writer); run = new WinLLDP(); // Send first packet immediately sendPacket(); // Run the LLDP packet sender every X seconds Debug.WriteLine("Starting timer", EventLogEntryType.Information); timer.Interval = TimeSpan.FromSeconds(10).TotalMilliseconds; timer.AutoReset = true; timer.Elapsed += triggerEvent; timer.Start(); // Wait for keypress Debug.WriteLine("Press key to stop", EventLogEntryType.Information); Console.ReadKey(); timer.Stop(); }
//public static string LogFile; public static bool OpenLogFile() { var txtListener = new TextWriterTraceListener("shadowsocks.log"); Debug.AutoFlush = true; Debug.Listeners.Clear(); Debug.Listeners.Add(txtListener); Trace.AutoFlush = true; Trace.Listeners.Clear(); Trace.Listeners.Add(txtListener); return true; /* try { string temppath = Path.GetTempPath(); LogFile = Path.Combine(temppath, "shadowsocks.log"); FileStream fs = new FileStream(LogFile, FileMode.Append); StreamWriterWithTimestamp sw = new StreamWriterWithTimestamp(fs); sw.AutoFlush = true; Console.SetOut(sw); Console.SetError(sw); return true; } catch (IOException e) { Console.WriteLine(e.ToString()); return false; } */ }
private static void WriteEntry(string type, string message) { try { DirectoryMethod.DirectoryMethod temp = new DirectoryMethod.DirectoryMethod(); temp.CreateDirectory(Properties.Settings.Default.FMLogs); using (TextWriterTraceListener writer = new TextWriterTraceListener(Path.Combine(Const.CurrentApplication, Properties.Settings.Default.FMLogs, DateExtension.DateExtension.DayToday() + "- Logs.txt"))) { Trace.AutoFlush = true; Trace.Listeners.Add(writer); string messagetoWrite = string.Format("{0} - {1} {2}", DateExtension.DateExtension.HourToday(), type, message); //Message du fichier de logs et debug Output Trace.WriteLine(messagetoWrite); //Message console ConsoleListener.ConsoleListener.WriteInConsole(messagetoWrite); Trace.Listeners.Remove(writer); } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } }
/// <summary> /// Main Execution. UI handled in separate method, as this is a procedural utility. /// </summary> /// <param name="args">Not used</param> private static void Main(string[] args) { string serverUrl, destProjectName, plansJSONPath, logPath, csvPath; UIMethod(out serverUrl, out destProjectName, out plansJSONPath, out logPath, out csvPath); teamCollection = new TfsTeamProjectCollection(new Uri(serverUrl)); workItemStore = new WorkItemStore(teamCollection); Trace.Listeners.Clear(); TextWriterTraceListener twtl = new TextWriterTraceListener(logPath); twtl.Name = "TextLogger"; twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime; ConsoleTraceListener ctl = new ConsoleTraceListener(false); ctl.TraceOutputOptions = TraceOptions.DateTime; Trace.Listeners.Add(twtl); Trace.Listeners.Add(ctl); Trace.AutoFlush = true; // Get Project ITestManagementTeamProject newTeamProject = GetProject(serverUrl, destProjectName); // Get Test Plans in Project ITestPlanCollection newTestPlans = newTeamProject.TestPlans.Query("Select * From TestPlan"); // Inform user which Collection/Project we'll be working in Trace.WriteLine("Executing alignment tasks in collection \"" + teamCollection.Name + "\",\n\tand Destination Team Project \"" + newTeamProject.TeamProjectName + "\"..."); // Get and print all test case information GetAllTestPlanInfo(newTestPlans, plansJSONPath, logPath, csvPath); Console.WriteLine("Alignment completed. Check log file in:\n " + logPath + "\nfor missing areas or other errors. Press enter to close."); Console.ReadLine(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); // This would prevent TextWriterTraceListener from buffering trace messages but cause // it to flush them as each trace message is sent to listener if (env.IsDevelopment()) { Trace.AutoFlush = true; } var listener = new TextWriterTraceListener("AspNet5LoggingService.txt"); listener.Filter = new SourceFilter("AspNet5LoggingService"); loggerFactory.AddTraceSource( new SourceSwitch("AspNet5LoggingSwitch", "Verbose"), listener ); app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(); }
public TraceLogger(string fileName) { Guard.ArgumentNotEmpty(() => fileName); _traceSource = new TraceSource("SmartStore"); _traceSource.Switch = new SourceSwitch("LogSwitch", "Error"); _traceSource.Listeners.Remove("Default"); var console = new ConsoleTraceListener(false); console.Filter = new EventTypeFilter(SourceLevels.All); console.Name = "console"; var textListener = new TextWriterTraceListener(fileName); textListener.Filter = new EventTypeFilter(SourceLevels.All); textListener.TraceOutputOptions = TraceOptions.DateTime; _traceSource.Listeners.Add(console); _traceSource.Listeners.Add(textListener); // Allow the trace source to send messages to // listeners for all event types. Currently only // error messages or higher go to the listeners. // Messages must get past the source switch to // get to the listeners, regardless of the settings // for the listeners. _traceSource.Switch.Level = SourceLevels.All; }
public GSM_SMS() { //spDriver = new SerialPortDriver(); spDriver = new SerialPortDriver(9600, 8, StopBits.One, Parity.None, Handshake.None); responseTimeout = int.Parse(ConfigurationSettings.AppSettings["ResponseTimeout"]); transactionTimer = new System.Timers.Timer(responseTimeout); transactionTimer.Elapsed += new ElapsedEventHandler(transactionTimeout); transactionTimer.AutoReset = false; transactionEvent = new AutoResetEvent(false); _gsmSMSTrace = new TraceSource("GSM_SMSTrace"); _gsmSMSTrace.Switch = new SourceSwitch("GSM_SMSTraceSwitch"); String gsmSMSTraceFile = ConfigurationSettings.AppSettings["GSM_SMSTraceFile"]; if (gsmSMSTraceFile != String.Empty && gsmSMSTraceFile!= null) { _gsmSMSTraceListener = new TextWriterTraceListener(gsmSMSTraceFile); _gsmSMSTrace.Listeners.Add(_gsmSMSTraceListener); _gsmSMSTrace.Switch.Level = SourceLevels.Information; } else { _gsmSMSTrace.Switch.Level = SourceLevels.Off; } }
static void Main() { if (!EventLog.SourceExists("SelfMailer")) { EventLog.CreateEventSource("SelfMailer", "Mes applications"); } EventLog eventLog = new EventLog("Mes applications", ".", "SelfMailer"); eventLog.WriteEntry("Mon message", EventLogEntryType.Warning); BooleanSwitch booleanSwitch = new BooleanSwitch("BooleanSwitch", "Commutateur booléen."); TraceSwitch traceSwitch = new TraceSwitch("TraceSwitch", "Commutateur complexe."); TextWriterTraceListener textListener = new TextWriterTraceListener(@".\Trace.txt"); Trace.Listeners.Add(textListener); Trace.AutoFlush = true; Trace.WriteLineIf(booleanSwitch.Enabled, "Démarrage de l'application SelfMailer"); Project = new Library.Project(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Forms.Main()); Trace.WriteLineIf(traceSwitch.TraceInfo, "Arrêt de l'application SelfMailer"); }
public void set_up() { Debug.Listeners.Clear(); TextWriterTraceListener t = new TextWriterTraceListener("log.txt"); Debug.Listeners.Add(t); Debug.AutoFlush = true; Debug.WriteLine("0"); /*PlatformID platformID = Environment.OSVersion.Platform; if (platformID == PlatformID.Win32NT || platformID == PlatformID.Win32Windows) { Process process = new Process(); process.StartInfo.FileName = "icepacknode"; process.StartInfo.Arguments = "--start FerdaIcePackNode"; process.Start(); process.WaitForExit(); } else {*/ ProcessStartInfo psi = new ProcessStartInfo("icegridnode", "--Ice.Config=config --IceGrid.Registry.Data=registry --IceGrid.Node.Data=node --deploy application.xml --warn"); psi.CreateNoWindow = true; psi.WorkingDirectory = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "../db"); Process.Start(psi); /*ProcessStartInfo psi2 = new ProcessStartInfo("icepackadmin", "--Ice.Config=config -e \"application add 'application.xml'\""); psi2.CreateNoWindow = true; Process processReg = Process.Start(psi2); processReg.WaitForExit();*/ System.Threading.Thread.Sleep(5000); /*}*/ Debug.WriteLine("1"); this.manager = new ModulesManager(new string[0],new string[2]{"cs-CZ","en-US"}); Debug.WriteLine("2"); }
public static void ClassInitialze() { TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out); // Initialize default log factory // LoggerFactory.SetCurrent(new TraceSourceLogFactory(tr1)); LoggerFactory.SetCurrent(new TraceSourceLogFactory()); }
void PerformIncrementalUpdate() { SourceChangeList changes = this.ConstructSourceChangeList(); string expectedOutput = this.GetExpectedOutput(); //perform update Document originalDocument = this.compilationUnit.SourceContext.Document; Document changedDocument = this.currentDocument = this.GetChangedDocument(this.currentDocument, changes); lock (this){ //prevent asynchronous symbol table update event handler from producing output until after CheckUpdatedCompilation has run Compilation updatedCompilation = this.compiler.UpdateSymbolTable(this.compilation, originalDocument, changedDocument, changes, this.errors); this.CheckUpdatedCompilation(this.compilation, updatedCompilation); this.compilation = updatedCompilation; } //Give asynchronous symbol table update events time to complete Thread.Sleep(20); //Get actual output and compare with expected output string actualOutput = this.output.ToString(); if (expectedOutput != actualOutput) { Console.SetOut(this.savedConsoleOut); Console.WriteLine("Test {0} line {1} failed", this.testName, this.lineCounter - 1); Console.WriteLine("Actual output:"); Console.Write(actualOutput); Console.WriteLine("Expected output:"); Console.Write(expectedOutput); this.failures++; } Console.SetOut(new StringWriter(this.output = new StringBuilder())); System.Diagnostics.Debug.Listeners.Remove(this.traceListener); this.traceListener = new System.Diagnostics.TextWriterTraceListener(System.Console.Out); System.Diagnostics.Debug.Listeners.Add(this.traceListener); }
private static void CreateDebugListener() { return; string LogPath = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Viking\\Logs"; if (!Directory.Exists(LogPath)) Directory.CreateDirectory(LogPath); string FileName = LogPath +"\\" + DateTime.Now.ToString("MM.dd.yyyy HH.mm.ss") + ".log"; DebugLogFile = System.IO.File.CreateText(FileName); TextWriter SynchronizedDebugWriter = StreamWriter.Synchronized(DebugLogFile); TextWriterTraceListener Listener = new TextWriterTraceListener(SynchronizedDebugWriter, "Viking Log Listener"); Trace.Listeners.Add(Listener); Debug.Listeners.Add(Listener); ConsoleTraceListener DebugOutputListener = new ConsoleTraceListener(true); Trace.Listeners.Add(DebugOutputListener); Debug.Listeners.Add(DebugOutputListener); Trace.UseGlobalLock = true; }
static void Main() { Form1 frmBattMon_Form = null; // Create the TextWriterTraceListener objects for the Console window (tr1) and for a text file named Output.txt (tr2), // and then add each object to the Debug Listeners collection: // TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out); // Debug.Listeners.Add(tr1); TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("batt_mon_c#dbg.out.txt")); Debug.Listeners.Add(tr2); Debug.WriteLine("++Program::Main()"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // create new battmon form frmBattMon_Form = new Form1(); // run battmon form Application.Run(frmBattMon_Form); // we are exiting, tell worker thread to quit // instead may use ours frmBattMon_Form.bOnStopMonitoring(true); Debug.WriteLine("--Program::Main()"); Debug.Flush(); return; }
string _test_error_msg; // If set this will indicate error for tests usually run after calibration #endregion Fields #region Constructors /// <summary> /// The main form constructor /// </summary> public Form_Main() { // Init the trace listener try { Stream outResultsFile = File.Create("output.txt"); var textListener = new TextWriterTraceListener(outResultsFile); Trace.Listeners.Add(textListener); } catch (System.IO.IOException) { // Most likely we are already running MessageBox.Show("Unable to open trace listener.\r\n\"" + this.assemblyTitle + "\" may already be running?\r\nExiting...", this.assemblyTitle); this.Close(); } InitializeComponent(); // Create the app data folder if (!Directory.Exists(_app_data_dir)) { Directory.CreateDirectory(_app_data_dir); } // Init the log file initLogFile(); }
public void Test03() { string msg1, name; name = "MyXMLTraceWriter"; string fileName = string.Format("{0}_3.xml", this.GetType().Name); //Testing ctor(Stream, string) //Scenario 3: Vanilla - Pass in a valid name and check with the Name property try { CommonUtilities.DeleteFile(fileName); _stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); _textWriter = new TextWriterTraceListener(_stream, name); Assert.True(_textWriter.Name == name); msg1 = "HelloWorld"; _textWriter.WriteLine(msg1); _textWriter.Dispose(); Assert.True(CommonUtilities.TestListenerContent(new Type[] { typeof(TextWriterTraceListener) }, new string[] { fileName }, msg1)); } finally { CommonUtilities.DeleteFile(fileName); } }
// Create a constructor public CFile() { // Add a new listener to the class TextWriterTraceListener tr = new TextWriterTraceListener(System.Console.Out); Debug.Listeners.Add(tr); _sFileName = @Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "CStudents.txt"; }
static void Main(string[] args) { if (args.Length < 3) { Help(); } clientName = args[0]; CertPath = args[1]; pass = args[2]; SiteCode = args[3]; MPHostName = args[4]; // Creates the text file that the trace listener will write to. @"FolderIcon\Folder.ico" var outPutDirectory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); var Tick = DateTime.Now.Ticks.GetHashCode().ToString("x").ToUpper(); var logPath = outPutDirectory + "\\ClientFaux_" + Tick + ".txt"; if (File.Exists(logPath)) { logPath = outPutDirectory + "\\ClientFaux_" + Tick + "_1.txt"; Console.WriteLine("Logging as " + logPath); } Console.WriteLine("Logging to: " + logPath); System.IO.FileStream myTraceLog = new System.IO.FileStream(logPath, System.IO.FileMode.OpenOrCreate); // Creates the new trace listener. System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener(myTraceLog); Trace.Listeners.Add(myListener); //Get the domain name and cert path string DomainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; string CMServerName = MPHostName + "." + DomainName; //string CertPath = outPutDirectory + "\\MixedModeTestCert.pfx"; //check for a cert file, if we don't see it, give up if (File.Exists(CertPath)) { Console.WriteLine("Found cert file at " + CertPath); } else { Console.WriteLine("Could not find a cert PFX file at " + CertPath); return; } String machineName = System.Environment.MachineName; Console.WriteLine("Running on system[" + machineName + "], registering as [" + clientName + "]"); //string ClientName = machineName; SimulateClient(CMServerName, clientName, DomainName, SiteCode); }
private void InitializeTracing() { System.IO.FileStream myTraceLog = new System.IO.FileStream( AdvancedSettings.Default.LogFile, System.IO.FileMode.OpenOrCreate); // Creates the new trace listener. System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener(myTraceLog); System.Diagnostics.Trace.Listeners.Add(myListener); }
/// <summary>Logger釋放</summary> public static void Dispose() { if (myTraceLog != null) { myTraceLog.Close(); } myTraceLog = null; if (myListener != null) { myListener.Close(); } myListener = null; }
private static void Main() { if (Program.IsSingleInstance()) { System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); Program.logDirectory = System.AppDomain.CurrentDomain.BaseDirectory; Program.logDirectory = string.Format("{0}{1}log", Program.logDirectory, System.IO.Path.DirectorySeparatorChar); if (!System.IO.Directory.Exists(Program.logDirectory)) { System.IO.Directory.CreateDirectory(Program.logDirectory); } Program.logFileName = System.IO.Path.Combine(Program.logDirectory, string.Format("{0:yyyy.MM.dd}_{0:HH-mm}_OPCClient.log", System.DateTime.Now)); string message = ""; try { System.IO.FileStream stream = new System.IO.FileStream(Program.logFileName, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); Program.myTextListener = new MyTextWriterTraceListener(stream, ""); System.Diagnostics.Trace.Listeners.Add(Program.myTextListener); message = "Создание лог-файла..."; } catch (System.Exception ex) { Program.myTextListener = new MyTextWriterTraceListener(); System.Diagnostics.Trace.Listeners.Add(Program.myTextListener); message = string.Format("Ошибка при создании лог-файла: " + ex.Message, new object[0]); } System.Diagnostics.TextWriterTraceListener listener = new System.Diagnostics.TextWriterTraceListener(System.Console.Out); System.Diagnostics.Trace.Listeners.Add(listener); System.Diagnostics.Trace.WriteLine(message); System.Diagnostics.Trace.AutoFlush = true; System.Diagnostics.Trace.UseGlobalLock = false; while (true) { try { Program.sL = new SettingsLoader(); System.Windows.Forms.Application.Run(new OPCClientForm()); } catch (System.Exception ex) { if (System.Windows.Forms.MessageBox.Show(string.Format("Ошибка: {0}. Приложение будет закрыто. Перезапустить приложение?", ex.Message), "Ошибка", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Hand) == System.Windows.Forms.DialogResult.Yes) { continue; } } break; } } }
/// <summary> /// 設定Log路徑 /// </summary> /// <param name="path"></param> private static void SetLogFilePath(string path) { m_LogFilePath = path; if (myTraceLog != null) { myTraceLog.Close(); } myTraceLog = new System.IO.FileStream(path, System.IO.FileMode.Append); // Creates the new trace listener. if (myListener != null) { myListener.Close(); } myListener = new System.Diagnostics.TextWriterTraceListener(myTraceLog); System.Diagnostics.Trace.Listeners.Add(myListener); }
/// <summary> /// ロギングを初期化する /// </summary> static private void initLogging() { //Error以上のイベントが通過されるようにする logger.Switch.Level = System.Diagnostics.SourceLevels.Warning; //DefaultTraceListenerが必要なければ削除する logger.Listeners.Remove("Default"); //TextWriterTraceListenerオブジェクトを作成 System.Diagnostics.TextWriterTraceListener twtl = new System.Diagnostics.TextWriterTraceListener( Application.StartupPath + "\\log\\linearerror.log", "LogFile"); twtl.TraceOutputOptions = System.Diagnostics.TraceOptions.DateTime; //リスナコレクションに追加する logger.Listeners.Add(twtl); }
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) { //For Debugging Purpose only System.Diagnostics.TextWriterTraceListener tr1 = new System.Diagnostics.TextWriterTraceListener(System.Console.Out); System.Diagnostics.Debug.Listeners.Add(tr1); //get the directory that contains family tree json files string filelocation = ""; do { WriteLine("Please enter the full file location you want to save reports in: "); filelocation = ReadLine(); } while (!Directory.Exists(filelocation)); List <AncestryTree> files = new List <AncestryTree>(); try { var dir = Path.GetDirectoryName(filelocation); //get json files in directory string[] jsonfiles = Directory.GetFiles(dir, "*.json"); foreach (var file in jsonfiles) { System.Diagnostics.TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.OpenRead(file)); Debug.Listeners.Add(tr2); //read json into tree //add tree to array } //find and print common ancestors between pairs of trees var commonAncestors = AncestorsFromList(files); printAncestors(commonAncestors); ReadLine(); } catch (Exception e) { Console.WriteLine(e.ToString()); System.Diagnostics.Debug.WriteLine(e.ToString()); } }
static void Main(string[] args) { // Creates the text file that the trace listener will write to. System.IO.FileStream myTraceLog = new System.IO.FileStream("C:\\temp\\myTraceLog3.txt", System.IO.FileMode.OpenOrCreate); // Creates the new trace listener. System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener(myTraceLog); Trace.Listeners.Add(myListener); string DomainName = "FoxDeploy.local"; string MPHostname = "SCCM.FoxDeploy.local"; String machineName = System.Environment.MachineName; Console.WriteLine(machineName); string ClientName = "HamHam123"; Console.WriteLine("Connecting from " + ClientName); SimulateClient(MPHostname, ClientName, DomainName); }
private static void AddListener() { try { if (!Directory.Exists(Application.StartupPath + "\\Trace")) { Directory.CreateDirectory(Application.StartupPath + "\\Trace"); } if (!Directory.Exists(Application.StartupPath + "\\Trace\\" + DateTime.Now.ToString("MM"))) { Directory.CreateDirectory(Application.StartupPath + "\\Trace\\" + DateTime.Now.ToString("MM")); } if (Directory.Exists(Application.StartupPath + "\\Trace\\" + DateTime.Now.AddMonths(1).ToString("MM"))) { Directory.Delete(Application.StartupPath + "\\Trace\\" + DateTime.Now.AddMonths(1).ToString("MM"), true); } traceName = Application.StartupPath + "\\Trace\\" + DateTime.Now.ToString("MM") + "\\" + DateTime.Now.ToString("dd_TRACE") + ".log"; System.IO.StreamWriter writer = new System.IO.StreamWriter(traceName, true, System.Text.Encoding.GetEncoding("windows-1254")); System.Diagnostics.TextWriterTraceListener listener = new System.Diagnostics.TextWriterTraceListener(writer); System.Diagnostics.Trace.Listeners.Add(listener); System.Diagnostics.Trace.AutoFlush = true; System.Diagnostics.Trace.WriteLine("-> " + DateTime.Now.ToString() + "\tBaşladı"); } catch { ; } }
static void Main(string[] args) { // Setup a trace listener to the console Trace.AutoFlush = true; // First, determine the filename to use: string dir = Environment.CurrentDirectory + "\\"; string baseName = "hstlogfile." + DateTime.Now.ToShortDateString().Replace("/", "-"); string ext = ".txt"; // If this file exists, rename appropriately if (System.IO.File.Exists(dir + baseName + ext)) { int x = 1; while (System.IO.File.Exists(dir + baseName + "." + Convert.ToString(x) + ext)) { x++; } baseName = baseName + "." + Convert.ToString(x); } System.IO.FileStream traceLog = new System.IO.FileStream(dir + baseName + ext, System.IO.FileMode.OpenOrCreate); // Creates the new trace listener. System.Diagnostics.TextWriterTraceListener newListener = new System.Diagnostics.TextWriterTraceListener(traceLog); // Add the listener Trace.Listeners.Add(newListener); Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); // If the settings folder does not exist, create it if (!System.IO.Directory.Exists(Environment.CurrentDirectory + "\\settings")) { Trace.WriteLine("Settings folder was not found - it is being created."); System.IO.Directory.CreateDirectory(Environment.CurrentDirectory + "\\settings"); } Thread.CurrentThread.Priority = ThreadPriority.Lowest; // We don't want anything to interfere with // the game servers that are being managed. ////////////////////////////////////////////////////////////// // Initialization: Part One - Load settings from files ////////////////////////////////////////////////////////////// // Open the database connection string dbFile = Environment.CurrentDirectory + "\\settings\\global_settings.mdb"; if (!System.IO.File.Exists(dbFile)) { Trace.WriteLine("Database file not found - " + dbFile); Trace.WriteLine("Could not initialize - reinstall HST to repair this problem."); } DB.OpenDatabase(dbFile); // Start all of the server processes ServerManager.ServerList = new System.Collections.ArrayList(); // Load the server list from the database OleDbDataReader dr = DB.GetData("select * from servers"); if (dr.HasRows) { while (dr.Read()) { string startupFolder = dr.GetString(dr.GetOrdinal("installed_dir")); HaloServer h = new HaloServer(startupFolder); h.name = dr.GetString(dr.GetOrdinal("name")); h.id = Convert.ToString(dr.GetInt32(dr.GetOrdinal("server_id"))); h._ipAddress = System.Net.IPAddress.Parse(dr.GetString(dr.GetOrdinal("ip_address"))); h._port = dr.GetInt32(dr.GetOrdinal("port")); h._commandLine = dr.GetString(dr.GetOrdinal("commandline")); h._parameters = dr.GetString(dr.GetOrdinal("parameters")); ServerManager.ServerList.Add(h); h.Start(); } } else { Trace.WriteLine("No servers found."); } dr.Close(); string input; while (true) { input = Console.ReadLine().ToUpper(); if (input == "QUIT") { // There are still child threads running - we need to fix that. foreach (System.Collections.DictionaryEntry de in ServerManager.ServerList) { GameServer g = (GameServer)de.Value; g.Stop(); } break; } if (input.StartsWith("STOP")) { GameServer g = (GameServer)ServerManager.ServerList[0]; Trace.WriteLine("Stopping Server: " + g.name); g.Stop(); } if (input.StartsWith("START")) { GameServer g = (GameServer)ServerManager.ServerList[0]; Trace.WriteLine("Starting Server: " + g.name); g.Start(); } /*if (input.StartsWith("WEB")) * { * if (hServ.Active) * { * Trace.WriteLine("Web server active."); * Trace.WriteLine("IP: " + hServ.Ip); * Trace.WriteLine("Port: " + Convert.ToString(hServ.Port)); * Trace.WriteLine(" "); * } * else * { * Trace.WriteLine("Web Server not currently active."); * } * }*/ } }
/// <summary> /// Run a suite /// </summary> /// <returns>true if suite succeeds, false if it fails.</returns> private static bool RunSuite(string suiteName) { System.Diagnostics.Debug.Listeners.Remove("Default"); StringBuilder source = null; StringBuilder expectedOutput = null; StringBuilder actualOutput = null; ArrayList suiteParameters = new ArrayList(); ArrayList compilerParameters = null; ArrayList testCaseParameters = null; bool xamlSuite = false; int errors = 0; main.assemblyNameCounter = 0; try{ StreamReader instream = File.OpenText(suiteName); int ch = instream.Read(); int line = 1; while (ch >= 0) { compilerParameters = (ArrayList)suiteParameters.Clone(); bool skipTest = false; if (ch == '`') { ch = instream.Read(); bool parametersAreForEntireSuite = false; if (ch == '`') { parametersAreForEntireSuite = true; ch = instream.Read(); if (ch == 'x') { xamlSuite = true; while (ch != 13) { ch = instream.Read(); } } } while (ch == '/') { //compiler parameters StringBuilder cParam = new StringBuilder(); do { cParam.Append((char)ch); ch = instream.Read(); }while(ch != '/' && ch != 0 && ch != 10 && ch != 13); for (int i = cParam.Length - 1; i >= 0; i--) { if (!Char.IsWhiteSpace(cParam[i])) { break; } cParam.Length = i; } string cp = cParam.ToString(); if (cp == "/p:v2" && TargetPlatform.TargetVersion.Major < 2) { skipTest = true; } compilerParameters.Add(cp); } if (parametersAreForEntireSuite) { suiteParameters.AddRange(compilerParameters); } if (ch == 13) { ch = instream.Read(); } if (ch == 10) { line++; ch = instream.Read(); if (parametersAreForEntireSuite && ch == '`') { continue; } } } if (ch == ':') { ch = instream.Read(); while (ch == '=') { //test case parameters StringBuilder tcParam = new StringBuilder(); ch = instream.Read(); //discard = while (ch != '=' && ch != 0 && ch != 10 && ch != 13) { tcParam.Append((char)ch); ch = instream.Read(); } for (int i = tcParam.Length - 1; i >= 0; i--) { if (!Char.IsWhiteSpace(tcParam[i])) { break; } tcParam.Length = i; } if (testCaseParameters == null) { testCaseParameters = new ArrayList(); } testCaseParameters.Add(tcParam.ToString()); } if (ch == 13) { ch = instream.Read(); } if (ch == 10) { ch = instream.Read(); line++; } } source = new StringBuilder(); while (ch >= 0 && ch != '`') { source.Append((char)ch); ch = instream.Read(); if (ch == 10) { line++; } } if (ch < 0) { Console.WriteLine("The last test case in the suite has not been provided with expected output"); errors++; break; } ch = instream.Read(); if (ch == 13) { ch = instream.Read(); } if (ch == 10) { line++; ch = instream.Read(); } int errLine = line; expectedOutput = new StringBuilder(); while (ch >= 0 && ch != '`') { expectedOutput.Append((char)ch); ch = instream.Read(); if (ch == 10) { line++; } } if (expectedOutput.Length > 0 && expectedOutput[expectedOutput.Length - 1] == 10) { expectedOutput.Length -= 1; } if (expectedOutput.Length > 0 && expectedOutput[expectedOutput.Length - 1] == 13) { expectedOutput.Length -= 1; } ch = instream.Read(); if (ch == 13) { ch = instream.Read(); } if (ch == 10) { ch = instream.Read(); line++; } if (skipTest) { continue; } actualOutput = new StringBuilder(); TextWriter savedOut = Console.Out; Console.SetOut(new StringWriter(actualOutput)); System.Diagnostics.TextWriterTraceListener myWriter = new System.Diagnostics.TextWriterTraceListener(System.Console.Out); System.Diagnostics.Debug.Listeners.Add(myWriter); try{ int returnCode = RunTest(Path.GetFileNameWithoutExtension(suiteName), source.ToString(), actualOutput, compilerParameters, testCaseParameters, xamlSuite); if (returnCode != 0) { actualOutput.Append("Non zero return code: " + returnCode); } }catch (Exception e) { actualOutput.Append(e.Message); } compilerParameters = null; testCaseParameters = null; Console.SetOut(savedOut); System.Diagnostics.Debug.Listeners.Remove(myWriter); if (actualOutput.Length > 0 && actualOutput[actualOutput.Length - 1] == 10) { actualOutput.Length -= 1; } if (actualOutput.Length > 0 && actualOutput[actualOutput.Length - 1] == 13) { actualOutput.Length -= 1; } if (!expectedOutput.ToString().Equals(actualOutput.ToString())) { if (errors++ == 0) { Console.WriteLine(suiteName + " failed"); } Console.WriteLine("source({0}):", errLine); if (source != null) { Console.WriteLine(source); } Console.WriteLine("actual output:"); Console.WriteLine(actualOutput); Console.WriteLine("expected output:"); if (expectedOutput != null) { Console.WriteLine(expectedOutput); } } } instream.Close(); if (errors == 0) { Console.WriteLine(suiteName + " passed"); return(true); } else { Console.WriteLine(suiteName + " had " + errors + (errors > 1 ? " failures" : " failure")); return(false); } }catch { Console.WriteLine(suiteName + " failed"); Console.WriteLine("source:"); if (source != null) { Console.WriteLine(source); } Console.WriteLine("actual output:"); Console.WriteLine(actualOutput); Console.WriteLine("expected output:"); if (expectedOutput != null) { Console.WriteLine(expectedOutput); } return(false); } }
public static void Main(string[] args) { //using (BleBeaconServerContext db = new BleBeaconServerContext()) //{ /*Console.WriteLine("Beacons:"); * foreach (BleBeacon beacon in db.BleBeacons) * { * Console.WriteLine("Mac: " + beacon.MacAddress); * } */ Console.WriteLine("Starting BleBeaconServer v" + progVersion()); string filename = null; int port = 0; bool noConsole = false; bool help = false; bool debug = false; for (int i = 0; i < args.Length; i++) { if (args[i].StartsWith("-")) { if (args[i] == "-f") { if (i + 1 < args.Length) { filename = args[i + 1]; } } else if (args[i] == "-p") { if (i + 1 < args.Length) { int.TryParse(args[i + 1], out port); } } else if (args[i] == "--no-console") { noConsole = true; } else if (args[i] == "--debug") { debug = true; } else if (args[i] == "--help") { help = true; } } } if (filename != null && File.Exists(filename)) { grafanaFileWriter = new BeaconDataGrafanaFileWriter(filename); } else if (filename != null) { Console.WriteLine("Filepath '" + filename + "' doesn't exists!"); PrintUsageText(); return; } else { Console.WriteLine("Please submit a filename"); PrintUsageText(); return; } if (port == 0) { Console.WriteLine("Cannot start without port information."); PrintUsageText(); return; } if (help) { PrintUsageText(); return; } if (debug) { debugListener = new TextWriterTraceListener(Console.Out); debugListener.Filter = new SourceFilter("debug"); System.Diagnostics.Trace.Listeners.Add(debugListener); //Trace.WriteLine("Testing debug listener 1"); //Trace.WriteLine("Testing debug listener 2"); } Console.WriteLine("Using port " + port); if (filename != null) { Console.WriteLine("Starting grafana filewriter with file '" + filename + "'"); } if (noConsole) { Console.WriteLine("Selected no console"); } if (debug) { Console.WriteLine("Printing out debug information"); } packetHandler = new BeaconPacketHandler(); BeaconPacketHandler.BeaconDataReceived += BeaconPacketHandler_BeaconDataReceived; udpListener = new UdpListener(port, 524288); UdpListener.BeaconPacketReceived += UdpListener_BeaconPacketReceived; Console.CancelKeyPress += Console_CancelKeyPress; while (!closing) { if (!noConsole) { updateConsole(packetHandler.CopyOfDistances, packetHandler.CopyOfLocations); } if (closing) { Trace.WriteLine("Closing down..."); break; } else { Thread.Sleep(1000); //Trace.WriteLine("Sleeping " + 1 + " seconds... "); continue; } } //} }
public TextlogOutput() { tw = new TextWriterTraceListener(logFile); System.Diagnostics.Trace.Listeners.Add(this); }
public void StartUp() { // Setup a file0based Trace Listener Trace.AutoFlush = true; // First, determine the filename to use: string dir = Environment.CurrentDirectory + "\\"; string baseName = "hstlogfile." + DateTime.Now.ToShortDateString().Replace("/", "-"); string ext = ".txt"; // If this file exists, rename appropriately //if (System.IO.File.Exists(dir + baseName + ext)) //{ // int x = 1; // while (System.IO.File.Exists(dir + baseName + "." + Convert.ToString(x) + ext)) // { // x++; // } // baseName = baseName + "." + Convert.ToString(x); //} System.IO.FileStream traceLog = new System.IO.FileStream(dir + baseName + ext, System.IO.FileMode.OpenOrCreate); // Creates the new trace listener. System.Diagnostics.TextWriterTraceListener newListener = new System.Diagnostics.TextWriterTraceListener(traceLog); // Add the listener Trace.Listeners.Add(newListener); Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); // If the settings folder does not exist, create it if (!System.IO.Directory.Exists(Environment.CurrentDirectory + "\\settings")) { Trace.WriteLine("Settings folder was not found - it is being created."); System.IO.Directory.CreateDirectory(Environment.CurrentDirectory + "\\settings"); } Thread.CurrentThread.Priority = ThreadPriority.Lowest; // We don't want anything to interfere with // the game servers that are being managed. ////////////////////////////////////////////////////////////// // Initialization: Part One - Load settings from files ////////////////////////////////////////////////////////////// // Read the settings.ini file for global settings string settingsFile = Environment.CurrentDirectory + "\\settings\\settings.ini"; if (!System.IO.File.Exists(settingsFile)) { Trace.WriteLine("Applications settings file (" + settingsFile + ") does not exist!"); Trace.WriteLine("Could not initialize - reinstall HST to repair this problem."); return; } IConfigSource source = new IniConfigSource(settingsFile); string installedFolder = source.Configs["Paths"].GetString("InstalledFolder"); string dataFolder = source.Configs["Paths"].GetString("DataFolder"); ServerManager.ServerList = new System.Collections.ArrayList(); HaloServer h = new HaloServer(installedFolder); h._ipAddress = System.Net.IPAddress.Parse(source.Configs["Settings"].GetString("IPAddress")); h._port = Convert.ToInt32(source.Configs["Settings"].GetString("Port")); h._commandLine = "haloceded.exe"; h._parameters = "-ip " + h._ipAddress + " " + "-port " + Convert.ToString(h._port) + " " + "-path \"" + dataFolder + "\""; ServerManager.ServerList.Add(h); }