Archive for the ‘C#’ Category

ASP.NET ClientID & jQuery small trick

February 8, 2010

Up to ASP.NET 3.5 the client ids for .NET controls is not for passionate readers it looks like this: “ctl00_ctl00_decoratedArea_contentArea_homeSearch_mileageDropDownRow”
On the other hand the client name is “ctl00$ctl00$decoratedArea$contentArea$homeSearch$mileageDropDownRow” so this does not really help.

If you have to reference this from client code:
1) Migrate to asp.net 4.0 ( best option )
2) Use <%controlName.ClientID %>, but this only applies in a aspx or ascx file

If you are writing code in a js file there is no easy way, but the jquery to the resque!
Just use selector like this $(‘id$=shortServerId’)
This selects all elements which have attribute id ending with ‘shortServerId’ and returns them as array. If you want to apply non-jquery code to your selection as normal DOM functions first reference to array element of choice like this.

var allElements = $('id$=shortServerId');
if(allElements.length > 0) {
    yourDomFunciton(allElements[0]);
}

Needless to say it is a lot better to make yourself a favor and use only jQuery for  DOM modifications.

References
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
http://weblogs.asp.net/dotnetstories/archive/2009/10/27/asp-net-4-0-and-clientid-mode.aspx

How to detect UTF8 encoded text

February 6, 2010

What is UTF8 encoding and how to detect it?

You can find UTF8 specification documents at the end of this post.

The long story short UTF8 is a unicode text representation that may use one to four bytes to represent a single text character.

How to detect it?
First the easy solution would be to check for the Byte Order Mark at the beginning. For UTF8 it is: ef bb bf.
However a lot of UTF8 files do not use it and generally Unix/Linux programs do not ust UTF8 with BOM and some of them may not handle it well.

So how to detect UTF8 without BOM?

Basically check up the file if it only contains byte sequences list in the following table:

00..7F	 	 	 
C2..DF	80..BF 	 	 
E0	A0..BF	80..BF 	 
E1..EF	80..BF	80..BF 	 
F0	90..BF	80..BF	80..BF
F1..F3	80..BF	80..BF	80..BF
F4	80..8F	80..BF 	80..BF

I have created little c# library that does exactly this:
http://www.codeplex.com/utf8checker

There are unit tests too using some extensive utf8 sample files.

Feedback and questions welcome!

Rerefences

http://www.unicode.org/versions/corrigendum1.html

http://www.ietf.org/rfc/rfc2279.txt

http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335

http://www.cl.cam.ac.uk/~mgk25/unicode.html

Unit Tests 101 – how to write testable code

November 22, 2008

Reposting this entry I wrote for my company’s blog

Hi, I am Test Engineer at AutoScout24 in Munich and will be writing about Unit Tests, testability, Acceptance Tests and developing high quality software. In this post I want to go in go into the testability topic – what makes code testable and what not. It may seem obvious how to do it for the people, that are going the TDD way, but sometimes it is hard for new developers to adopt the art of writing Unit Tests.
Writing Unit Tests is all about being able to use the classes you develop in isolation, without having to instantiate their external dependencies, or a database, filesystem, webserver or something else running.
So it all boils down to the question – how to make the class dependencies exchangeable. Let’s assume we have the following code:

Code:

public class ClassInTest {
 public bool DoStuff() {
   IExternalDependency dependency = new ExternalDependency(...);
   return dependency.Something();
 }
}

Unit Test:
impossible to write

For this example we have pretty simple code to test and just want to concentrate in making it testable.
The main issue with this code is that, the class instantiates the ExternalDependency by itself. Considering that when writing an Unit Test we are interested in the functionality of ClassInTest only, we would like to ignore the ExternalDependency and replace it with some kind of fake implementation

The first approach would be to encapsulate the object instantiation with a static method within the class.

Code:

public class ClassInTest {

  static IExternalDependency dependency;

  public static IExternalDependency CreateExternalDependency(...) {
    if(dependency == null) {
      dependency = new ExternalDependency(...);
    }
    return dependency;
  }

   public static void SetExternalDependency(IExternalDependency aDependency) {
     dependency  = aDependency;
   }

   public bool DoStuff() {
     IExternalDependency dependency = CreateExternalDependency(...);
     return     dependency.Something();
   }
}

Unit Test:
public class ClassInTestTest {
  public void DoStuffTest() {
    IExternalDependency mock = new Mock<IExternalDependency>();
    mock.Expect(x => x.Something()).Returns(true);
    ClassInTest.SetExternalDependency(mock.Object);

    ClassInTest classInTest = new ClassInTest();
    Assert.IsTrue(classInTest.DoStuff());
  }
}

To go one step further we could write a class responsible only for object creation – a factory.

Code:

public class ClassInTest {

  public bool DoStuff() {
    IExternalDependency dependency = CreateExternalDependency(...);
    return     dependency.Something();
  }
}

public class ClassInTestFactory {
  static IExternalDependency dependency;

  public static IExternalDependency CreateExternalDependency(...) {
    if(dependency == null) {
      dependency = new ExternalDependency(...);
    }
    return dependency;
  }
}

  public static void SetExternalDependency(IExternalDependency aDependency) {
    dependency  = aDependency;
  }
}

Unit Test:
public class ClassInTestTest {
  public void DoStuffTest() {
    IExternalDependency mock = new Mock<IExternalDependency>();
    mock.Expect(x => x.Something()).Returns(true);
    ClassInTestFactory.SetExternalDependency(mock.Object);

    ClassInTest classInTest = new ClassInTest();
    Assert.IsTrue(classInTest.DoStuff());
   }
}

This way we have clean separation between classes, that know how to create objects and classes who do the actual work. As a side effect we have to write a factory class for every second class in the application.

The last and clearly the best approach we are going to examine is the dependeny injection path – let all the wiring work to an external container, which knows how to create all registered classes and do not bother writing code for this yourself, be it a static method within the class or factory. The point is to have each class to declare its dependencies in the constructor or as properties

Code:

public class ClassInTest {
  public ClassInTest(IExternalDependency dependency) {
    this.dependency = dependency;
  }

  public bool DoStuff() {
    return     dependency.Something();
  }
}

Unit Test:
public class ClassInTestTest {
  public void DoStuffTest() {
    IExternalDependency mock = new Mock<IExternalDependency>();
    mock.Expect(x => x.Something()).Returns(true);

    ClassInTest classInTest = new ClassInTest(mock.Object);
    Assert.IsTrue(classInTest.DoStuff());
  }
}

This is clearly less code and makes it easier to test, the important thing is to examine the client code – how is ClassInTest used in production, without the container:

Client Code without usage of dependency injection container:

ClassInTest classInTest = new ClassInTest(new ExternalDependency());

In real life when you have a lot of dependencies, each of them having a lot of other dependencies it is very hard burden to pass all the arguments by yourself. Let the container do it for you.

Client with dependancy injection:

ClassInTest classInTest = container.Resolve<ClassInTest>();

Notice that you don’t have to bother what does the ClassInTest need to be instantiated. The “magic” is that IExternalDependency is registered within the container, so we just request some object and let the container do the heavy lifting – examining what constructors it has and resolving the needed arguments.

If are you looking for dependency injection container you can try AutoFac, Castle Windsor, StructureMap or Microsoft Unity, just to name a few.

It is not always possible to switch to dependency injection in a large project – then factories are you best choice. But keep in mind, that dependency injection is the way to go and do your best to prepare your project for it.

Happy programming!

GUIDs, their representation and Base64

February 26, 2008

Everyone knows what a GUID is – 128 bit number, that is supposed to be global unique and it is used for identifier for different types of objects, COM objects most notably.
Usually they are formatted as hex string like {F7F052A2-8BC7-4b84-8330-228BCA8A6E19}. A tool for
creating guids can is guuidgen.exe, there are also System.Guid class and CoCreateGuid API.
Sometimes GUIDs have to be formatted more compactly, for instance in the IFC Specification GUIDs have to be formatted as Base64, making them string with 22 characters length.
Sadly the base64 encoding is non-compatible with the .NET implementation, which makes it a hard task to convert System.Guid object to required format.
IFC Base64 is using 0-9A-Za-z_$ characters and .NET implementation is using something like A-Za-z0-9 for encoding table.
There is some sample C code on the ifc wiki site, so I went for the easy solution – make a dll and call it from .NET.
The problems with this approach kept comming one after another – mostly dll was not always found in Web scenario, due to deployment issues. But there are also other possible hurdles – 64bit migration, deployment on Mono and so on.
So I needed a pure managed implementation of Base64 encoding for GUIDs.
Some googling brought me to sample code, that I adjusted it to the spec and here is the solution:

public class Managed {

  public static string GetId(Guid guid) {
    return ToBase64String(guid.ToByteArray());
  }

  public static string GetId() {
    return ToBase64String(Guid.NewGuid().ToByteArray());
  }

  public static readonly char[] base64Chars = new char[]
  { '0','1','2','3','4','5','6','7','8','9',
  'A','B','C','D','E','F','G','H','I','J','K','L','M',
  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  'a','b','c','d','e','f','g','h','i','j','k','l','m',
  'n','o','p','q','r','s','t','u','v','w','x','y','z',
  '_','$' };

  public static string ToBase64String(byte[] value) {
    int numBlocks;
    int padBytes;

    if ((value.Length % 3) == 0) {
      numBlocks = value.Length / 3;
      padBytes = 0;
    } else {
      numBlocks = 1 + (value.Length / 3);
      padBytes = 3 - (value.Length % 3);
    }
    if (padBytes < 0 || padBytes > 3)
      throw new ApplicationException("Fatal logic error in padding code");

    byte[] newValue = new byte[numBlocks * 3];
    for (int i = 0; i < value.Length; ++i)
      newValue[i] = value[i];

    byte[] resultBytes = new byte[numBlocks * 4];
    char[] resultChars = new char[numBlocks * 4];

for (int i = 0; i < numBlocks; i++) {
  resultBytes[i * 4 + 0] = 
       (byte)((newValue[i * 3 + 0] & 0xFC) >> 2);
  resultBytes[i * 4 + 1] =
       (byte)((newValue[i * 3 + 0] & 0x03) << 4 |
       (newValue[i * 3 + 1] & 0xF0) >> 4);
  resultBytes[i * 4 + 2] =
        (byte)((newValue[i * 3 + 1] & 0x0F) << 2 |
        (newValue[i * 3 + 2] & 0xC0) >> 6);
  resultBytes[i * 4 + 3] =
        (byte)((newValue[i * 3 + 2] & 0x3F));
 }

 for (int i = 0; i < numBlocks * 4; ++i)
   resultChars[i] = base64Chars[resultBytes[i]];

   string s = new string(resultChars);
   return s.Substring(0, 22);
 }
}

So if you have to encode something as Base64 or deal with GUIDs with one way or another – this may be helpful to you.
Original code by James McCaffrey (more…)