Thursday, January 12, 2012

Performance Counters in .Net


Introduction

Performance counters allow us to monitor physical devices such as Processor, Memory, CLR, Network, Threads etc. Windows provides performance monitor utility to view performance counters. To open that utility need to go to Start -> Run and type “perfmon” and press enter. Below is the screenshot of Performance Monitor utility.



This application monitors various system components, as per above image it displays the processor time utilization. There are multiple performance counters available to monitor different devices. Those performance counters are grouped under categories. Below screenshot displays Add Counter window of performance monitor utility.



Above image displays various categories like Processor, Process, Print Queue, Power Meter etc. Each category has its own counters, as per above image Processor category has “% C1 Time”, “% C2 Time” and so on. Category may have instances and if it has then it will be displayed in instance list. Instance list of selected category is available below the category list. 

Enumerating available categories

Dotnet provides PerformanceCounterCategory class to get all the categories of performance counters. This class is available in System.Diagnostics namespace. GetCategories methods returns collection of PerformanceCounterCategory. Let’s have a look on below code.

//Get all performance categories
PerformanceCounterCategory[] perfCats = PerformanceCounterCategory.GetCategories();
foreach (PerformanceCounterCategory category in perfCats.OrderBy(c => c.CategoryName))
{
    Console.WriteLine("Category Name: {0}", category.CategoryName);
}

Output –

Category Name: .NET CLR Data
Category Name: .NET CLR Exceptions
Category Name: .NET CLR Interop
Category Name: .NET CLR Jit
…
Category Name: Active Server Pages
Category Name: APP_POOL_WAS
Category Name: ASP.NET
…
Category Name: Per Processor Network Interface Card Activity
Category Name: PhysicalDisk
Category Name: Print Queue
Category Name: Process
Category Name: Processor
…
…
…

The above code displays all available performance counter categories order by category name.

Performance Counters by Category

Below example demonstrates how we can get all the performance counters for given category. We can also get all the counters for all the categories if you don’t specify category name in below code but it will take a while to execute. So in below code I have retrieved performance counters only for "Memory" category.

//Get all performance categories
PerformanceCounterCategory[] perfCats = PerformanceCounterCategory.GetCategories();

//Get single category by category name.
PerformanceCounterCategory cat = perfCats.Where(c => c.CategoryName == "Memory").FirstOrDefault();
Console.WriteLine("Category Name: {0}", cat.CategoryName);

//Get all instances available for category
string[] instances = cat.GetInstanceNames();
if (instances.Length == 0)
{
    //This block will execute when category has no instance.
    //loop all the counters available withing category
    foreach (PerformanceCounter counter in cat.GetCounters())
        Console.WriteLine("     Counter Name: {0}", counter.CounterName);
}
else
{
    //This block will execute when category has one or more instances.
    foreach (string instance in instances)
    {
        Console.WriteLine("  Instance Name: {0}", instance);
        if (cat.InstanceExists(instance))
            //loop all the counters available withing category
            foreach (PerformanceCounter counter in cat.GetCounters(instance))
                Console.WriteLine("     Counter Name: {0}", counter.CounterName);
    }
}

Output –

Category Name: Memory
     Counter Name: Page Faults/sec
     Counter Name: Available Bytes
     Counter Name: Committed Bytes
     Counter Name: Commit Limit
     Counter Name: Write Copies/sec
     Counter Name: Transition Faults/sec
     Counter Name: Cache Faults/sec
     Counter Name: Demand Zero Faults/sec
     Counter Name: Pages/sec
     Counter Name: Pages Input/sec
     Counter Name: Page Reads/sec
     Counter Name: Pages Output/sec
     Counter Name: Pool Paged Bytes
     Counter Name: Pool Nonpaged Bytes
     Counter Name: Page Writes/sec
     Counter Name: Pool Paged Allocs
     Counter Name: Pool Nonpaged Allocs
     Counter Name: Free System Page Table Entries
     Counter Name: Cache Bytes
… … …

The above code returns name of the counters available in 'Memory' category. Memory category doesn’t contain any instances so it will list all the performance counters without displaying instance name. We can also execute same code for category which has instances. So let’s execute the same code with “Processor” category.

PerformanceCounterCategory cat = perfCats.Where(c => c.CategoryName == "Processor").FirstOrDefault();

Output –

Category Name: Processor
  Instance Name: _Total
     Counter Name: % Processor Time
     Counter Name: % User Time
     Counter Name: % Privileged Time
     Counter Name: Interrupts/sec
     Counter Name: % DPC Time
     Counter Name: % Interrupt Time
     Counter Name: DPCs Queued/sec
     Counter Name: DPC Rate
     Counter Name: % Idle Time
     Counter Name: % C1 Time
     Counter Name: % C2 Time
     Counter Name: % C3 Time
     Counter Name: C1 Transitions/sec
     Counter Name: C2 Transitions/sec
     Counter Name: C3 Transitions/sec
  Instance Name: 0
     Counter Name: % Processor Time
     Counter Name: % User Time
     Counter Name: % Privileged Time
     … … …
  Instance Name: 1
     Counter Name: % Processor Time
     Counter Name: % User Time
     Counter Name: % Privileged Time
     … … …

As per change in category of above code, now output displays all the performance counters available in 'Processor' category. Processor category has three instances so it will list all the performance counters with instance name.

Reading Performance Counter Value

PerformanceCounter class used to retrieve value of performance counter. This class is also available in System.Diagnostics namespace. We need to pass CategoryName, CounterName and InstanceName (Optional) to PerformanceCounter class constructor or we need to set those properties to performance counter instance explicitly. Performance counter instance has NextValue method which can be used to retrieve the value of give performance counter. 

Let’s have a look on below code.

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,1);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();

void timer_Tick(object sender, EventArgs e)
{
    using (PerformanceCounter perfCounter = new PerformanceCounter("Memory",
             "Available MBytes"))
    {
        float value = perfCounter.NextValue();
        Console.WriteLine("Total Memory Available: {0} MB.", value);
    }
}

Output –

Total Memory Available: 236 MB.
Total Memory Available: 239 MB.
Total Memory Available: 236 MB.
Total Memory Available: 231 MB.
Total Memory Available: 218 MB.
Total Memory Available: 221 MB.
Total Memory Available: 237 MB.
Total Memory Available: 237 MB.



Adding custom categories and counters

The new counters and categories can be added and measured through C# code. Dotnet provides PerformanceCounterCategory class to create new category and CounterCreationData class to create new performance counter.  You can create multiple counters under single category. The create method of PerformanceCounterCategory accepts collection of CounterCreationData. Let’s have a look on below code.

string category = "MyCategory";
string counter1 = "Counter1";
//Check whether category is exist or not
if (!PerformanceCounterCategory.Exists(category))
{
    //creates collection of CounterCreationData
    CounterCreationDataCollection counterDataCollection =
           new CounterCreationDataCollection();

    //added new CounterCreationData to counterDataCollection
    counterDataCollection.Add(new CounterCreationData(counter1,
          "My custom counter", PerformanceCounterType.NumberOfItems32));

    //Creates new category based on information and creates
      counters available in counter data collection
    PerformanceCounterCategory.Create(category, "My Category", PerformanceCounterCategoryType.SingleInstance, counterDataCollection);
}

Output –

As per above image from performance monitor tool, MyCategory is created and Counter1 is added to it. You can delete category by calling PerformanceCounterCategory.Delete method. To create and delete performance counters and categories you need administrative privileges. 



See Also –

Friday, January 6, 2012

How to create Stop Watch application in WPF?



Dotnet provides StopWatch class to measure elapsed execution time. Stopwatch is available in System.Diagnostics namespace. Stopwatch provides Start and Stop method to start/stop stopwatch. IsRunning property returns true or false based on stopwatch instance is running or not. It also provides Elapsed and ElapsedMilliseconds to get execution time. We can clear elapsed time by calling Reset method on stopwatch instance.

Let’s have a look on below code.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="0.3*"/>
        <RowDefinition Height="0.2*"/>
        <RowDefinition Height="0.5*"/>
    </Grid.RowDefinitions>
    <TextBlock Name="ClockTextBlock"
                TextAlignment="Center"
                VerticalAlignment="Center"
                FontSize="35" Foreground="Red"
                Grid.ColumnSpan="4"
                Grid.Row="0" />
    <Button Content="Start"
            Name="StartButton"
            Grid.Row="1"
            Grid.Column="0"
            Width="60" Height="35"
            Click="StartButton_Click" />
    <Button Content="Add"
            Name="AddButton"
            Grid.Row="1"
            Grid.Column="1"
            Width="60" Height="35"
            Click="AddButton_Click" />
    <Button Content="Stop"
            Name="StopButton"
            Grid.Row="1"
            Grid.Column="2"
            Width="60" Height="35"
            Click="StopButton_Click" />
    <Button Content="Reset"
            Name="ResetButton"
            Grid.Row="1"
            Grid.Column="3"
            Width="60" Height="35"
            Click="ResetButton_Click" />
    <ListBox Name="TimeElapsedItems"
                Margin="5" Width="150"
                Grid.Row="2"
                Grid.ColumnSpan="4" />
</Grid>

public partial class StopWatchDemo : Window
{
    DispatcherTimer dt = new DispatcherTimer();
    Stopwatch stopWatch = new Stopwatch();
    string currentTime = string.Empty;
    public StopWatchDemo()
    {
        InitializeComponent();
        dt.Tick += new EventHandler(dt_Tick);
        dt.Interval = new TimeSpan(0, 0, 0, 0, 1);
    }

    void dt_Tick(object sender, EventArgs e)
    {
        if (stopWatch.IsRunning)
        {
            TimeSpan ts = stopWatch.Elapsed;
            currentTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            ClockTextBlock.Text = currentTime;
        }
    }
    private void StartButton_Click(object sender, RoutedEventArgs e)
    {
        stopWatch.Start();
        dt.Start();
    }

    private void StopButton_Click(object sender, RoutedEventArgs e)
    {
        if (stopWatch.IsRunning)
            stopWatch.Stop();
    }

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {
        TimeElapsedItems.Items.Add(currentTime);
    }

    private void ResetButton_Click(object sender, RoutedEventArgs e)
    {
        stopWatch.Reset();
        stopWatch.Start();
    }
}



As per above code, four button are added, Start, Stop, Reset and Add. Start will start the stopwatch and stop will stop the stopwatch. Reset will reset elapsed time to zero and Add button will add elapsed time of stopwatch to Listbox.

How to get execution time of code?

Stopwatch class used to examine execution time of code. We can efficiently find execution time of particular method or block of code. This is incredibly useful while performing diagnostics or performance analysis.

void MyMethod(object sender, RoutedEventArgs e)
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    for (int i = 0; i < 10000000; i++)
        Console.Write("");

    stopWatch.Stop();
           
    TimeSpan ts = stopWatch.Elapsed;
    Console.WriteLine(String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));
}

Output
00:00:01.15

Above code examine total time to execute for loop. Just before starting for loop stopwatch is started and after completing for loop immediately stops stopwatch. It will find total time to execute this for loop.

See Also - 

Monday, January 2, 2012

How to Read/Write Windows Event Logs?


Windows provides central logging mechanism to write/read logs. Windows provides three most popular event logs,

  • Application
  • System
  • Security
Application related events are logged under application log similarly System and Security related events logged under system and security logs respectively. 
Below image displays Windows logs.


Event Log


EventLog class provides interaction with windows event logs. Using EventLog we can read from existing log and write entries to log. We can also create new custom event source other than system defined event source.


void EventLogDemo_Loaded(object sender, RoutedEventArgs e)
{
    EventLog.WriteEntry("Application", "Your application loaded successfully...");
}

The above line of code makes log entry in Application Log defined in Windows Logs with custom message.




We can also create our own custom log and write event logs on newly defined log.


void EventLogDemo_Loaded(object sender, RoutedEventArgs e)
{
    if (!EventLog.SourceExists("TempLog"))
    {
        EventLog.CreateEventSource("TempLog", "Application");
        Console.WriteLine("Event log created sucessfully");
    }
    EventLog.WriteEntry("TempLog", "Your application loaded successfully...");
}

As per above image, Application log displays one log created in Application log and displays custom message. EventLog.CreateEventSource method creates event source. This method requires Administrative rights to execute.  Once event source is created we can add new event log on it.

Reading Event Log


We can read event log list using EventLog class. EventLog class provides GetEventLogs method which returns collection of EventLogEntry. This method retrieves all entries from given log. See below code,


void EventLogDemo_Loaded(object sender, RoutedEventArgs e)
{
    EventLog appLog = new EventLog("Application");

    foreach (EventLogEntry entry in appLog.Entries)
        Console.WriteLine("Index: {0}, Source: {1}, EntryType: {2}, Time: {3}, Message: {4}",
            entry.Index, entry.Source, entry.EntryType, entry.TimeWritten, entry.Message);
}


Above code retrieves all log information from Application log. Similarly we can read all the items from System, Security and other custom logs. The above code will take some time to execute because it will retrieve all the items available in Application log. Below code retrieve single log item from Application event log.


EventLog appLog = new EventLog("Application");
EventLogEntry lastEntry = appLog.Entries[appLog.Entries.Count - 1];
Console.WriteLine("Index: {0}, Source: {1}, EntryType: {2}, Time: {3}, Message: {4}",
        lastEntry.Index, lastEntry.Source, lastEntry.EntryType, lastEntry.TimeWritten, lastEntry.Message);



How to get call stack programmatically?



StackTrace class is useful to get an execution call stack of running program.  StackTrace class provides information which is useful while debugging application. StackFrame class contains useful information like filename, line number and column number. StackFrame is created while execution of program on every method calls. StackFrame information will be the most useful while debugging application. StackTrace and StackFrame class are available inside System.Diagnostics namespace. 


Let’s have a look on below code.


public class StackTraceTest
{
    public StackTraceTest()
    {
    }

    public void method1()
    {
        method2();
    }
    public void method2()
    {
        method3();
    }
    public void method3()
    {
        try
        {
            throw new Exception("An error occured");
        }
        catch (Exception ex)
        {
            StackTrace st = new StackTrace(true);
            Console.WriteLine("Call Stack :");

            foreach (StackFrame sf in st.GetFrames())
                Console.WriteLine("File: {0}, Method: {1}, 
                    Line: {2}, Column: {3}, Offset: {4}", 
                    sf.GetFileName(),
                    sf.GetMethod().Name,
                    sf.GetFileLineNumber(),
                    sf.GetFileColumnNumber(),
                    sf.GetILOffset()
                    );
        }
    }
}

public static void main()
{
    StackTraceTest stest = new StackTraceTest();
    stest.method1();
}

Output

File: StackTraceDemo.xaml.cs, Method: method3, Line: 52, Column: 13, Offset: 21
File: StackTraceDemo.xaml.cs, Method: method2, Line: 42, Column: 9, Offset: 7
File: StackTraceDemo.xaml.cs, Method: method1, Line: 38, Column: 9, Offset: 7

As per above output, StackTrace and StackFrame class are providing useful information while debugging. GetFrames method returns collection of StackFrame classes. Each stackframe instance provides information like method name, file name, line number, column number, offset etc.


Below is the snapshot of CallStack window from Visual Studio



See Also – 

How to get list of running processes in C#?



Process class provides GetProcess method to get all running processes. The GetProcesses method returns collection of process. Similarly GetCurrentProcess method returns currently running process. Process class is available in System.Diagnostics namespace. 


Let’s have a look on below code.

void ProcessThreads_Loaded(object sender, RoutedEventArgs e)
{
    foreach (Process p in Process.GetProcesses())
        Console.WriteLine("{0} | {1} | {2}", p.ProcessName, p.Id, p.Threads.Count);


    Console.WriteLine("Current Process");

    Process current = Process.GetCurrentProcess();
    Console.WriteLine("{0} | {1} | {2}", current.ProcessName, 
                       current.Id, current.Threads.Count);
}

Output


svchost | 616 | 13
SearchIndexer | 3344 | 14
lsm | 584 | 12
spoolsv | 1764 | 13
COH32 | 5112 | 3
WPFTestApplication.vshost | 2660 | 14
lsass | 576 | 9
RegSrvc | 2348 | 4
COH32 | 4908 | 1
SNAC | 1360 | 13
services | 568 | 6
explorer | 5884 | 26
svchost | 956 | 19
iexplore | 756 | 16
ccSvcHst | 1540 | 36
svchost | 3704 | 5
rundll32 | 3868 | 2
…
…
…

Current Process
WPFTestApplication.vshost | 2660 | 14

The above output displays all the processes with its name, id and total thread count. The last line displays currently running process.

Displaying Process Threads


We can get list of all the threads running under process using Threads collection of Process instance. Let’s have a look on below code.

void ProcessThreads_Loaded(object sender, RoutedEventArgs e)
{
    foreach (Process p in Process.GetProcesses())
    {
        Console.WriteLine("{0} | {1} | {2}", p.ProcessName, p.Id, p.Threads.Count);
        DisplayThreads(p);
    }
}

private void DisplayThreads(Process p)
{
    foreach (ProcessThread thread in p.Threads)
    {
        Console.WriteLine("          {0} | {1} | {2} | {3}", thread.Id,
            thread.PriorityLevel, thread.ThreadState, thread.TotalProcessorTime);
    }
}

Output

wininit | 468 | 3
          472 | Highest | Wait | 00:00:00.4992032
          556 | Normal | Wait | 00:00:00
          564 | Normal | Wait | 00:00:00
LMS | 1252 | 8
          1304 | Normal | Wait | 00:00:00.0468003
          1336 | Normal | Wait | 00:00:00
          1924 | Normal | Wait | 00:00:00.2496016
          2072 | Normal | Wait | 00:00:00.0624004
          2180 | Normal | Wait | 00:00:08.6424554
          1692 | Normal | Wait | 00:00:00
          5552 | Normal | Wait | 00:00:00
          3700 | Normal | Wait | 00:00:00
…
…
…


Above code displays list of processes along with their ProcessThreads.


See Also – 
How to create custom Application Domain?
How to get system hardware information?
How to pass data as an argument to Thread?