Saturday, 27 October 2012

How to Sync Multiple Google Calendars to the Windows 8 Calendar

Windows 8 makes it able to store your Google credentials to receive and display mails, sync your contacts or display your calendar in the preinstalled Windows Calendar App. Unfortunately it appears that only the root calendar is synced by default.

Solution:

  1. Download the User-Agent Switcher from the Chrome Web Store
  2. Select the iPhone User Agent
    User-Agent Switcher - Select the iPhone User Agent
  3. Go to https://m.google.com/sync/settings/iconfig/
  4. Deactivate JavaScript in Browser Settings (“Show advanced settings...” –> “Content settings…”)
  5. Click on your Windows Mail Device
  6. In the URL change supportMultipleCalendars=false to supportMultipleCalendars=true
  7. Submit URL (Enter)
  8. Select the Calendars you want to Sync
    Google Calendar Sync Options
  9. Click Save
  10. Readd your Google Account to your Windows Calendar App
Windows 8 Calendar App - Multiple Google Calendars
posted on Saturday, 27 October 2012 19:19:59 (GMT Daylight Time, UTC+01:00)  #    Comments [1]

Error Adding Your Google Account to Windows 8

I received the following error adding your Google Account to Windows 8 with the checked “Include your Google contacts and calendars” option: “Unable to connect. Ensure the information you’ve entered is correct.”

Unable to connect. Ensure the information you've entered is correct

Removing the German specific googlemail.de / gmail.de suffix and replacing it by gmail.com solves the problem!

posted on Saturday, 27 October 2012 18:03:33 (GMT Daylight Time, UTC+01:00)  #    Comments [0]
Sunday, 03 June 2012

MovieMaker.exe – System Error on Windows 7 N

I encountered the following error today:

MovieMaker.exe - System Error
MovieMaker.exe - System Error

The program can't start because MF.dll is missing from your computer.
Try reinstalling the program to fix this problem.

It looks like it's not a very common, but clearly reproducible error that will occurs on Windows 7 N with a freshly installed Windows Live Movie Maker.

Solution

Download the Media Feature Pack (KB968211) package.

You have to reboot after the installation.

posted on Sunday, 03 June 2012 13:51:47 (GMT Daylight Time, UTC+01:00)  #    Comments [0]
Thursday, 08 March 2012

Encrypted SQL CE Database in Windows Phone 7

Porting my new Android game QuizBurner to Windows Phone 7.1 (Mango) was really fun. Microsoft created a clean and .NET _friendly_ environment and makes it easy for .NET developers to get some things done. I can’t bring myself to call it “.NET”, because it has too many incompatibilities - it’s more a simplified and in few ways modified copy of the .NET Framework.

Dependency

Access existing Database

Shipping existing databases within the the application is an essential prerequisite for my game. We are able to store the database side by side to the assembly, by using the “appdata” keyword instead of the “isostore” within the connection string.

Data Source = 'appdata:/db.sdf'; File Mode = read only;

Please mention that we only have read only access to that database, so we should also specify the “read only” parameter.

Database Encryption

So far so good – assuming that we are able to encrypt CE databases very easily, we just have to specify a password here too:

Data Source = 'appdata:/db.sdf'; File Mode = read only; Password = 'oni7sak2';

Since it couldn't have been that easy, we are receiving the following exception:

The database encryption mode is invalid.  [ Input Encryption Mode = 0 ]

I did some research and found out that the default encryption method in 3.5 is AES128/SHA1 and the default encryption method in 4.0 is AES128/SHA2.

List of default encryption algorithms used in SQL Compact:

 .---------------------------------------------------------------------------------.
| Version | Default Encryption | Authentication | Provider                         |
|---------+--------------------+----------------+----------------------------------|
| 3.0     | RC4                | MD5            | PROV_RSA_FULL, MS_ENHANCED_PROV  |
| 3.1     | RC4                | MD5            | PROV_RSA_FULL, MS_ENHANCED_PROV  |
| 3.5     | AES128             | SHA1           | PROV_RSA_AES, MS_ENH_RSA_AES_PRO |
| 4.0     | AES128             | SHA2           | ?                                |
`----------------------------------------------------------------------------------'

Further research showed me that WP7 is based on 3.5 and uses some features of 4.0, also the encryption methods. It looks like it’s a mixture of both versions.

Conclusion

That led me to the following conclusion:

Encrypted databases created in Microsoft SQL Server Management Studio (2008) are not compatible with WP7 and created Databases by WP7 are not compatible with the SSMS. It appears that the encrypted database created using Mango WPDT can not be opened in desktop (either using Visual Studio 2010 or SQL Server 2008 Management Studio). Both VS2010 and SQL Server 2008 MS shows an encryption mode is invalid when trying to open it.

There is no (supported) way to use encrypted SQL CE databases in WP7 if they are not created by WP7 itself.

Microsoft declines support to that approach by using the following statements:

  • SQLCE is not directly exposed to 3rd party applications in Windows Phone 7 and beyond. Microsoft exposes LINQ To SQL, which happens to use SQLCE as the underlying storage provider in Windows Phone Mango (7.1).
  • Previous knowledge of how SQLCE worked in one of its many previous incarnations will not help much in WP7 app development, as the build on Windows Phone is slightly different than other flavors.
  • Microsoft does not support loading a database which was created on SQLCE for desktop or any previous version of Windows CE.
  • Microsoft does allow the developer to specify a password on the database through LINQ To SQL.
  • Microsoft does not allow you to specify the encryption settings on the LINQ To SQL connection string.

Source: http://forums.create.msdn.com/forums/t/95939.aspx

posted on Thursday, 08 March 2012 12:30:48 (GMT Standard Time, UTC+00:00)  #    Comments [1]
Friday, 13 January 2012

Advanced Proxy-Classes for Razor-Templating by using DynamicObject

As described in my earlier post Creating Proxy-Classes for ViewModel’s (MVVM) by using DynamicObject with DynamicObject’s you have the ability to easily extend and override members of you DomainModel for binding purposes without changing it in any way. You can use that approach in ASP.NET MVC to write easy readable templates, without creating @helper’s for ViewModel related data manipulation.

Domain Model

Let me explain that approach by a simple example. Assuming that we have to build a catalog system based on an existing DomainModel where we have some Articles, n corresponding Prices and due to normalization corresponding price PriceCampaigns to label and specify the Prices.

DomainModel

Creating some Objects

Let's use the following mocking for our examples:

var listPriceCampaign = new PriceCampaign() { Name = "list" };
var retailPriceCampaign = new PriceCampaign() { Name = "retail" };

var article = new Article() { OrderNumber = "4202.9", Description = "Doomsday Machine" };

var listPrice = new Price() { Value = 99.99m, Article = article, Campaign = listPriceCampaign };

article.Prices.Add(listPrice);
listPriceCampaign.Prices.Add(listPrice);

var retailPrice = new Price() { Value = 17.99m, Article = article, Campaign = retailPriceCampaign };

article.Prices.Add(retailPrice);
retailPriceCampaign.Prices.Add(retailPrice);

Template Usage

We are now able to produce the following output by using our DomainModel:

OrderNumber: 4202.9
Description: Doomsday Machine
Price: $17.99
ListPrice: $99.99

To map the prices to the Razor template we can do it either the old fashioned way:

@{
  // bad code for determining list- and retail price
  var listPrice = 0.00m;
  var retailPrice = 0.00m;

  foreach(var price in Model.Prices)
  {
    if (price.Campaign.Name == "list")
      listPrice = price.Value;
    else if (price.Campaign.Name == "retail")
      retailPrice = price.Value;
  }
}
OrderNumber: @Model.OrderNumber
Description: @Model.Description
Price: $@retailPrice
ListPrice: $@listPrice

Or we can do it by using LINQ:

@{ // good code (still bad approach) for determining list- and retail price }
OrderNumber: @Model.OrderNumber
Description: @Model.Description
Price: $@Model.Prices.Where(p => p.Campaign.Name == "retail").First().Value
ListPrice: $@Model.Prices.Where(p => p.Campaign.Name == "list").First().Value

ViewModel-Proxy

Now let’s create the simplified ViewModel-Proxy by using DynamicObject as described in Creating Proxy-Classes for ViewModel’s (MVVM) by using DynamicObject.

public abstract class BaseViewModelProxy<T> : DynamicObject
{
  protected T _domainModel;

  private PropertyInfo[] _objectProperties;
  private PropertyInfo[] objectProperties
  {
    get
    {
      if (objectProperties == null)
        this._objectProperties = typeof(T).GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

      return this._objectProperties;
    }
  }

  public BaseViewModelProxy(T domainModel)
  {
    this._domainModel = domainModel;
  }

  public override bool TryGetMember(GetMemberBinder binder, out object result)
  {
    var pi = this._objectProperties.FirstOrDefault((p) => p.Name == binder.Name);

    if (pi != null)
    {
      result = this._domainModel != null ? pi.GetValue(this._domainModel, null) : null;
      return true;
    }
    else
      return base.TryGetMember(binder, out result);
  }

  public override bool TrySetMember(SetMemberBinder binder, object value)
  {
    var pi = this._objectProperties.FirstOrDefault((p) => p.Name == binder.Name);

    if (pi != null)
    {
      if (this._domainModel != null)
      pi.SetValue(this._domainModel, value, null);
    
      return true;
    }
    else
      return base.TrySetMember(binder, value);
  }
}

We also create a BaseCollectionDictionaryModel<T> and BaseModelCollectionDictionaryModel<T, E> that implements IDictionary<string, T> so we are able access collection items by associative indices for collection items in our template.

public abstract class BaseCollectionDictionaryModel<T> : DynamicObject, IDictionary<string, T>, IList<T>
{
  private IList<T> _domainModelCollection;
  private List<PropertyInfo> _keyFieldPropertyInfoStack;

  public BaseCollectionDictionaryModel(IList<T> domainModelCollection, string keyFieldPath)
  {
  this._domainModelCollection = domainModelCollection;

  this._keyFieldPropertyInfoStack = new List<PropertyInfo>();

  buildPropertyInfoStack(keyFieldPath, typeof(T));
  }

  private void buildPropertyInfoStack(string path, Type type)
  {
  var stack = path.Split(new char[] { '.' });

  var pi = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(p => p.Name == stack[0]);

  this._keyFieldPropertyInfoStack.Add(pi);

  if (stack.Length > 1)
    buildPropertyInfoStack(path.Substring(stack[0].Length + 1), pi.PropertyType);
  }

  public T this[string key]
  {
  get
  {
    // we could also use LINQ Dynamic Expressions instead
    foreach (T o in this._domainModelCollection)
    {
    Object r = o;

    foreach (PropertyInfo pi in this._keyFieldPropertyInfoStack)
      r = pi.GetValue(r, null);

    if ((string)r == key)
      return o;
    }

    throw new KeyNotFoundException();
  }
  set { throw new NotImplementedException(); }
  }

  // insert some more IDictionary<string, T>, IList<T> implementations here
}

public abstract class BaseModelCollectionDictionaryModel<T, E> : BaseCollectionDictionaryModel<E>, IDictionary<string, T>, IList<T>
{
  public BaseModelCollectionDictionaryModel(IList<E> domainModelCollection, string keyFieldPath)
  : base(domainModelCollection, keyFieldPath)
  {
  }

  public virtual List<T> getModelCollection(IEnumerable<E> items)
  {
  throw new NotImplementedException();
  }

  public virtual T getModel(E item)
  {
  throw new NotImplementedException();
  }

  public ICollection<string> Keys
  {
  get { return base.Keys; }
  }

  public ICollection<T> Values
  {
  get { return getModelCollection(base.Values); }
  }

  public T this[string key]
  {
  get { return getModel(base[key]); }
  set { throw new NotImplementedException(); }
  }

  // insert some more IDictionary<string, T>, IList<T> implementations here
}

Now to the simple part, the implementation. We've to create some ViewModel classes based on our abstract class BaseViewModelProxy<T>. We also "override" the collection properties so we can use them as IDictionary<string, T> in our template, they will also return our proxified types.

public class ArticleModel : BaseViewModelProxy<Article>
{
  public ArticleModel(Article article)
  : base(article)
  {
  }

  public PriceModelCollectionDictionaryModel Prices
  {
  get { return new PriceModelCollectionDictionaryModel(this._domainModel.Prices); }
  }
}

public class PriceModel : BaseViewModelProxy<Price>
{
  public PriceModel(Price price)
  : base(price)
  {
  }

  public ArticleModel Article
  {
  get { return new ArticleModel(this._domainModel.Article); }
  }

  public PriceCampaignModel Campaign
  {
  get { return new PriceCampaignModel(this._domainModel.Campaign); }
  }
}

public class PriceCampaignModel : BaseViewModelProxy<PriceCampaign>
{
  public PriceCampaignModel(PriceCampaign priceCampaign)
  : base(priceCampaign)
  {
  }

  public PriceModelCollectionDictionaryModel Prices
  {
  get { return new PriceModelCollectionDictionaryModel(this._domainModel.Prices); }
  }
}

public class PriceModelCollectionDictionaryModel : BaseModelCollectionDictionaryModel<PriceModel, Price>
{
  public PriceModelCollectionDictionaryModel(IList<Price> prices)
  : base(prices, "Campaign.Name")
  {
  }
}

public class PriceCampaignModelCollectionDictionaryModel : BaseModelCollectionDictionaryModel<PriceCampaignModel, PriceCampaign>
{
  public PriceCampaignModelCollectionDictionaryModel(IList<PriceCampaign> priceCampaigns)
  : base(priceCampaigns, "Name")
  {
  }
}

New Template Usage

The new template usage is much more simpler and that's how all the hard work pays out:

OrderNumber: @Model.OrderNumber
Description: @Model.Description
Price: $@Model.Prices["retail"].Value
ListPrice: $@Model.Prices["list"].Value
posted on Friday, 13 January 2012 16:24:12 (GMT Standard Time, UTC+00:00)  #    Comments [0]
Monday, 28 November 2011

Creating a Generic 32bit Wrapper Application

Visual Studio Platform Target Settings

A couple of days ago I was asked if there is a way to interop with a native 32bit library from within an 64bit .NET application. Since the bitness is defined at process level and in .NET the bitness of the starting project determines the bitness of the process, there is only one way to achieve that: you have to spawn a new process, a 32bit process.

The following example of a generic 32bit wrapper application demonstrates how to execute managed code in a simple manner. The wrapper, targeting the x86 platform, is able to execute the specified static method "Main" of the given assembly. The assembly doesn't have to be an executing assembly itself.

// usage: RunAs32Bit.exe [ASSEMBLY] [ARGS ...]
static void Main(string[] args)
{
  var assembly = Assembly.LoadFile(Path.GetFullPath(args[0]));
  var type = assembly.GetTypes().FirstOrDefault(t => t.GetMethod("Main") != null);
  var member = type.GetMethod("Main");
  var arguments = args.Where((v, i) => i > 0).ToArray();

  member.Invoke(type, new object[] { arguments });
}

Spawning a new process that will do some stuff (e.g. interop) may also mean that you have to do some inter-process communication (IPC). I suggest you to use WCF for that approach.

posted on Monday, 28 November 2011 12:12:35 (GMT Standard Time, UTC+00:00)  #    Comments [0]
Wednesday, 19 October 2011

Saving Clicks by replacing Radio Buttons

There are many cases where radio buttons are really useful, but they are also often misused.

I'm in space. SPAAACE!

And there are many ways to fail with them. Good placement of radio buttons is very important to make absolutely clear which radio buttons belong to a group. Therefore they shouldn't be placed too far from each other and a spacing to other controls and especially other radio button groups is the key. If you’ve ever seen some radio button floating incoherent in space, or wrongly grouped ones, you know what I'm talking about.

Another popular bad usage of radio buttons is when they provoke unnecessary clicks like in this example when configuring the Server Group Properties of the Microsoft Team Foundation Server 2010:

Team Foundation Server "Group Properties"

Seriously, did you intuitively figured out how the radio buttons behave here?

Another well known example for this is the dialog in Excel when you’re about to delete some cells:

Excel "Delete" dialog

In many cases it would be better to drop some action buttons to avoid some extra clicks.

When you open an Office Document in Microsoft SharePoint 2010 you will get the following dialog:

SharePoint 2010 "Open Document" dialog

The preferred design would look like:

Preferred SharePoint 2010 "Open Document" dialog

Another example of this would be the "Paste Special" dialog from the Windows Live Writer:

Windows Live Writer "Paste Special" dialog

That could look like:

Preferred Windows Live Writer "Paste Special" dialog

Saving clicks is a especially a common task when it comes to touchscreen optimized interfaces. There are already many examples how that can be achieved:

Windows 7 "Copy File" dialogAndroid radio button submenu
posted on Wednesday, 19 October 2011 00:18:13 (GMT Daylight Time, UTC+01:00)  #    Comments [1]
Sunday, 16 October 2011

High speed Android "emulation" using VirtualBox with Android-x86

Ever tried to speed up the Android-Emulator? You can tweak the emulator by using a snapshots to increase the booting performance of the emulator and apply some nasty registry hacks to tweak the speed at runtime. However, applying all of those tweaks improve the performance insignificant. Developing and especially debugging android applications with the emulator provided by the SDK is pain in the ass.

The Android-x86 Project

There is a solution to increase the debugging performance dramatically. Instead of running an emulator that emulates a real ARM processor with a lot of overhead, there is the Android-x86 project. It’s an open source project, that provides the ability to run Android directly on top of your x86 CPU.

You can run Android-x86 on most popular Virtual Machines like VMWare, QEmu and VirtualBox. I successfully tried to run it on all of those 3 Virtual Machines and I recommend VirtualBox for this approach, since it’s free and doesn’t need any special configurations to run smooth and very very fast.

Setting up Android-x86 with VirtualBox

At the first step we need the installation image of Android-x86. I used the the android-x86-2.3-RC1-eeepc.iso that can be downloaded here: http://www.android-x86.org/download.

Let’s create a Virtual Machine that will be able to run this image. I used the following setup for my machine:

VirtualBox Settings
  • target OS: Linux
  • target OS version: other
  • 1 GB RAM
  • a dynamically sized VDI drive, 500 MB

Now mount the image to the machine, boot it and choose "Installation – Install Android-x86 to harddisk".

Android-x86 Installation

During the installation you have to create a new partition, don’t forget to make it bootable:

  • select "Create" by using the arrow keys
  • select "Primary"
  • set the preferred size, or simply hit enter
  • select "Bootable"
  • select "Write"
  • confirm by typing "yes"
  • select "Quit"

Once the partition is created properly you will be able to choose and format it.

Choose Partition

Now complete the installation with the following steps:

  • format sda1 as ext3
  • click "yes" to install the Grub boot loader
  • you may click also "yes" to install the /system directory as read-write

After those steps you have to reboot. Although our installation is  complete and bootable, I suggest to make some changes for enabling other screen resolutions.

Changing Screen-Resolution

The screen resolution can be added as a booting parameter, or you can use a parameter that lets you choose the resolution every time the system boots. To do so, we need to change the configuration of the Grub boot-loader. Since we are not able to access the configuration from within our installed system, boot again from the image and choose "Live CD - Debug mode".

Now we have to mount our booting partition and edit the "menu.lst", containing our boot menu and the booting parameters.

mkdir /boot
mount /dev/sda1 /boot
vi /boot/grub/menu.lst

Let’s take a look at the lines, starting with "kernel" – as you can see, there are already few parameters passed to the kernel. There is also the option "androidboot_hardware" that we want to change to "generic_x86", since we are not using an EeePC.

To select the resolution at start up we have to add the "vga=ask" parameter and could change the line to something like this:

kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=generic_x86 acpi_sleep=s3_bios,s3_mode vga=ask SRC=/android-2.3-RC1

If you want to add a specific resolution directly to a boot menu entry, simply add the "DPI" and "UVESA_MODE" parameters instead:

kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=generic_x86 acpi_sleep=s3_bios,s3_mode DPI=240 UVESA_MODE=480x720 SRC=/android-2.3-RC1

You have to save the menu.lst after editing (press ESC and type :wq).

We are now ready to start the installed system – don’t forget to unmount the image first!

Booting the System and getting the Mouse to work

The booting performance is really great, isn’t it? As you might doubt out, your mouse is not yet working within the VM – click "Disable Mouse Integration" on the "Machine" menu or press Host key + I.

VirtualBox Disable Mouse Integration

The default keyboard layout of your Android-x86 system:

  • "Windows Key" corresponds to the Android Home button
  • ESC corresponds to the Android back button
  • F2 corresponds to the Android menu button
  • F3 corresponds to the Android search button
  • Alt+F1 switches to console mode
  • Alt+F7 switches to GUI mode

Connecting as Android Virtual Device

To establish a connection between the host and the Android-x86 system and using the VM as AVD you have to configure the networking options of your VM. There are different ways to get this done. The simplest solution to connect both systems would be the usage of the "Host-only Adapter". Go to your VM network settings and change the "Attached to:" option to "Host-only Adapter".

VrtualBox Network Settings: Host only Option

Once you have set up the network, start your VM and use the "netcfg" command to output the actual network configuration of your Android system. You should get something like 192.168.56.101 for the VM and the host will be bound to 192.168.56.1.

On the host go to your SDK tools and start "adb" with the "connect" parameter:

adb connect 192.168.56.101

Congratulations! You now have a fully functional and very very fast AVD, running inside of a VM and booting in a blink of an eye.

Devices Eclipse

You are now also able to select the newly created AVD as device in Eclipse.

posted on Sunday, 16 October 2011 03:44:35 (GMT Daylight Time, UTC+01:00)  #    Comments [0]
Tuesday, 04 October 2011

Creating Proxy-Classes for ViewModel’s (MVVM) by using DynamicObject

The Model-View-ViewModel (MVVM) design pattern is a common approach when it comes to WPF, Silverlight and ASP.NET MVC development. The separation of DomainModel, View and ViewModel removes virtually all “code-behind” from the View layer. That makes the application highly modular. If you have some experience in creating multilayer applications and creating database layers, the benefits of decoupling Model and View should be obvious. However, the benefits of creating a ViewModel layer might require some explanation.

The ViewModel

The ViewModel provides a view-specific representation of the data. So it’s a subset or transformation of the DomainModel. It is a “Model made for a View” - a common approach is to create one ViewModel for every particular View and keep them distinct from the DomainModel types. In most cases that goes with the principle that the View dictates the design of the ViewModel and to pass only required and optimal formatted information's to the View.

Let’s say we have the following DomainModel, containing information's about an Article we get from our database:

public class Article
{
  public int Oid { get; set; }
  public string Articlenumber { get; set; }
  public string Description { get; set; }
  public decimal Price { get; set; }
  public DateTime PublicationDate { get; set; }
}

Furthermore we want to display detail information’s about an Article inside an ArticleDetail view, so we have to create a ViewModel to pass:

public class ArticleDetailModel
{
  public string Articlenumber { get; set; }
  public string Description { get; set; }
  public string Price { get; set; }
  public string PublicationDate { get; set; }
}

The ViewModel contains all information’s we want to display inside of the ArticleDetail view. In addition the data provided is already formatted (Price, PublicationDate) to fit the needs of the view.

That's how the instantiation of the ViewModel may appear in some kind of spaghetti code:

ArticleDetailModel m = new ArticleDetailModel();

m.Articlenumber = article.Articlenumber;
m.Description = article.Description;
m.Price = article.Price.ToString(CultureInfo.CurrentUICulture);
m.PublicationDate = article.PublicationDate.ToString(CultureInfo.CurrentUICulture);

If we now choose to add an ArticleEdit view for editing an existing Article, we have to create a new ViewModel, most likely including the “Oid” property as reference to the record.

Proxy Properties

If you might doubt, that approach results in having many different ViewModel’s for every View we create and many lines of code to handle the instantiation of the ViewModel’s and the formatting of data passed.

There are different approaches to make that procedure more elegant. A solution might be the AutoMapper library, that provides the functionality to map the DomainModel to the ViewModel.

Another approach is the implementation of proxy behavior for each property provided by the ViewModel. Proxy properties usually looks like this:

public string Price
{
  get { return this._domainModel.Price.ToString(CultureInfo.CurrentUICulture); }
  set { this._domainModel.Price = decimal.Parse(value); }
}

At this point I suggest you to take a look at the DynamicProxy library of the Castle Project. It provides functionality for generating .NET proxies on the fly at runtime and may fit your requirements in that case too.

DynamicObject Proxy

My solution of implementing the ability of proxy properties is to use the dynamic objects of the .NET Framework 4.0. DynamicObject’s allow you to determine at run time how to handle property requests and let you “extend” your DomainModel that way. With the power of dynamic objects you are also able to “route” all existing properties to the underlying DomainModel, so you may only have to touch the ones that require explicit formatting. You will be also able to flatten existing relations inside of your DomainModel by using this approach.

The implementation of the DynamicObject Proxy could look like this:

public abstract class ViewModelProxy<T> : DynamicObject, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler  PropertyChanged;

  protected T _domainModel;

  private PropertyInfo[] _objectProperties;
  private PropertyInfo[] objectProperties
  {
    get
    {
      if (objectProperties == null)
        this._objectProperties = typeof(T).GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

      return this._objectProperties;
    }
  }

  public override bool TryGetMember(GetMemberBinder binder, out object result)
  {
    var pi = this._objectProperties.FirstOrDefault((p) => p.Name == binder.Name);

    if (pi != null)
    {
      result = this._domainModel != null ? pi.GetValue(this._domainModel, null) : null;
      return true;
    }
    else
      return base.TryGetMember(binder, out result);
  }

  public override bool TrySetMember(SetMemberBinder binder, object value)
  {
    var pi = this._objectProperties.FirstOrDefault((p) => p.Name == binder.Name);

    if (pi != null)
    {
      if (this._domainModel != null)
      pi.SetValue(this._domainModel, value, null);
    
      if(PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(binder.Name);

      return true;
    }
    else
      return base.TrySetMember(binder, value);
  }
}

All ViewModel’s are now able to inherit the ViewModelProxy<T> class to provide access to all properties of our DomainModel type. We are also able to implement new properties, or “override” existing ones.

That’s how the example ArticleDetailModel would look like:

public class ArticleDetailModel : ViewModelProxy<Article>
{
  public ArticleDetailModel(Article article)
  {
    this._domainModel = article;
  }

  public string Price
  {
    get { return this._domainModel.Price.ToString(CultureInfo.CurrentUICulture); }
    set { this._domainModel.Price = decimal.Parse(value); }
  }
  public string PublicationDate
  {
    get { return this._domainModel.PublicationDate.ToString(CultureInfo.CurrentUICulture); }
    set { this._domainModel.PublicationDate = DateTime.Parse(value); }
  }
}
posted on Tuesday, 04 October 2011 00:04:06 (GMT Daylight Time, UTC+01:00)  #    Comments [0]
Saturday, 01 October 2011

Understanding the benefits of a Dependency Injection Container (IOC)

Ever wanted to program like a ninja? A couple of days ago I stumbled upon Ninject, an open source dependency injector (DI) for .NET. The entire design of the project is hilarious, I felt like a ninja and like I’m doing something really cool and sneaky by playing around with the framework. Although using dependency injection is very common, the usage of an DI framework is something new for many developers.

Dependency Injection is an implementation of the Inversion of Control pattern.  There are two possible implementations for IoC:

  • Service Locator or Dependency Lookup: container provides callback functionality and lookup context, components are requested by using the locator (container) API. A dependency to the locator and API persists, central binding and  contextual binding is possible.
    Service Locator
  • Dependency Injection: implementation without dependency to a container API possible, able to manage lifecycles (scope, request, singleton, thread, transient), lookup and contextual binding abilities are depending on the DI framework.

The idea behind DI and Inversion of Control is the use of the so-called “Hollywood Principle” – “don’t call us, we’ll call you!”

Simple Dependency Injection

Let me provide you an example of DI without using any DI framework. It’s a common approach, that you likely know.

When an object needs another object to operate properly, we have a dependency. In the following example we have a Service and a Client, where the Client class is tightly coupled with the Service class:

public class Service
{
  public void Serve()
  {
    // do some serving stuff
  }
}

public class Client
{
  private Service _service;

  public Client()
  {
    this._service = new Service();
  }

  public void Start()
  {
    this._service.Serve();

    // do some client stuff
  }
}
Dependency

Dependency injection eliminates that tight coupling and makes the application more flexible and reusable:

public interface IService
{
  public void Serve();
}

public class Service : IService
{
  public void Serve()
  {
    // do some serving stuff
  }
}

public class Client
{
  private IService _service;

  public Client(IService service)
  {
    this._service = service;
  }

  public void Start()
  {
    this._service.Serve();

    // do some client stuff
  }
}
Simple Dependency Injection

Sample Builder-Implementation:

var client = new Client(new Service());

client.Start();

The Injection happens in the constructor, by passing the Service that implements the IService-Interface. The dependencies are assembled by a “Builder”, his responsibilities are as follows:

  • knowing the types of each IService
  • according to the request, feed the abstract IService to the Client

The example above uses Constructor Injection. There are the following 3 possible implementations of DI:

  • Interface Injection
  • Setter Injection
  • Constructor Injection

What's wrong with the approaches?

Up till this point, you should no doubt realize the important role the dependency injection above. In fact, as you may have doped out, there are some issues with the approaches:

  • It is hardcoded: it can't be reused across applications, due to hardcoded factories - that makes the code stringent to particular implementations
  • Interface dependent: interfaces are used for decoupling the implementation and the object creation procedure
  • Instantiating is custom: instantiations are very much custom to a particular implementation
  • Everything is compile time: all dependent types for the objects in the instantiation process (factory) have to be known at compile time

Service Locator

A common approach to achieve assembling the Client could be the following implementation, by using service locator to avoid some of the issues described before:

public class Locator
{
  private static Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>();

  static Locator()
  {
    dictionary.Add(typeof(IService), typeof(Service));
  }

  public object Create(Type type)
  {
    if ((type == null || !dictionary.ContainsKey(type)))
      throw new NullReferenceException();

    return Locator.CreateInstance(dictionary[type]);
  }

  public T Create<T>()
  {
    return (T)Create(typeof(T));
  }
}

Usage:

var client = new Client(Locator.Create<IService>());
Service Locator

Extending the Locator looks like a great solution here - by using a service locator it should be possible to achieve some runtime capabilities and a clean and modular way to map interfaces to types. The more complex your requirements, the more complex would be the Locator. Implementing the ability to configure the Locator by using a XML configuration file, implement conditional operation by reflecting types, attributes and even parameter names sounds like a great solution, didn't it?
What if the Client will get some more dependencies to inject? What if that happens to the implementations of the IService too? What if that happens only to a few implementations of the IService? What about unit testing and setting up type mappings depending on the environment we are in? What about decoupling the instantiation process a bit more? What about controlling the life cycle of the created objects?

Good news here! There is already a solution to achieve those requirements: the container way :)

If you are interested in more specific information about the service locator pattern and why it should be avoided I recommend the Service Locator is an Anti-Pattern blog post from Misko Hevery.

Using Dependency Injection Containers (IOC)

IOC assigns the responsibility of creating and coupling of objects to a configurable Framework, according to a component model. The code of the object will become independent of the environment and the concrete implementation of the class, it depends on and makes particular unit-testing more easily.

There are many dependency frameworks for .NET to chose from. The following examples are done by using Ninject, which comes with the following features:

  • compact and easy to understand
  • lightweight, focusing the core functionalities
  • fast, it takes advantage of code generation in the CLR
  • doesn’t uses XML
  • takes advantage of the capabilities of the IDE and IntelliSense
  • supports contextual binding

Let me demonstrate you the power of IOC by implementing it to our Client/Service example:

public interface IService
{
  public void Serve();
}

public class Service : IService
{
  public void Serve()
  {
    // do some serving stuff
  }
}

public class Client
{
  private IService _service;

  public Client(IService service)
  {
    this._service = service;
  }

  public void Start()
  {
    this._service.Serve();

    // do some client stuff
  }
}

Did you noticed that there is no change of the example at all? The difference in this example relies only on the usage of the provided classes. Like many IoC containers, Ninject uses a central object (kernel) to provide concrete implementations of dependencies at run-time. The StandardKernel is the default implementation of such an object. So lets do it the Ninject-Way:

using (IKernel kernel = new StandardKernel())
{
  kernel.Bind<IService>().To<Service>();

  var client = new Client(kernel.Get<Service>());
}

The example above demonstrates the usage of Ninject but it's far away from impressing, isn't it? Let us see Ninject performing something more clever:

using (IKernel kernel = new StandardKernel())
{
  kernel.Bind<IService>().To<Service>();

  var client = kernel.Get<Client>();
}

Did you see some kind of ninja stuff happened here? Ninject is able to build a Client and taking care of providing the dependencies.

Since this post is about IOC in general and not providing detailed information about Ninject, let us start only a short survey to the more complex ninja abilities.

Contextual binding:

// only if we're injecting in to the Client
kernel.Bind<IService>().To<Service>().WhenInjectedInto<Client>();

// assuming we have a a Settings object, providing a boolean property "OnlineMode" and two types implementing the IService interface
kernel.Bind<IService>().To<OnlineService>().When(request => kernel.Get<Settings>().OnlineMode);
kernel.Bind<IService>().To<LocalService>().When(request => !kernel.Get<Settings>().OnlineMode);

Controlling the life cycle of the objects:

Since the kernel provides us the objects of the types we are requesting, it is also easily able to take control of the different lifecycle-scopes the objects are in. Ninjects provides the following 4 scopes:

  • Transient (default)
  • Singleton (only one instance)
  • Thread (one instance per thread)
  • Request (one instance per web request)

The following example demonstrates how requesting objects in singleton scope works:

kernel.Bind<IService>().To<Service>().InSingletonScope();

var client1 = kernel.Get<Client>();
var client2 = kernel.Get<Client>();

Assert.Same(client1, client2);

Please note that this is only a short summary of what IOC and especially Ninject can do for you. If you are interested in becoming an IOC-Ninja, I suggest you to read the Ninject Walkthrough on CodePlex. If you are new to dependency injection at all, my recommendation is to start with Manual Dependency Injection as described at the beginning of the post.

posted on Saturday, 01 October 2011 08:17:11 (GMT Daylight Time, UTC+01:00)  #    Comments [3]