Archive for the ‘.NET’ 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

Advertisements

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

BASTA! 2009 Konferenz

February 25, 2009

Diese Woche bin ich auf der BASTA! .NET Konferenz in Darmstadt und ich würde diese Konferenz weiter empfehlen. Es bieten sich einige sehr gute Möglichkeiten sich mit Kollegen auszutauschen und über neue Technologien informieren.

Eine echte Herausforderung bei den meisten Konferenzen ist welche Vorträge man auswählen soll, wenn zu jedem Zeitpunkt 6 gleichzeitig laufen und die Hälfte davon ist interessant und/oder relevant.

Ein Paar Tipss dazu:

  • Der Speaker ist genau so wichtig, wie das Thema, oder sogar noch wichtiger. Ein herrvorragender Vortrag zum “unwichtigen” Thema bring wesentlich mehr,  als  ein schlechter Vortrag  zum top aktuellen Thema
  • Beschränken Sie sich nicht nur auf Technologien, die Sie bei dem jetzigen Job einsetzen, oder einsetzen werden. Ein breites Technologieportofolio gehört zu dem Entwicklerberuf
  • Besuchen Mal eine oder andere nicht technologisch bedingte Präsentation. Kenntnisse in Sachen wie Selbstorganization, Projekt Management, Schätzung sind oft viel wichtiger. Bonus:  Wissen in diesen Bereichen ist auch nach 20 Jahren nicht veraltet.

Back to basics – the law of leaky abstractions

November 30, 2008

Back to basics – the law of leaky abstractions

When developing web applications we use high-level web frameworks and full featured controls that abstract generating the html output for us. It is however always useful to know, that what html gets generated.
Every now that I see ASP.NET code, that uses LinkButton, which posts back to the server just to redirect to the link url, issuing two http requests for something, that can be achieved with a simple html anchor.

Knowing what your framework or compiler generates was always useful. Is it an old saying, that the good C programmer knows the assembly generated by the compiler. These days seeing and understanding the html source, generated from your framework is a lot easier, so do it.

“The law of leaky abstractions” is a classical software development article by Joel Spolsky
http://www.joelonsoftware.com/articles/LeakyAbstractions.html

Dependeny Injection vs Encapsulation

November 24, 2008

Dependency Injection vs Encapsulation

When trying to show coworkers of the advantages of Dependency Injection I often encounter the argument, that it hurts one of the major object-oriented principles – encapsulation.

Let us consider the following basic example of class that has two dependencies, created in the constructor:

public class SomeClass
{
	IWriter writer;
	ILogger logger;

	public SomeClass()
	{
		this.writer = new StreamWriter();
		this.logger = new RegistryLogger();
	}
}

Client code:

SomeClass someClass = new SomeClass();

SomeClass has direct dependencies and can’t be used without them and is clearly not testable. Let us see a implementation with dependency injection:


public class SomeClass : ISomeClass
{
	IWriter writer;
	ILogger logger;

	public SomeClass(IWriter writer, ILogger logger)
	{
		this.writer = writer;
		this.logger = logger;
	}
}

This is clearly much better, but is considered to be violating the encapsulation principle form some developers. Encapsulation principle tells us to hide the class inner workings form the user. This is important in order to allow us to change the class implementation without changing all of its clients. This is a valid point, that I respect, we all strive to the “low maintenance road” (Ayende) – the most important thing in software development.

However let us look at the client code and see if it actually breaks the encapsulation principle:

ISomeClass someClass = Container.Resolve<ISomeClass>();

What we see here is that, the client code does not even know a damn thing about the class dependencies!
We just let the dependency injection container do the heavy lifting for us and don’t worry how to create all of the class dependencies.
In practice we actually do not even have the possibility to use the constructor!
That’s true – in production code instantiating a class from the constructor would require creating all of its dependencies, which would require instantiating their dependencies and so on. It would be safe to say, that the developers can’t even use the constructor and must instantiate their objects using the dependency injection container, which is so much easier.

So the user of the code does not actually even know what kind if dependencies a class has – all of this because of the dependency injection container. So actually instead of breaking encapsulation we are driving it to a whole new level – each individual class does not get to decide what kind of object it needs – everything gets configured in the configuration of the container. This definitely does not break the encapsulation principle. It makes it hold even stronger.

As a side note I want to point out, that I am definitely against the point of view “If you let the developers to bad things, then they will”. If you don’t trust your developers you shouldn’t hire them in the first place. Treat all the of the developers as stars and they will be.

Happy dependent less programming!

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…)