TopMenu

Basics of Caliburn Micro with simple injector IOC in WPF mvvm–Part I BootStrapper

This is the first part of post series for basics of using Caliburn micro for MVVM framework in WPF. In this blog post we will see the benefits of using a MVVM framework and how it can ease your life when working with MVVM design specially with WPF. For the series I’ve chosen Caliburn Micro because this is a lightweight, powerful, easy to use and highly recommended framework with a very good technical documentation. Second we’ll talk about the SimpleInjector for IOC (Inversion of control) because this is reported as fastest and easy to use IOC container framework. IOC container is required with Caliburn micro in the bootstrapper(Entry point) to register all the view model types and other types so that they can be resolved at run times. The IOC keeps our application fully decoupled and this is what MVVM is for. You’ll see the true MVVM taste here with fully decoupled views and view models in upcoming posts.

So Let’s get started with the first step writing the Bootstrapper for the WPF application:

Application Bootstrapper – The bootstrapper is required to register and configure all the runtime and startup components. This will be your entry point of your WPF application. And rather than directly adding the referencing of your startup window you’ll be registering the bootstrapper in App.XAML

Writing the bootstrapper -

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Caliburn.Micro;
  6. using DataGridSample;
  7. using SimpleInjector;
  8.  
  9. namespace CaliburnMicroMvvmWpfDemo
  10. {
  11.     internal class AppBootstrapper : Bootstrapper<MainWindowView>
  12.     {
  13.         /// <summary>
  14.         /// The global container.
  15.         /// </summary>
  16.         public static readonly Container ContainerInstance = new Container();
  17.  
  18.         protected override void Configure()
  19.         {
  20.             ContainerInstance.Register<IWindowManager, WindowManager>();
  21.             ContainerInstance.RegisterSingle<IEventAggregator, EventAggregator>();
  22.  
  23.             ContainerInstance.Verify();
  24.         }
  25.  
  26.         protected override IEnumerable<object> GetAllInstances(Type service)
  27.         {
  28.             return ContainerInstance.GetAllInstances(service);
  29.         }
  30.  
  31.         protected override object GetInstance(System.Type service, string key)
  32.         {
  33.             return ContainerInstance.GetInstance(service);
  34.         }
  35.  
  36.         protected override void BuildUp(object instance)
  37.         {
  38.             ContainerInstance.InjectProperties(instance);
  39.         }
  40.     }
  41. }

In the above code in order to create a bootstrapper we just need to tell the inbuilt Bootstrapper<> the type of startup window view model and inherit the class in our AppBootstrapper class. Now we need to override few inbuilt method of Bootstrapper<> in order to complete the configuration. Register the interfaces of IWindowManager and IEventAggregator (Optional and for later use) in the configure method. Just use the above code to write your initial bootstrapper though you need to add more lines of code in the Configure method to register your all other view model types later.

Updating the App.XAML

To add the entry of bootstrapper change the App.xaml file to look something like below.

  1. <Application x:Class="CaliburnMicroMvvmWpfDemo.App"
  2.              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.              xmlns:Boot ="clr-namespace:CaliburnMicroMvvmWpfDemo">
  5.     <Application.Resources>
  6.         <ResourceDictionary>
  7.             <ResourceDictionary.MergedDictionaries>
  8.                 <ResourceDictionary>
  9.                     <Boot:AppBootstrapper x:Key = "bootStrapper" />
  10.                 </ResourceDictionary>
  11.             </ResourceDictionary.MergedDictionaries>
  12.         </ResourceDictionary>
  13.     </Application.Resources>
  14. </Application>

Once you changed the above setting your application is ready to launch. You have successfully created the entry point for the application. Now to have your Global even handler Caliburn Micro provide overrides for internal exception handlers which you had in App.xaml.cs. Below events could be added in the AppBootstrapper class.

  1. protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
  2. {
  3.     // do custom code here which you want to run on startup
  4.     base.OnStartup(sender, e);
  5. }
  6.  
  7. protected override void OnUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
  8. {
  9.     // Write you custom code for handling Global unhandled excpetion of Dispatcher or UI thread.
  10.     base.OnUnhandledException(sender, e);
  11. }

Here in this post I tried to cover the starting step of adding the bootstrapper for caliburn micro. Also if you can see we have create our MainWindowViewModel class first but haven’t wrote anything in it neither we have any view here. In the post we’ll see creating main window view model and basic binding and other MVVM stuff.

Hope you enjoyed it. Please leave a comment or suggestion.

Administering windows machine programmatically

image courtesy 123rf.comBeing a .Net developer, Automation engineer or IT administrator we always in need of dealing with windows machine configuration and settings. Most of the time changing/updating system setting programmatically. If you’re an Automation engineer you must be using scripting language(vbscript, jscript) cause you’re in love with it, If you’re a .Net developer must be using win32 library. Being an IT administrator you may be using Powershell. All interfaces are to interact with the kernel of windows and sending/querying/invoking inbuilt methods. If you heard of WMI (Windows Management Instrumentation) or even if you didn’t then no worries you’ll know everything after reading this article about what, why and how(s) of WMI.

What is WMI?

Windows Management Instrumentation (WMI) is a scalable, extensible management infrastructure, included as part of Windows 2000 and later. An implementation of the Web-based Enterprise Management (WBEM), and based on the Common Information Model (CIM) adopted by the Distributed Management Task Force (DMTF), it includes a rich set of management data about computer systems, the operating system, and applications on a given managed system.

Purpose

Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems. You can write WMI scripts or applications to automate administrative tasks on local/remote computers but WMI also supplies management data to other parts of the operating system and products, for example System Center Operations Manager, formerly Microsoft Operations Manager (MOM), or Windows Remote Management (WinRM).

Where applicable

WMI can be used in all Windows-based applications, and is most useful in enterprise applications and administrative scripts. System/IT administrators can find information about using WMI at the TechNet ScriptCenter,

WMI and .Net framework

The System.Management namespace is the WMI namespace in the .NET Framework. This namespace includes the following first-level class objects that support WMI operations:

  • ManagementObject or ManagementClass: a single management object or class, respectively.
  • ManagementObjectSearcher: used to retrieve a collection of ManagementObject or ManagementClass objects based on a specified query or enumeration.
  • ManagementEventWatcher: used to subscribe to event notifications from WMI.
  • ManagementQuery: used as the basis for all query classes.

Using these class libraries, A developer can monitor, get reports, and manage local resources seamlessly.

Writing a sample code to create a system restore point using C# programmatically:

To start writing a sample application you must know few things. There namespaces stored on the windows machine and can be found under the “root”. so all namespaces will be start with a path like “\root\DEFAULT”, “\root\CIMV2” etc. Under there namespaces there are classes available named as “Win32_Environment” or “Win32_ComputerSystem” etc. Then we have methods and properties associated with each class.

Below is the sample code that will create a system restore point.

  1. using System;
  2. using System.ComponentModel;
  3. using System.Management;
  4. using System.Windows.Forms;
  5.  
  6. namespace WMISample
  7. {
  8.     public class CallWMIMethod
  9.     {
  10.         public static void Main()
  11.         {
  12.             try
  13.             {
  14.                 ManagementClass classInstance =
  15.                     new ManagementClass("root\\DEFAULT",
  16.                     "SystemRestore", null);
  17.  
  18.                 // Obtain in-parameters for the method
  19.                 ManagementBaseObject inParams =
  20.                     classInstance.GetMethodParameters("CreateRestorePoint");
  21.  
  22.                 // Add the input parameters.
  23.                 inParams["Description"] = "Test Restore point";
  24.                 inParams["EventType"] = 100; // 100 -BeginSystemChange value
  25.                 inParams["RestorePointType"] = 0; // 0 - Application install restore point type
  26.  
  27.                 // Execute the method and obtain the return values.
  28.                 ManagementBaseObject outParams =
  29.                     classInstance.InvokeMethod("CreateRestorePoint", inParams, null);
  30.                 
  31.                 // Custom code to throw the Win32 exception for information related to the error code
  32.                 int success = Convert.ToInt32(outParams["ReturnValue"]);
  33.                 if (success != 0)
  34.                 {
  35.                     throw new Win32Exception(success);
  36.                 }
  37.                 // List outParams
  38.                 Console.WriteLine("Out parameters:");
  39.                 Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);
  40.             }
  41.             catch (ManagementException err)
  42.             {
  43.                 MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
  44.             }
  45.         }
  46.     }
  47. }

The above code is handling the status codes return from InvokeMethod(). The Win32Excpetion class can return the exact meaning of the returned status code.

Run this code and when you go to the system restore window from Computer –> Properties –> System protection –> System Restore you’ll find your recently created restore point there.

SNAGHTML290c1a1c

Similarly you can also write code to restore the windows system to a previously created Restore point.

Now to help you with the Namespaces and Class search for particular action on windows there’s whole documentation available in details on MSDN.

Don’t worry, To ease the process of finding the namespace, class and method and properties info Microsoft have create an tool. This tool can also generate write code for you for a particular action. Download the WMI code generator. This tool can generate WMI programs in various languages like C#, VisualBasic, VB script etc. There’s an option available in Menu items “Code Language” choose your favorite one.

Here are few snapshots from the Tool:

SNAGHTML290de45d

image

Things to Keep in mind before you start playing:

1. Firstly before running any code against you machine. “Make sure you know what you’re doing”. I will not responsible if you break your machine changing un necessary settings.

2. This is not guaranteed that the code generated from this tool will run on all machine of windows. It might run on few machines but you might have to put some tweaks to run the code on different version of Windows operating systems.

Please leave a comment/suggestion if you read it till this point.

(images courtesy - wpclipart.com & 123rf.com)

Manage Nuget packages with source control

Nuget is the visual studio plugin that allows you to download and install the libraries directly into your solution. It’s another adapted technology by Microsoft to save the time for searching and installing libraries in your projects. If you’re not aware about the Nuget then visit Nuget.org.

Why should I know about Nuget?

For example if you are using entity framework in your project in Visual studio 2012 then you’ll notice when you add the Ado.net Entity Data Model then your project will take little time to get the latest release of Entity framework through nuget. Then in your solution directory you’ll find a Packages folder and a package.config file added in your project. Similary, there are many projects who are hosted on Nuget server ready for download, install and use in your projects. For e.g. MVC scaffolding, Log4Net, Rhino mocks, JQuery, Json.NET, Castle Windsor etc. and lot many more.

So if you’re on VS2010 or earlier version just get the VS plugin available for your version of visual studio and get ready to have all these libraries to install in your project.

Should I check in the Packages folder in the Source Control to make them available for peers?

Answer is “NO”. You should not checkin packages folders as this will increase the size of repository and become overhead when taking latest (as the packages folder have size in MBs).

Now if you want to have your installed libraries available to all the peers then here’s the tip that should use to make the overcome the burden of putting packages into the source control repository.

Install the Nuget package manager:

If you’re connected to internet you can download the nuget package manager from Online gallery from Tools -> Extension Manager

In the Extension Manager dialog box, select the Online Gallery tab, and enter "nuget" in the search box to find the NuGet Package Manager extension.

Select NuGet Package Manager and then click Download.

If you want to download the nuget packages installer separately then it’s available on Visual Studio Gallery.

Download and install your desired package/library from Nuget.

Now before proceeding for checkin you must enable the setting for restoring the missing packages from visual studio 2012.

clip_image001

This will add following files in your solution.

clip_image002

Finally it’ll add the following setting in the Nuget.Config file that will prevent the packages to be added into the source control.

clip_image003

Here’s the complete documentation for above steps.

Note: This setting will instruct the MSBUILD to download the files before building the project. But there’s another option you need to enable to get the packages restored while building.

Go to Tools -> Options -> Package manager

And check the check box for “Allow Nuget to download the missing packages during builds”.

There are other option available if you don’t have VS installed and you need to enable this option for Build server e.g. CCnet etc. Just set the environment variable EnableNuGetPackageRestore to "true".

If you are working with .Net 2.0 or so you can readout this to get the setting enabled restoring packages during build requires explicit consent from the user.

And you’re done. Next time you don’t need to carry those library files with your source controls. And this keep your repository neat and clean.

SQL Server 2008 R2 on windows 8 Error 17058 when starting the service

Windows 8 is the new operating system from Microsoft and now it’s spreading through the development systems replacing windows 7. So you may need to re-install your sql server and Visual studio etc. Recently I was trying to install the sql server 2008 on my x64 based windows 8 machine, I ran into this error after installing the Sql Server 2008 R2 the service was not getting started. When opened the service configuration manager then I got “WMI provider Error” Unable to call a remote procedure or something like that.

Now do not panic and just install the Sql server 2008 SP1 and the problem will be gone.

After installing this if will able to see everything is back in Sql server configuration manager. But if you’re still not able to restart the service just go to the error log of Sql server. You can find it by right clicking on the service from configuration manager and select properties. Now go to advance tab and open the Dump directory option.

clip_image001

Now open the error log file and see what the last error has logged there. Most probably you’ll see the error for VIA service enable and VIA is deprecated in this version something like that. So just come back to the configuration manager select the client protocols for <<Your Sql server instance name>> and disable the VIA protocol.