Wednesday, September 9, 2009

Strategy Pattern with C#

Strategy Pattern classified under Behavioural Pattern encapsulates an algorithm inside a class.

Strategy Pattern is a class that has to perform strategically depending on user input, platform information and so on.. Depending on user input, a different algorithm will be used; however, the end result is the same.

To explain this through example, I have used three diferrent search algorighm, each with its own performance and accuracy trade-off. One of them is very computation-intensive, but does a more thorough job, while another is faster but generates results that may be inaccurate for very data. My application will ask the user for the desired performance and then invoke the appropriate algorithm. To this end, I will encapsulate my algorithms in classes that demonstrate Strategy Pattern.

iSearch.cs
This interface will be implemented by various classes with different search algorithm


namespace MyProject.StrategyPattern.Search
{
public interface iSearch
{
string Search(string keyword);
}
}



Search.cs
Having implemented all three algorithms in this manner mentioned below, I can now design the client that decouples it from the implementation details of any specific algorithm. The client holds a reference to the interface, and does not need to know anything about the concrete implementation of the interface.


namespace MyProject.StrategyPattern.Search
{

public class ListSearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + "with List Search Algorithm";
}

#endregion
}


public class TreeSearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + " with Tree Search Algorithm";
}

#endregion
}


public class BinarySearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + " Binary Search Algorithm";
}

#endregion
}

}


SearchKeyword.cs
Finally, I create an instance of the SearchKeyword class and, depending on user input, initialize it with the appropriate algorithm. The Test method of the SearchKeyword class invokes the Search method of the iSearch interface that every algorithm implements

namespace MyProject.StrategyPattern
{
public class SearchKeyword
{
private iSearch _search;

public SearchKeyword(iSearch Search)
{
_search = Search;
}

public string SearchString(string Keyword)
{
return _search.Search(Keyword);
}


}
}



< Back to Design Patterns

Tuesday, September 8, 2009

Singleton Pattern with C#

Singleton Pattern which is classified under Creational Pattern which focuses on having only one instance of object at any given time.

To give an example, windows directory service which has multiple entries but you can only have single instance of it through out the network.

  • A singleton is the sole instance of some class.
  • It is most often the case that the singleton should also be globally accessible, and this is achieved by making the creation method/property public.
  • Note that in the code below, the class constructor is private to avoind creating instance of class.
Creating Class which will return only one instance:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyProject.SingletonSample.Evaluation;

namespace MyProject.SingletonSample
{
public class Singleton
{
// Private Constructor to not allow to creating instance
private Singleton() { }

private static iEvaluation instance;

// Creates and maintains single instance of Evaluation Class
public static iEvaluation Instance
{
get
{
if (instance == null)
{
instance = new Evaluation.Evaluation();
}
return instance;
}
}

}
}


Creating Instance of Singleton class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyProject.SingletonSample.Evaluation;

namespace MyProject.SingletonSample
{
class Program
{
static void Main(string[] args)
{
EvalData ed1=new EvalData();
ed1.Name = "Aaaa";
ed1.Comment = "Added with ED1";
ed1.DateSubmitted = DateTime.Now;

EvalData ed2 = new EvalData();
ed2.Name = "Bbbb";
ed2.Comment = "Added with ED2";
ed2.DateSubmitted = DateTime.Now;

Singleton.Instance.AddEval(ed1);
Singleton.Instance.AddEval(ed2);

Console.ReadKey();
}
}
}

< Back to Design Patterns

Design Patterns

Design Patterns are recurring solution to recurring problems in software architecture. A design pattern can solve many problems by providing a framework for building an application.

Design patterns which make the design process cleaner and more efficient, are especially well-suited for object-oriented languages such as C#. Existing design patterns make good templates for the objects, allowing you to build software faster, re-use the code, and a pattern which is acceptable organisation wide.

Design patterns can improve the extensibility of your applications and the reuse of your objects. Software design and architecture without a rudimentary understanding of design patterns is unthinkable. Most software applications and systems incorporate one or more design patterns which we all might have come across, but don't know them as patterns.

A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment. In other words, a pattern suggests a solution to a particular problem or issue in object-oriented software development

There are three basic classification of patters:

~ Creational
  1. Singleton Pattern
~ Structural, and
  1. Facade Pattern
  2. Decorator Pattern
~ Behavioural pattern
  1. Strategy Pattern

Thursday, July 2, 2009

Simple Way To Output XML to Browser

I have seen many Blogs and Posts where people do lot of hard work just to display the XML onto the web page. Well its very easy but people dont know which TAG do this

When you paste the XML on a .htm file, browser renders the XML Attributes as HTML attributes and displays the output. It wont display the way you see in a notepad file or in Visual Studio.

Some time during XML programming (I mean reading/writing/parsing/traversing), we get an error saying some issue with XML, but we can't see the extire XML because browser renders like a html file.

Without wasting more time, in order to print or show the XML content on browser, put the entire XML content in <XMP></XMP> tag and see the magic.


Below is the XML which I had put in a web page with and following 2 images shows the difference.


Output without <XMP></XMP> Tag:




Output with <XMP></XMP> Tag:





Similar Tags:

Display XML to Browser,
Print XML to Browser,
Output XML to Browser,
Viewing XML file in Browser.

Saturday, March 21, 2009

Free Open source Encryption Software- TrueCrypt

This is an amazing open source on-the-fly disk encryption software for Windows, Mac and Linux. You can encrypt entire disk (internal/external/USBs) as well as encrypt any files/folders into encrypted file which can be mounted later.

TrueCrypt has an fantastic feature of two levels of encryption which helps to protect the volume in case if you have to reveal the password. In this case he creates a Hidden Volume which will never be known to others and opened with another password. It uses Encryption Algorithm such as AES-256, Serpent, Twofish and mode of operation is XTS

Advantage is you don't need to decrypt every files/folders to view it. You just have to mount with correct password and it operates as normal volume.

Only disadvantage is that IF YOU FORGET THE PASSWORD, YOU WILL LOOSE ALL DATA.

READ THE DOCUMENTATION AND TUTORIAL BEFORE INSTALLING...

URL to site: http://www.truecrypt.org/
Download: http://www.truecrypt.org/downloads
Docs: http://www.truecrypt.org/docs/

Thursday, February 12, 2009

Deleting Services Forcefully from Services MMC

Few days back I modified my Windows Service .NET Application and compiled to MSI to be re-installed. Somehow during un-install process, service was not removed from Services Microsoft Management Console (MMC) and it came to my notice during re-installation of MSI.

As there is no Delete option available in Services MMC, it was becoming a nightmare to re-install it. Some how I found SC.EXE which is a command line program to communicate with Service Control Manager and Services.

There are many available options but what interested me is you can Create, Start, Stop, Delete a service with a Command Line.

Creating a Service:

sc.exe create PayCalcService binPath= "C:\Program Files\PaymentCalculation\paycalc.exe" DisplayName= "PaymentCalculationService"

Starting a Service:
sc.exe start PaymentCalculationService

Stopping a Service:
sc.exe stop PaymentCalculationService

Deleting a Service:
sc.exe delete PaymentCalculationService

Hope this helps for similar problems...

Monday, February 18, 2008

Shortcut to create Property out of Field - C#

To create Property out of Field, you need to declare a field as private and create Property for the field. But now you can create Property out of Field with combination of three keys. Yeah..., its Ctrl+R+E.
Declare the field as private and press "Ctrl+R+E" on the field name. It will popup a dialog where you can set the name of property (its almost what you want). Click OK to create Property in your C# code.


Property gets created automatically on click of OK