Sunday, December 23, 2012

Silly but useful stuff - Part 1 (.Net)


Collection and List
Let's have a look at this snippet:























In first sight, most of you might feel that both List and Collection will contain print numbers from 1 to 6. Am I right?

But Alas! There is a hidden gotcha in it ;)
Because the actual output is:







What happen surprised???

If you have ever tried to get in depth of Collection and List, then you might know the answer. Well, the answer is pretty simple. MSDNdocumentation clearly states that "Initializes a new instance of the Collection class as a wrapper for the specified list".

And on the other hand, MSDN documentation states that "Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied."

Hope now it is clear to you.

So, the moral of the story is, one should be very cautious while using List and Collection else it can bite you really very-very hard.

Saturday, November 3, 2012

Converting a given string to Title Case

To convert string in title case is bit tedious and may require lot of code as there is no direct method available in C#.Net  in String class. So, here I am sharing a method, which will be the extension method for String class and can be used to convert given string to title case.
Here I am using CultureInfo from Globalization and ToTitleCase method of TextInfo class.


public static class StringExtensions
{
    public static string ConvertToTitleCase(this string input)
    {
        System.Globalization.CultureInfo cultureInfo =
        System.Threading.Thread.CurrentThread.CurrentCulture;
        System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;
        return textInfo.ToTitleCase(input.ToLower());
    }
}

Hope reusing this will save lot of your time :)

Wednesday, October 24, 2012

Changes in Visual Studio 2012

Introduction

Nowadays, we see that software development process is shifting from enterprise-driven process to consumer-focused approach, in which applications are fully based on the taste of consumer market and the devices they want to use. And the speed at which these devices and platform are emerging, it is becoming more and more challenging for developers. Earlier applications were used to run on a server or a desktop but today many more devices like smartphones, tablets are becoming ubiquitous. So, in this case developer must either create applications that work on multiple platforms or make applications tailored to each platform with similar logic and the most important thing is, there should be a connected experience that allow user to seamlessly move among all these devices and platforms.
But as long as Microsoft is with developers, developers need not worry. Agree ??? 

Visual Studio 2012 

Launch of Visual Studio 2012 solved a lot of problems. Now instead of the developer worrying about platform and devices, Visual Studio will take care of it. Isn't it good? Visual Studio 2012 makes it easy to develop apps for multiple platforms including Windows Smartphones, slates, Xbox and of course traditional desktops. With the birth of Portable Libraries, developer can write and compile the code once and then deploy the assembly anywhere. Enhanced version of Team Foundation Server is another major addition. Continuing to all these, one major change are App Store which help consumer to quickly search and acquire the required application software. In App Store, Applications can be monetized also either by charging or including advertisements in the application. Visual Studio 2012 provides integrated tools to publish our applications in this app store.

Major changes done in Visual Studio 2012
  • Interface of Visual Studio is redesigned in order to remove significant clutter from the screen, while still providing a fast access to major features.
  • Visual Studio 2012 is not only for developers, but many other people like stakeholders, architects, project managers, designers, testers etc.
  • Visual Studio 2012 helps developer create applications that span device boundaries. Project templates, debugging tools and portable class libraries all help to make this process easier 
  • Visual Studio 2012 supports developers by enabling them to create solutions that are highly scalable, supporting a range of models from durable full duplex synchronous services to high-throughput asynchronous services.
  • Developing a scalable solution is only half the challenge: You must also provide a suitable environment to act as a host. With Visual Studio you can develop for a range of infrastructure choices. Whether you choose to target a physical server, a virtual server, or a private or public cloud, Visual Studio 2012 is your solution. If you decide to use the Windows Azure™ public cloud offering, you can deploy directly from Visual Studio to the cloud. Visual Studio also includes IIS Express (lightweight IIS), which is suitable for testing the apps.

Visual Studio Team Foundation Server 2012

  • It enables stakeholders to participate as equally as developers throughout the application life cycle and help developers in faster delivery with more business value.
  • As earlier version, Visual Studio TFS can be installed on local server but in Visual Studio 2012, Team Foundation Server is available as an online SaaS version.
  • Sometimes, some teams may be using a different development environment, such as Eclipse™. Visual Studio Team Foundation Server 2012 provides adapters to connect to supported IDEs so that developers can work in their preferred development environment. 

Blend

  • It enables developer to create more stunning applications using XAML.
  • Portability between Visual Studio 2012 and Blend has been improved, and the design surface in Visual Studio has been upgraded to more closely match the experience in Blend.

Visual Studio Test Professional 2012

  • This helps testing process to fully integrate into Software Development Life Cycle (SDLC).
  • Using this test cases and testing can be performed more quicker using the same tools as developers.
  • It allows Exploratory Testing, which enables testing without creating any formal test plans. It allows Test Manager to record, attach screenshots, and create a test case
  • Testing on remote devices without installing Visual Studio 2012 or Test Manager on the device itself (only a small test agent need to be installed on the device). 
There are lots of interesting facts, which are associated with Visual Studio 2012, which I'll be posting as and when I'll get time.  

Monday, October 22, 2012

Windows App Splash Screen - Beginners Tutorial

Introduction
Continuing to my previous article title, here we will see about splash screens, how to set the splash screen image and how to change the background color. 

Splash Screen
Every Windows Store app must have splash screen. Splash screen consists of image and a background color. Whenever the user will launch application, splash screen will be the first to come up. Now you might be thinking, what is the purpose of splash screen???
We all know that, whenever any application is launched, lot many things happened at backend before our application is fully launched. So, splash screen provides a way to hide all those background details from the user. This splash screen is launched, when application is initialized and as soon as our application is ready for interaction, this splash screen goes off. Isn't it a nice thing ?
Now question is can we customize this splash screen ? Then my answer will be Yes. You can customize image as well as background color. Enough of theory, let's try it out ...

Demo and sample code
Open the project in Visual Studio. Open the package.appxmanifest file from the solution explorer. Opening the manifest file by double clicking will automatically open the file in Visual Studio Manifest Designer as
















Open the ApplicationUI tab and scroll till the end, until you find Splash Screen section. If you have not modified anything in Splash Screen section, you will be able to see "images\splashscreen.png" path in the Splash Screen field and if you want to see the markup code for it then open your manifest file in the notepad or any text editor as:  
<applications>
    <application id="App" entrypoint="HelloWorldSample.App" executable="$targetnametoken$.exe">
      <visualelements description="HelloWorldSample" backgroundcolor="#464646" foregroundtext="light" smalllogo="Assets\SmallLogo.png" logo="Assets\Logo.png" displayname="HelloWorldSample">
        <defaulttile showname="allLogos">
        <splashscreen image="images\splashscreen.png">
      </splashscreen>
    </defaulttile>
  </visualelements></application></applications>


If you want to change this default image, then click on browse the browse button to select the image of your choice. Note: Please make sure that the image you are selecting must be of 620 x 300 pixels. 
Now coming to Background Color, it is also pretty simple. In the Splash Screen sectioour n, you will find the field with title Background Color. You can enter the color of your choice in this field. Setting of background color is optional for splash screen.

Things to remember while customizing splash screen:
BE careful while customizing the splash screen: As it is the first screen or let's say welcome screen of our app, it should have a good combination of image and background color. It should be very appealing. Here one thing to keep in mind is, when your application is launched, only the background color is adjusted as per the screen size, not the image size. Image size will always be intact.

USE extended splash screen
If you feel that your application needs to perform lots of background tasks before the user interation can happen or before the landing page appears, then extend your splash screen in a way, that it gives user a pleasing experience, instead of annoying.  Alternatively, you can provide additional information on the splash screen, in order to keep user busy by showing more interesting information about your application.

NEVER display advertisements
The purpose of splash screen is to let user know that app is loading, using the same for advertising and other useless stuff can confuse user also.

NEVER display about page
The main purpose of splash screen is to give user a smooth loading experience. So, your splash screen should never show information about version, date , etc.

USE proper image
It is always recommended to use the image, which gives idea about your application

USE progressbar
If you feel that your application is going to take more than a few seconds, then it is always good to show user a progress bar about application loading process.

Saturday, October 20, 2012

Creating Windows Store app - Beginners tutorial

Introduction
In this tutorial we will be creating a very basic Windows Store App using XAML and C#. As this is the very first tutorial of this series, I'll be focusing mainly on project setup and basic workflows and later on, in other upcoming series, I'll be picking up more advance concepts. So, before moving forward, let's talk about the environment setup to execute our app.

Pre-requisite
In order to complete Windows 8 metro style app, our machine need following things:
  • You need Windows 8 with Microsoft Visual Studio Express 2012
  • You need developer license 

Creating a project

  • Launch Visual Studio 2012. Select File >> New Project. The New Project dialog window appears and from the left pane you can select template of your choice
















In the left panel, you can select 'Windows Store' template. Once selected, center pane will show you the list of available items for the selected template. Here we are using Blank App, which will not contain any user controls by default. If require, we can add the controls at later point of time.
Give the name and location of the project and press OK button. After clicking on OK, you will see the structure similar to as shown below:























Here you will see that, your solution contains lots of file. I'll try to brief about each of these items.
  1. Logo.png and SmallLogo.png images - to display in the start screen
  2. StoreLogo.png - to represent your app in Windows store
  3. SplashScreen.png - to show at startup of your application
  4. MainPage.xaml - to run our app
  5. Package.appxmanifest - to describe your app and lists all the files that your app contains
These above files are required for all Windows Store apps, which are built using XAML and C#. While using Blank App template, we can replace our blank page with any other page templates, in order to take advantage of layout and other helper classes. 

Replacing the MainPage

  • Delete the MainPage.xaml from Solution Explorer by rightclick nad select Delete
  • Select Project >> Add New Item
  • SelectWindows Store from left pane and pick any page template from center pane. Here I am selecting Basic Page
  • Enter the name of the page. Here I am giving MainPage.xaml. First time when you add a new page to the Blank Template, Visual Studio will show you a message as











Click Yes, to add these files. You will see, all the newly added files under the Common folder.
Build your app and now you will be able to see your page in design view. Press F5 and you will be able to see your app running as:














At this point of time, there is no button to close the app. So, you can use Alt+F4 to close it, typically we don't close Windows App (what is the reason behind this, we will see in our next article of this series). Now press the Windows key, you will be able to see a new tile added for your new app. Now to run the app, you can click or tap on that directly. Isn't it a good feature ???
Congratulations on building your first Windows store app.

Working with App.xaml

App.xaml is one of the most important files as this file is store the things, which you can access across the application. Double click and open the file. You will notice that, it contains a ResourceDictionary, which in turn has a reference of StandardStyles.xaml ResourceDictionary. This StandardStyles.xaml contain lots of style, which give look and feel to our app:

<application.resources>
        <resourcedictionary>
            <resourcedictionary.mergeddictionaries>                
                <resourcedictionary source="Common/StandardStyles.xaml">
                  </resourcedictionary>
        </resourcedictionary.mergeddictionaries>
 </resourcedictionary></application.resources>


Now go to code behind file of App.xaml. It contains a constructor, which calls InitializeComponent() method. This is the auto generated method, whose main purpose is to iniyialize all the elements, which are declared in xaml file. It also contains the suspension and activation methods as:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
 
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227

namespace HelloWorldSample
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
 
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args" />Details about the launch request and process.
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;
 
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
 
                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }
 
                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
 
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
 
        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender" />The source of the suspend request.
        /// <param name="e" />Details about the suspend request.
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }
}

Now moving to MainPage.xaml. This file defines the UI for your app. In code behind of this file, you will notice that, it uses LayoutAwarePage, which extends Page class and provides various mathods for navigation, view management and page management. In MainPage.xaml.cs file, you can add logic and event handlers for your application. The Basic Page template has two mathods, which you can use to save and load the page state.
protected override void LoadState(Object navigationParameter, Dictionary<string,string> pageState)
  {  }
 
 protected override void SaveState(Dictionary<string,string> pageState)
 {  }

Adding content to MainPage.xaml
Open MainPage.xaml from solution explorer. Now if you want to add more content, just open the xaml and start adding it as:

<stackpanel margin="120,80,0,0" grid.row="1">
                <textblock width="Auto" height="29" text="Welcome to my first windows store app">

Run your application by pressing F5 and you will see below changes:




Hope this material will be a very good start for beginners.

The URL you requested has been blocked as per DOT guidelines

Today while doing internet surfing, I found that few sites are giving error message as: 








and the solution to this error is:
  1. Go to this URLand download Tor Browser Bundle 
  2. Extract the downloaded folder on your machine
  3. Run start Tor for browser
  4. And you are done. Now access the internet and your issue is resolved. 
Hope it helps :)

Monday, August 27, 2012

Out-Of-Memory error and Visual Studio crashes


As part of assignment, I was working on a project, which is having 137 projects Windows Form in a solution. Whenever I was building my solution, I was getting Out-Of-Memory error and due to this my Visual Studio use to get crash. Then the only solution left with me was to restart my Visual Studio L. Earlier I as facing this issue once a while, but from last week, it is occurring frequently. Hope you can imagine, how painful it is restart the Visual Studio every now-and-then, especially when your solution contains such a huge number of projects. My error was something like this: “The "ResolveManifestFiles" task failed unexpectedly.System.OutOfMemoryException: Insufficient memory to continue the execution of the program.” 


The only thing, which was coming into my mind, was that it is due to Visual Studio’s memory limits. I also tried to minimize Visual Studio, but no luck :(.
After consulting with few people, I got an idea to breakup my solution into multiple solutions. But again, it was not the best solution for me because my project was already on the last stage (about to over) and it was not the correct time to take this much big risk. So, I dropped this suggestion also.  

After hitting my head for 4-5 days, I reached to some conclusion. One of the reasons was Heap fragmentation, due to which, my Virtual Memory was keep raising and ultimately it was affecting my GC. But this reason was also not 100% correct. Because Virtual Memory will rise, only when I’ll run my application. But in my case, I was getting error during build itself. So, again no luck :(

While doing analysis on the same, I thought, let’s open manifest file and check once. And luckily I got the clue. On opening manifest file, I found that there are lot of hash values which are nothing but my image files. In my project I was using approx 150 image files. According to my project requirement, we were not supposed to deploy those image files. Then what those files were doing there, why they are part of my manifest?  Now a very BIG question was, how those image files became part of my manifest?

This happened because Visual Studio, by default sets image’s ‘Build Action’ property to ‘Content’. As soon as I changed this property to ‘None’, my error goes off. This one small property worked like a charm for me :)

By setting ‘Build Action’ property to ‘None’, I was able to reduce the size of manifest file to approx 0.9GB.

I shared this as a tip, so that you need not to spend 5-6 days, to analyze the issue :)

Wednesday, August 15, 2012

Starting with Prism - Part 2 of n

Background

Continuing to my Prism series 1 of n, in this series, I am going to talk about a few more interesting concepts like Modules and Views.

Modules

In this article, we will talk about how to take other views/logic and broken down into a small pieces called Modules and use them in your Prism application. We gonna start-up by talking about What a Module is, then registering Modules, loading Modules and then we will talk about how to initialize a Module.

What is a Module?

You can think Module as a building block for our Prism application. It is a package that contains all the functionalities and resources required for our application. Prism provides a support for run-time Module management in our application, in which each Module can be developed and tested independently. Prism application loads the Modules as and when they are required. Before moving forward, let’s have a look at how our application was architected inside Visual Studio prior to the concept of Modules.
In above figure, we have single solution and inside that we have single project and within that project we have every single view, all our services, and all our business logic. I mean, single project contain each and everything, which is required for my project. Now, we want to identify, how we can break down our application into smaller pieces called Modules as shown in below figure:
Now, if you look at our solution, you will see that we still have that main project with Shell and Regions in it whereas all the major functionality is defined outside the main project. From above figure, we can see that each Module is independent of each other. Here each module can be single class library or a DLL or a XAP, that includes a collection of other related components.
Each Module has a central class that implements the IModule interface and this is what identifies as a library to a Prism library. This interface has a single method in it called Initialize, which is responsible for initializing a Module and integrating it to your Prism application and all can talk later on with this module.
Creating a Module
In order to create a Module, one needs to add below reference to the project:
  • Microsoft.Practices.Prism.dll
Next we need to add a class library and inherit IModule interface, as:
public class MyModule : IModule 
{ 
   public void Initialize()
   { // TO DO: } 
}

Registering and Discovering Modules

All the Modules need to be loaded at runtime in particular application. ModuleCatalog contains information about all Modules to be loaded, it knows the location and it knows the order in which they are going to be loaded. It even knows that a particular module is dependent on another Module. I hope, one thing is clear that we need to register our Module to ModuleCatalog via code, XAML or by a configuration file. 

Loading Module

Well, next process in Module lifetime is loading a Module. All of the assemblies that contain the Module need to be loaded into the memory. This can be from disk, directory or the web link (only for SL). Prism allows us to control, when to load a module. They can be loaded as soon as possible, which is known as ‘When available’ or can be loaded, when a application need them, which is known as ‘On-demand’. 

Guidelines for loading the Module

It is always good to decide prior that when we want to load our Module. Never forget to think on below points: 
  • Is it required to run the application – If it is, then it must be downloaded with the application and has to be initialized when the application loads 
  • Always used – If it is, it can be downloaded in the background, when it becomes available 
  • Rarely used – If this is the case, then it can be downloaded in the background and can be initialized on demand

Initializing Module

The last phase in the Module’s lifecycle is initializing Modules. IModule.Initialize() does this for us. In this method, we write a code to register our types, we can even subscribe to services or events. We can even work with shared services. We can also compose our view into the Shell. So, basically the Initialize() method is where you can put all your code which make your Module ready for consumption in our Prism application.

Views

Most of the applications require some type of interface with user can interact with. Here we will talk about Views, which will provide the interface to the user and will also see, how to add views to the Prism application. We will touch upon, what a View is, about View Composition, View Discovery and View Injection. 

What is a View?

In layman term, View is simply the interface that user uses to interact with the application. But in Prism application, this concept is bit different. In Prism, View is only the portion of user interface. It is a smaller unit of user interface, which encapsulates a piece of functionality and is coupled with other parts of user interface. Let’s take an example of Outlook. In Outlook, we have toolbar at top and a navigation bar on left side. If you will look closely into it, you will find that, both of these parts have no dependency. For example, outlook toolbar can probably have its own View and has no dependency on other parts of the application. Its main function is to send messages and the actions which are needed to be performed. And the same is true for navigation area, the email list, the content area and even for a status bar. So, we can see that a Outlook is composed of multiple Views. 
Composite View
In Prism, a View can be made up of multiple Views, which is also called as Composite View. Here Composite View can be think of Parent with, having its child view, again sub child view, etc. View can be composed of User control, Page, Data Template, etc. Basically, it can be anything, which can be used to display information to the user. We can also have multiple instances of Views. For example, tab control with a number of tabs showing the same view.
Please keep in mind, while creating a View, design patterns are not required. There is nothing specific to the Prism library that requires you to use the design pattern to bind a View. But one can use any of the available design patterns for creating a View.
Sample code for implementing Views
Let’s create a View, by adding a user control MenuBarView
<UserControl>
  <Button>MenuBar</Button>
<UserControl>
Please note, here I am not using any type of design pattern namely MVC, MVP to create my views. Next thing, we need to do is to register our View with container. In order to do that, you need to open your Module class. In theInitialize() method, we need to register our view with our container. And of course, in order to do this we need a reference to a container.
Likely, it is pretty easy again. Let’s start by adding reference of Microsoft.Practices.Unity.dll. Then we need to add a constructor for our Module class as:
public class MyModule : IModule
{
   IUnityContainer _container; 
   public MyModule(IUnityContainer container)
    { _container = container ;}
   public void Initialize()
    { _container.RegisterType<MenuBarView>(); }
}
So, what’s happening in above code. Here, whenever Module is created, Prism is identifying a container, which is Unity container here. Once the container is identified, our Initialize() method is called and we start registering our types with the container So, once our types are registered with container, we can start using them in the module.
Composing Views
So, next step is composing our views. Here, I am going to use MVVM. Most of us are already aware, that in MVVM, we start with creating interfaces. Here also, I am creating public interfaces named IView and IViewModel. Now,
Let’s create a View, by adding a user control MenuBarView:
public interface IView
{
  IViewModel ViewModel {get; set;}
}
and
public interface IViewModel
{
  IView View {get; set;}
}
Please remember, in MVVM, ViewModel can never have direct reference of View and that’s the reason, I createdIView. Now add another interfaces for our View and ViewModel named IMenuBarView and IMenuBarViewModel, as:
public interface IMenuBarView: IView { }
Now, go to the View (MenuBarView) code behind implement the interface IMenuBarView, as:
public partial class MenuBarView: UserControl, IMenuBarView
{ 
  public MenuBarView()
  { 
   InitializeComponent();
  }
  public IViewModel ViewModel
  {
   get{ return (IMenuBarViewModel)DataContext;}
   set{ DataContext = value; }
  }
}
Next thing, we need to do is, go to IMenuBarViewModel and implement IViewModel as:
public interface IMenuBarViewModel: IViewModel
{
  public MenuBarView()
  { 
   InitializeComponent();
  }
  public IViewModel ViewModel
  { 
   get{ return (IMenuBarViewModel)DataContext;}
   set{  DataContext = value; }
  }
}
Now, we will create a ViewModel named MenuBarViewModel,as:
public class MenuBarViewModel: IMenuBarViewModel
{
 public MenuBarViewModel( IMenuBarView view)
 {
  View = view; 
  View.ViewModel = this;
 }
 public IView View 
 {get; set;}
}
We are not yet done. First, we need to register all our new types to container, inside Module class, as:
public class MyModule : IModule
{
 IUnityContainer _container;
 public MyModule(IUnityContainer container)
 {
   _container = container ;
 }
 public void Initialize()
 {
  _container.RegisterType<IMenuBarView, MenuBarView>();
 }
}
What above snippet is doing is, whenever I’ll ask for type IMenuBarView, I’ll get instance of MenuBarView and we also have to do the same thing for our IMenuBarViewModel, as:
public class MyModule : IModule
{
 IUnityContainer _container;
 public MyModule(IunityContainer container)
 {
   _container = container ;
 }
 public void Initialize()
 {
  _container.RegisterType<IMenuBarView, MenuBarView>(); 
  _container.RegisterType<IMenuBarViewModel, MenuBarViewModel>();
 }
}
Now, if you will run your application, you will still get an empty Shell. This is because, we haven’t composed our view yet.

View Composition

View Composition is the process of constructing a view. View consists of many visual elements. As and when these elements will be created, Views will be displayed in the Regions, created by Shell. These items can be displayed using automatic View Discovery or by using View Injection.

View Discovery

With View Discovery, views are added to Regions automatically. To enable View Discovery, we need to set a relationship in the Region-View registry between a region’s name and a type of view. To do this, one can simply call the RegionManager.RegisterViewWithRegion(name, type). Typically this is done, when a Module initializes or when user performs an action. When the Region is created, it looks for all the view types that are associated with the Region and automatically instantiates those views.
A side-effect of this behaviour is that we don’t have explicit control of when to load and display a view inside a Region.
Sample code for View Discovery
Let’s open our MyModule class and add the following code:
public class MyModule : IModule
{
 IUnityContainer _container;
 IRegionManager _manager;
 public MyModule(IUnityContainer container, IRegionManager manager)
 {
  _container = container ;
  _manager = manager;
 }
 public void Initialize()
 { 
   _container.RegisterType<IMenuBarView, MenuBarView>();
   _container.RegisterType<IMenuBarViewModel, MenuBarViewModel>();
   _manager.RegisterViewWithRegion(RegionNames.MenuBarRegion, typeof(MenuBarView));}
 }
Now, whenever the Region is created, the Region will automatically initialize and instantiate our MenuBar item. Now at this point, if you will run this, you will see your MenuBarView in Shell.
Here, we have very limited control on how and when MenuBar is initialize and instantiated.
View Injection
With View Injection, views are added programmatically to the Region. This can also be done, when a Module initializes or as a result of user interaction. One can achieve View Injection by couple of different ways. This can be done by calling RegionManager.Region[“Name”].Add(view, name) or we can get an instance of an IRegion from aRegionManager and then work with the Region directly as IRegion.Add(view, name).
Please keep in mind that while programmatically adding views, one need to activate/deactivate views. For example, if your content control has a Region, which already contains a view and if you add a new view to it, you need to deactivate the current view for the newly injected view to show.
So, as we can see View Injection gives us more control over views to be loaded and display. We can also remove views from the Region.
One thing to keep in mind with View Injection is that you can’t add a View to Region that has not been created. For View Discovery, view is automatically created when a Region is created. So, one should be aware of what all Regions have been created, before you try to inject a view into it.

Sample code for View Injection

Let’s again open our MyModule class and add the following code:
public class MyModule : IModule
{
  IUnityContainer _container;
  IRegionManager _manager;
  public MyModule(IUnityContainer container, IRegionManager manager)
  {
   _container = container ;
   _manager = manager;
  }
  public void Initialize()
  { 
    _container.RegisterType<IMenuBarView, MenuBarView>(); 
    _container.RegisterType<IMenuBarViewModel, MenuBarViewModel>();

     var viewModel = _container.Resolve<IMenuBarViewModel>(); 
    _manager.Regions[RegionNames.MenuBarRegion].Add(viewModel.View);
 }
}
Now, run the application, you will be see your MenuBar view. Sometimes, we need a more control of the Region and in that case, we can get instance of the Region using IRegion as:
public class MyModule : IModule
{
  ...
  ...
  public void Initialize()
  {
   ... 
   ...
   var viewModel = _container.Resolve<IMenuBarViewModel>();
   IRegion region = _manager.Regions[RegionNames.MenuBarRegion];
   region.Add(viewModel.View);
   }
}
Now run the application, and you will get the expected output.
Hope you enjoyed reading this article. 
Just watch my next article of this series, which is going to publish soon !!!