Tuesday, May 31, 2016

Singleton Pattern


Singleton pattern ensures a class can have only single instance during the lifetime of an application.

When to use Singleton Pattern?

When you want to create single object only once during application life you can go with Singleton Pattern. The implementation and use of singleton pattern is very easy. See below example.

Code –
public class Singleton
{
    //private static member.
    private static Singleton instance;
   
    //Private constructor prevents instance creation of class from outside.
    private Singleton() { }
   
    //This static method responsible for creation of instance of this class.
    public static Singleton GetInstance()
    {
        //create new instance only in first call, rest of the time it will return existing object
        if (instance == null)
            instance = new Singleton();

       return instance;
    }

    public void Display()
    {
        Console.WriteLine("Display Method called from Singleton Class...");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Singleton singleObject =  Singleton.GetInstance();
        singleObject.Display();
        Console.Read();
    }
}

Output –



Another way (via Property) to implement singleton pattern.


public class Singleton
{
    //private static member.
    private static Singleton instance;

    //Private constructor prevents instance creation of class from outside.
    private Singleton() { }

    //This static method responsible for creation of instance of this class.
    public static Singleton Instance
    {
        get
        {
            //create new instance only in first call, rest of the time it will return existing object
            if (instance == null)
                instance = new Singleton();

            return instance;
        }
    }

    public void Display()
    {
        Console.WriteLine("Display Method called from Singleton Class...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Singleton singleObject = Singleton.Instance;
        singleObject.Display();
        Console.Read();
    }
}

Output –

Same as above example.

Advantages - 

  • Class can perform additional functionalities other than creation of an object.
  • This is referred as Lazy Initialization approach since instance of an object is not created until user call instance property or method. This approach avoids instantiating singletons class when application starts.

Disadvantage -

  • Singleton pattern is not thread safe by default. You need to write additional code to make it thread safe. I'll post article for Thread safe singleton pattern in few days.

Hope you liked this article. Please leave your feedback.

References –


See Also –

Monday, October 15, 2012

Visual Studio not automatically building application on pressing F5 key


Recently I was facing one issue with Visual Studio 2010. When I change some code in Visual Studio 2010 and hit F5, it is not building application and running old compiled version. Every time I want to debug an application, I have to first manually build application and then hit F5  key to debug my application. Usually visual studio automatically builds application on hitting F5 key.

I found interesting solutions from internet to resolve this issue. You need to open the Configuration Manager from Debug Dropdown or right click on Solution and open Configuration Manager Window. Now click on Build Checkbox.


Another solution would be useful if your Project is out of date or you have installed newer version. Go to Tool -> Option -> Project and Solutions -> Build and Run from Visual Studio. Now select “Always build” or “Prompt to build” option of “On Run, when project are out of date”.


Hope this small Tip might help you to fix this issue.

See Also –

Sunday, October 14, 2012

How to get list of System Colors in WPF


You might aware about available System Colors in Windows machine. You might have changed system colors using below window. If you change color and appearance of any item (e.g. color, font, size, font color etc.) it will change appearance and color of all the application available in windows. In short you can change system’s default appearance and color using below dialog.


In this post I will demonstrate how you can get available list of system colors dynamically using WPF application. Let’s have a look on below example.

XAML
<Window x:Class="WpfApplication1.SysColors"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="System Colors" Height="300" Width="300">
<Grid>
<DataGrid Name="grdSysColorList"
          AutoGenerateColumns="False"
          GridLinesVisibility="Vertical">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Color"
                                Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Margin="5">
                        <TextBlock.Background>
                            <SolidColorBrush Color="{Binding Color}" />
                        </TextBlock.Background>
                    </TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Name"
                            Binding="{Binding Name}"
                            Width="200"/>
    </DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

Code
public partial class SysColors : Window
{
public SysColors()
{
    InitializeComponent();
    LoadSystemColors();
}
public void LoadSystemColors()
{
    List<SysColorItem> sysColorList = new List<SysColorItem>();
    Type t = typeof(System.Windows.SystemColors);
    PropertyInfo[] propInfo = t.GetProperties();
    foreach (PropertyInfo p in propInfo)
    {
        if (p.PropertyType == typeof(Color))
        {
            SysColorItem list = new SysColorItem();
            list.Color = (Color)p.GetValue(new Color(),
                BindingFlags.GetProperty, null, null, null);
            list.Name = p.Name;

            sysColorList.Add(list);
        }
        else if (p.PropertyType == typeof(SolidColorBrush))
        {
            SysColorItem list = new SysColorItem();
            list.Color = ((SolidColorBrush)p.GetValue(new SolidColorBrush(),
                BindingFlags.GetProperty, null, null, null)).Color;
            list.Name = p.Name;

            sysColorList.Add(list);
        }
    }
    grdSysColorList.ItemsSource = sysColorList;
}
}

public class SysColorItem
{
public string Name { get; set; }
public Color Color { get; set; }
}
}

Output


In above example you can see DataGrid having two columns Color and Name. Color displays various system colors and name displays its name. I have retrieved this system colors using Reflection. First I have retrieved type of SystemColors and then retrieved all the properties having Color and SolidColorBrush type. In last i have bind that list of SystemColors to DataGrid.


How to apply system colors to WPF controls

In above example we saw how we can retrieve list of system colors dynamically. Now let’s see how you can apply system colors to WPF control.

<Button Background="{x:Static SystemColors.MenuHighlightBrush}"
        Content="Click Me!!!"
        Height="40" Width="150"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">



Above code demonstrates how you can apply MenuHighlightBrush to Button’s background. Similarly you can apply other system colors as well. SystemColors has all the colors defined as Static property so we have used {x:Static} markup to retrieve system color.

As per above example, if your application running and MenuHighlightBrush color is changed in background then your application will not display newly changed color. If you want to do so you can use DynamicResource markup. DynamicResource will update resources dynamically whenever it changed while your application is running. Let’s have a look on below code snippet which used DynamicResource.

<Button Background="{DynamicResource {x:Static SystemColors.MenuHighlightBrushKey}}"
        Content="Click Me!!!"
        Height="40" Width="150"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">
</Button>

In above code I have used DynamicResource markup to display resources dynamically. If MenuHighlightBrushKey changed in background then your application will display newly changed value.

Here one thing to noticed that I have used resource key in second example while in first example I have used brush. The reason behind that is DynamicResource markup uses resource key.

Hope you liked this post. You can checkout below link to know more about System Colors in WPF.
http://blogs.msdn.com/b/wpf/archive/2010/11/30/systemcolors-reference.aspx

See also –

Sunday, September 16, 2012

Logical Operators (Bitwise and Boolean) in C#


C# provides many operators which are widely used in various applications depending upon their use. This operators are very basic and everyone knows about it but few thing i wanted to highlight in this post which might not known to many developers. So In this post i will explain few important things about Logical and Bitwise AND/OR/XOR operators with example.

Logical AND (&&) Operator

Logical AND performs Boolean operation with two expression and returns true if both expressions are true and returns false if any one expression is false. If first expression is false then it will not check another expression and returns false. Let’s have a look on below code snippet.

int x = 3;
int y = 0;

if ((y > x) && (x / y > 0))
    Console.WriteLine("Logical AND Operation");


The above code will run and compile successfully. In above code second expression seems to throw Dividebyzero exception but first expression returns false so it will not evaluate second expression and assume that first expression is false so entire expression is false.


Logical OR (||) Operator

If we perform logical OR in above example, if first expression is true then it will not evaluate second expression. In logical OR any one expression must be true if first expression is true then others will be skipped.

Note - The disadvantage of logical operators are if second expression doesn’t evaluate then there might be possibility for bug in application. These types of bugs are difficult to find. Sometimes logical operators are called as short circuit operators as well.

Bitwise AND (&) operator

Bitwise operator can operate on integral and Boolean expression. They can operate with two operands and both operands must be evaluated. If first expression returns false even though it will evaluates second expression. Let's have a look on below code.

int x = 3;
int y = 0;

if ((y > x) & (x / y > 0))
    Console.WriteLine("Bitwise AND Operation");

The above code will throw an exception because bitwise (&) AND evaluates both expressions and as per above code second expression throws dividebyzero exception. This above example shows bitwise Boolean condition. There are four possible values for Boolean bitwise AND (&) operations.

Bitwise AND (&)
Expression 1
Expression 2
Result
True
True
True
True
False
False
False
True
False
False
False
False

Similarly we can perform bitwise AND on integral numbers as well. This bitwise AND on integral numbers will first convert numbers into binary and then perform AND operations on it. Let’s have a look on below code.

int x = 5;  // Binary Equivalent  - 0101
int y = 7;  // Binary Equivalent  - 0111

//   0101
// & 0111
//  -----
//   0101

int result = x & y; //output  = 5

The above code demonstrates bitwise AND (&) operation between variable x and y. The binary equivalent of x is 0101 and y is 0111. Now bitwise AND (&) operation will perform AND between binary values of x and y as displayed in commented code above. The result will return 5 in decimal number.

Bitwise OR (|) operator

Similarly we can perform Bitwise OR between two operands like bitwise AND. Bitwise OR performs OR operation on binary equivalent numbers. Let’s have look on below code which is modified version of above code.

int x = 5;  // Binary Equivalent  - 0101
int y = 7;  // Binary Equivalent  - 0111

//   0101
// | 0111
//  -----
//   0111

int result = x | y; //output  = 7

In above code Bitwise OR will be applied to the binary equivalent numbers of x and y values. Below is the table which explains bitwise OR results between two expressions.

Bitwise OR (|)
Expression 1
Expression 2
Result
True
True
True
True
False
True
False
True
True
False
False
False

Bitwise Exclusive OR (^) operator

Bitwise Exclusive OR can be applied to two operands and behave similar to Bitwise AND/OR. This performs XOR operation between binary equivalent numbers. Below table explains bitwise XOR results between two expressions.

Bitwise XOR
Expression 1
Expression 2
Result
True
True
False
True
False
True
False
True
True
False
False
False


Usage of Bitwise Operators

Bitwise operators are used in multiple places and also called as fundamental operators on computers. Below are few areas where bitwise operators majorly used.
  • Low level programming
  • Hardware device drivers creation
  • Creating protocols
  • Communicating with ports and sockets
  • Graphics driver
  • Gaming
  • Communicating with physical devices
  • Encryption
  • Data Compression

Hope this post helps you to understand basic concept of Logical and Bitwise Operators in Dotnet. Please leave your feedback in comments section below.

Monday, July 9, 2012

File System Watcher class in .Net (C#)


Sometime you might need to monitor changes like files added, deleted, renamed for particular folder. To do so, .net provides FileSystemWatcher class to monitor such kind of activity for particular folder or file.

FileSystemWatcher class provides some events which are fired when some action done to the folder like file created, deleted, renamed etc. You can also specify filter to file system watcher if you want to watch only text file or music files etc. It also provides an option to include subdirectories to watch or monitor.

Let’s have a look on below code snippet

void FileSystemWatcherDemo_Loaded(object sender, RoutedEventArgs e)
{
    //creates an instance of FileSystemWatcher
    FileSystemWatcher watcher = new FileSystemWatcher();
    //set folder or file path to watch
    watcher.Path = @"D:\Temp\Test";
    //watches txt files only
    watcher.Filter = "*.txt";
    //enable watching subdirectories also
    watcher.IncludeSubdirectories = true;

    watcher.Created += new FileSystemEventHandler(watcher_Created);
    watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
    watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
    watcher.Changed += new FileSystemEventHandler(watcher_Changed);
           
    //starts watching/monitoring folder or file
    watcher.EnableRaisingEvents = true;
}

void watcher_Changed(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File changed - {0}, change type - {1}", e.Name, e.ChangeType);
}

void watcher_Renamed(object sender, RenamedEventArgs e)
{
    Console.WriteLine("File renamed - old name - {0}, new name - {1}", e.OldName, e.Name);
}

void watcher_Deleted(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File deleted - {0}", e.Name);
}

void watcher_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File created - {0}, path - {1}", e.Name, e.FullPath);
}

Output –
File created - Text2.txt, path - D:\Temp\Test\Text2.txt
File created - Text1.txt, path - D:\Temp\Test\Text1.txt
File renamed - old name - Text2.txt, new name - Text3.txt
File deleted - Text3.txt

As per above code, I have chosen Test folder to monitor file system changes. After running this application, if I add, delete, rename any text file to this folder, it will notify FileSystemEvent to raise respective event and the code written in respective event handler will execute.

See Also -