Caliburn.Micro Template Pack

Reworked on the Caliburn.Micro Template Pack recently. Thought it was necessary to provide the developers the ability to Create Bootstrapper as an Item Template. It also provides the option to develop the Pack more in coming days. You can access the Template Pack from Marketplace using the link here. Details of the pack is as follows.

Caliburn.Micro Template Pack for WPF

Caliburn.Micro Template Pack for WPF contains a comprehensive collection of Project Templates and Code Snippets for developing WPF application using Caliburn.Micro

Project Templates

  •  WPF Application that utilizes Caliburn.Micro for MVVM Framework

Item Templates

  •  Bootstrapper Class with MEF as IoC
  •  Bootstrapper Class with SimpleContainer as IoC

Code Snippets

  • propcm – Creates Property with NotifyOfPropertyChange and backing field
  • funcm – Creates function with Guard methods


Caliburn.Micro #005 : Bootstrapper with MEF

Previously, we learnt how to use SimpleContainer to set up our IoC Containers. We would be now looking into making the application more loosely coupled by leveraging the MEF. Just like with SimpleContainer, we would be focusing on the basic steps while configuring the IoC – Registering the IoC Container with Caliburn Micro and then registering the Service bindings. Let’s go ahead override the necessary methods

private CompositionContainer _Container;

protected override object GetInstance(Type service, string key)
  string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;
  var exports = _Container.GetExportedValues(contract);
  if (exports.Any())
      return exports.First();
      throw new Exception("Could not find the key");

protected override void BuildUp(object instance)

protected override IEnumerable GetAllInstances(Type service)
  return _Container.GetExportedValues(AttributedModelServices.GetContractName(service));

We will now go ahead and register our Service Bindings. This is where things get interesting.

protected override void Configure()
  _Container = new CompositionContainer(
                new AggregateCatalog(AssemblySource.Instance.Select(x=> new AssemblyCatalog(x)).OfType())
  var batch = new CompositionBatch();
  batch.AddExportedValue(new WindowManager());
  batch.AddExportedValue(new EventAggregator());


As seen in the code above, we are using the AssemblySource to parse the ViewModels in the Assembly.

That’s it in Bootstrapper, but do not forget to decorate your View Model class with [Export()] Attribute and Constructor with [ImportingConstructor]. (For injecting dependency)

public class ReportViewModel :Screen, IReport
  publicReportViewModel(IEventAggregator EventAggregator)
    // Do Constructor tasks

We will delve into EventAggregators later, but for the moment, consider it an example of how to inject a dependency in the constructor when working with MEF.

Code sample for this post can be found here. The complete list of tutorials on Caliburn.Micro can be accessed here


Caliburn.Micro #004 : Bootstrapper with SimpleContainer

Let’s take a step back and look into our Bootstrapper in detail now. The first version of Bootstrapper we declared earlier is a rather simple one, without utilizing the some of the functionalities which takes Caliburn.Micro, or for that matter, any MVVM Framework ahead. The implementation of IoC Container.
We would be concentrating into two different IoC Containers – a Caliburn.Micro in-build container called SimpleContainer and the MEF (Microsoft Extensibility Framework) based Container. In this first part, we would be concentrating on the SimpleContainer. Let’s begin by declaring the interface contract for our Shell View Model.
  public interface IShell

I would leave the implementation of ShellViewModel and ShellView to the discretion of the reader, considering that is not what we are focusing on this particular session. We would instead focus on the Bootstrapper Class and how we would be triggering the ShellViewModel from it by utilizing the IoC container. We would however, write our OnStartup method, triggering the ShellViewModel through the IShell interface.
protected override void OnStartup(object sender, StartupEventArgs e)
The first step is to configure the container with the Caliburn Micro Framework. We accomplish this by overriding 3 methods, the GetInstance, GetAllInstances and BuildUp.
private SimpleContainer _Container = new SimpleContainer();

protected override object GetInstance(Type service, string key)
  return _Container.GetInstance(service, key);

protected override IEnumerable GetAllInstances(Type service)
  return _Container.GetAllInstances(service);

protected override void BuildUp(object instance)
Service Binding
Most of the code above are self explanatory. Having registered/configured your IoC Container with the framework, the next task is to register your contracts. We do this by overriding the Configure Method.
protected override void Configure()
  _Container.Instance(new WindowManager());
Notice the three different methods we have used to register the service bindings. The Instance Method registers a pre-constructed instance with the type. This is similar to the Singleton method, however with a significant difference. The instance of Instance Method is pre-constructed while for the Singleton Method registration, the instance of Type is created only when first requested.
That’s it, the IoC container would now do the magic for us, by resolving the contracts when required.
There is another approach (method) to register the Service Binding, which focuses on auto-resolution of the Type by scanning the assembly for any implementation of the particular contract. For example, if we need to replace the service binding of IShell with assembly inspection, we would do the following.
In the next part of Caliburn.Micro Tutorial, we will look into implementing the IoC container with the more advanced, MEF based IoC Containers.
Sample code for this section can be found here. For complete list of tutorials on Caliburn.Micro, please follow this link


Caliburn Micro #003 : Events (Short Hand Syntax)

Previously, We looked at one approach of binding Events to Controls. However, the convention based approach is one of the least used approaches in Caliburn Micro. Think about it, if you need to bind more than one event to the control, say for example, the Click Event and MouseOver Event, this approach would fall short.
Thankfully, Caliburn Micro provides another approach, based on Event Triggers, which solves this problem. While there is a long annotation version of the approach, we would stick to the shorthand version, which is, designed to be more developer friendly.
Convention Based Approach
Let’s declare a button and assign a OnClick Event to the control using the convention based approach first.
 <Button  x:Name="ClearTextMethod">Clear</Button>

Now, Let’s change the signature to Event Trigger based approach. First, we need to add a namespace in our XAML Headers.


Event Trigger Based Approach
And now we will attach the event. Notice the change in Syntax.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod]" />

As mentioned earlier, this approach allows us to attach more events to the Control. If we need to attach a MouseOver Event to the above button, all we need to do is add another pair of [Event][Action] separated by a semi-colon

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod];[Event MouseLeave]=[Action AnotherMethod]" />

Passing Parameter

We could also pass parameters to the method, with the same syntax.

A word of caution though when you pass a boolean parameter to the method. For example, invoking the method with following syntax doesn’t quite work.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod(true)]" />

The workaround is fairly simple thought, just include a single quote around the string representing True/False. We can modify the syntax as following.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod('true')]" />

Complete list of tutorials on Caliburn.Micro can be found here

Caliburn Micro #02 : BindableCollection & Events

In the previous part of this series, we looked into some of the basics of using Caliburn Micro. In this part, we will continue with few more examples, how to invoke a method on an event.

But before we do that, let’s expand our application a bit. Currently the application has two Text controls , wired up to a property (FirstName) in the View Model. Let’s expand it further and have 2 more properties, LastName and FullName.

Our expanded ViewModel Looks like following now.

private string _FirstName = "Jia Anu";

public string FirstName
 get { return _FirstName; }
 _FirstName = value;

private string _LastName;

public string LastName
 get { return _LastName; }
 set {
 _LastName = value;

We will add additional controls to our View, and add the necessary binding.

        <!--Row 1 Starts here -->
        <Label Grid.Column="0" Grid.Row="0">Full Name</Label>
        <TextBlock Text="{Binding Path=FullName, Mode=OneWay}" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2"></TextBlock>
        <!--Row 1 Ends here -->

        <!--Row 2 Starts here -->
        <Label Grid.Column="0" Grid.Row="1">First Name</Label>
        <TextBox x:Name="FirstName" Grid.Row="1" Grid.Column="1"></TextBox>
        <!--Row 2 Ends here -->

        <!--Row 3 Starts here -->
        <Label Grid.Column="0" Grid.Row="2">Last Name</Label>
        <TextBox x:Name="LastName" Grid.Row="2" Grid.Column="1"></TextBox>
        <!--Row 3 Ends here -->

Bindable Collections

Let’s expand it futher, let’s introduce a model now. We will add a model in our Model Folder.

public class DeparmentModel
public string DepartmentName { get; set; }
public string Supervisor { get; set; }


And introduce two new properties for our View Model.

private BindableCollection _DepartmentCollection = new BindableCollection();

public BindableCollection DepartmentCollection
get { return _DepartmentCollection; }
_DepartmentCollection = value;


private DeparmentModel _SelectedDepartment;

public DeparmentModel SelectedDepartment
get { return _SelectedDepartment; }
_SelectedDepartment = value;

We will delve more into BindableCollection later, but for now, let’s think of it as a means for binding to a combo box. Since we are not using any Db for this example, lets hard code some values in the constructor.

public ShellViewModel()
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Finance", Supervisor = "John Tommothy" });
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Development", Supervisor = "Alex Brown" });
DepartmentCollection.Add(new DeparmentModel() { DepartmentName = "Human Resource", Supervisor = "Dennis Burton" });

We will add a Combo box and another Text Area in our XAML to accodomate the changes. The XAML looks like following now.

        <!--Row 4 Starts here -->
        <Label Grid.Column="0" Grid.Row="3">Department</Label>
        <ComboBox Grid.Column="1" Grid.Row="3" ItemsSource="{Binding DepartmentCollection}" DisplayMemberPath="DepartmentName"
                 SelectedItem="{Binding SelectedDepartment,Mode=OneWayToSource}" ></ComboBox>
                <!--Row 4 Ends here -->

        <!--Row 5 Starts here -->
        <Label Grid.Column="0" Grid.Row="4">Supervisor</Label>
        <TextBlock Grid.Column="1" Grid.Row="4" x:Name="SelectedDepartment_Supervisor"></TextBlock>
        <!--Row 5 Ends here -->

Run our application and you can now see the combo box in action. Everytime you change the Department, the corresponding Supervisor is displayed the TextArea.

Events and EventGuards

Now then, lets head to adding a button to clear the selected values. We will first introduce a method.

public void ClearTextMethod(string firstName,string lastName)
FirstName = string.Empty;
LastName = string.Empty;

We are passing two parameters, however we are not quite using it. However, the sigificance of the parameters come into light when we add our second method, CanClearTextMethod

public bool CanClearTextMethod(string firstName, string lastName)
return !string.IsNullOrEmpty(firstName);

Notice the naming patterns used for the methods and parameters. The ‘Can’ Method is named in such a way that it prepends ‘Can’ to the ClearTextMethod. This aids Caliburn Micro to recognize this method needs to be evaluated to enable CanClearTextMethod.

Also the parameters. They are named as similiar as the FirstName and LastName Properties. These are the properties which dictate whether to enable the method or not, which is being passed as paramers. Ensure the naming is correct and Caliburn Micro does the magic for you.

Lets add the necessary XAML for adding a button and wiring it up with the method.

        <Button Grid.Column="0" Grid.Row="5" x:Name="ClearTextMethod">Clear</Button>

The entire code sample for this examples can be found here. 

Complete List of Tutorials on Caliburn.Micro can be found here

Caliburn Micro #01 : Introduction

It has been long since i blogged, having caught up with the Product Release and Year End Vaccations. As the calender turns, it would be a good time to learn something new.

If you are building an WPF application and is looking out for MVVM Frameworks, you would be surprised with the amount of choices you are bestowed with. Despite Prism standing out as aruguably the most complete package available, there are times when you would like to try out a different framework. That brings us to Caliburn Micro, a light weight MVVM Framework, which might not be as powerful as Prism, but still does its work in a simple and easy way.

Bonus :  Caliburn.Micro Starter Kit Extensions for WPF is now available at Visual Studio Marketplace

Okay, that’s for an Intro, lets get our hands dirty and create a customary ‘Hello World’ app using Caliburn Micro. Let’s kick start our Visual Studio , create a new WPF Application and do the obvious step, add ‘Caliburn Micro’ Nuget package.

CM Demo 01.JPG

Once you have the necessary dependencies in, we will start with creating our ‘Hello World’ application. Normal WPF application would have ideally looked for the “StartupUri” Tag under your app.xaml to kick start your first page. The Caliburn.Micro works differently. So lets first go ahead and remove the StartUri tag and replace it with bit of XAML to ensure it takes advantages of features of Caliburn.Micro.

Our App.Xaml would now look like following.

<Application x:Class="App001.App"
                    <local:Bootstrapper x:Key="Bootstrapper"></local:Bootstrapper>

As you can see we have replaced the StartupUri and added a Resource Dictionary called Bootstrapper. At this point, Bootstrapper doesn’t exist, so we will go ahead and create it. Bootstrapper will act as the entry point for our WPF application and would point to the Screen that needs to be loaded first.

public class Bootstrapper : BootstrapperBase
 #region Constructor
 public Bootstrapper()

 protected override void OnStartup(object sender, StartupEventArgs e)

As seen in the code above, the Bootstrapper class is derieved from BootstrapperBase class from the Caliburn.Micro library. We have done two things here.
a) Called the Initialize method in the default constructor.
b) Override ‘OnStartUp’ method and called a single method, DisplayRootViewFor, pointing to the Base View Model which we want to load first. In this particular example, we have called it ShellViewModel.

As in the earlier case, we do not have the ShellViewModel class defined at the moment, which obviously becomes our next step. Prior to which, we will create 3 folders, each representing the three components of MVVM in the project – Models, Views, ViewModels. Remember naming the folders exactly the same, with names denoting plurals, so that we can take advantage of the Caliburn Magic.

We will now create the ShellViewModel Class under the ViewModels Folder.

public class ShellViewModel:Screen

Let’s keep it simple for the moment, san any properties and derieve it from Screen Class ( we will delve into other derivative options later). We will add the View for the ViewModel, again keeping it devoid of complicated controls for the sake of example.

        <TextBlock Text="Jia"></TextBlock>

As seen the in code above, we have called it ShellView and have placed it under the Views Folder. The naming is of foremost importance here as the Caliburn Framework relies heavily on the naming conventions to wireup the View and View Model. Unlike, Prism you don’t need to set the ‘Autowireviewmodel’ property, this is being automatically done by the Caliburn framework as long as you follow the naming convensions.

For sake of simplicity being the first example, we have hard coded the values for TextBlock and TextBox, we will replace it with binding as we move on with the example.

That’s it, you are all set to run the basic ‘Hello World’.

Okay, let’s now add couple of Properties and bind them to our controls. Let’s go ahead and create the properties in ViewModel.

private string _FirstName = "Jia Anu";

public string FirstName
get { return _FirstName; }
_FirstName = value;

Now let’s head towards the View and wireup the FirstName property. Modified XAML looks as below.

           <TextBlock Text="{Binding Path=FirstName, Mode=OneWay}" ></TextBlock>
        <TextBox x:Name="FirstName" ></TextBox>

Now you can run the application and see the magic of MVVM model in action via Caliburn Micro. In the next post, we will delve more into the CM features. The code for this project can be found here

An Introduction to EcSolvo.RestHelper

This post intends to act as an introductory guide on the EcSolvo.RestHelper Nuget. It takes you through the Main Methods that you would be using in your routine tasks.

RestHelper Constructor and ExecuteAsync

The RestHelper Constructor and ExecuteAsync Method is the heart of RestHelper Library. It is build on ‘Pit of Success’ philosophy, removing possible erroneous steps by the consuming Developer.
The RestHelper Constructor takes a single Parameter, which is the base address of your API.The ExecuteAsync is an Asynchronous Method which take in two Parameters,
b) Resource (URL to the exact API Resource)

For GET Request

For Handling URI Parameters, the EcSolvo.RestHelper Library exposes a method called ‘AddURLParameters’, which helps to add parameters to the QueryString dictionary.

private string _BaseAddress = "http://localhost:8888/";
var resourceURL = "api/user/SingleParamStringResponse";
var restHelper = new EcSolvo.RestHelper(_BaseAddress);
string ParameterKey = "VariableStr";
string ParameterValue = "DummyString";
restHelper.AddURLParameters(ParameterKey, ParameterValue);
var result = await restHelper.ExecuteAsync(HttpMethod.Get, resourceURL);

The library works even if the parameter passed is a Complex Parameter (Controller uses FromUri Attribute).

For POST Request

For Handling OnBody Parameter in POST Request, the library exposes a method called ‘AssignMessageBodyParameter’.

var result = await restHelper.ExecuteAsync(HttpMethod.Post, resourceURL);

If the POST Request have additional URI Parameters, it can use the ‘AddURLParameters’ Method to add it to the dictionary.