myfavoritemovies.us

September 16, 2008

Exception handling in NUnit

Filed under: NUnit,Tips and Tricks — Tags: , — @ 2:52 pm

This is very simple but I thought, it is worth a note (or for my note taking).  Before I go into handling exception, I need to tell you something I read couple of days ago. I can not remember which blog (I follow lot of blogs) but it kinda stuck with me. When you code you try to follow the following four things

  • Make it correct
  • Make it clear
  • Make it concise
  • Make it fast
I was tossed it to my friend Jim at work (I consider him very sharp and talented and look up to him). Here is what he has to say 
  • Write a test
  • Make it pass
  • Refactor
  • Optimize if needed <- condition seldom met, may be 1/10000 loops
  • repeat the loop
If you look closely both of them are same. What Jim specified in the loop above more of TDD in mind and the earlier one is much more general and it can adapt to any environment. But I thought it is worth sharing.
Lets go back to NUnit thing I was talking about. In one of coding situation, I need to throw an exception with just a string. Something like the following
throw new Exception(“Test exception”);
Now when you test it in NUnit, you need to make sure you use
[ExpectedException(“System.Exception”, ExpectedMessage=”Test exception”)]
thats it, nothing more. See this is very simple blog.

September 2, 2008

Factory pattern through reflection.

Last week I came across a situation where, I need to implement bunch of classes which perform same task differently when it is called. (Simply put, factory pattern). So I thought, based on GOF it is a simple implementation.

Create a abstract factory class and then create sealed worker class which implement the actual task. Simple enough. In the main program have a switch which checks the incoming parameter and based on the parameter, we create instance of a proper worker class and vola we got the implementation done.

Now the point to remember here is, if we need to add a new worker class, what are all the elements involved? First you need to add a new case statement for the new worker class initation and then add the new worker class itself. Two code changes. Not a big deal. But if you happen to have too many implementation or in other words too many worker implementation then your switch statement could grow larger and larger.

This limiation forced me to think if there is any other way of creating classes on the fly. I talked to one my collegue and he pointed me to one his implementation he is currently using that is using reflection. So here is how it is implemented.

First create the interface you would like the factory workers to implement. Something like the following;

IWorker.cs

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

namespace TraditionalFactory
{
public interface IWorker
{
void SayName(string name);
}
}

You can see all we are trying to implement is a ‘SayHello’ method. Following two are two worker implementation of the Factory Interface;

Worker1.cs:


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

namespace TraditionalFactory
{
public class Worker1:IWorker
{
#region IWorker Members

public void SayName(string name)
{
Console.WriteLine("Name from first worker is {0}", name);
}

#endregion
}
}

Worker2.cs


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

namespace TraditionalFactory
{
public class Worker2:IWorker
{
#region IWorker Members

public void SayName(string name)
{
Console.WriteLine("Name from second worker {0}", name);
}

#endregion
}
}

Based on the interface and the worker implementation there is nothing new. The code that make this one work without big switch statement is in the main program.

Program.cs


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

namespace TraditionalFactory
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Which worker to run (Worker1 or Worker2?");
string workerName = Console.ReadLine();
Type workerType = Type.GetType("TraditionalFactory."+workerName);
IWorker worker = (IWorker)Activator.CreateInstance(workerType);
worker.SayName("data passed");
Console.ReadKey();
}
}
}

This factory model implementation compltly depends on the reflection feature of C#. This also depends on the the consumer to this program aware of which worker they need to consume by name or you need to create a dictionary mapping of the user input to worker class mapping of some sort. For this implementation I am assuming the consumer knows which worker to use.

The point of interests are, first creating the type of the class we are going to instantiate. In our class we are going to find the factory interface type of execuing assembly using ‘Type.GetType’ method call. Which looks at the executing assembly or clr to see if it finds matching type. If you look at the code closely, since we already know which worker that we are interested to consume based on ‘workerName’, we look for the namespace + workerName in the GetType. (This is where reflection come into get the type of the class we are trying to consume). Once the type identified, we call in the ‘Activator.CreateInstance’ method to create the instance of the worker class through the interface and then execute the public method from the interface. Thats it, we got ourself Factory pattern implemented.

The benefit of this implementation is that, when you want to add a new worker class, you simply add the worker class, compile it and deliver the exe. No more main program change. One code change and you are done.

The problems I see with the implementation is that, you need agree on how the consumers are going to consume the worker class and make appropriate mapping before hand or make the consure to call in with appropriate worker name explicitly (like the example below).

One for my notes….

August 2, 2008

Starting Windows App from Web application with parameters!

Filed under: Tips and Tricks — @ 2:51 am

There will be times you need to invoke windows app from a web application. Not only you need to call the windows application you may need to pass parameters to the windows application.

Here is how went about to solve the problem. I created the windows application as a click once application and publised it. One important part you have to remember is to enable the windows application to accept parameters. This option is under publish tab under project properties. While you are in publish tab, choose options button and check the check box pretaining to enabling the windows application to accept paramters.

To enable the windows application to get parameters from the web application you have to add the following code segment in the windows application.

if (ApplicationDeployment.IsNetworkDeployed)
{
string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query
}

It is important that we add initial ‘if’ statement to make sure we try to get the parameter only if the application is in network installed. If you are testing the appliation locally then this part of the code will not work. Also after you get the queryString, you need to split the key value pair to get your required information.

So the bottom line, develop the windows application with above mentioned code snippet in the contructor of the form. Also make application aware of the parameter coming in from web application in the publish options.

Now lets look at the web side. When you deploy the windows application, normally it get deployed with the following url like

http://servername/appname/setup.exe

now from web site to launch the application, you would call the following url

http://servername/appname/appname.application

and add the parameter with following string pattern

?key=value

Thats it, now when you run the web application, the link will launch the application from the publish folder and the when the application run, the windows application will get the parameters from the web application through activation uri.

** The activation url might return zero or null value if you try to test the code with localhost. You have to test with actual computer name in the web application link.

Ads by AdGenta.com

Tags: , , ,

Powered by Qumana

April 29, 2008

Compiler complains about ‘Linq’

Filed under: Linq — Tags: , , — @ 6:37 am

I developed an application using VS 2008 and build on the box and everything was good. Now we were implementing the code compile in the CI environment. Where I installed .Net framework 3.5.

Now when I try to compile the code in Ci environment I get an error ‘Linq’ is missing. I checked assemblies and found System.Xml.Linq is in the GAC. I even added that as a reference to in the compile task. That didn’t resolve the problem. After some research I found out that, it looks like System.Linq is in System.Core.dll and even though it is in the GAC, we must explicitly include that as a reference during compile. Once I added that as a part of reference, the Linq error went away.

So, be careful on this.

CAB and Dynamic Menuitem generation

There comes a time, when you are developing CAB application you may need to insert menu items on the run. CAB comes with a feature to add the menu items from the app.config instead of entering each menu item in the shell itself. I rather keep it in the XML than in the shell, that way shell will continue to be shell. This out of box method also gives you a feature to associate command the required menu item click event as well.

If you are beginning to work on this item, I would recommend you to download Microsoft patterns and practices Composite Application Block Hands on Lab. This particular item was discussed in lab 3. If you follow the instruction in the lab you will understand how easy to add menu items dynamically from XML.

I would like to point out couple of things when you are adding the feature to your application;

1. Please remember to add the new section for ‘shellitems’ in the app.config. If you are wondering where it is used, it is used in the LoadFromConfig (UIElementBuilder).

(more…)

NUnit in VS2008

Filed under: Tips and Tricks — Tags: , — @ 2:58 am

Even though VS2008 comes with Microsoft version of the unit testing, I still prefer NUnit. The real reason is one less to learn and on the other hand NUnit does gives me all the good things required for my TDD. I can imagine Microsoft test suite might give lot of nice integration with VS2008, NUnit can be integrated nicely to get what you want. There are third party tools you can buy that will integrate NUnit nicely into Visual Studio but I am not sure about VS2008 and if you are a person like me, I do not like to spend money on a tool if there is a way you can do it. By the way, if I spend money I spend it on book 🙂

My first approach and easy approach is to attach NUnit process to my Debug process and put break point in the line of code where I want to debug and everything goes well. Well, let me explain what I meant by this. Here are my steps, this can change based on your preference;

(more…)

April 24, 2008

Finding a pattern in a string

Filed under: regex,Tips and Tricks — Tags: , — @ 7:52 pm

It is easier to use Regex to find the string pattern you are looking for in a string using C#. If you are not sure how to use them, please use this link.

If you are trying to find a string with control characters please remeber to use ‘\’ character in front of it. Most of the time, you may not be looking for a string with special characters in it. If you are then make user you use correct character.

For example, I have a string x = “$\John\Mary”

I need to replace $\John\ with say blank, I want only Mary from that string. Then you need to do the following

string result = Regex.Replace(x, @”/$/\John/\”, “”);

With this each control character is preceded by / so that, regex will use that as a normal character otherwise, regex will try to interpret them as special character and you will not find the match.

Finding string from an array

Filed under: Linq,Tips and Tricks — Tags: , , , — @ 2:26 pm

I ran into a situation where, I need to find a string from a string array where I know only the part of the string I am looking for. So if I would be writing the code in C#2.0 the code would be something like the following;

string[] array = {“help”,”Csharp rocks”,”I am learning”};

string findString = “rocks”;

string matchedString=””;

foreach(string str in array)

{

if (str.Contains(findString))

{

matchedString = str;

break;

}

}

if (matchedString.Length > 0)

{

// the code to handle the logic goes here.

}

(more…)

Powered by WordPress