Saturday, July 4, 2015

C# in Nutshell Chapter 13 - Diagnostics and Code Contracts

Conditional Attribute

The Conditional attribute instructs the compiler to ignore any calls to a particular class or method, if the specified symbol has not been defined.

 static void Main()

        public static void WriteLine() { Console.WriteLine("HelloWorld"); }

In Visual Stuido project property -> Build -> Optional compiling symbol to set it

The Conditional attribute is ignored at runtime—it’s purely an instruction to the compiler.

Debug and Trace Classes

Code Contracts

public static bool AddIfNotPresent<T> (IList<T> list, T item)
Contract.Requires (list != null); // Precondition
Contract.Requires (!list.IsReadOnly); // Precondition
Contract.Ensures (list.Contains (item)); // Postcondition
if (list.Contains(item)) return false;
list.Add (item);
return true;

The preconditions are defined by Contract.Requires and are verified when the method starts. The postcondition is defined by Contract.Ensures and is verified not where it appears in the code, but when the method exits. Preconditions and postconditions act like assertions and, in this case, detect the following errors:
  • A bug in the method whereby we forgot to add the item to the list
  • A bug in the method whereby we forgot to add the item to the list
Preconditions and postconditions must appear at the start of the method. 

Windows Eventlog

To write to a Windows event log:
1. Choose one of the three event logs (usually Application).
2. Decide on a source name and create it if necessary.
3. Call EventLog.WriteEntry with the log name, source name, and message data.

The source name is an easily identifiable name for your application. You must register a source name before you use it—the CreateEventSource method performs this function. You can then call WriteEntry :
const string SourceName = "MyCompany.WidgetServer";
// CreateEventSource requires administrative permissions, so this would
// typically be done in application setup.
if (!EventLog.SourceExists (SourceName))
EventLog.CreateEventSource (SourceName, "Application");
EventLog.WriteEntry (SourceName, "Service started; using configuration file=...", EventLogEntryType.Information);

The Stopwatch Class

The Elapsed property returns the elapsed interval as a TimeSpan :

Stopwatch s = Stopwatch.StartNew();
System.IO.File.WriteAllText ("test.txt", new string ('*', 30000000));
Console.WriteLine (s.Elapsed); // 00:00:01.4322661

No comments:

Post a Comment