Subscribe RSS 2.0 cshandler feeds

Monday, 20 May 2013

Basics of Caliburn Micro in WPF mvvm–Part II Binding

In the first part of the MVVM using caliburn micro with WPF we saw how to write the bootstrapper to setup everything for the caliburn micro library. Now in this part we’ll see how to start creating new pages in the application and how the binding and events are being defined using this small library project with power of MVVM.

Before we start I would recommend you to go through the previous article showing how to do setup. Once you done with the setup you can design the MainWindowView.Xaml file.

Naming Conventions in Caliburn micro

The caliburn micro built so that it can predict the view and viewmodel mapping just by the names. So if you view should be named like MainWindowView and your view model should be named as MainWindowViewModel. This way caliburn will automatically search for the view when loading the view model in the memory.

clip_image001

Designing MainWindowView

You can have multiple controls defined in your sample page. Let’s take the below as the sample view model

<Window x:Class="Admiral.MDS.WizardUI.Views.MainWindowView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="{Binding DisplayName}" Height="350" Width="525"
        WindowStyle="None" WindowState="Maximized" WindowChrome.IsHitTestVisibleInChrome="True" WindowStartupLocation="CenterScreen">
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" Height="50">
            <TextBox x:Name="SearchText" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="12" Height="24" Width="100" />
            <Button x:Name="Search"></Button>
        </StackPanel>
    </Grid>

Now here we have a button and textbox. Let’s see the code for the View model of this window the caliburn micro is doing to provide in a easy to write code way.


using System;
using System.ComponentModel;
using System.Windows;
using Caliburn.Micro;
 
using ILog = log4net.ILog;
 
namespace SampleApplication
{
    /// <summary>
    /// The main window view model.
    /// </summary>
    internal class MainWindowViewModel : Conductor<IScreen>.Collection.OneActive
    {
        /// <summary>
        /// The container.
        /// </summary>
        private readonly SimpleInjector.Container container;
 
        /// <summary>
        /// holds teh event aggregator
        /// </summary>
        private readonly IEventAggregator eventAggregator;
 
        /// <summary>
        /// The logger.
        /// </summary>
        private ILog logger;
 
        /// <summary>
        /// The searchText property.
        /// </summary>
        private string searchText;
 
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindowViewModel"/> class.
        /// </summary>
        /// <param name="container">
        /// The container.
        /// </param>
        /// <param name="eventAggregator">
        /// The event aggregator.
        /// </param>
        public MainWindowViewModel(SimpleInjector.Container container, IEventAggregator eventAggregator)
        {
            this.container = container;
 
            this.DisplayName = "Sample main window view model";
            this.eventAggregator = eventAggregator;
            this.eventAggregator.Subscribe(this);
 
            this.logger = this.container.GetInstance<ILog>();
 
            this.logger.Info("MainWindow view loaded");
 
        }
 
        /// <summary>
        /// Gets or sets the message.
        /// </summary>
        public string SearchText
        {
            get
            {
                return this.searchText;
            }
 
            set
            {
                this.searchText = value;
                this.NotifyOfPropertyChange(() => this.searchText);
            }
        }
        /// <summary>
        /// Search action
        /// </summary>
        public void Search()
        {
            MessageBox.Show(String.Format("Search is being performed for text {0}", this.SearchText));
        }
    }
}

So in the view model we have defined a property named SearchText and a void method named Search. Other setup we have done in the constructor of the MainWindowViewModel class.

Now here’s the magic start. You don’t have to write anything else so just press F5 and run the application.

You can ask question how the control on the view are bound to the property and the method is bound with the Click action of the button. Here’s the magic that happened behind the scene, We talked about the naming conventions if you look at the View then we have the Textbox named same as the property defined in the Viewmodel similarly the button have the same name as the Method. This is how the caliburn detects and map the property and method to the controls with their kind.

We’ll look at more advance stuff in upcoming posts on caliburn micro. So tuned in and happy programming.

Visual studio 2012 and .Net 4.5 expert development cookbook by Abhishek sur

Recently, I have been reading a book Authored by a friend Abhishek sur. He’s a dedicated community guy with great deep knowledge of .Net framework and C# language. So finally I got the chance to spend my time reading all recipes he made throughout the book. I found it of my interest so I would like to write some feedback on the same:

clip_image001

Audience the book is targeting -

I would say this book is for developers who are above level 200(Intermediate) and familiar with terms of .Net development as well the as the challenges they have faced during the development. Few recipes are providing the solution for the same. Chapter 5 page 272 (Weak even pattern) is showing how you can get rid of Memory leaks produced by strong coupling of subscriber and listener.

What the book is covering?

Taking the reader to the next level the book is Including the latest Visual studio 2012 features with .Net 4.5 framework capabilities. Also there are few chapters where Author is deep diving into the concepts behind the scenes. Chapter 2 (Basics of .NET Programs and Memory Management) is the very good example. This book is not taking you to the expert level of only one topic but to show you the diversity of development and how the new Visual studio and .net 4.5 helps you in various ways.

I found this book really interesting as every next chapter is like swinging in the mood. Since it’s covering all the new enhancements so the diversity was expected.

You can order your copy from here.

Or you can enter into the contest the Author have announced here to get the FREE copy of the book.

Happy Learning!!

Saturday, 18 May 2013

Manually Installing language pack on Windows8

In need of installing a language pack on windows 8 we can easily install the new language pack from the control panel –> Languages. But this requires you to connected to internet to download and install the selected language pack. In this post I’ll tell you how to install the language pack if you have the language pack already downloaded or on some other media.

There’s an wizard to install the languages on Windows8. It can be found under the

C:\Windows\System32\lpksetup.exe

image

Though it uses another utility to install the language packs lpkinstall.exe which is also available in the same directory i.e. System32. This lpkinstall.exe is a command line utility and  can be used to install the language packs in a silent mode.

Now you just need to follow the below steps:

1. Launch the lpksetup.exe. You’ll see the below window asking for install/uninstall of the language pack.

SNAGHTML2bc3bf4e

2. Click the Install display languages option and browse the folder that contains your language packs on your local media.

SNAGHTML2bc5fb06

Now click next and install.

And you’re done. Hope this Tips helps those windows users who don’t know that there’s option available to install the language packs offline as well. Good luck :)

Sunday, 31 March 2013

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)