Strategy Design Pattern with C#

Strategy design pattern is a behavioral design pattern. It is a particular software design pattern where algorithms are selected at runtime.

According to the book of Design Pattern (Gang of Four) – “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. “

The key phrases of definition are “Family of algorithms”, “encapsulate”, and “interchangeable”. Actually, Strategy Pattern encapsulates a collection of functions that do similar yet not identical jobs. Client is not bound to call fixed methods; rather it can change its strategy dynamically at run time. Client don’t call any methods directly by instantiating concrete classes. It sets its strategy via context class.

There are three main parts in strategy pattern:

  1. Strategy – An interface that defines how the algorithm will be called.
  2. Concrete Strategy – The implementation of the strategy.
  3. Context – It holds the concrete strategy.

StrategyPattern

Implementation:

Suppose you have two lists of items. Item here integer numbers. Now, if you want to search an item from either of the lists. You can use either one of the algorithms from Linear Search or Binary search. Since binary search algorithm cannot search data without sorted list, we take here a sorted list. Now the strategy of client to use which one – Binary search or linear search. Let’s implement the problem by strategy pattern using c#.

Step 1: Create an Interface for Strategy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Strategy defines how algorithm will be called
///

public interface ISearchStrategy
{
int Search(int[] list, int item);
}
}

Step 2: Create concrete strategy (Linear Search)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Concrete strategy(Linear Search Algorithm)
///

public class LinearSearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Linear Search");
int position = 0;

for (int i = 0; i < list.Count(); i++)
{
if (list[i] == item)
{
position = i;
break;
}
}

return position;
}

#endregion
}
}

Step 3: Create concrete strategy (Binary Search)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Concrete strategy(Binary Search Algorithm)
///

public class BinarySearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Binary Search");

int beg = 0;
int end = list.Count() - 1;
int mid = (int)((beg + end)/2);
int position = 0;

while (beg <= end && list[mid] != item)
{
if(item < list[mid])
end = mid - 1;
else
beg = mid + 1;

mid = (int)((beg + end)/2);
}

if (list[mid] == item)
position = mid;
else
position = 0;

return position;
}

#endregion
}
}

Step 4: Create a context class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Concrete strategy(Linear Search Algorithm)
///

public class LinearSearch : ISearchStrategy
{
#region ISearchStrategy Members

public int Search(int[] list, int item)
{
Console.WriteLine("Linear Search");
int position = 0;

for (int i = 0; i < list.Count(); i++)
{
if (list[i] == item)
{
position = i;
break;
}
}

return position;
}

#endregion
}
}

Step 5: Client class to demonstrate strategy pattern

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
///
/// Client class
///

class Program
{
static void Main(string[] args)
{

int[] sortedList = { 1, 2, 3, 4, 5, 6, 7, 8 };

//Instance of context to follow different strategies
SearchList objSearchList = new SearchList();

objSearchList.SetSearchStrategy(new BinarySearch());
objSearchList.Search(sortedList, 4);

objSearchList.SetSearchStrategy(new LinearSearch());
objSearchList.Search(sortedList, 7);

Console.ReadLine();
}
}
}

Output:
output_strategyPattern

Abstract Factory Pattern with C#

Abstract factory pattern is a creational design pattern. Creational design pattern is deals with object creation mechanism. Object creation mechanism is changed on the basis of problem. Abstract factory pattern provides an interface to create families of related or dependent objects without specifying their concrete class. It is identified on the basis of problem complexity. It is encapsulated the process of instantiation of family of classes. Abstract factory pattern is widely used in framework and libraries to encapsulate the family of classes.

Elements of Abstract Factory Pattern:

  1. Abstract Factory – An Interface to create families of related or dependent item object.
  2. Concrete Factory – Implement the interface to create families of related item object.
  3. Abstract Item – An interface to create concrete item object.
  4. Concrete Item – Implement the interface to create concrete item object.
  5. Client – Uses Interface (abstract Item) provided by abstract factory and access concrete object by this interface.

Implementation:

Here I implemented abstract factory pattern in International Cricket Team by C#. The UML diagram is given below.

AFP-1

Step 1: Create interface for Item class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
///
/// Interface for Item class
///

public interface ICricketer
{
string BattingStrength();
string BowlingStrength();
string AllroundingStrength();
string IconPlayer();
}
}

Step 2: Create Factory Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
///
/// A Factory interface
///

public interface ICricketerFactory
{
ICricketer GetCricketer(CricketerBase cricketerBase);
}
}

Step 3: Define the type of Base object

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Define the type of Base Object
///

public enum CricketerBase
{
AustralianCricketer,
BangladeshiCricketer,
EnglishCricketer,
IndianCricketer,
PakistaniCricketer
}

}

Step 4: Create Concrete factory class for Asian Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Concrete factory class for Asian Cricketer
///

public class AsianCricketerFactory : ICricketerFactory
{

#region ICricketerFactory Members

public ICricketer GetCricketer(CricketerBase cricketerBase)
{
ICricketer objICricketer = null;

switch (cricketerBase)
{
case CricketerBase.BangladeshiCricketer:
objICricketer = new BangladeshiCricketer();
break;
case CricketerBase.IndianCricketer:
objICricketer = new IndianCricketer();
break;
default:
break;
}
return objICricketer;
}

#endregion
}
}

Step 5: Create Concrete factory class for European Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
///
/// Concrete factory class for European Cricketer
///

public class EuropeanCricketerFactory : ICricketerFactory
{

#region ICricketerFactory Members

public ICricketer GetCricketer(CricketerBase cricketerBase)
{
ICricketer objICricketer = null;

switch (cricketerBase)
{
case CricketerBase.EnglishCricketer:
objICricketer = new EnglishCricketer();
break;
default:
break;
}
return objICricketer;
}

#endregion
}
}

Step 6: Create Item class for Bangladeshi Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Item class for Bangladeshi Cricketer
///

public class BangladeshiCricketer : ICricketer
{
#region ICricketer Members

public string BattingStrength()
{
return "60%";
}

public string BowlingStrength()
{
return "70%";
}

public string AllroundingStrength()
{
return "85%";
}

public string IconPlayer()
{
return "Shakib Al Hasan";
}

#endregion
}
}

Step 7: Create Item Class for Indian Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Item class for Indian Cricketer
///

public class IndianCricketer : ICricketer
{

#region ICricketer Members

public string BattingStrength()
{
return "85%";
}

public string BowlingStrength()
{
return "60%";
}

public string AllroundingStrength()
{
return "70%";
}

public string IconPlayer()
{
return "Shachin Tendulkar.";
}

#endregion
}
}

Step 8: Create Item class for Pakistani Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Item class for Pakistani Cricketer
///

public class PakistaniCricketer : ICricketer
{

#region ICricketer Members

public string BattingStrength()
{
return "75%";
}

public string BowlingStrength()
{
return "85%";
}

public string AllroundingStrength()
{
return "75%";
}

public string IconPlayer()
{
return "Shahid Afridi.";
}

#endregion
}
}

Step 9: Create Item class for English Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Item class for English Cricketer
///

public class EnglishCricketer : ICricketer
{

#region ICricketer Members

public string BattingStrength()
{
return "75%";
}

public string BowlingStrength()
{
return "80%";
}

public string AllroundingStrength()
{
return "70%";
}

public string IconPlayer()
{
return "Kavin Pietersen";
}

#endregion
}
}

Step 10: Create a client class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

///
/// Client Class
///

class Program
{
static void Main(string[] args)
{
AsianCricketerFactory objAsianFactory = new AsianCricketerFactory();
ICricketer objIAsianCricketer = objAsianFactory.GetCricketer(CricketerBase.BangladeshiCricketer);
Console.WriteLine("Bangladesh Cricket Team\nBatting Strength:" + objIAsianCricketer.BattingStrength());
Console.WriteLine("Bowling Strength:" + objIAsianCricketer.BowlingStrength());
Console.WriteLine("Allrounding Strength:" + objIAsianCricketer.AllroundingStrength());
Console.WriteLine("Icon Player:" + objIAsianCricketer.IconPlayer());

Console.WriteLine();

EuropeanCricketerFactory objEuropeanFactory = new EuropeanCricketerFactory();
ICricketer objIEuropeanCricketer = objEuropeanFactory.GetCricketer(CricketerBase.EnglishCricketer);
Console.WriteLine("England Cricket Team\nBatting Strength:" + objIEuropeanCricketer.BattingStrength());

Console.WriteLine("Bowling Strength:" + objIEuropeanCricketer.BowlingStrength());
Console.WriteLine("Allrounding Strength:" + objIEuropeanCricketer.AllroundingStrength());
Console.WriteLine("Icon Player:" + objIEuropeanCricketer.IconPlayer());

Console.ReadLine();

}
}
}

Output:
AFP-Output

Retrieve Store Procedure’s Output parameter by C# (ASP.net)

How to retrieve store procedure’s output parameter by C#? Here I have explained with a simple example. I created a simple store procedure with output parameter. Then I catch it from code behind page of asp.net and displayed it to a label. Here I used a class DBConnector to connect with database. Lets look on the demo.

Step 1: Set connection string in web.config.


     


Step 2: Create a store procedure with output parameter.

CREATE PROCEDURE [dbo].[sp_output_param]
(
     @input_param VARCHAR(200)
    , @Response VARCHAR(250) OUTPUT
)
AS
    --DECLARE @myName
BEGIN  
    SET @Response = 'Welcome ' + @input_param
END

Step 3: Create a DBConnector Class to retrieve data from database.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
 
public class DBConnector
{
    private string connectionString = null;
    private SqlConnection sqlConn = null;
    private SqlCommand cmd = null;
 
    public DBConnector()
    {
        connectionString = ConfigurationManager.ConnectionStrings["SQLServerConnectionString"].ToString();
    }
 
 
    public SqlCommand GetCommand()
    {
        cmd = new SqlCommand();
        cmd.Connection = sqlConn;
        return cmd;
    }
 
    public SqlConnection GetConn()
    {
        sqlConn = new SqlConnection(connectionString);
        return sqlConn;
    }
 
}

Step 4 : Create a label name lblMsg in asp page. Then in a button event, write the following code. You will see your desired output in the lebel which is actually the value of output parameter. Here btnGetOutputParam_Click is the click event of Button btnGetOutputParam.

protected void btnGetOutputParam_Click(object sender, EventArgs e)
{
        SqlConnection sqlConn;
        SqlCommand cmd;
 
        DBConnector objDBConnector = new DBConnector();
        sqlConn = objDBConnector.GetConn();
 
        cmd = objDBConnector.GetCommand();
 
        SqlDataReader rdr = null;
 
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "sp_output_param";
        cmd.Parameters.AddWithValue("@input_param", "Mahedee");
        cmd.Parameters.Add("@Response", SqlDbType.VarChar, 250);
        cmd.Parameters["@Response"].Direction = ParameterDirection.Output;
 
        try
        {
            if (sqlConn.State == ConnectionState.Closed)
                sqlConn.Open();
 
            rdr = cmd.ExecuteReader();
 
            string outputValue = cmd.Parameters["@Response"].Value.ToString();
            this.lblMsg.Text = outputValue;
        }
        catch (Exception exp)
        {
            throw (exp);
        }
        finally
        {
            if (sqlConn.State == ConnectionState.Open)
                sqlConn.Close();
        }
 
    }

You will see in label – Welcome Mahedee which is provided by output parameter of store procedure.

Generate image on the fly by ASP.NET

Generating image on the fly is not difficult in asp.net. Here I have created national flag of Bangladesh on the fly and displayed this as JPEG image format in asp.net web form. So let’s start to draw an image on the fly.

Step 1: Add a new web form in ASP.net website.

Step 2: In the Page_Load of the web form write the following code

protected void Page_Load(object sender, EventArgs e)
{
//Define the rectangle with (x co-ordinate, y co-ordinate, width, height)
RectangleF rectF = new RectangleF(0, 0, 400, 200);
Bitmap img = new Bitmap(400, 200, PixelFormat.Format24bppRgb);
Graphics grphs = Graphics.FromImage(img);
SolidBrush bgBrush = new SolidBrush(System.Drawing.Color.Green);

grphs.FillRectangle(bgBrush, rectF);

SolidBrush elpsBgBrush = new SolidBrush(System.Drawing.Color.Red);

//Fill the interior of an ellipse by the pair of co-ordinates and height and width
grphs.FillEllipse(elpsBgBrush, 140, 40, 130, 130);

int fontSize = 20;
string fontName = "Arial" + ".ttf";
PrivateFontCollection privateFontCollection = new PrivateFontCollection();
privateFontCollection.AddFontFile(@"C:/WINDOWS/Fonts/" + fontName);

FontFamily fontFamily = privateFontCollection.Families[0];

// Set font style
int fontStyle = Convert.ToInt32(Request.Form.Get("fontstyle"));
string text = "Bangladesh";

SolidBrush fgBrush = new SolidBrush(System.Drawing.Color.Yellow);
FontStyle style = FontStyle.Bold;

StringFormat format = new StringFormat();
format.FormatFlags = StringFormatFlags.DirectionRightToLeft;

Font font = new Font(fontFamily, fontSize, style, GraphicsUnit.Pixel);

grphs.DrawString(text, font, fgBrush, rectF, format);

Response.ContentType = "image/jpeg";
img.Save(Response.OutputStream, ImageFormat.Jpeg);

// Dispose objects
img.Dispose();
}

Here RectangleF stores a set of four floating-point numbers that represent the location and size of a rectangle. Here first pair is (x,y) co-ordinate and second pair is width and height. SolidBrush define a brush of single color. FillRectangle and FillEllipse is responsible for both Filling rectangle and Ellipse. Graphics.DrawString is used to draw text in the rectangle.

Now run the website. Yes! You have drawn your desired National Flag of Bangladesh and its look like this.

Output:

National Flag bangladesh