Monday, January 23, 2012

FileStream in .Net (C#)


FileStream class can be used to read / write data to files. FileStream class is derived from abstract Stream class. FileStream supports synchronous or asynchronous read/write operations. By default FileStream opens file synchronously. FileStream also supports random access using seek method. You can open file by passing string file name (path) to FileStream constructor. You can also specify FileMode and FileAccess along with filename. FileMode specifies how file should open while FileAccess specifies file should open for Read or Write or Both operations


Below is the details about FileMode and FileAccess enum.

FileModes
Description
Open
Opens an existing file for writing.
OpenOrCreate
Opens an existing file if not found creates new.
Create
Creates new file, if exists it will be overwrite.
CreateNew
Creates new file, if already exists throws an error.
Append
Opens an existing file and seek to end. If not exists creates new file.

FileAccess
Description
Read
Allows only read from file.
Write
Allows only write to file.
ReadWrite
Allows read/write to file.

Below examples shows how we can use FileModes and FileAccesss with FileStream.

//Opens an existing file for read operations
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Open, FileAccess.Read);

//Opens an existing file for write operations
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Open, FileAccess.Write);

//Opens an existing file for read/write operations
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Open, FileAccess.ReadWrite);

//creates new file, if exists it will be overwritten
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Create);

//Opens an existing file and seek to end. if not exists creates new file.
FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Append);

Read/Write data using FileStream Read/Write methods.

//Write data
using (FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Create, FileAccess.Write))
{
    string start = "Hello World!!!";

    byte[] byts = System.Text.Encoding.ASCII.GetBytes(start);

    fs.Write(byts, 0, byts.Length);
}

//Read data
using (FileStream fs = new FileStream(@"d:\temp\test.txt", FileMode.Open, FileAccess.Read))
{
    byte[] byts = new byte[1024];
    while (fs.Read(byts, 0, byts.Length) > 0)
    {
        Console.WriteLine(System.Text.Encoding.ASCII.GetString(byts));
    }
}

Output –



See Also - 

Friday, January 20, 2012

BinaryReader and BinaryWriter in .Net (C#)


BinaryReader and BinaryWriter classes are available in System.IO namespace. BinaryReader and BinaryWriter classes are used to write primitive data types to file (primitive data types like int, decimal, float, double, long, short etc.). It also allows us to write strings and array of primitive data types along with primitive data types. The data stored inside file is not human readable because it’s stored in binary format. To store data in normal text you can use StreadReader and StreamWirter class instead. Please go through StreamReader and StreamWriter article for more information.


Read/Write text to file using BinaryReader and BinaryWriter

//writes data to test.bin file using binarywriter
using (BinaryWriter bw = new BinaryWriter(new FileStream(@"d:\Temp\test.bin", FileMode.Create)))
{
    for (int i = 0; i < 5; i++)
    {
        bw.Write(i);
    }
}

//reads data from test.bin file using binaryreader
using (BinaryReader br = new BinaryReader(new FileStream(@"d:\Temp\test.bin", FileMode.Open)))
{
    for (int i = 0; i < 5; i++)
    {
        br.ReadInt32();
    }
}

Output –

StreamReader and StreamWriter in .Net (C#)



StreamReader and StreamWriter classes are available in System.IO namespace. StreamWriter class used to write text (string) in file. StreamWriter class inherits from abstract TextWriter class. StreamReader class used to read text (string) from file. StreamReader class inherits from abstract TextReader class. 


Below are some useful methods of StreamReader and StreamWriter class.

Methods
Description
StreamWriter.Write
Writes text to file.
StreamWriter.WriteLine
Writes text to file, followed by line terminator.
StreamReader.Read
Reads text from file.
StreamReader.ReadLine
Reads line from file.

Read/Write text to file using StreamWriter.WriteLine and StreamReader.ReadLine

string[] names = new string[] { "Mitesh", "Jayesh", "Pritesh", "Kalpesh" };
void ReadWriteText()
{
    //write names to test.txt file
    using (StreamWriter sw = new StreamWriter(@"d:\Temp\Test.txt"))
    {
        foreach (string name in names)
            sw.WriteLine(name);
    }

    //read names from test.txt file
    using (StreamReader sr = new StreamReader(@"d:\Temp\Test.txt"))
    {
        string name = string.Empty;
        while ((name = sr.ReadLine()) != null)
        {
            Console.WriteLine(name);
        }
    }
}

Output –

Read/Write text from file using StreamReader.ReadLine and StreamWriter.Write


void ReadWriteText()
{
//write string/charactors to test.txt file
using (StreamWriter sw = new StreamWriter(@"d:\Temp\Test.txt"))
{
    foreach (char character in "Hello World!")
        sw.Write(character);
}

//read string/charactors from test.txt file
using (StreamReader sr = new StreamReader(@"d:\Temp\Test.txt"))
{
    string name = string.Empty;
    while ((name = sr.ReadLine()) != null)
    {
        Console.WriteLine(name);
    }
}
}

Output –

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 -