My Development Notes

By Haemoglobin
3/10/2010 (revision 1)

Logging and Systems Management

EventLog

if (!EventLog.SourceExists("My App Source"))
    /*Requires admin permissions (run during setup). 
    * Can use the pre-existing Application log if necessary.*/
    EventLog.CreateEventSource("My App Source", "My App Log");

EventLog myLog = new EventLog("My App Log"); 
myLog.Source = "My App Source"; 
myLog.WriteEntry("Error description", EventLogEntryType.Error[Information|Warning|FailureAudit],[eventID],[category],[byteArray]);

foreach (EventLogEntry entry in myLog.Entries) {
    entry.Message
    entry.Source
    entry.EntryType
}

Debug/Trace

The only difference between Debug and Trace is Debug is only shown in Debug builds.

Debug[Trace].Listeners.Add(New ConsoleTraceListener()); 
Debug[Trace].AutoFlush = true; 
Debug.Indent(); 
Debug.WriteLine("Debug output"); 
Debug.Unindent(); 
Debug.WriteLineIf(bool, string); 
Debug.Assert(bool, string); //Error window popup

<configuration>
   <system.diagnostics>

      <trace autoflush="false" indentsize="3" >
        <listeners>
            <add name="TextTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="output.txt" />
            <remove name="Default"/>
        </listeners> 
      </trace>

      <switches> 
        <add name="DataMessagesSwitch" value="[0|1]"/>
        <add name="TraceLevelSwitch" value="[0(Off)|1(Errors)|2(Warning)|3(Info)|4(Verbose)]"/>
      </switches> 
   </system.diagnostics>
</configuration>

Performance Counters

   
//Reading performance counters
PerformanceCounter pc = new PerformanceCounter([catagoryName],[counterName],[instanceName]);
pc.NextValue(); //First always returns 0. Sleep between calls. 

//Adding custom performance counter
PerformanceCounterCategory.Create("CategoryName", "CategoryHelp", PerformanceCounterCategoryType.MultiInstance[SingleInstance], "CounterName", "CounterHelp"); 

//Multiple counters for category
CounterCreationDataCollection counters = new CounterCreationDataCollection(); 
counters.Add(new CounterCreationData("Counter Name", "Counter Help", PerformanceCounterType.NumnberOfItems64)); 
PerformanceCounterCategory.Create("CategoryName", "CategoryHelp", PerformanceCounterCategoryType.MultiInstance[SingleInstance], counters); 

//Providing data to performance counter 
PerformanceCounter pc = new PerformanceCounter("Category Name", "Counter Name", false (read-only)); 
pc.RawValue = 5; 
pc.Decrement(); //thread safe (but slower)
pc.Increment(); //thread safe (but slower)
pc.IncrementBy(4); //thread safe (but slower)

Managing Computers

Processes

foreach (Process p in Process.GetProcesses()) {
    p.Id, p.ProcessName, p.Refresh(), p.BasePriority
    p.Modules [ProcessModule collection] .ModuleName, .ModuleMemorySize
}

Process.GetProcessById(), Process.GetProcessByName(), Process.GetCurrentProcess()
Process.Start("Notepad.exe", @"c:\textfile.txt"); 

Management Information

Accessed through WMI

ManagementScope scope = new ManagementScope(@"\\localhost\root\cimv2"); 
scope.Connect(); 

ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery("SELECT * FROM [Win32_OperatingSystem|Win32_LogicalDisk]")); 
ManagementObjectCollection queryCollection = searcher.Get(); 
foreach(ManagementObject m in queryCollection) {
    m["WindowsDirectory"], m["Version"], m["Manufacturer"]
    m["Name"], m["Description"]
}

WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\""); 
ManagementEventWatcher watcher = new ManagementEventWatcher(query); 
ManagementBaseObject e = watcher.WaitForNextEvent(); 
e["TargetInstance"]["Name"]; 
watcher.Stop(); 

//Or
watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived); 
watcher.Start();
Console.ReadKey(); 
watcher.Stop(); 

public void OnEventArrived(object sender, EventArrivedEventArgs e) {
    ManagementBaseObject evt = e.NewEvent; 
    evt["TargetInstance"]["Name"];  
}
  • List item

Comments

Powered by BlogEngine.NET 1.6.1.0 | Design by styleshout | Enhanced by GravityCube.net | 1.4.5 Changes by zembian.com | Adapted by HamishGraham.NET
(c) 2010 Hamish Graham. Banner Image (c) Chris Gin