Design Patterns(C#): Basic example Strategy pattern

In this example I´m going to explane the strategy pattern. With this example you can do a calculation with two numbers (-/+) and expand the number of operators (/, *, etc.).

First create a interface which defines the interface of the operator classes. For this example an operator can only calculate two values.
[code language=’c#’]
//The interface for the strategies
public interface ICalculateInterface
{
//define method
int Calculate(int value1, int value2);
}
[/code]

Next create the operators (strategies) Minus (which subtract value 2 from value 1) and Plussus (which addition value 1 with value 2). The classes need to inherit from the interface ICalculateInterface.
[code language=’c#’]
//Strategy 1: Minus
class Minus : ICalculateInterface
{
public int Calculate(int value1, int value2)
{
//define logic
return value1 – value2;
}
}

//Strategy 2: Plussus
class Plussus : ICalculateInterface
{
public int Calculate(int value1, int value2)
{
//define logic
return value1 + value2;
}
}
[/code]

At last we need to create a Client that will execute the strategy.
[code language=’c#’]
//The client
class CalculateClient
{
private ICalculateInterface calculateInterface;

//Constructor: assigns strategy to interface
public CalculateClient(ICalculateInterface strategy)
{
calculateInterface = strategy;
}

//Executes the strategy
public int Calculate(int value1, int value2)
{
return calculateInterface.Calculate(value1, value2);
}
}
[/code]

Now we have two operators (minus & plussus) and a client (CalculateClient) that can execute the operators. Let’s test the code. Create a new webapplication, console app or something else that can write output. For this example I will use a webpage.

Initialize a new CalculateClient with argument operator Minus of Plussus and Calculate two values.
[code language=’c#’]
protected void Page_Load(object sender, EventArgs e)
{
CalculateClient minusClient = new CalculateClient(new Minus());
Response.Write(“
Minus: ” + minusClient.Calculate(7, 1).ToString());

CalculateClient plusClient = new CalculateClient(new Plussus());
Response.Write(“
Plussus: ” + plusClient.Calculate(7, 1).ToString());
}
[/code]

This code will give the following output.
[code language=’html’]

Minus: 6

Plussus: 8
[/code]

The great thing about this pattern is that you can easily add new opertators (strategies) to your code.

Cheers,
Pieter

Asp.Net: Webtest trough proxy (WebTestPlugin)

The test-team came to me with a problem involving connection errors while running webtests trough the company proxy. The webrequest needed to go to the webproxy including authentication. Visual Studion 2008 doesn’t support proxy authentication out of the box, but you can create a WebTestPlugin that does the authentication for every request.

The following class inherits from WebTestPlugin and overrides the PreWebTest method. In the PreWebTest method it will authenticate the request with your credentials.

[code language=’c#’]
public class LoadTestProxyAuthentication : WebTestPlugin
{
        public override void PreWebTest(object sender, PreWebTestEventArgs e)
        {
            // Create WebProxy (enter your proxy url)
            WebProxy webProxy = new WebProxy(“ProxyAdres”);

            // Use the proxy for the webtest
            e.WebTest.WebProxy = webProxy;

            e.WebTest.PreAuthenticate = true;
            NetworkCredential proxyCredentials;

            proxyCredentials = new NetworkCredential();

            proxyCredentials.Domain = “domain”;
            proxyCredentials.UserName = “username”;
            proxyCredentials.Password = “password”;
            e.WebTest.WebProxy.Credentials = proxyCredentials;
        }
 }
[/code]

How to use the webtestplugin
Ad the class to your test project, change the credentials and proxyadres. After a build open the webtest press the ‘add  Webtest plugin’ button (on the top screenmenu), select the LoadTestProxyAuthentication and press OK. You need to add the webtestplugin for every webtest.

Now you can run your webtests trough the proxy.

Hope it helps,
Pieter

Asp.Net: keyboard sort items

As proof of concept I wanted to sort images in a Grid by keyboard. The sort logic needed to be implemented on the server. My solution for this problem is a combination of Javascript and C#.

First add following html to you .aspx. Notice that the body tag has runat=”server” and a ID.
[code language=’html’]
<body runat=”server” ID=”bodyTag”>

[/code]

Now add the following JavaScript to your page. This script will fetch all keyboard input and press the corresponding button.
[code language=’js’]

document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
switch (keycode) {
case 37:
var obj = document.getElementById(”);
obj.focus();
obj.click();
break;
case 38:
var obj = document.getElementById(”);
obj.focus();
obj.click();
break;
case 39:
var obj = document.getElementById(”);
obj.focus();
obj.click();
break;
case 40:
var obj = document.getElementById(”);
obj.focus();
obj.click();
break;
}

}

[/code]

At last we need to add the following C# code to the page.
[code language=’c#’]
protected void Page_Load(object sender, EventArgs e)
{
//Ad clientside onkeypress event to the body
bodyTag.Attributes.Add(“OnKeyPress”, “keyhandlers()”);
}

protected void DownButton_Command(object sender, CommandEventArgs e)
{
//Just for testing
clickedLabel.Text = (string)e.CommandArgument;
}
[/code]

Enjoy, Pieter

Asp.Net: DataPager problem with Listview

When using the Datapager with a ListView I had the following problem. When clicking a paging button for the first time nothing happens.But when I click a button the second time, then the page from the first click loads.

I search the internet for a solution and found that you need to add some code to the OnPagePropertiesChanging event of the list view to reload the DataPager.

The following code is the solution to my problem. Including a fix that the data doesn’t get loaded two times.

[code language=’c#’]
private List productList;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        fillGrid();
}

private void fillGrid()
{
    if(productList == null)
        productList = getproducts();
    ListView1.DataSource = productList;
    ListView1.DataBind();
    DataPager1.DataBind();
}

public List getproducts()
{
    using (AdventureWrksDataContext db = new AdventureWrksDataContext())
    {
        return db.Products.ToList();
    }
}

protected void lvproducts_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
    DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
    fillGrid();
}

[/code]

You can download the solution (PagingExample.zip (83.05 kb))

Cheers,

Pieter