## The old plain C language

A friend of mine is taking a basic course in computer programming, and actually he is studying the basic of C language. Yesterday he told me that he must do a very simple exercise that will print on screen a triangle like this
XXXXXXXXXX
XXXXXXXXX
XXXXXXXX

And so on. He asked me if I could review his solution before he give his program to the teacher, because he is moving from the old house to a new house and actually he do not have access to a computer to try his solution. This morning I decided to refresh my knowledge of C solving this simple exercise, I must admit that I love C/C++â€¦.I cannot explain but they are really fascinating languages (I love assembly language too)

#includeÂ “stdio.h”
#includeÂ “memory.h”
Â
#defineÂ NUM_OF_CHARSÂ 10
Â
intÂ main()Â {
Â Â Â
charÂ str[NUM_OF_CHARSÂ +Â 1];
Â Â Â
intÂ I;
Â Â Â memset(str,Â
‘X’,Â NUM_OF_CHARS);
Â Â Â
forÂ (IÂ =Â NUM_OF_CHARS;Â IÂ >Â 0;Â –I)Â {
Â Â Â Â Â Â str[I]Â =Â
‘\0’;Â
Â Â Â Â Â Â printf(
“%s\n”,Â str);
Â Â Â }Â
}

The ability to manage memory of a string is one of the feature that I missed most when I program in C#.

Alk.

## 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

Â

## 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]
Entity ent = new Entity();
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();
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();
LangCode.It, new EntityResources(“Nome”, “Descrizione”));
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();
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.