Category Archives: Uncategorized

Have you heard about TypeScript?

JavaScript as a language does not have object-oriented patterns in mind. With this I don’t mean that you can’t write object oriented code, but you have to do it by your own. OO is not part of the language itself. Well, there are many frameworks which jump into this area by bringing some helper functions to get inheritance and all the workarounds needed for OO and modularization stuff. But as a result it blows up the JavaScript code and it gets even harder to read and maintain it.

Is TypeScript a bad idea? I think not, because it adds the syntactic sugar needed to concentrate on the app-logic and takes away the clutter needed for OO/modularization . Take a look to other languages: the language Objective-C extends the C programming language to object-oriented programming language, but it is C-code. Or take a look to C++. It adds object oriented features to the C programming language, so it can include C-code.

So take a step back and think about JavaScript as a language not as a runtime. Then I see TypeScript as the abstraction I’m waiting for a long time. Have a look at the TypeScript code below. On the left side all the OO-stuff and modularization is well abstracted and I can concentrate on the app-logic. On the right side is the code needed for app-logic and OO/ modularization stuff produced from TypeScript compiler. Of course after working for years with JavaScript you might be familiar with the right side also, but maintaining code like this is even hard.




And then there are other features such a type-checking, refactoring, etc. which TypeScript enables since the code contains type information.




My new phone – Nokia Lumia 800

Recently wrote a small windows phone 7 app:

With this app I participated then in the Microsoft Switzerland App Contest and finally won a brand new Windows Phone 7 Nokia Lumia 800.

And today is a lucky day. Here is my new phone. Thanks to Microsoft!




Touch enabled runtime for Windows Slates Apps




Before Microsoft is changing the game next week at BUILD conference in Anaheim, I want to post one of our current developments. Driven by a project need, we have built a real touch enabled windows slate runtime.

The runtime includes:

  • touch enabled date picker
  • touch enabled Combobox with popover selector
  • touch enabled Checkbox with popover selector
  • A virtual touch keyboard which is fully integrated into the runtime in order that the textbox can be correct positioned. So the keyboard will never hide the textbox target. The keyboard provides full input scope for numbers, text and special signs (inspired by the Windows Phone 7 keyboard).
  • A navigation service to move from one to other screens.
  • Metro UI style (not yet finished). We believe Windows 8 will push Metro much more. On the other side, we experienced a much better rendering performance on slates which haven’t that much of CPU and GPU power as on a standard desktop. This allows us to use the runtime on lower equipped hardware too.
  • touch enabled Textbox with select, copy, paste and delete functionality.
  • touch enabled multiline, long-text control which morphs to a larger editor while in edit mode.
  • touch enabled list box which allows for very smooth touch scrolling, including a bounce effect if it reaches the end.
  • Full Screen app style, without windows border and chrome.
  • Message box service
  • And much more….


Deep knowledge in Windows Phone 7 programming allowed us to get the most possible out of WPF in which we have built the runtime, so that the controls and application feels like a real world touch application like other known platforms. We’ve had enough of words. The best way to show our first release is a short video.



Btw. This video was recorded by a Windows Phone 7! Not that bad for a phone.


What’s coming next?

  • Thumbstoning the View State, in order that the user can exit the app at any time and restart it at the position he has left the app (Similar as we know form the Windows Phone).
  • Improving Metro style
  • Adding more controls
  • See what is coming with the Windows 8 announcement next week….
Tagged , ,

Using Google’s LibPhoneNumber in Microsoft.NET with C#

LibPhoneNumber from Google is an awesome library. LibPhoneNumber is a Java, C++ and Javascript library for parsing, formatting, storing and validating international phone numbers. You can input any phone number from over the world and the lib is telling you if the phone number might be valid, from which country the phone number is and the number format which is common for the number type and region.




Well, I was looking for such functionality, because our CRM users have to enter phone numbers from all over the world and we want to format and validate the phone number. Unfortunately there is no C# or VB.NET version available from this great Google library so I ended in doing some tests to integrate them into Microsoft.NET environment.


The first try

I’ve build my own JavaScript function the get the needed functionality running (region code, number formatting) in my own html site. Then I merged all related Google JS files from the closure-libaray into one single file with help of the Google This task is very good documented by Google.

So, after that I was looking for a JavaScript engine running in .NET, so that I can execute JS-code in managed .NET runtime. I thought the DLR support of .NET would be the best environment to do this. Unfortunately there is no official JS engine from Microsoft so far. So I ended in trying some engines found on did the job. This engine can interpret the Google JS file (which has a size of ~500kb and is quite big) and returns the correct result. I should mention here that other engines did also work but sometimes with a wrong result. But stop, there is still a problem with this JS engine: it does not run under 64bit system. This is because the engine used the v8 engine from Google behind the scenes and the v8 only supports 32bit (x86) architectures. There are some hacks to use v8 under 64bit but these seems to be too much experimental.


Second try

I’ve tried to convert the Java code into C# manually and by a converter tool. Result: no success, because there are too much of specialties in the code and my java knowledge is somewhat old.


Third try

There is a C++ version available and I thought it should be possible to use it via p/invoke within .NET. But there seems to be a similar issue with 32/64bit systems. So I did not further investigate into this possibility.


Last and successful try

So finally I’ve tried to use the phone metadata directly within C#. Google’s metadata behind the Java project is a very well structured XML document written by Google which contains a lot of regex patterns. These patterns build a structure to find out to which country a number belongs and which number format is common for a specific region.




I was very surprised how easy it was to use this metadata XML in my own code. With just a few lines and within two hours the prototype was working…. well, to finalize the library has cost me another day…



At the end I thought it is worth to share my code with other C#/VB.NET folks. You can grab the code here. It does not everything the original Google library can do; I just implemented the cases that we need in our project (resolve the region and common format for any phone number). Here is a quick example of the C# code (from the Unit Test project…)




Let me see if someone other is interested to use this C# version. If so i can put the code onto or so. Any feedback is highly appreciated.


Happy coding

Tagged , , ,

Just bought a Mac

For testing reasons we bought us a new MacBook. We need them mainly to test some web projects in the Safari browser and to check whether our Silverlight client works well on an Apple machine.



Nothing special, just a simple MacBook… but my frist ever… Smiley


…grab the newest Silverlight Plugin…


Since that there are no signs that Apple will allow Silverlight on iOS, I decided to start with iPhone and iPad development just for fun and experimental stuff. Recently I’ve started with learning objective-c and cocoa framework. Fortunately there exists a cross-compiler solution with the MonoTouch framework so that I can use my favorite programming language, C#, on the Mac.


Expression Blend Samples not working with Silverlight 4 and WPF 4

This blog post is just to document my experience with the Expression Blend Sample source together with Silverlight 4 or WPF 4.0

If you are using the Expression Blend Samples from codeplex ( then you might experience some problems when using the included triggers and behavior within SL4 or WPF4 runtime. The problem is that a dependency property with the type System.Windows.Data.Binding is not set to due to a change in the MS.Internal.Data.DynamicValueConverter class. Since SL4 / WPF4 the DynamicValueConverter uses the value of the binding instead of the binding instance itself. As example, the Command property of the InvokeDataCommand trigger is declared as System.Windows.Data.Binding, but the DynamicValueConverter will return the value of the binding, an ICommand compatible instance, and not the binding instance itself. So, the command property will always be null, because DynamicValueConverter cannot cast the object. And if the command binding cannot be set, the BindingListener, which is used internally, will not work correctly.


If we change the binding target from a dependency property to a simple CLR property, then the DynamicValueConverter can set the property and InvokeDataCommand works as before.


I’ve found that codeplex user AvdMeulen changed the whole Expression sample source and submitted a zip package on codeplex. See link below.


Let’s go into more details:

Silverlight 3 does not allow using data binding on types which are NOT inherited from class FrameworkElement. That means that the entire Silverlight standard behaviors and triggers do not support data binding, because the Trigger and Behavior classes are directly derived from DepedencyObject. Nevertheless, if you use data-binding with a trigger- or behavior property in Silverlight 3, then the binding system does not execute the binding, but it tries to set the binding instance itself to the property as a value of type System.Windows.Data.Binding. This will be done through the MS.Internal.Data.DynamicValueConverter class. If the target property is not of type System.Windows.Data.Binding it will not work and you get an AG_E_PARSER_BAD_PROPERTY_VALUE exception from the XAML parser. Based on this binding-engine behavior, Pete Blois invented the BindingListener class.
His trick was to declare properties on behaviors and triggers as type of System.Windows.Data.Binding in order to get them bindable. The binding is still not executed by the binding system and to bind them he declared a dummy attached dependency property and set the binding instance to the attached dependency property. The result is that the attached dependency property can execute the binding and we can just listen to when the attached dependency property changes. This results in a full functional binding for non-FrameworkElements. All this is encapsulated in the BindingListener class.

But now, why it does not work for SL4 anymore? The answer can be found in the breaking changes for Silverlight 4.



With SL4 it’s now possible to data binding dependency properties on triggers and behavior too, which makes the BindingListener class useless. This is also the reason why the Binding property remains null, because the SL4 binding engine set a BindingExpression and not the Binding itselfs and the BindingExpression tries to set the Command value instead of the Binding instance.


Link resources:

Tagged ,

RelativeSource Binding with FindAncestor mode in Silverlight

Silverlight 3 introduced the RelativeSource Binding that is well known from WPF. Unfortunately Silverlight only supports the two modes Self and TemplatedParent.


I don’t know why the FindAncestor mode is missing in Silverlight’s RelativeSource binding, but there is a real need for that in Silverlight too. I’m finding me quite often in a dead-end ifI want to set a binding to a command or value in the view model within a list box item template. The problem in the example below is that the list box item has its own data context set to an item in the items-collection.


In the case above I really need a relative binding to set a binding to the RemoveCommand and to the global Picklist collection as comboxbox source. On solution is to create a bidirectional relationship between the view models behind the scene in order to get a reference to the parent view model within the child view model. But this not the solution I was looking for.

After some googling I found a binding helper written by Colin Eberhardt which enables it to use a relative binding with help of an attached dependency property.


Explained in brief: Colin uses an attached property to set his own relative source binding configuration for an specific element. When the attached property becomes attached to the target element it adds a handler for the elements loaded event. Within the event handler, he walks up the visual tree to find the specified ancestor and constructs a binding expression between the source and target properties.

Based on Colin’s idea I’ve created a similar implementation which provides some different behaviors:

  • Support for a list of relative binding. This allows binding more than one property of an element.
  • It does not use a relay object in the middle of the binding. It is a pure binding without any custom code in between. This gain in a better performance, especially when using a storyboard to animate the data bound value.
  • I have added some special type of relative binding mode which is called as ParentDataContext mode. In that mode it walks up the visual tree until it finds a new data context. This is very helpful when having templates in an ItemsControl, ListBox or DataGrid.
  • Support for non-dependency property as source, e.g. direct usage of view model properties.
  • Support for property path syntax for the source property, e.g. DataContext.Person.Name
  • The AncestorType allows to set a base class as type criteria instead of the concrete type, e.g. if the concrete element is of type Grid, then the AncestorType can be set to Panel.
  • Allows to set the relative binding for attached properties too, e.g. to bind TooltipService.Tooltip property.
  • Allows to use OneWay or OneTime binding mode.
  • Allows to set any other binding parameter such as ValidatesOnNotifyDataErrors, ValidatesOnExceptions, ValidatesOnDataErrors, NotifyOnValidationError and ConverterCulture.
  • Enables to set the XAML namespace for controls which are not in the core-control assembly.

How to use

Let’s have a look at some examples.

1. Simply relative binding with ancestor type

            <local:RelativeSourceBinding Path="DataContext.Picklist"
                    TargetProperty="ItemsSource" RelativeMode="FindAncestor"
                    AncestorType="UserControl" />


2. Bind two or more properties by adding a list of binding definitions

            <local:RelativeSourceBinding Path="DataContext.Picklist"
                    TargetProperty="ItemsSource" RelativeMode="FindAncestor"
                    AncestorType="UserControl" />
            <local:RelativeSourceBinding Path="DataContext.Tooltip"
                    TargetProperty="(ToolTipService.ToolTip)" RelativeMode="FindAncestor"
                    AncestorType="UserControl" />



3. Bind any attached dependency property

<local:RelativeSourceBinding Path="DataContext.Tooltip"
        TargetProperty="(ToolTipService.ToolTip)" RelativeMode="FindAncestor"
        AncestorType="UserControl" />



4. Bind an attached dependency property from any assembly. Just specify the XAML namespace as in the example below

<local:RelativeSourceBinding Path="DataContext.Tooltip"
        RelativeMode="FindAncestor" AncestorType="UserControl" />



5. Use the parent data context instead an ancestor type

<local:RelativeSourceBinding Path="RemoveCommand" TargetProperty="Command"
        RelativeMode="ParentDataContext" />



6. The mode ParentDataContext is set as default behavior. So in most cases you can just write xaml as following:

<Button Content="Remove" CommandParameter="{Binding}">
        <local:RelativeSourceBinding Path="RemoveCommand" TargetProperty="Command" />

<ComboBox Grid.Column="1">
            <local:RelativeSourceBinding Path="Picklist" TargetProperty="ItemsSource"/>
            <local:RelativeSourceBinding Path="Tooltip" TargetProperty="(ToolTipService.ToolTip)" />



7. Use a converter and other binding settings

<local:RelativeSourceBinding Path="Application.IsEnabled"
        TargetProperty="Visibility" Converter="{StaticResource VisibilityConverter}"
        ValidatesOnNotifyDataErrors="True" ValidatesOnExceptions="True"
        ValidatesOnDataErrors="True" NotifyOnValidationError="True" />


Source Code & Demo Project

Here you can find the full source code within a demo project.

Tagged ,

Type.GetType implementation with help of XamlReader

The Type.GetType method is different in Silverlight than in the standard .NET runtime. In Silverlight we must provide the fully qualified assembly name to get a type from an assembly. Only built in controls such as Button, Grid, ListBox, etc. or types in the executing assembly are excluded from this rule. Fully qualified assembly name means you must provide the version, culture and public key token. That means that the following GetType usage works well, until the target assembly version changes from 1.0 to 1.1.

Type.GetType("MyComponent.MyType, MyAssembly, Version=, Culture=neutral, PublicKeyToken=4bec85d7bec6698f")

And do we really want to have such Xaml or code behind files?

<local:MyCustomElement Grid.Row="2" Grid.Column="1"
   ItemType="MyComponent.MyType, MyAssembly, Version=, Culture=neutral, PublicKeyToken=4bec85d7bec6698f" >


Iterate over Assembly Parts

One option to load a type just by its type-name and assembly-name is to iterate over all loaded assemblies. The method AppDomain.CurrentDomain.GetAssemblies() does not exist in Silverlight, but we can iterate over all assembly parts that are included in the deployment, e.g. all assemblies that are in the XAP file. I’ve found a blog post from Malcolm Jack in which he describes how to iterate over the parts to find a type by its name.

An this is how it works in brief: loop through each assembly part, getting the assembly, then use assembly.GetType to load the type.

This is the code this short explanation:

public static Type GetAssemblyType(string assemblyName, string className)
    StreamResourceInfo info = Application.GetResourceStream(new Uri(assemblyName, UriKind.Relative));
    Assembly assembly = new AssemblyPart().Load(info.Stream);
    Type type = assembly.GetType(className);
    return type;

public static Type GetAssemblyType(string className)
    Type type = null;
    foreach (AssemblyPart part in Deployment.Current.Parts)
        type = GetAssemblyType(part.Source, className);
        if (type != null)
    return type;


Unfortunately this solution has two drawbacks:

1. Dynamic loaded assemblies downloaded with help of a web client instance are not part of the deployment, e.g. the code cannot find types in those assemblies. You can add an additional part to the collection after each downloaded dll, but you do not have a guarantee this will be done.

AssemblyPart part = new AssemblyPart();
Assembly assm = part.Load(e.Result);


2. The second issue is when using application library caching to reduce the XAP size.


If this option is enabled, it will change the application manifest and the XAP no longer includes those assemblies which do support assembly caching. See Tim Heuer’s posts to get more detail how it works.

The cached assemblies are now declared as external parts as you can see in the manifest file (AppManifest.xml):

<Deployment ... >
    <ExtensionPart Source="" />
    <ExtensionPart Source="" />
    <ExtensionPart Source="" />
    <ExtensionPart Source="" />


In the end when the application starts those external assemblies will still be downloaded before the main form is added to the visual tree.


Iterating over all external parts is not that easy as iterating over all assembly parts, because it needs to download the source again and this is an asynchron operation.


The Solution: Using the XamlReader

I’ve found a solution by using the XamlReader to resolve types during parsing a xaml string. Unfortunately there is no StringToTypeConverter in Silverlight and the Xaml parser uses some hard coded logic to resolve System.Type properties only for certain type like Style and ControlTemplate. However, we can use a Style or ControlTemplate class and use the TargetType property to retrieve the type information. And these lines of code show how it works:

// create xaml with a simply Style element and set the TargetType property with the provided type name
string xaml = "<Style xmlns='' ";

// set the xaml namesapce if provided
if (!string.IsNullOrWhiteSpace(xamlNamespace))
    xaml += string.Format("xmlns:tmp='{0}' TargetType='tmp:{1}' />", xamlNamespace, className);
    // Core controls such as Button, Grid, ListBox, etc do not need a namespace
    xaml += string.Format("TargetType='{0}' />", className);

// let the XamlParser load the type via the TargetType property 
Style style = XamlReader.Load(xaml) as Style;

if (style != null)
    Type targetType = style.TargetType;
    return targetType;


Xaml parsing is not the fastest way to get a type. Therefore I encapsulated the functionality into a small class which maintains a cache for types which are already parsed.

The class provides four different ways to get a type:

// for types in the executing assembly or types in the core-control 
// assembly such as Button, Grid, etc. Just provide the type name.

// The type name with its xaml namespace
TypeLoader.GetType("Grid", "clr-namespace:System.Windows.Controls;assembly=System.Windows");

// Type name, namespace and assembly name as separate parameters
TypeLoader.GetType("Grid", "System.Windows.Controls", "System.Windows");

// Or with the assembly qualified type name, without version, culture and public key token
TypeLoader.GetType("System.Windows.Controls.Grid, System.Windows");


Here are some other examples:

// *** toolkit controls ***
// returns null, because NumericUpDown is in toolkit and not in core control assembly
               "System.Windows.Controls", "System.Windows.Controls.Input.Toolkit");
TypeLoader.GetType("System.Windows.Controls.NumericUpDown, System.Windows.Controls.Input.Toolkit");

// *** main application ***
// returns null, because MainPage is not in core-control assembly
//Type mainPage1 = TypeLoader.GetType("MainPage"); 
TypeLoader.GetType("MainPage", "clr-namespace:TypeLoaderDemo;assembly=TypeLoaderDemo");
TypeLoader.GetType("MainPage", "TypeLoaderDemo", "TypeLoaderDemo");
TypeLoader.GetType("TypeLoaderDemo.MainPage, TypeLoaderDemo");

// *** 3rd party libs ***
TypeLoader.GetType("MyButton", "clr-namespace:TypeLoaderControlLib;assembly=TypeLoaderControlLib");
TypeLoader.GetType("MyButton", "TypeLoaderControlLib", "TypeLoaderControlLib");

Demo Project and Source Code


Here you can find the TypeLoader implementation or a full demo project including TypeLoader source, examples, assembly parts iteration and dynamic assembly loading.