13. Diagnostics || C# 10 Flashcards
What are the ‘preprocessor directives’?
Preprocessor directives are special instructions to the compiler that begin with the # symbol and must on entirely separate line. They execute before the main compilation takes place
~~~
#if TESTMODE
Console.WriteLine();
#endif
~~~
By using conditional compilation we can perform major refactoring under a conditional compilation directive, so we can switch between old and new versions and write libraries that can compile against multiple runtime versions, leveraging the latest features where available.
Another advantage - debugging code can refer to types in assemblies that are not included in deployment.
Suppose I want to write a method that would be called only if we are in TESTMODE environment. How can I do that?
By adding ‘Conditional’ attribute above the method:
~~~
[Conditional(“TESTMODE”)]
static void LogStatus (string msg)
{
…
}
~~~
What do you know about Debug and Trace classes?
Debug and Trace classes are static classes that provide basic logging and assertion capabilities. The two classes are very similar; the main difference is their intended use. The Debug class is intended for debug builds; the Trace class is intended for both debug and release builds.
You define the methods with either:
[Conditional(“DEBUG”)]
or
[Conditional(“TRACE”)]
Both Debug and Trace classes provide Write
, WriteLine
and WriteIf
methods. The output is sent to the debugger’s output wondow : Debug.WriteIf(x>y, "x is greater that y");
The Trace class also provides the methods TraceInformation
, TraceWarning
and TraceError
What is a TraceListener
?
The Trace class has a static Listeners
property that returns a collection of TraceListeners
instances. These are responsible for processing the content emitted by the Write
, Fail
and Trace
methods.
By default Trace.Listeners collection each item contains Default TraceListener. What are the main features of it?
- When connected to a debugger, such as Visual Studio, messages are written to the debug output window; otherwise, messages content is ignored;
- When the Fail method is called (or an assertion fails), the application is terminated;
Lets assume I want to add logging to my program in 3 ways:
1. Log to a file;
2. Log to a console;
3. Log to Windows event log;
How can I achieve that with Trace class?
We should add 3 listeners:
~~~
// Clear the default listener:
Trace.Listeners.Clear();
// Add a writer that appends to the trace.txt file:
Trace.Listeners.Add(new TextWriterTraceListener(“trace.txt”));
// Obtain the console’s output stream, then add that as listener:
System.IO.TextWriter tw = Console.Out;
Trace.Listener.Add(new TextWriterTraceListener(tw));
// Set up a Window Event log source and then create/add listener.
//CreateEventSource requires administrative elevation, so this would typically be done in application setup:
if(!EventLog.SourceExists(“DemoApp”))
EventLog.CreateEventSource(“DemoApp”, “Application”);
Trace.Listeners.Add(new EventLogTraceListener (“DemoApp”))
~~~
When logging we usually have 3 kinds of messages: Information, Errors and Warning. How can I get them written in Trace class?
First we need to create a TraceListener:var tl = new TextWriterTraceListener(Console.Out);
Then we call 3 different methods for each type:Trace.Write()
or Trace.Fail()
or Trace.Assert()
- InformationTrace.TraceError
- ErrorTrace.TraceWarning
- Warning
In some cases when using TraceListeners, the messages dont get logged to the file, why? What can we do to prevent that?
Some listeners, such as TextWriterTraceListener, ultimatelly writes to a stream which is a subject to caching, so therefore:
* The message might not appear in the output stream immediately;
* If not flushed before closing the app, we can loose what’s been cached (and not logged yet);
As general rule, call Close (it calls Flush, close file handlers and so on) before an application ends, and call Flush anytime you want to ensure that current message data is written.
How to get all running processes, how to select one and then - stop it?
To get all running processes:var processes = Process.GetProcesses()
Select one:var selectedP = processes.WorkingSet64
Stop selected one:selectedP.Kill()
What are the StrackTrace and StackFrame classes?
The StackTrace and StackFrame classes provide a read-only view of an execution call stack. You can obtain stack traces for the current thread (that is ProcessTread and not System.Threading.Tread objects) or an Exception object. Such information is useful mostly for diagnostic purposes.
StackTrace represents a complete call stack;
StackFrame represents a single method call within that stack.
What if for diagnostic purposes I wanted to get more info than Exception’s StackTrace property can suggest, what is my other option?
To create a StackTrace object an pass the exeption to the constructor. In that way we will get detailed view of where exactly the exception was thrown when the app is deployed and no debugging .pdb files are available for such info.
What is Windows Event Logs?
A centralized logging mechanism provided by the Win32 platform.
We can use the same Debug and Trace classes to write to a Window event log if we first register an EventLogTraceListener.
But with the EventLog class we can write directly to a Windows event log without using Trace or Debug.
There are 3 standard Windows event logs:
1. Application (most applications normally writes to)
2. System
3. Security
How can I write to and read from the Event Log?
To write to event log we need:
1. To choose to which of 3 event logs we want to write to;
2. If not created yet, create a source
3. Call EventLog.WriteEntry, passing a) log name, b) source name and c) message data
EventLog.CreateEventSource(“SourceName”, “Application”);
EventLog.WriteEntry(“SourceName”, “Services started”, EventLogEntryType.Information);
READING:
EventLog log = new EventLog(“Application”);
Console.WriteLine(log.Entries[0].Message);
what are the Performance Counters?
Its a performance-monitoring infrastructure, which consists of a set of performace counters that the system and application expose.
They are grouped into the categories like “System”, “Processor” and so on. One group of performance counters monitor one aspect of the system or application.
What does the Stopwatch class do?
The Stopwatch class provides a convenient mechanism for measuring execution times. Stopwatch, compared to DateTime.Now and Environment, uses the highest-resolution mechanism that the OS and hardware provide, which is typically less than a microsecond (compared to 15ms)
Stopwatch.StartNew();