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.


//The interface for the strategies
public interface ICalculateInterface
{
//define method
int Calculate(int value1, int value2);
}

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.


//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;
}
}

At last we need to create a Client that will execute the strategy.


//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);
}
}

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.


protected void Page_Load(object sender, EventArgs e)
{
CalculateClient minusClient = new CalculateClient(new Minus());
Response.Write("<br />Minus: " + minusClient.Calculate(7, 1).ToString());

CalculateClient plusClient = new CalculateClient(new Plussus());
Response.Write("<br />Plussus: " + plusClient.Calculate(7, 1).ToString());
}

This code will give the following output.


<br />Minus: 6
<br />Plussus: 8

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.


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;
        }
 }

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: invoke WCF method with WCF Test Client

When deploying a Silverlight application we ran into problems a WCF web-service, to find out what the problem was I wanted to invoke the method.

Microsoft shipped an application for invoking methods from your Windows PC (WCFtestclient.exe). The following steps explain how to use WCFtestclient.exe.

First startup Visual Studio 2008 Command Prompt. In the command prompt type wcftestclient, the application will startup.

Now we need to add the Service. Click File and Add Service.

 

Add the URL to your service in the pop-up and pres ok. The service will now add all methods from your service. You can add multiple service URLs.

Double click the method you want to invoke from the tree on the left pane. Enter the values that are required for the Invoke and press Invoke. The method will be invoked.

The right bottom pane will show the response. In my case this shows the Stack-trace because of the error. Normally this will show the web-service response (XML).

With the stack-trace I could located the error and fix it.

Hope this helps,

Pieter

Asp.Net: Charting Control (Error ChartImg.axd)

After installing and playing with the Asp.Net Charting control I decided to use it for a customer. When integrating the control to the project I got the following error

"Error executing child request for ChartImg.axd"

This error occurred because I did not update my web.config file. You have to add the following appSettingkey, httpHandler and handler.

[code:xml]

<appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:TempImageFilesDit;" />
</appSettings>
<httpHandlers>
    <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
</httpHandlers>

<handlers>
    <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>

[/code]

More info about the Charting control:
http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx

Enjoy charting,
Pieter

.Net: Example basic consoleapplication with parameters

This is a basic example of an console-application with parameters used for a scheduled tasks.

The application will be scheduled to run every day with the -n parameter. But the application can also run on a specific date by using the -d parameter.


class Program
{
 //Parameters
 private static DateTime theDate;
 private static RunMode mode = RunMode.NotSpecified;

 static void Main(string[] args)
 {
  if (CollectParameters(args))
  {
   Console.WriteLine("Beginning appliation in mode "{0}" with date {1}.", mode, theDate);
   Logger.LogEvent("Starting StatisticConsoleApp", args, (int)Logger.LogType.Message);

  }
 }

 private static bool CollectParameters(string[] args)
 {
  if (args.Length &gt; 0)
  {
   for (int ii = 0; ii &lt; args.Length &amp;&amp; mode == RunMode.NotSpecified; ii++)
   {
    //Default commands for support -h and /?
    if (args[ii].ToLower().Trim() == &quot;-h&quot; || args[ii].Trim() == &quot;/?&quot;)
    {
     PrintHelpText();
     return (false);
    }
    else
    {
     //Get clear input params
     string inputParam = args[ii].ToLower().Trim();
     inputParam = Regex.Replace(inputParam, &quot;[/-]&quot;, &quot;&quot;);

     switch (inputParam)
                    {
                        case &quot;n&quot;:
                            mode = RunMode.Normal;
                            theDate = DateTime.Now;
                            break;

                        case &quot;d&quot;:
                            mode = RunMode.SpecificDate;
                            if ((ii + 1) &lt; args.Length)
                            {
                                theDate = Convert.ToDateTime(args[ii + 1]);
                            }
                            break;
       default:
        if(args[ii].Substring(0,1) == &quot;-&quot;)
         Console.WriteLine(&quot;Unknown switch {0}. Ignoring this switch.&quot;, args[ii]);
        break;
      }
    }
   }

   if (mode != RunMode.NotSpecified)
   {
    return true;
   }
   else
   {
    Console.WriteLine(&quot;No valid parameter specified. Aborting processing.....&quot;);
    return false;
   }
  }
  else
  {
   PrintHelpText();
   return false;
  }
 }
 private static void PrintHelpText()
 {
  Console.WriteLine(&quot;nUsage: Statisticprocess application&quot;);
  Console.WriteLine(&quot;&quot;);
  Console.WriteLine(&quot;  -n&quot;);
  Console.WriteLine(&quot;    The application will run in normal mode.&quot;);
  Console.WriteLine(&quot;    The statistics will be processed with the current date.&quot;);
  Console.WriteLine(&quot;  -d&quot;);
  Console.WriteLine(&quot;    The application runs in &#039;specific date&#039; mode.&quot;);
  Console.WriteLine(&quot;    The statistics will be processed with the input date&quot;);
  Console.WriteLine(&quot;    The date may be specified in any format as long as it can be &quot;);
  Console.WriteLine(&quot;    translated unambiguously into a proper date.&quot;);
  Console.WriteLine(&quot;&quot;);
  Console.WriteLine(&quot;&quot;);
  Console.WriteLine(&quot;    Note: Only one mode can be specified.&quot;);
  Console.WriteLine(&quot;          If two modes are specified, the second mode is ignored.&quot;);
  Console.WriteLine(&quot;&quot;);
  Console.WriteLine(&quot;    Example: In this example application runs in &quot;specific date&quot; mode &quot;);
  Console.WriteLine(&quot;             for the date &quot;10-sep-2006&quot;.&quot;);
  Console.WriteLine(&quot;&quot;);
  Console.WriteLine(&quot;    TOOLNAME [-d 1-jan-2009]&quot;);
  Console.WriteLine(&quot;&quot;);
 }
}


If you copy this class into your program.cs you will get some errors concerning my own loghandler and the missing RunMode enum. To fix this delete the code lines for the logging and add the following enum to your console application.



public enum RunMode : byte
 {
  NotSpecified,
  Normal,
  SpecificDate
 }


This is not the clearest example but if you have any questions don’t hesitate to ask.

Running WCF on IIS 5 (Windows XP)

After running WCF on my Vista laptop (IIS7) I needed to deploy the application on some Windows XP computers. Again some strange errors occurred:

[code:html]

Error Description: "This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection.
Parameter name: item"

[/code]

The problem is that WCF cannot handle more than one identity (host headers) per website. At first I configured IIS to have one HostHeader. That solution was just to dirty. So I kept on searching the internet.


You can fix this problem by adding prefix-key(s) in the baseAddressPrefixFilters section of the Web.Config:

[code:xml]
<system.serviceModel>
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
        <add prefix=”http://www.local.develop”/>

</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</system.serviceModel>
[/code]


Hope this helps.


Sources:
http://geekswithblogs.net/robz/archive/2007/10/02/WCF-in-IIS-with-Websites-that-have-Multiple-Identities.aspx
http://blogs.msdn.com/rampo/archive/2008/02/11/how-can-wcf-support-multiple-iis-binding-specified-per-site.aspx

Microsoft Tag: Snap my vCard

When surfing the internet I start reading about Microsoft Tag Beta (of course). With Microsoft Tag you can create links with a image-pattern. The image-pattern can be decoded to a link with the Microsoft Tag program on your Windows Mobile (with camera).

You can create graphical image-patterns with the following actions:

  • Link to an URL
  • Free text
  • vCard
  • Dialer

It looks very promising. Not every tag on a screen gets recognized at once, but the printed tags work very well.

I've placed my vCard in a tag on my blog. Just try to tag it 😉