Csharp/C Sharp/Development Class/Debug Trace
Содержание
- 1 A simple demonstration of the Debug class
- 2 Debug and Profile
- 3 Debug and Trace Output
- 4 Debug class
- 5 Defensive Programming:Conditional Methods
- 6 Demonstrate indenting debug messages
- 7 demonstrates debug output
- 8 Demonstrates routing debug messages to a file
- 9 illustrate the use of the debugger
- 10 Trace class: listener and writeline
- 11 Trace to debuger: writeline and flush
- 12 Trace to event log
- 13 Tracing Example
- 14 Tracing To A File
- 15 Using BooleanSwitch
- 16 Using Switches to Control Debug and Trace:BooleanSwitch
- 17 Using Switches to Control Debug and Trace:TraceSwitch
- 18 Using Switches to Control Debug and Trace:User-Defined Switch
A simple demonstration of the Debug class
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// DebugTst.cs -- A simple demonstration of the Debug class.
//
// Compile this program with the following command line:
// C:>csc /debug:full /d:DEBUG DebugTst.cs
using System;
using System.Diagnostics;
using System.IO;
namespace nsDebugTest
{
public class DebugTst
{
static void Main()
{
// Debug.Listeners.Clear();
// Debug.Listeners.Add (new TextWriterTraceListener(Console.Out));
// Debug.AutoFlush = true;
Debug.WriteLine ("Debug is on");
clsTest test = new clsTest(42);
test.ShowValue();
}
}
class clsTest
{
public clsTest (int num)
{
m_Num = num;
}
int m_Num;
public void ShowValue()
{
try
{
DoSomething ();
}
catch (Exception e)
{
Console.WriteLine (e.StackTrace);
}
if (m_Num < 50)
{
Debug.WriteLine (m_Num + " is less than 50");
}
}
void DoSomething ()
{
Debug.WriteLine (Environment.StackTrace);
}
}
}
Debug and Profile
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.Diagnostics;
namespace Client.Chapter_16___Debugging
{
public class PoorMansProfiler
{
[STAThread]
static void Main(string[] args)
{
DateTime Start = DateTime.Now;
DateTime End = DateTime.Now;
TimeSpan CallTime = End - Start;
Console.WriteLine("Call Time(MS): " + CallTime.Milliseconds.ToString());
}
}
}
Debug and Trace Output
using System;
using System.Diagnostics;
class MyClass
{
public MyClass(int i)
{
this.i = i;
}
[Conditional("DEBUG")]
public void VerifyState()
{
Debug.WriteLineIf(debugOutput, "In VerifyState");
Debug.Assert(i == 0, "Bad State");
}
static public bool DebugOutput
{
get
{
return(debugOutput);
}
set
{
debugOutput = value;
}
}
int i = 0;
static bool debugOutput = false;
}
public class DebugandTraceOutput
{
public static void Main()
{
Debug.Listeners.Clear();
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
MyClass c = new MyClass(1);
c.VerifyState();
MyClass.DebugOutput = true;
c.VerifyState();
}
}
Debug class
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.IO;
using System.Diagnostics;
namespace Client.Chapter_16___Debugging
{
public class Class1Chapter_16___Debugging
{
[STAThread]
static void Main(string[] args)
{
int i = 0;
Trace.Assert((i == 1), "My Trace Assertion");
Debug.Assert((i == 1), "My Debug Assertion");
}
}
}
Defensive Programming:Conditional Methods
using System;
using System.Diagnostics;
class MyClass
{
public MyClass(int i)
{
this.i = i;
}
[Conditional("DEBUG")]
public void VerifyState()
{
if (i != 0)
Console.WriteLine("Bad State");
}
int i = 0;
}
public class DefensiveProgrammingConditionalMethods
{
public static void Main()
{
MyClass c = new MyClass(1);
c.VerifyState();
}
}
Demonstrate indenting debug messages
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Indent.cs -- Demonstrate indenting debug messages.
//
// Compile this program with the following command line:
// C:>csc /debug:full /d:DEBUG Indent.cs
using System;
using System.Diagnostics;
namespace nsDebugging
{
public class Indent
{
static public void Main ()
{
Debug.Listeners.Clear ();
Debug.Listeners.Add (new TextWriterTraceListener(Console.Out));
Debug.AutoFlush = true;
Debug.IndentSize = 5;
Debug.WriteLine ("First level debug message.");
Debug.Fail ("It failed!");
FirstMethod ();
Debug.WriteLine ("Return to first level debug message.");
}
static private void FirstMethod ()
{
// Debug.Indent ();
++Debug.IndentLevel;
Debug.WriteLine ("Second level debug message");
SecondMethod ();
Debug.WriteLine ("Return to second level debug message");
// Debug.Unindent ();
--Debug.IndentLevel;
}
static private void SecondMethod ()
{
Debug.Indent ();
Debug.WriteLine ("Third level debug message.");
Debug.Unindent ();
}
}
}
demonstrates debug output
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
#define DEBUG
/*
Example21_11.cs demonstrates debug output
*/
using System;
using System.Globalization;
using System.Diagnostics;
public class Example21_11a {
public static void Main()
{
TextWriterTraceListener tl = new TextWriterTraceListener(Console.Out);
Debug.Listeners.Add(tl);
Debug.WriteLine("Starting Main()");
// create a date and a currency value
DateTime dtNow = DateTime.Now;
Double curOriginal = 12345.67;
// and format the variables for a specific culture
CultureInfo ci = new CultureInfo("en-US");
string sLocalizedDate = dtNow.ToString("d", ci);
string sLocalizedCur = curOriginal.ToString("c", ci);
Debug.Assert(sLocalizedDate != null, "Localized date has no content");
// print them out
Console.WriteLine(sLocalizedDate);
Console.WriteLine(sLocalizedCur);
Debug.WriteLine("Exiting Main()");
}
}
Demonstrates routing debug messages to a file
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Listener.cs -- Demonstrates routing debug messages to a file.
//
// Compile this program with the following command line:
// C:>csc /debug:full /d:TRACE Listener.cs
using System;
using System.Diagnostics;
using System.IO;
namespace nsDebugTest
{
public class Listener
{
static void Main(string[] args)
{
EnableDebugging();
Trace.AutoFlush = true;
Trace.WriteLine ("Debug is on");
// Add the fllowing three lines to start another listener:
FileStream strm = new FileStream ("Once.txt", FileMode.Create);
TextWriterTraceListener listen = new TextWriterTraceListener (strm);
Trace.Listeners.Add (listen);
int Num = 1;
Trace.Assert (Num == 0, "Num is not equal to 0");
// Add the following three lines:
Trace.Listeners.Remove (listen);
listen.Flush ();
strm.Close ();
clsTest test = new clsTest(42);
test.ShowValue();
// Trace.Listeners.Remove ("Console");
// Trace.WriteLine ("\r\nConsole output has been disabled");
}
static void EnableDebugging ()
{
Trace.Listeners.Clear();
// Trace.Listeners.Add (new TextWriterTraceListener(Console.Out, "Console"));
Trace.Listeners.Add (new TextWriterTraceListener(Console.Out, "Console"));
FileStream strm = new FileStream ("./Trace.out", FileMode.Create);
StreamWriter writer = new StreamWriter (strm);
Trace.Listeners.Add (new TextWriterTraceListener(writer));
}
}
class clsTest
{
public clsTest (int num)
{
m_Num = num;
}
int m_Num;
public void ShowValue()
{
try
{
DoSomething ();
}
catch (Exception e)
{
Console.WriteLine (e.StackTrace);
}
if (m_Num < 50)
{
Debug.WriteLine (m_Num + " is less than 50");
Console.WriteLine (m_Num + " is less than 50");
}
}
void DoSomething ()
{
Trace.WriteLine (Environment.StackTrace);
}
}
}
illustrate the use of the debugger
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example13_10.cs is used to illustrate the use of the debugger;
this program attempts to access an invalid array element
*/
using System;
public class Example13_10
{
public static void Main()
{
try
{
const int ArraySize = 5;
// create an array
int[] myArray = new int[ArraySize];
// set the elements of the array using a for loop
for (int count = 0; count <= ArraySize; count++)
{
myArray[count] = count;
Console.WriteLine("myArray[" + count + "] = " +
myArray[count]);
}
}
catch (System.IndexOutOfRangeException e)
{
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("StackTrace = " + e.StackTrace);
}
}
}
Trace class: listener and writeline
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.IO;
using System.Diagnostics;
namespace Client.Chapter_16___Debugging
{
public class Class1Chapter_16___Debugging1
{
[STAThread]
static void Main(string[] args)
{
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
Trace.WriteLine("My Trace to the console");
}
}
}
Trace to debuger: writeline and flush
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.IO;
using System.Diagnostics;
namespace Client.Chapter_16___Debugging
{
public class TracingToDebugger
{
[STAThread]
static void Main(string[] args)
{
Trace.WriteLine("My Trace String");
Trace.Flush();
}
}
}
Trace to event log
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.IO;
using System.Diagnostics;
namespace Client.Chapter_16___Debugging
{
public class TracingToEventLog
{
[STAThread]
static void Main(string[] args)
{
//You can change the listener with the following code
EventLogTraceListener EventListener = new EventLogTraceListener("MyApp");
Trace.Listeners.Add(EventListener);
Trace.WriteLine("My Trace String To Console");
}
}
}
Tracing Example
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.Diagnostics;
namespace Client.Chapter_16___Debugging
{
public class TracingExample
{
static void Main(string[] args)
{
TraceSwitch General = new TraceSwitch("General", "Application Switch");
Trace.WriteLineIf(General.TraceError, "General - Error Tracing Enabled");
Trace.WriteLineIf(General.TraceWarning, "General - Warning Tracing Enabled");
Trace.WriteLineIf(General.TraceInfo, "General - Info Tracing Enabled");
Trace.WriteLineIf(General.TraceVerbose, "General - Verbose Tracing Enabled");
TraceSwitch MyComponent = new TraceSwitch("MyComponent", "Application Switch");
Trace.WriteLineIf(MyComponent.TraceError, "MyComponent - Error Tracing Enabled");
Trace.WriteLineIf(MyComponent.TraceWarning, "MyComponent - Warning Tracing Enabled");
Trace.WriteLineIf(MyComponent.TraceInfo, "MyComponent - Info Tracing Enabled");
Trace.WriteLineIf(MyComponent.TraceVerbose, "MyComponent - Verbose Tracing Enabled");
}
}
}
/*
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<switches>
<add name="General" value="1" />
<add name="MyComponent" value="3" />
</switches>
</system.diagnostics>
</configuration>
*/
Tracing To A File
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.IO;
using System.Diagnostics;
namespace Client.Chapter_16___Debugging
{
public class TracingToAFile
{
[STAThread]
static void Main(string[] args)
{
FileStream Log = new FileStream("Log.txt", FileMode.OpenOrCreate);
Trace.Listeners.Add(new TextWriterTraceListener(Log));
Trace.WriteLine("My Trace String To Log File");
Trace.Flush();
Log.Close();
}
}
}
Using BooleanSwitch
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
using System.IO;
using System.Diagnostics;
namespace Client.Chapter_16___Debugging
{
public class UsingBooleanSwitch
{
static BooleanSwitch MySwitch = new BooleanSwitch("MyData", "MyModule");
[STAThread]
static void Main(string[] args)
{
MySwitch.Enabled = true;
if (MySwitch.Enabled)
Console.WriteLine("Error happened!");
}
}
}
Using Switches to Control Debug and Trace:BooleanSwitch
// compile with: csc /D:DEBUG /r:system.dll boolean.cs
using System;
using System.Diagnostics;
class MyClass
{
public MyClass(int i)
{
this.i = i;
}
[Conditional("DEBUG")]
public void VerifyState()
{
Debug.WriteLineIf(debugOutput.Enabled, "VerifyState Start");
if (debugOutput.Enabled)
Debug.WriteLine("VerifyState End");
}
BooleanSwitch debugOutput =
new BooleanSwitch("MyClassDebugOutput", "Control debug output");
int i = 0;
}
public class UsingSwitchestoControlDebugandTraceBooleanSwitch
{
public static void Main()
{
Debug.Listeners.Clear();
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
MyClass c = new MyClass(1);
c.VerifyState();
}
}
Using Switches to Control Debug and Trace:TraceSwitch
using System;
using System.Diagnostics;
class MyClass
{
public MyClass(int i)
{
this.i = i;
}
[Conditional("DEBUG")]
public void VerifyState()
{
Debug.WriteLineIf(debugOutput.TraceInfo, "VerifyState Start");
Debug.WriteLineIf(debugOutput.TraceVerbose,
"Starting field verification");
if (debugOutput.TraceInfo)
Debug.WriteLine("VerifyState End");
}
static TraceSwitch debugOutput =
new TraceSwitch("MyClassDebugOutput", "Control debug output");
int i = 0;
}
public class TraceTraceSwitch
{
public static void Main()
{
Debug.Listeners.Clear();
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
MyClass c = new MyClass(1);
c.VerifyState();
}
}
Using Switches to Control Debug and Trace:User-Defined Switch
// compile with: csc /r:system.dll file_1.cs
using System;
using System.Diagnostics;
enum SpecialSwitchLevel
{
Mute = 0,
Terse = 1,
Verbose = 2,
Chatty = 3
}
class SpecialSwitch: Switch
{
public SpecialSwitch(string displayName, string description) :
base(displayName, description)
{
}
public SpecialSwitchLevel Level
{
get
{
return((SpecialSwitchLevel) base.SwitchSetting);
}
set
{
base.SwitchSetting = (int) value;
}
}
public bool Mute
{
get
{
return(base.SwitchSetting == 0);
}
}
public bool Terse
{
get
{
return(base.SwitchSetting >= (int) (SpecialSwitchLevel.Terse));
}
}
public bool Verbose
{
get
{
return(base.SwitchSetting >= (int) SpecialSwitchLevel.Verbose);
}
}
public bool Chatty
{
get
{
return(base.SwitchSetting >=(int) SpecialSwitchLevel.Chatty);
}
}
protected new int SwitchSetting
{
get
{
return((int) base.SwitchSetting);
}
set
{
if (value < 0)
value = 0;
if (value > 4)
value = 4;
base.SwitchSetting = value;
}
}
}
class MyClass
{
public MyClass(int i)
{
this.i = i;
}
[Conditional("DEBUG")]
public void VerifyState()
{
Console.WriteLine("VerifyState");
Debug.WriteLineIf(debugOutput.Terse, "VerifyState Start");
Debug.WriteLineIf(debugOutput.Chatty,
"Starting field verification");
if (debugOutput.Verbose)
Debug.WriteLine("VerifyState End");
}
static SpecialSwitch debugOutput =
new SpecialSwitch("MyClassDebugOutput", "application");
int i = 0;
}
public class TraceUserDefinedSwitch
{
public static void Main()
{
//TraceSwitch ts = new TraceSwitch("MyClassDebugOutput", "application");
//Console.WriteLine("TraceSwitch: {0}", ts.Level);
Debug.Listeners.Clear();
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
MyClass c = new MyClass(1);
c.VerifyState();
}
}