Babylon.NET - translating software made easy

A friend of mine (and former boss… oh yeah, quite some time ago), Martin Geier, wrote a nice application that allows you to translate .NET resources from one language to another. The program is called Babylon.NET and has been released at redpin.eu.

The application targets one specific problem: translation of applications. I don’t know how often you had to do that but I’m from a region where a lot of people speak German and Italian. We, therefore, know both languages and have the benefit of publishing software for both languages. But translating software (even that it has gotten better with the advent of Visual Studio .NET, 2005, 2008) is still a very tedious and error-prone task.



Babylon.NET focuses on .NET projects created in Visual Studio. It offers features that are tailored to support developers or translators during their tasks while translating projects hat have been created in Visual Studio and are managed with Visual Studio. Some of these features are:

  • Directly reads Visual Studio project files to start a new translation project.
  • Synchronizes changes in the Visual Studio project with the translation project at any time.
  • Writes localized resource strings directly to the Visual Studio resource files.
  • Keeps track of the translation status for every single resource string in every locale.
  • Supports the reviewing process of the localization by keeping track of the quality status for every single recource string in every locale.
  • Automatic verifier checks for common problems during localization such as inconsistent translations, string.Format placeholder errors or punctuation errors.
  • Separate, restricted “Translator” editition can be given to every translator working on the project.
  • Offers a modern, simple and intuitive user interface tailored to the localization process.

These are only some of the interesting features in Babylon.NET that you might find interesting when translating a piece of software. For more information please visit the website at redpin.eu. They have also a trial version for download. :)

Published on Aug 31st, 2008 — Tags: , , , ,
Comments (1)    digg it!    kick it   

Implementing the IDisposable interface

First it seems that the IDisposable interface is really easy to implement. It has only one method and how hard could it be to implement one method?! Soon after the first random exceptions happen you might realize that the IDisposable interface is a tough one.

There are a few things that should be considered when implementing the destruction process of a .NET class:

  1. Make sure you have a destructor in the class: to ensure that unmanaged resources get cleaned up.
  2. Try to follow a pattern that you can easily apply to all the various classes that need disposal.
  3. Try to follow the guidelines for the .NET IDisposable interface.

Looking at the samples you will see that Microsoft usually implements a method that can be called form both, the destructor and the IDisposable’s Dispose method. I usually follow that and create a second (and private; could also be protected) Dispose method that takes an argument saying it was called from the destructor or the IDisposable’s Dispose.

In that overloaded Dispose method I make sure that during a call from the destructor no managed class gets touched at all. That’s important because during garbage collection managed class instances get destroyed in a random order. It’s not guaranteed that any of the managed instances that you hold inside your class (as class fields) is still alive during a destructor call. This is one of the most important things to keep in mind when implementing the IDisposable interface.

I pointed out “managed classes” because pointers to native code are still alive (the GC ignores them). You need to manually clean them up inside of the overloaded Dispose method.

My code snippet for an implementation looks like this:

public sealed class Foo : IDisposable
{
    // this field is true when the class has been disposed.
    private bool _disposed;

    /// <summary>
    /// Destructor of the Foo Class.
    /// </summary>
    ~Foo()
    {
        // call the dispose method with false since
        // the garbage collector is destroying the
        // instance.
        Dispose(false);
    }

    /// <summary>
    /// Disposes the current instance of the class.
    /// </summary>
    /// <param name="disposing">True when this method is
    /// called form the dispose method of IDisposable.</param>
    private void Dispose(bool disposing)
    {
        // return if this instance is already disposed.
        if (_disposed)
            return;

        if (disposing)
        {
            // it is save to access member variables (class fields)
            // inside of this block. This block is only entered
            // when the Dispose method of IDisposable is invoked.
            // you should dispose (call the Dispose method) of
            // member variables (class fields) inside of this block.
        }

        // outside of the "disposing" block it is only save to
        // release native (unmanaged) resources. If you have
        // class fields holding a pointer to a native piece
        // of memory you can safely free that.

        // it is not save to access other managed classes from
        // here. They might have been destroyed by the garbage
        // collector already! There is no way to force the GC
        // to destroy objects in a certain order.

        _disposed = true;
    }

    #region IDisposable Members

    /// <summary>
    /// Disposes the current instance of the class.
    /// </summary>
    public void Dispose()
    {
        // call the dispose method with true, since
        // we are inside the Dispose method of IDisposable.
        Dispose(true);

        // make sure the GC is not going to call the destructor
        // of this class again. This saves time during garbage
        // collection.
        GC.SuppressFinalize(this);
    }

    #endregion
}

Published on Aug 24th, 2008 — Tags: , ,
Comments (9)    digg it!    kick it   

Chris at the profs: Compilers, Languages and the Future

A few days ago - while being on the road for our Academic Community Launch - Mario, Alex and I had the chance to speak with Hanspeter M?ssenb?ck, professor at the University of Linz, and Markus L?berbauer, who is an assistant at the university.

During the interview we have spoken about languages, compilers, the work at university and what is going to come up in the future. Prof. M?ssenb?ck and Mr. L?berbauer also gave us information on what students should study to be ready for the future.

Tune in if you are interested in languages, compilers, the .NET Framework and JAVA.

Published on Apr 16th, 2008 — Tags: , , , ,
Comments (0)    digg it!    kick it   

Adding some dynamic to C#: interface wrapping

C# is not a dynamic language. That’s for sure! Recently, the adding of the var keyword, anonymous types and lambda expressions have added some “dynamic” to the language. But still it’s not a dynamic language.

I have heard people saying that C# is never going to be a dynamic language. But it seems as if the next version is going to add more dynamic to the language.

C# being completely static sometimes bothers me; it’s not that often but sometimes I would like to do something and it’s only possible with a lot of walk arounds and sometimes even minor hacks. One thing, for example, is that you can’t really return an instance of a anonymous type from a method without doing a little bit of weird looking hacking (greetings to Tomas; it was cool to chat with you in the metro at the end of TechEd).

Wouldn’t it be cool if an anonymous type could be wrapped into an interface and you could return that? Also, wouldn’t it be cool to wrap any type (also the one that are part of the .NET Framework) into an interface; independent of the type implementing that interface. Let’s say you have objects that implement a Close method and you want to define an interface called IClosable. Now if a class implements the Close method you want to wrap it into the IClosable interface and store all these instances in a Dictionary for later usage.

With C# you can’t do that because it’s not possible to cast an object to an interface if not implemented.

Still that feature would be interesting to have in some scenarios and that’s why I implemented a class that enables that. In enables you to wrap any class into an interface, when the class implements the methods and properties that are required by the interface. The class doesn’t need to implement the interface!

public interface IFoo
{
    string Name { get; }
    int Age { get; }
}

class Program
{
    static void Main(string[] args)
    {
        IFoo foo = CreateDynamicType();

        var name = foo.Name;
        var age = foo.Age;

        // output the results.
        Console.WriteLine(name + ” “ + age);
    }

    public static IFoo CreateDynamicType()
    {
        // create the anonymous type.
        var f = new { Name = “Test”, Age = 100 };

        // wrap the interface around the type.
        IFoo foo = f.WrapIntoInterface<IFoo>(false);
        if (foo == null)
            throw new Exception(“Houston, we’ve had a problem.”);

        return foo;
    }
}

The example shows the wrapping of an anonymous type into the IFoo interface.

Making this work involves a little bit of magic and some deeper knowledge of the CLR and IL. The .NET Framework offers in the System.Reflection.Emit namespaces classes that allow creating assemblies, modules, types, methods, properties etc. during runtime. I have used these classes to create the solution.

If the user wants to wrap a class with an interface a new in-memory class is generated and that new class implements the required interface. The generated class has also a constructor that takes the original class as argument. If one of the interface methods or properties are invoked the call is forwarded to the inner class.

The in-memory generated class for the example before looks like this:

// This class implements the IFoo interface and
// wraps the original instance.
public sealed class <>f__AnonymousType0`2<>IFoo__$wrapper$! : IFoo
{
    // The original instance.
    private <>f__AnonymousType0<string, int> _original;

    // The constructor takes the original instance.  In this case an
    // instance of the anonymous class.
    public <>f__AnonymousType0`2<>IFoo__$wrapper$!(
        <>f__AnonymousType0<string, int> type1)
    {
        this._original = type1;
    }

    // other methods, like Equals, ToString etc.; collapsed.

    // The property calls are forwarded to the original object.
    public override int Age
    {
        get { return this._original.Age; }
    }

    public override string Name
    {
        get { return this._original.Name; }
    }
}

I’m cheating a little bit under the covers by creating this dynamic class; C# hasn’t become dynamic from the sudden. But creating the in-memory class does the job very nicely and the user doesn’t see it.

To enhance speed I’m also adding the generated types to a dictionary. That increses speed because for further requests the type can be reused and doesn’t need to be generated again.

This approach could also be extended to enable aspect-oriented programming for C# or .NET in general. The idea would be to add call backs before and after the method/property/etc. calls are forwarded to the inner (wrapped) class.

Interesting in playing with this code? Click here to download the full source code (including the example of this post).

Published on Mar 21st, 2008 — Tags: , , ,
Comments (4)    digg it!    kick it   

Writing data to an XML file in Visual Basic 9 (Part 4) - Separating the logic from the UI

The discussion, over at Channel 8, is getting more interesting. Alex is now asking me how to separate the UI from the business logic:

Now I’m just working on customizing the interface and this guy called Eric Seib said I should remove what code I can from the interface into seperate code files so I will start on that. I tried before but I kept having issues because as you know most of the code accesses text boxes on the form so it has to be there :| what do you think? Is it worth removing what code I can from the interface?

I haven’t done this in the previous posts because these are just samples. I didn’t separate the logic from the UI and add much error handling (and other stuff) for the sake to keep the code simple and easy to understand.

Now, for this blog post and to answer the question from Channel 8 I have decoupled the logic from the UI. Everything that is application logic has been moved to so called business objects. I have also tried to follow some common guidelines and therefore tried to stay a little bit conform with design patterns.

This is what I have done; in the form of a class diagram:

I have created a new class called “User”. I didn’t come up with a better name because I don’t know what Alex’ application is going to do: so I named it User. As you can see this class has some methods to load, save and delete itself. All the logic that’s relevant to the class is found in the class itself. It exposes also all the relevant information, such as FirstName, LastName, Location, etc., via properties.

To make it more convenient to load a list of “users” I have implemented the “UserLoader”. This class has just one method: LoadAll. The method loads all User objects that are found in the data path.

And last but not least the Settings class holds the data path information. It holds a property that returns the path to the xml files (the user xml files).

An updated version of the project can be downloaded from here.

Published on Mar 1st, 2008 — Tags: , , ,
Comments (4)    digg it!    kick it   

Writing data to an XML file in Visual Basic 9 (Part 3)

Over at Channel 8, Alex Mills asked another question:

As you know my program is built and expanded from the code you wrote, very much appreciated. You designed that when you click edit it opens the XML in a new window. Is it possible that when the listview selected index changes, it automatically loads a couple of nodes of the xml to text boxes on the main form. With one click to be used as a quick reference feature, but I still want to have the seperate editor as I dont want have all the text boxes on the main form. Is this possible?

Everything is possible :) As far as I have understood he needs something that looks like this:

To make this possible we first need to put some controls on the form. :) Next, we need to register (actually, we registered it already in the second example, but I didn’t mentioned it explicitely) the SelectedIndexChanged event of the ListView.

This event is always fired when the ListView’s selected item has changed. That applies also if the selection has been changed to no item being selected anymore. That comes in very handy because we want to clear the textboxes when no item has been selected and fill the textboxes when an item has been selected:

Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged

    ‘ enable or disable the buttons whether an item has been selected.
    Button1.Enabled = (ListView1.SelectedItems.Count > 0)
    Button3.Enabled = (ListView1.SelectedItems.Count > 0)

    ‘ check if an item has been selected
    If ListView1.SelectedItems.Count > 0 Then

        ‘ get the item from the list view.
        Dim path = CType(ListView1.SelectedItems.Item(0).Tag, FileInfo)

        ‘ load the preview data.
        LoadPreview(path.FullName)
    Else

        ‘ clear the preview text boxes.
        ClearPreview()

    End If

End Sub

The first two lines in the method are already here from the second sample. They only enable or disable the “Edit” and “Delete” buttons depending on whether an item has been selected or not. The if statement then checks whether an item has been selected. If one has been selected the selected item’s tag is read (remember, from sample two, the tag contains our file information object) and feed into a new method that is called LoadPreview. LoadPreview is for the most part only a copy of the code that is used in the constructor of the edit form and looks like this:

Private Sub LoadPreview(ByVal path As String)

    ‘ make sure that a path has been given
    If path = Nothing Then
        Throw New ArgumentNullException(“path”)
    End If

    ‘ load the xml document from the given path
    Dim xml = New XmlDocument()
    xml.Load(path)

    ‘ get the different nodes from the xml file and put them in the text boxes.
    ‘ ATTENTION: here should also added a check for the values being Nothing.
    Dim firstName = xml.SelectSingleNode(“//firstname”)
    TextBox1.Text = firstName.InnerText

    Dim lastName = xml.SelectSingleNode(“//lastname”)
    TextBox2.Text = lastName.InnerText

    Dim location = xml.SelectSingleNode(“//location”)
    TextBox3.Text = location.InnerText

End Sub

We get the path as argument of the method and load the XML file. After that we use some XPath to get the values in the XML file and put them in the different textboxes.

The ClearPreview is very simple and looks like this:

Private Sub ClearPreview()

    ‘ set all text boxes to an empty string.
    TextBox1.Text = String.Empty
    TextBox2.Text = String.Empty
    TextBox3.Text = String.Empty

End Sub

The full source code of the sample can be downloaded from here.

Published on Feb 28th, 2008 — Tags: , , ,
Comments (3)    digg it!    kick it   

Writing data to an XML file in Visual Basic 9 (Part 2)

Yesterday I have posted a blog post to answer a question that has been asked in the Channel 8 forums. The question was: “How can I save some values in text fields (on a form) as XML to the disk?”. After having written the blog post the guy asked me if he could also ask me further questions on the topic and I agreed.

So the next questions that came up in the forums are the following (summed up because the post is to long to be quoted):

  • How can I write an XML file to the Windows’ User folder? How do I get this folder?
  • How can I create an own folder with .NET?
  • How can I load the XML file again?
  • How can I show a list with all the files the folder holding my XML files?

Getting the Windows’ User folder is rather easy because the .NET Framework has a class called Environment. The class has a method called GetFolderPath that returns the locations of so called “special folders”. The Windows’ User folder is such a special folder.

Writing the XML file to that given path looks like this:

‘ create the file name. use the GetFolderPath to get the folder of my documents.
Dim path = New DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & “\Waterpoints\”)
‘ if the path doesn’t exist create it.
If Not path.Exists Then
    path.Create()
End If

‘ create the file name from the path and the text box value.
Dim fileName = System.IO.Path.Combine(path.ToString(), firstNameTextBox.Text & “.xml”)

‘ compile the xml.
Dim xml = <?xml version=“1.0″ encoding=“utf-8″?>
          <userrecord>
              <firstname><%= firstNameTextBox.Text %></firstname>
              <lastname><%= lastNameTextBox.Text %></lastname>
              <location><%= locationTextBox.Text %></location>
          </userrecord>

‘ write the xml to the file.
xml.Save(fileName)

This code snippet addresses also the second question. There is a line in the code that checks whether the path already exists. If that’s not the case the Create method on the path is executed to create the directory. .NET makes creating paths really easy :)

The next question was on how to load an XML file. The .NET BCL (Base Class Library) offers a class that’s called XmlDocument. That class allows loading XML files and to search within the loaded files. XmlDocument creates a so called DOM while loading the file. A DOM is a structure that allows navigating and searching.

‘ load the xml document from the given path
Dim xml = New XmlDocument()
xml.Load(path)

‘ get the different nodes from the xml file and put them in the text boxes.
‘ ATTENTION: here should also added a check for the values being Nothing.
Dim firstName = xml.SelectSingleNode(“//firstname”)
firstNameTextBox.Text = firstName.InnerText

Dim lastName = xml.SelectSingleNode(“//lastname”)
lastNameTextBox.Text = lastName.InnerText

Dim location = xml.SelectSingleNode(“//location”)
locationTextBox.Text = location.InnerText

For the search part I’m using XPath. XPath is a handy query languages for XML files that searches within the DOM. The code doesn’t do any error handling. In the case of the XPath queries you sould always check if a result is returned. If the query doesn’t find an item this results in returning an object that is Nothing.

The last question was on how to show a list of XML files in a list view. For that I have created a new form: the MainForm. This form holds only a ListView and 3 buttons: one to create a new XML file, one to edit and one to delete an XML file.

The code to load the list looks like this:

Private Sub LoadFiles()

    ‘ remove all items in the list view.
    ListView1.Items.Clear()

    ‘ get the directory. if it does exist get the files from there.
    Dim directory = New DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & “\Waterpoints”)
    If directory.Exists Then

        ‘ get all xml files in the given directory.
        Dim files = directory.GetFiles(“*.xml”)

        ‘ loop over the files and add them to the list view.
        For Each file In files
            Dim listItem = New ListViewItem(Path.GetFileName(file.FullName))
            listItem.SubItems.Add(file.FullName)
            listItem.Tag = file

            ListView1.Items.Add(listItem)
        Next

    End If
End Sub

This code is a little bit more complex. The complex part is how to fill the ListView with data. The ListView expects a ListViewItem. I set the Text property on that item (via the constructor) to the name of the file (without directories; the Path class offers useful methods to extract different parts of a path) and the first sub item to the FullName of the file (the FullName includes also the directories).

I have also set the file as “tag” of the ListViewItem. That’s handy because later when one of the items is selected I can retrieve the original file object from the tag. You can see the tag as a pocket where you can put one additional object in.

savetoxml2.png

I have also added more code (found in the sample sources) that enables and disabled the edit and delete button depending on whether an item has been selected in the list view.

The full source code of the sample can be downloaded here.

Side note: The example contains no error handling. I haven’t added that because the code gets a lot longer when doing error handling. Error handling should be added to the final application to make it more robust. For an introduction on how to do error handling in VB.NET click here.

Published on Feb 24th, 2008 — Tags: , , ,
Comments (9)    digg it!    kick it   

When even the Dictionary is to slow…

Most people who are developing in .NET will have used the Dictionary<K, V> class that has been introduced with .NET 2.0 or even the Hashtable class that came with .NET 1.0. And therefore they will be familiar with the code for looking up data in the hash table:

// initialize the dictionary.
Dictionary<string, object> dictionary = // some dictionary.

object value = null;
// try to get the value and store it into the value variable.
if (!dictionary.TryGetValue(key, out value))
{
    // we were not able to get the value. do something.
}

You probably consider this code to be fast because hash tables have an average lookup time of O(1):

Hash tables support the efficient insertion of new entries (O(1)), and the time spent searching for the required data is often independent of the number of items stored (O(1) on average).

Therefore you might never have explicitely measured the speed of the Dictionary or Hashtable classes.

I didn’t measure it neither, until I once attached a profiler to one of my projects that heavily relies on data that is stored in a hash table (the hash table is used as cache in my scenario). And it was so damn slow! Fetching the data from the dictionary was faster than using a linked list or even an array. But it was slow and a bottleneck in my application.

I did some analysis and understood that I’m fetching the same item from the dictionary several times in sequence. The only problem why I couldn’t pass it around was that I needed it in different parts of the application. These parts are independent of each other and I couldn’t pass the item (from the hash table) from one class to another because the items are internal information and shouldn’t be part of any method calls.

My solution was to store the last item and its key somewhere in my cache class (outside of the hash table). Now, when a request for an item comes in, the class checks the key against the key of the last item. If they match the last item is returned and the items is never looked up in the hash table.

internal sealed class Cache
{
    private Dictionary<string, object> _cache =
        new Dictionary<string, object>();
    private string _key = null;
    private object _value = null;

    public void Add(string key, object value)
    {
        _cache.Add(key, value);
    }

    public object Get(string key)
    {
        // check if the keys match.
        if (_key == key)
            return _value;

        // get the value if the keys didn’t match.
        object value = null;
        _cache.TryGetValue(key, out value);

        // store the current item as last item.
        _key = key;
        _value = value;

        return value;
    }
}

This change gave me an incredible speed improvement and made me look different at the classes that come with the .NET framework. They are probably implemented in the best way they could but you should always think how you could improve the code in your current scenario and not only rely on the implementation that comes with the framework.

Published on Feb 21st, 2008 — Tags: , ,
Comments (3)    digg it!    kick it