Failing tests as a reminder of unimplemented requirement

December 16th, 2008

I am a new comer to the art of unit testing and it has not yet become the part of my coding routine. However, even this early I have realized how useful writing unit tests can be. Specially writing unit tests gives you the understanding how the class will be used and where the errors can arise etc. For example passing the Type System.String to a method where the method expects a Type which implements a particular interface ICommand should result in an error because the System.String does not certainly implements the interface ICommand. But does the method validate the input?

Now writing a test for this case is very simple. Just create the object, call the method with System.String as the Type parameter.

[Test]
[ExpectedException(typeof(ArgumentException))]
public void CanNotRegisterTypesNotImplementingICommand()
{
CommandLocater locater=new CommandLocater();
locater.RegisterCommand(1,typeof(string));
}

Certainly I haven’t implemented the validation code for checking this, so the test is certainly failing. Until I feel like doing this validation, this test will always fail. Lot better than forgetting to write this code and getting an unrelated exception in any other section of the code is getting a failing test which will make sure that I’ll write the code necessary to implement this requirement.
“Always write tests to break your code.”

Sorting list the easy way using lambda expressions

December 15th, 2008

Introduction of lambda expressions in .NET 3.5 have simplified many operations. One of them is sorting List<t> of complex types. For example assume that we have a type named Person and it has a Name property among other properties. Now if we want to sort a list of List<Person> on the Name property, we just have to use a single line of code.

list.Sort((p1,p2)=>p1.Name.CompareTo(p2.Name));

Or to sort on the Age property

list.Sort((p1,p2)=>p1.Age.CompareTo(p2.Age));

Here we are creating a delegate of Comparison<Person> using lambda expression and passing it to one of the overload of sort () method which accepts a Comparison<t>. The following code is breakdown of the above one liner into 2 lines.

Comparison<Person> pc=(p1,p2)=>p1.Name.CompareTo(p2.Name);
                                            list.Sort(pc);

In short, we can use lambda expression to create delegates inline and pass them where ever a delegate can be passed. The List<t> class itself has many methods where you can pass delegates to perform certain actions. For example List<t>.ForEach() method.

list.ForEach(o => Console.WriteLine(o.Name));

Here we are outputting the names of persons in the list to the console without using a foreach loop.

Always explicitly detach explicitly attached event handlers

December 6th, 2008

We extensively use events in our .net programs. Most of the times, it doesn’t give you debugging worries. However in some cases, it can become an issue where your object containing event handler doesn’t get garbage collected due to event raising object holding a reference to the listener object. This happens when you listen to the events from a long lived object compared to the listening object.

If you are coding in VB.NET then using the handles clause will guard you to an extent. Just remember to set the withevents variable to nothing after done. This will remove bindings between your event handlers and the object.

However, if we are programming in C# or have to use AddHandler statements in VB.NET for attaching event handlers, remember to explicitly detach the handler from the event.

As I said earlier, most of the times this does not become an issue at all. However, while creating highly event driven classes for your application, you don’t want objects sticking around more than they need to be. Also since the handler is still attached to the event, the handler will get invoked each time the event is fired. You can think the issues arising when this happens.

Keep an eye on how you attach event handlers and make sure that you are detaching them in time.

Is it OK to not have explicit return statements in functions?

November 12th, 2008

Simple answer: no. There are basically two types of methods in .NET world. First those do not return any values (void methods in C# or subroutines in VB). Second those methods which do return some values (non void methods in C# and functions in VB)

So, failing to have a return statement where the calling code expects one, should be reason enough to cause a compilation error. Not so in VB.NET 2005, at least not with the default configuration.

Couple of days ago I spend few minutes understanding this same issue. Yes, not explicitly returning any value from a function is a huge programming error. But it becomes even worse when you don’t get to know it until runtime.

The value returned to the caller when there isn’t any explicit return statement in the code is the default value for the return type of the function. Or in other words, the result will be as if you have returned nothing. For example, if you have following function in your code:

Private Function test() As Integer

End Function

Then somewhere else have this statement:

MessageBox.Show(test.ToString())

The program will compile normally and produce a message box with 0 (the default value of integer) in it. If we change the return type of the test method to string, the function will be returning nothing (return nothing) the default value for any object.

Does anyone know any way around this issue, any changes to configuration? So that VB.NET compiler becomes stricter? Yes, it isn’t such a problem. But still, the compiler should alert us to such silly mistakes which we may make time to time.

hide email and other sensitive information from spam harvesters

October 16th, 2008

Often we have to display email addresses and other contact information on our pages. For example providing a mailto link etc. However, along with the intended users, some other persons/bots are also interested in getting those email IDs for sending spams. For this, spammers use special bots for harvesting email/contact info from the web. In this post, I will show a method using javascript and any server side language by which we can easily protect such important information.

Read the rest of this entry »

creating GUIDs in .net

October 13th, 2008

After an interval of more than 2 weeks, I am back online blogging. Today I will share a quick tip on how to create a guid in C# and vb.net. For a description about GUIDs, visit this Wikipedia page.

A guid in the .net world is represented by the System.Guid class. The Guid class has many constructors which takes 0 or more arguments and constructs a guid from it. However, if we want to create a random guid, using the parameter less constructor would not do. A guid created using the parameter less constructor contains all zeros. So how to create a unique guid?

Guid.NewGuid() method

The Guid class has a static method named NewGuid() which creates and returns a new random guid. Let’s see a example.

C#
Guid g=Guid.NewGuid();
                             MessageBox.Show(g.ToString());
VB.NET
Dim g As Guid =Guid.NewGuid()
                             MessageBox.Show(g.ToString())

Here we are simply creating a new guid and using ToString() method for displaying it. You can also get byte representation of the guid using ToByteArray() method.

Enjoy!

Expanding paths containing Environment variables

September 24th, 2008

Sometimes we may need to expand paths like “%systemroot%\program.exe” etc programmatically. Specially values in the registry are encoded in this format. The .net framework provides us a straightforward method using which we can easily convert strings containing such special variables into their values.

Environment.ExpandEnvironmentVariables() method

Read the rest of this entry »

Accessing all the opened forms

September 23rd, 2008

While developing win forms applications, sometimes we may want to get the list of all currently opened forms in the application. The below code snippet show how we can access and enumerate through the instances of opened forms. The snippet enumerates through all the forms and display their title.

string str="";
foreach(Form f in Application.OpenForms)
              str+= f.Text + " ";

MessageBox.Show(str);

The Application.OpenForms collection contains references to all the opened forms owned by the application.

Note: The OpenForms property returns a read-only collection, so we can not modify the collection directly.

Hope it will be helpful for someone

Annoying the user: Please enter numbers only

September 18th, 2008

Everyone of us sometime or other had to restrict the user from entering non-numeric values in to a text field. We normally validate user input when user presses the submit button or when the user leave the input field and display the error message in a span or using alert() javascript function.

However what will happen if we validate user input as the user is typing in the field and also use a alert box to display error message instead of showing it in a span?

Please do not do this ever and annoy your dear visitors and make them ask “who developed this crap?”.

In the recent past, I had to fill out a form where I was supposed to enter my phone number and they ware using this annoying technique. Now I mistyped my number and the validation script throws an alert(). I press “OK” by pressing space bar and to silence my screen reader, I pressed “ctrl”. You can guess the result. The alert comes again!

So, we developers should never try to annoy our users using this kind of unnecessary tricks, instead we should make our user interfaces as smooth as possible to use for both normal users and users with special needs.

Never try to outsmart your visitors because situation will outsmart us! And never try to lock the user’s keyboard because it’s their keyboard and they are free to use it as they like.

displaying html or other files using their default application

September 16th, 2008

Sometimes, we may want to show user a readme file or start any application or open any document on the system. For openning any file with their default file open handeler, we just have to use following one liner.

System.Diagnostics.Process.Start(@"d:\niran\readme.htm");

You can pass the path to any file or path to any executable and it will be opened like when you double-click on it in windows explorer. In fact, you can also open web addresses using this method in the default browser of the system.

System.Diagnostics.Process.Start(@"http://www.nirandas.com/blog/");

Passing arguments

We can also pass arguments while starting any executable using the second parameter.
System.Diagnostics.Process.Start(@"mysql.exe",@"-u root -p");

Here we are starting the application "mysql" and passing it "-u root -p" as command line arguments. The Process.Start() method also takes many other parameters other than discussed here allowing us more finer controll.

You can easily launch files/applications using this one line of code. Enjoy,


© 2008 By Nirandas, All rights reserved.