Difference between C# and VB, simple add

Sometimes differences between C# and VB could be subtle, for example consider these very simple two snippets of code, what they will print?

   Sub Main()
      Console.WriteLine(
“Result is “ + Sum(Integer.MaxValue, 1))
   
End Sub
 
   
Public Function Sum(ByVal a As Integer, ByVal b As Integer)
      
Return a + b
   
End Function

   static void Main(string[] args) {
      
Console.WriteLine(“Result is “ + Sum(Int32.MaxValue, 1));
   }
 
   
public static Int32 Sum(Int32 a, Int32 b) {
      
return a + b;
   }

The first snipped written in VB throws a System.OverflowException, because the result of the operation cannot be stored into an integer value. The behavior of C# can be more surprising because it print Result is -2147483648 showing a result that is clearly wrong. This example shows that VB and C# have very different semantic even for basic operation. But what is the reason for such a different behavior? If we look at MSIL code we can see that VB compiler produces this code

    L_0002: ldarg.1 
    L_0003: add.ovf 
    L_0004: box int32 
 
As you can see the add operation gets translated with opcode add.ofv, where ofv means overflow. This particular operation throws an exception if the result of the operation will result in a overflow. C# generates this snippet.

    L_0002: ldarg.1 
    L_0003: add 
    L_0004: stloc.0

Generated MSIL is different because C# compiler use the add
opcode that will not check for an overflow. The question is: why such different behavior? VB.NET descends from VB6 where all arithmetic operations are checked, so this semantic is maintained even if for .NET version, C# descends from C++ where aritmetic operation does not check for an overflow. The primary reason is efficiency, let’s look at real IA32 code generated by the JIT compiler through disassembly window. This is the assembly generated for the add.ofv opcode (VB).

        Dim result As Integer = a + b
0000002e  mov         eax,ebx 
00000030  add         eax,dword ptr [ebp-40h] 
00000033  jno         0000003A 
00000035  call        79747E72 
0000003a  mov         dword ptr [ebp-44h],eax

After the add operation there is a jno opcode that means “Jump if not overflow“, if the operation will result in a overflow, the instruction does not jump and instruction at offset 35 calls a system routine that will throw the exception. The cost of checking overflow is a branch instruction after every arithmetic operation, for this reason C# compiler does not insert overflow check instruction for arithmetic operation. If you don’t like this, you can force C# compiler to insert overflow checking instruction with checked keyword

checked {
   
return a + b;
} 

With the checked keyword we can choose to do checked operation only for specific parts of the code. VB is less flexible, because has a compiler operation that will disable overflow check for all the assembly, not showing the granularity of C#.

Alk.

Localizable Entities With Nhibernate Part 3

Now that the Entity object works as expected the only issue remaining is the integration with NHibernate. First Step is creating mapping file to store the object in the database. Database structure is very simple, just a table for the Entity class plus another table for localized resources.

Against this database schema we can map the Entity class with this mapping file.

<?xml version=1.0 encoding=utf-8 ?>
<hibernate-mapping xmlns=urn:nhibernate-mapping-2.2 
                  assembly=Example1 
                  namespace=Example1 
                  default-lazy=false>
   <class name=Entity table=Entity>
      <id name=Id unsaved-value=0>
         <generator class=native />
      </id>
 
      <property name=SomeCode column=somecode type=Int32 />
      <map name=Resources table=EntityResources lazy=false fetch=join>
 
         <key column=entityid />
         <composite-index class=Registry.LangCode, Registry>
            <key-property name=Code column=langcode access=property />
         </composite-index>
 
         <composite-element class=EntityResources>
            <property name=Name column=name />
            <property name=Description column=description />
         </composite-element>
      </map>
   </class>
</hibernate-mapping>

Dictionary properties are mapped with the element <map> on the database table EntityResources, then we needs to specify the key tag that contains the foreign key, in our model the column entityid. Keys of the dictionary are instances of LangCode class, so we need to specify a <composite-index> tag with class attribute, inside the composite-index nhibernate we need to specify which columns of the table are used to build the key part of the dictionary with the element <key-property>. In this example the LangCode is composed only by language code, so it maps to the single column langcode. For the element we needs also to specify a <composite-element>, but now this class maps to the two column Name and Description of the table. This completes the mapping.

To conclude this tutorial it is interesting to show some HQL queries that can be used to manage this particular entity. A main disadvantage of this mapping scheme is that when we load a list of Entity objects used only to show data to the user, each instance of the Entity class will contains all resources for each language supported, this waste a lot of memory and also retrieve too much data from database. If we are sure that all the objects have resources for current language, and the current language will not change for the lifetime of the object, we can do a HQL query to retrieve only the resource for current language, this avoid to load localization data for language that will be not necessary.

from Entity as E left join fetch E.Resources as res where INDEX(res) = ‘it’

This query uses the special syntax INDEX() that permits to specify criteria for the key of a dictionary. The purpose of this query is to retrieve all entities but only with the ‘it’ resource. The left join fetch is used to use an eager fetch strategy, if a simple join would be used, NHibernate would have done a first select to retrieve the entity list, and subsequently a single select for each entity to retrieve the resource corresponding to ‘it’ language.

As usual you can search inside the description or name property, but you must pay attention. A query like this

select distinct from Entity as E join E.Resources as res where res.Description like ‘des%’

actually search for entities that have one of its localization resource with a value like des%. Suppose that an entity has two resources: the ‘it’ has Description property equal to “Descrizione” and ‘de’ has Description property equal to “Schilderung”. If current language is de and you run the previous query, the previous entity is returned, because it has the ‘it’ resource that satisfy the match, but when you show the Description property to screen it shows “Shilderung” because ‘de’ is the current language. This kind of experience can be frustrating for the user that really does not understand why this object had matched the filter. To avoid this problem the INDEX(res) = :langcode filter should be included for each query that does a filtering on localizable properties of the entity.

For those interested in performances, the previous HQL query produce this SQL (Captured with profiler)

select distinct entity0_.Id as Id0_, entity0_.somecode as somecode0_ 

from Entity entity0_ inner join EntityResources resources1_ on entity0_.Id=resources1_.entityid 

where (resources1_.description like ‘des%’)

As you can see the query is efficient because it join directly the two tables and does not suffer for the n-select problem. Please do not forget to use select distinct on HQL query because if it’s not specified and an entity has more than one resource that matches the filter, the query returns duplicate results.

I hope this little tutorial can help anyone that needs to use localizable entities with NHibernate.

Alk.

Localizable entities with Nhibernate Part 1

Localizable entities with Nhibernate Part 2

Example Code.

Â

Localizable entities with Nhibernate part 2

After the creation of Registry pattern I need to create a localization scheme that will satisfy the remaining points of the list; first of all I write some tests following the best practices of Test Driven Development. The class under test will be called Entity, and has an integer property and two string properties that are to be localized. The scheme I used to localize the entity is to enclose all localizable properties in a different class called EntityResources, and storing all resources of an Entity instance through a simple IDictionary<LangCode, EntityResources>. This scheme has the advantage to be enough flexible to satisfy all my requirements, while keeping the class simple. The first test checks that a single localization is handled correctly

[Test]
public void TestAddLocalization() {
Entity ent = new Entity();
ent.AddResource(
LangCode.En, new EntityResources(“Name”, “Description”));
Registry.
InstanceRegistry.CurrentLangCode = LangCode.En;
Assert.AreEqual(“Name”, ent.Name);
Assert.AreEqual(“Description”, ent.Description);
}

Then a couple of test to check that default localization is used when exact localization is not present

[Test]
public void TestDefaultLocalization1() {
Entity ent = new Entity();
ent.AddResource(
LangCode.En, new EntityResources(“Name”, “Description”));
Registry.
InstanceRegistry.CurrentLangCode = LangCode.De;
Assert.AreEqual(“Name”, ent.Name);
Assert.AreEqual(“Description”, ent.Description);
}
[
Test]
public void TestDefaultLocalizationEnglishDefault() {
Entity ent = new Entity();
ent.AddResource(
LangCode.It, new EntityResources(“Nome”, “Descrizione”));
ent.AddResource(
LangCode.En, new EntityResources(“Name”, “Description”));
Registry.
InstanceRegistry.CurrentLangCode = LangCode.De;
Registry.
InstanceRegistry.DefaultLangCode = LangCode.En;
Assert.AreEqual(“Name”, ent.Name);
Assert.AreEqual(“Description”, ent.Description);
}

The most interesting tests are those used to test transparent localization features such as this one

[Test]
public void TestAutomaticLocalization() {
Entity ent = new Entity();
Registry.
InstanceRegistry.CurrentLangCode = LangCode.It;
ent.Name =
“Nome”;
ent.Description =
“Descrizione”;
Assert.AreEqual(“Nome”, ent.Name);
Assert.AreEqual(“Descrizione”, ent.Description);
Registry.
InstanceRegistry.CurrentLangCode = LangCode.En;
ent.Name =
“Name”;
ent.Description =
“Description”;
Assert.AreEqual(“Name”, ent.Name);
Assert.AreEqual(“Description”, ent.Description);
Registry.
InstanceRegistry.CurrentLangCode = LangCode.It;
Assert.AreEqual(“Nome”, ent.Name);
Assert.AreEqual(“Descrizione”, ent.Description);
}

This test verify that a user can actually set properties of the Entity object without worrying if a suitable localization ResourceEntity already exists on the object. This feature is very useful for my project, but can be a little bit confusing. Let’s make an example: if current language is ‘de’ and the user ask for an object that has no resource for ‘de’ LangCode, the Entity class shows Name and Description properties taking default resource. At this time if the user changes the value of one of these properties a new localization resource gets created for ‘de’ language and added to Entity object transparently. If this is not the behavior you needs, simply disable this feature and throw an exception or permit the user to modify the default resource.

Now it’s time to look at Entity’s code, first of all the class stores all localization resources inside a IDictionary<LangCode, EntityResource>, Name and Description properties simply look for a suitable resource to show to the user.

public String Name {
get { return GetResource().Name; }
set { GetOrCreateResource().Name = value; }
}

public String Description {
get { return GetResource().Description; }
set { GetOrCreateResource().Description = value; }
}

As you can see the getter part of the property calls GetResource() method to find the most suitable resource, while setter part uses GetOrCreateResource() that actually create a new resource if the current language missing it. GetResource() simply check if a resource for the current language is present in the dictionary, if not it calls GetDefaultResource() that simply checks if the dictionary contains the resource for the default language. If the dictionary is empty, GetResource() returns an instance of a default resource.

protected
EntityResources GetResource() {

LangCode locinfo = Registry.InstanceRegistry.CurrentLangCode;
if (mResources.ContainsKey(locinfo))
return mResources[locinfo];
else
return GetDefaultResource();
}

protected virtual EntityResources GetDefaultResource() {
if (mResources.ContainsKey(Registry.InstanceRegistry.DefaultLangCode))
return mResources[Registry.InstanceRegistry.DefaultLangCode];
foreach (KeyValuePair<LangCode, EntityResources> element in mResources) {
return element.Value;
}
return EntityResources.DefaultResource;
}

GetOrCreateResource() is a little bit interesting because it handle transparent localization. It first checks if a resource for the current langcode is present, if not it creates a new EntityResource making a clone of the current resource. This is necessary because if the user change only one property and a new resource needs to be created, the caller should see the other properties unchanged.

protected EntityResources GetOrCreateResource() {
LangCode locinfo = Registry.InstanceRegistry.CurrentLangCode;
if (mResources.ContainsKey(locinfo))
return mResources[locinfo];
else {
EntityResources newResource = (EntityResources) GetResource().Clone();
AddResource(locinfo, newResource);
return newResource;
}
}

That’s all, with this scheme the Entity object now supports the concept of localization and thanks to the registry pattern we can access the current language and the default language from every classes. This scheme has some disadvantages, first of all an Entity object needs to contain all the resources for all languages to support Transparent localization, this approach uses more memory than a plain object. A second issue is that accessing Name and Description properties is slower compared to standard properties implemented with a private field. If performance is a key issue, and if the profiler shows you that the implementation of localized entities really impacts on your performance, you can adopt an internal cache of the resources. The first time that Name or Description properties are called, we store current resource in a private field as well as the current language, at each call we simply check if the language is changed, if not we can return cached resource without incurring in the penality of calling GetResource() or GetOrCreateResource(). My approach is not to worry too much about performance until a profiler shows me where and when the performance are poor and the code needs to be tuned, so previous scheme suits well most of my needs.

In the next part of this tutorial I’ll finally show you how to map this class with NHibernate along with some queries to work with localized objects.

Alk.

Localizable Entities With Nhibernate – Part 1

Localizable Entities With Nhibernate – Part 3

Localizable entities with Nhibernate Part 1

In a recent project I face the need to localize some entity with nhibernate. First of all I found this interesting post of Ayende that show an interesting solution, but it does not fits well in my project. I need a localization scheme with these features.

  • Orthogonal to the user, and completely transparent
  • The user should be able to change localization text
  • The user can choose whathever language he desires, if no suitable localization exists the entity must returns a default localization
  • The user can add a new localization language for the entity even if the language is not actually present.

At first these features seems very complicated, and I begin to work on a possible scheme that satisfies all of them. First of all the concept of current language should be orthogonal to the user, it means that the user should ask nhibernate to load an entity without worrying of the language. This kind of problems can be solved by the Registry pattern from Fowler (POEAA). This pattern description states: “A well-known object that other objects can use to find common objects and services”, this seems to me a suitable pattern to store the concept of “Current Language”. First of all I create the interface of my Registry in another assembly.

public interface IRegistry {
LangCode CurrentLangCode { get; set;}
LangCode DefaultLangCode { get; set;}
}

As you can see this registry has only two property that can be used to get/set the current language and the default language, both of them stored as a custom LangCode object. I prefer to use a LangCode custom object because I’m working with a legacy database that stores lang code strings with char(5) fields, so if I simply use a string to store current lang code I’ll end in comparing “it” with “it ” because the database pads the string with space chars, due to the fact that the fields are fixed length strings. LangCode class is a very straightforward one:

public class LangCode : IEquatable<LangCode> {

internal LangCode() {
}

public LangCode(String langcode) {
mCode = langcode.Trim();
}

public String Code {
get { return mCode; }
set { mCode = value.Trim(); }
}
private String mCode;

#region Static lancode

public static LangCode It = new LangCode(“it”);
public static LangCode En = new LangCode(“en”);
public static LangCode De = new LangCode(“de”);

#endregion

#region IEquatable<LangCode> Members

public bool Equals(LangCode other) {
return String.Compare(this.mCode, other.mCode, true) == 0;
}

public override bool Equals(object obj) {
if (obj == null) return false;
if (obj.GetType() != typeof(LangCode)) return false;
return Equals((LangCode) obj);
}

public override int GetHashCode() {
return mCode.GetHashCode();
}

#endregion
}

I simply implement IEquatable interface and Equals() method, I also trim all lang code so I can use my legacy database that stores codes in fixed length string columns. To access Registry I simply used Windsor container and a static class:

readonly static IRegistry sRegistry = IoC.Resolve<IRegistry>();

static public LangCode CurrentLangCode {
get { return sRegistry.CurrentLangCode;}
set { sRegistry.CurrentLangCode = value; }
}

static public LangCode DefaultLangCode {
get { return sRegistry.DefaultLangCode; }
set { sRegistry.DefaultLangCode = value; }
}
}

This makes possible to use different concrete classes to implement the registry, for example for a web application I can store the current language in user session, while for simple windows application I simply set the language programmatically by code in member variables.

public class WinFormRegistry : IRegistry {

public LangCode CurrentLangCode {
get { return mCurrentLangCode; }
set { mCurrentLangCode = value; }
}
private static LangCode mCurrentLangCode = LangCode.En;

public LangCode DefaultLangCode {
get { return mDefaultLangCode; }
set { mDefaultLangCode = value; }
}
private static LangCode mDefaultLangCode = LangCode.En;
}

With castle Windsor I can specify in the app.config or web.config the right concrete class to use, this makes my Registry very flexible. Now the first point is satisfied, I have a registry that can be accessed from any class that needs to know current language or default languages. In the next post I’ll show you a possible scheme to handle a fully featured localized entity.

Alk.

Localizable Entities with Nhibernate – Part 2
Localizable Entities with Nhibernate – Part 3

Windsor Container, Resolve(IDictionary)

Castle framework is really interesting, but do not forget to checkout current trunk in subversion repository, since it is full of new and exciting features. In a little demo that I’m doing to made a screencast for dotnetmarche community, I show how to structure a simple web page to follow Design For Testability principles, and I made a really basic example of a page with a controller. Since the controller needs to use the session I abstracted the session with an interface

public interface ICustomWebContext {

    void AddToSession(String key, Object value);
    Object GetFromSession(String key);
    void ClearSession();
}

I admit that this is not really an exceptional interface J but it will live only for the sake of my screencast. Using this interface I can abstract the concept of session, so the controller is not forced to run inside a live asp.net application. For the website I plug into controller a simple class that simply stores objects into HttpContext.Current.Session, while for test I can use a simple Dictionary<String, object>. To assemble the object I use Windsor container, since it is lightweight and simple to use, but I need to use the current version in the trunk, since rc2 missed a functionality that I love too much. Here is the problem, page controller has this signature

public Page4Controller(IPageAddition page, ICustomWebContext context) {

it needs an instance of the IPageAddition interface, that abstract the methods of the UI interface and also need a concrete implementation of context. I need to create an instance of the Page4Controller whenever the page needs to perform some operation, and I need to pass the instance of the current page and the context. The page is different at each time while context is a singleton class. First I create a little helper class for Windsor

public static class IoC {

    private static IWindsorContainer _container =
         new WindsorContainer(
            new XmlInterpreter(new ConfigResource(“castle”)));

    public static T Resolve<T>() {
        return _container.Resolve<T>();
    }

    public static T Resolve<T>(string name) {
        return _container.Resolve<T>(name);
    }

    public static T Resolve<T>(params object[] values) {

        System.Collections.Hashtable arguments = new System.Collections.Hashtable();
        for (Int32 I = 0; I < values.Length; I += 2) {
            arguments.Add(values[I], values[I + 1]);
        }
        return _container.Resolve<T>(arguments);
    }
}

This is only a matter of convenience, the third resolve method is the interesting one, because it use container.Resolve<>(IDictionary) method, that is able to construct an object and lets the caller pass some of the dependencies. Caller code creates a Page4Controller object in this way.

Page4Controller controller = WebSite.IoC.Resolve<Page4Controller>(“page”, this);

Caller specify that the page argument should be passed the current instance of the page, while all other argument are passed according to the setting in config file.

<component
   id=PageControllerForPage4
   service=WebLogic3.Page4Controller, WebLogic3
   type=WebLogic3.Page4Controller, WebLogic3
   lifestyle=Transient/>
<
component 
         id=WebContext
         service=WebLogic3.ICustomWebContext, WebLogic3
         type=WebLogic3.StandardWebContext, WebLogic3 
         lifestyle=Singleton/>

Â

As you can see I specifify that the Page4Controller class has a lifestyle of transient, because I need a fresh controller at each page postback and the ICustomWebContext dependency is satisfied by the StandardWebContext class. With this useful feature, we can use object with mixed dependencies, some of them will be resolved by Windsor according to the configuration file, while some others are resolved directly by the caller.

Alk.