Infragistics WPF controls

Dependency Injection with the Microsoft Unity Container: Injecting multiple ICommand implementations

Injecting multiple ICommand implementations with the Microsoft Unity container Hello, and welcome to my second article on Dependency Injection and IoC with the Microsoft Unity Framework.  In my last post Dependency Injection and Inversion of Control with the Microsoft Unity Container I discussed the importance of coding to an interface and not a concrete implementation.  I also introduced the idea of dependencies, and dependency injection using Unity. As I've been working a lot lately in XAML using the MVVM (Model-View-ViewModel) Pattern, I find myself implementing a lot of ICommand classes.  The ICommand interface is very simple, with a method for execution, a method to check if the command can execute, and an event handler to specify the state of the command execution.  The interface is very useful because of the way that XAML can bind to these commands to perform actions on button click's and other user interface actions.   Dependency Injection with multiple ICommand implementations So I had a lot of implementations of the ICommand interface that were used to call on the service layer of my application to complete application tasks. My past experience up until this point never required for me to register one type with multiple interfaces.  Luckily, I found it that Unity has a nice way to handle this issue. So when I setup my container, I register the commands like this _container.RegisterType<ICommand, LoadQuizesCommand>("LoadQuizes"); _container.RegisterType<ICommand, CreateQuizCommand>("CreateQuiz"); _container.RegisterType<IQuizService, QuizService>(); _container.RegisterType<IMainQuizMenuViewModel, MainQuizMenuViewModel>(); Then here is the ViewModel where the dependencies are injected in the constructor. using Domain.QuizIt; using Microsoft.Practices.Unity; using QuizIt.ViewModels.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; using Service.QuizIt.Interfaces; namespace QuizIt.ViewModels { /// <summary> /// This represents the ViewModel that is bound to the Main Quiz user interface. /// </summary> public class MainQuizMenuViewModel : IMainQuizMenuViewModel { #region "public properties" public ICommand LoadQuizesCommand { get; set; } public ICommand CreateQuizCommand { get; set; } public IQuizService QuizServiceManager { get; set; } public List<Quiz> Quizes { get; set; } public string QuizName { get; set; } public string QuizDescription { get; set; } #endregion #region "constructors" public MainQuizMenuViewModel([Dependency("LoadQuizes")]ICommand loadQuizesCommand, [Dependency("CreateQuiz")]ICommand createQuizCommand, [Dependency]IQuizService quizServiceManager) { this.LoadQuizesCommand = loadQuizesCommand; this.CreateQuizCommand = createQuizCommand; this.QuizServiceManager = quizServiceManager; } #endregion } } Notice how I specify the same names in the Dependency attributes in the constructors as I did when registering the types.  This way I can specify the command by name and resolve different implementations for multiple ICommand interfaces. I hope you enjoyed reading this post.  Please feel free to comment if you have any tricks of your own with injecting multiple interfaces.   kick it on DotNetKicks.com


Introducing RavenDB: Welcome to the world of NoSQL

Relational Databases If you are a software developer then you probably have some sort of experience with a traditional RDBMS (Relational Database Management System).  SQL or structured query language is the language that you use to retrieve data from a SQL based database system.  SQL based database systems are based on relational algebra.  You initiate queries to retrieve sets or intersections of data.  These databases are defined by their schema.  The schema defines tables, columns, relationships, constraints, and keys.  SQL databases have been around for a long time and they aren't going anywhere anytime soon.  There is a time and place to use this type of system.  Typical uses include Data warehousing, data reporting, and application data storage.   Complexities of SQL based database systems With SQL based database systems you often need a database administrator to facilitate maintenance on the server.  In a clustered database environment, concurrency can become an issue when you need to combine data from multiple database systems into one central database.  Issues of replication or redundancy and back up disaster recovery requires an administrator that fully understands the way that SQL schema's and programming work. SQL to objects and objects to SQL When programming in SQL based databases, there is a fundamental challenge of pulling data from a database using SQL and transforming the set based results into an object's properties.  The same difficulties must be resolved when saving object properties back to the SQL database.  For the past 10+ years it has been up to the developer to write custom code to handle these issues.  Recently, ORM systems have assisted developers with this issue.  The schema still requires the developer to map object properties to database columns.  If the schema changes, you have to change database stored procedures, functions, as well as application code that deals with selecting and inserting and updating data.  The functions that facilitate relational databases create difficulties that must be solved to use the systems effectively. Repository pattern The repository pattern exists to provide a way to retrieve data from a routine that provides a layer of abstraction between the call and the underlying database server.  This is usually implemented by some interfaces and specific repository classes.  This adds to the amount of infrastructure boiler plate code that must be used in each application to simply retrieve data from an SQL database. Ditching the schema Recently there has been a lot of talk about NoSQL based databases.  When I first heard about this concept, I was very skeptical on how this would work.  I had been working with SQL for the past 10 years and it's what I've been used to.  I decided I would take a look at RavenDB to see what all the fuss was about.  RavenDB has changed my views on the issue. There are times when you have no need to worry about the way that your data is stored.  There are some instances in which you have no need to generate reports on data or utilize relationships.  Some times you simply need the ability to store an object's state and retrieve it later for use in your application.  This illustrates a perfect time to utilize NoSQL and RavenDB. Saving data the SQL way To save data in a typical RDBMS, you must create a SQL INSERT or UPDATE statement and traverse the properties values of the object that you wish to save to the database.  If the schema ever changes, you must change all application code that saves or retrieves data from a database. Setting up RavenDB Embedded  You must start by adding RavenDB to your solution.  I did this by using the Nuget package manager.  There are 3 ways to run RavenDB.  You can run RavneDB as an HTTP service, a Windows service, or when using RavenDB in a .NET application, you can run the RavenDB embedded server which allows RavenDB to execute as an in process DLL service.  This requires no server to run.  You simply point to a folder on your file system to save the data. Please note that when you save data to RavenDB, the objects are serialized to JSON for storage.  Here is a screen shot of how to get to the Nuget package manager.  Keep in mind that you want to add RavenDB once you have your solution open in Visual Studio.   Once you launch the package manager Search for RavenDB and choose the embedded server. The nuget package manager will discover and download the other package dependencies like the RavenDB client and Database packages. When you run RavenDB in Embedded mode, the DataDirectory property of the DocumentStore should be the directory that you wish to store the data saved to the database. Once you have a valid document store, you need to create a session to preform the save and query operations. The session object provides a way of saving and accessing data in the document store.   Querying data in RavenDB You can use Linq to query data from a RavenDB database.  Linq provides a strongly typed way of querying a RavenDB database by specifying object properties in the query.   Here is a complete example of saving and querying a RavenDB database. The example is a console application.   The application is made up of a Customer class, a DataAccessLayer class, and the main program class. The program will create an instance of the Customer class and save that object to the RavenDB database.  Next, the program will query the database to retrieve a Customer object with the ID of the object that was just saved.  The program will print the two Id's for comparison and await for the user to press a key to end the program. Customer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RavenDBExample { public class Customer { public Guid Id; public string CustomerName; public string CustomerAddress; } } DataAccessLayer.cs using Raven.Client; using Raven.Client.Embedded; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RavenDBExample { public static class DataAccessLayer { private static EmbeddableDocumentStore _documentStore; public static void SaveCustomer(Customer customer) { if (_documentStore == null) CreateDocumentStore(); using (IDocumentSession session = _documentStore.OpenSession()) { // Operations against session session.Store(customer); // Flush those changes session.SaveChanges(); } } private static void CreateDocumentStore() { _documentStore = new EmbeddableDocumentStore { DataDirectory = "Data" }; if (_documentStore == null) throw new NullReferenceException("Error creating document store"); _documentStore.Initialize(); } public static Customer LoadCustomer(Guid guid) { if (_documentStore == null) CreateDocumentStore(); using (IDocumentSession session = _documentStore.OpenSession()) { var customer = session.Query<Customer>().Where(cust => (cust.Id == guid)).FirstOrDefault(); return customer; } return null; } } } Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RavenDBExample { public class Program { public static void Main(string[] args) { var customerToSave = new Customer { Id = Guid.NewGuid(), CustomerName = "John Doe", CustomerAddress = "1234 Mystery Street, Somewhere, California, 55555" }; DataAccessLayer.SaveCustomer(customerToSave); var existingCustomer = DataAccessLayer.LoadCustomer(customerToSave.Id); if (existingCustomer == null) throw new NullReferenceException("Unable to load the customer"); Console.WriteLine("The CustomerID that was saved = {0} . The CustomerID loaded = {1} .", customerToSave.Id, existingCustomer.Id); Console.ReadKey(); } } }   There are other features as well such as change tracking. Change tracking occurs when you retrieve an object from the database, all changes to that object are tracked. You can later call save changes on the session to save the changes to the object. This concludes a high level discussion of NoSQL vs SQL database systems and specifically how to use the RavenDB document database. As you can see, if you have no need to apply relational algebra or care about the schema of a database then NoSQL based databases like RavenDB can be extremely useful. Download the full application example below RavenDBExample.zip (2.42 mb)   kick it on DotNetKicks.com      


Dependency Injection and Inversion of Control Ioc With the Microsoft Unity Container

Design for Reusability A well designed application should promote code reuse whenever possible.  Code reuse can save you time and money by allowing you to use components from previous applications to solve common problems in new projects.  The task of managing dependencies is one of the many concerns a developer faces when designing for reusability.  Dependencies are any classes that a particular class must directly instantiate and use in order to accomplish a task.  As a rule of thumb, it's good object oriented programming practice to code to an interface rather than a concrete implementation.  This will make your code flexible and built for change.   An example of a dependency You've been tasked to write a console application.  The application requires that the user authenticates before using any of the features and there is a requirement that all successfully log-ins are logged to a text file.  Here is the code for the example. TextLogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class TextLogger { public void LogMessage(string message) { //Code to write the message to a text file.... Console.WriteLine(string.Format("Logging the message to a text file: {0} ", message)); } } }   AuthenticationService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class AuthenticationService { public AuthenticationService() { } internal void Authenticate(string userName, string password) { //Authentication logic goes here TextLogger logger = new TextLogger(); logger.LogMessage("Login was successful"); } } }   Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { class Program { static void Main(string[] args) { AuthenticationService authenticationService = new AuthenticationService(); authenticationService.Authenticate(); } } } This is a basic example for demonstration purposes only.  Now, as you can see in the AuthenticationService Authenticate method we are instantiating an instance of the TextLogger class.  So now a few weeks pass by and the customer wants you to log to a database instead of a text file.  So you create  a new class. DBLogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class DBLogger { public void LogMessage(string message) { //Code to write the message to a database.... Console.WriteLine(string.Format("Logging the message to a database: {0} ", message)); } } } The AuthenticationService was dependent on the TextLogger and is now dependent on the DBLogger class.  The current design requires us to change the AuthenticationService any time the customer requests a new type of logger.  The same holds true for any unit tests that we write that uses a Logger class.  As you can see the design promotes tight coupling because we are coding to a concrete implementation which is not very flexible. Introducing an interface As we can see, both logger classes have one method called LogMessage.  They share the same interface.  This is a perfect example of an instance in which we should code to an interface.  So we start by creating an interface that matches the two logging classes. ILogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public interface ILogger { void LogMessage(string message); } } Now we could simply change the logger declaration in the AuthenticationService and be done with it, however, there are still some optimizations that can be achieved.  For instance, currently the Logger declaration is a local variable inside of the Authenticate method.  Imagine were to inject the ILogger as a parameter of the AuthenticationService constructor.  This is a much more flexible design because the AuthenticationService only has knowledge of an ILogger.  Since the implementation is injected via the constructor, the class is no longer tied to any one specific implementation. Here is the updated AuthenticationService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class AuthenticationService { //the logger is now a class field private ILogger logger; public AuthenticationService(ILogger implementation) { //The implementation is injected via the constructor logger = implementation; } internal void Authenticate(string userName, string password) { //Authentication logic goes here logger.LogMessage("Login was successful"); } } } DBLogger.cs updated using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnityExample { public class DBLogger : ILogger { public void LogMessage(string message) { //Code to write the message to a database.... Console.WriteLine(string.Format("Logging the message to a database: {0} ", message)); } } } The Unity Container The Unity container allows us to use code (or a configuration file) to associate an interface with a class.  This is typically done during your application start up or the set up of your unit tests.  You register your interface and class mappings.  Then later when it's time to instantiate an instance of your objects, you ask the container to resolve an instance of the object that you need.  The Unity container will perform an internal look up and it will resolve any dependencies that your object's constructor depends on.   I prefer to register my interface/class mappings in a class that I call a module.  When my application starts I load all modules to prepare the container to resolve all of the objects that I will need.  This abstraction allows you to easily switch an interfaces implementation at run time providing a high level of flexibility to your code.  Here is a brief example of how to use the Unity container.  You will need to download the Unity assemblies from nuget or from the Microsoft patterns and practices Unity Application block site.http://unity.codeplex.com/ LoggingModule.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace UnityExample { public class LoggingModule { IUnityContainer _iocContainer; public LoggingModule(IUnityContainer container) { _iocContainer = container; } public void Init() { //Add any logic here to look in a config file, check a property //or any other condition to decide which implementation is registered. //register the database logger to the ILogger interface _iocContainer.RegisterType(typeof(ILogger), typeof(DBLogger)); } } } Updated Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace UnityExample { class Program { private static IUnityContainer _iocContainer; static void Main(string[] args) { //create our container _iocContainer = new UnityContainer(); InitializeModules(); //the container knows how to create an AuthenticationService object //as well as what type of ILogger it takes because we registered //the required class in the loggerModule. var authenticationService = _iocContainer.Resolve<AuthenticationService>(); authenticationService.Authenticate("username", "password"); Console.WriteLine("press any key"); Console.ReadKey(); } private static void InitializeModules() { //pass the container to the module //so when we register the types we can resolve them var loggingModule = new LoggingModule(_iocContainer); loggingModule.Init(); } } }   This is a very basic introduction to Unity but you I hope that you can see the possibilities when you program to interfaces and let the container take control of object creation.  You could extend this example to create a ModuleInitializer class that takes the modules that need to be initialized.   The bottom line is Program to interfaces Inject dependencies via the constructor Register your dependency interfaces to the desired class in the unity container.  You can use a module approach if you so choose. As long as your interfaces are mapped to classes in your container, the container can resolve any dependencies that your object requires when instantiated. Download the source  UnityExample.zip (723.64 kb) Happy coding! kick it on DotNetKicks.com


Implementing a re-sizable composite view user interface using the MVVM pattern, the GridSplitter, and WPF UserControls.

  A composite view user interface In the world of WPF, the Model-View-ViewModel pattern is a great way to separate your UI from your business logic.  This decoupling allows you to easily unit test your code.  When implemented correctly, the MVVM pattern promotes a view agnostic structure which makes switching between different views extremely easy.  A composite view UI is basically a user interface that is made up of multiple independent views.  By independent, I mean that the views should be decoupled and unaware of each other.  In this tutorial, I will show you how to create the following UI.     Existing frameworks There are several existing frameworks that facilitate the implementation of the MVVM pattern and composite view applications.  MVVM Toolkit, MvvMLight, SoPrism, and Prism are a few examples of some of the existing libraries out there.  Prism is probably the most complete and extensive but it also has a large learning curve.  I decided that before I dive into learning the details of Prism, I would benefit by trying to code a composite application by hand.  The User Interface design The previous screen shot shows an application made up of a Window that contains a grid, a listview, and a ContentControl.  The ContentControl and ListView are separated by a GridSplitter control.  This allows the two views to be re-sized.  The ContentControl will have a UserControl injected into the content property as the ListView's selected item is changed. Here is the XAML markup <Window x:Class="OutlookLayoutPresenter.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:views="clr-namespace:OutlookLayoutPresenter.Views" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="128*" /> <ColumnDefinition Width="375*" /> </Grid.ColumnDefinitions> <ListView SelectionChanged="lstMenu_SelectionChanged" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="MenuDisplayText" x:Name="lstMenu"> </ListView> <ContentControl Grid.Column="1" Content="{Binding Path=Presenter.CurrentView}" x:Name="MainContent"> </ContentControl> <GridSplitter Grid.Column="1" Width="2" HorizontalAlignment="Left" /> </Grid> </Window> As you can see, we have a Grid with two columns.  The column on the left holds a ListView that that is data bound in the code behind.  The ContentControl's content property is also data bound to the Presenter.CurrentView property of our ViewModel.  I chose to implement a presenter object to handle the injection of the UserControl into the ContentControl.  We will start with the codebehind of our view to show how we are setting the DataContext. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using OutlookLayoutPresenter.Views; namespace OutlookLayoutPresenter { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private MainWindowViewModel _viewModel; public MainWindow() { InitializeComponent(); _viewModel = new MainWindowViewModel(); this.DataContext = _viewModel; lstMenu.ItemsSource = _viewModel; } void lstMenu_SelectionChanged(object sender, SelectionChangedEventArgs e) { var menuItem = (ViewMenuItems)e.AddedItems[0]; _viewModel.Presenter.DisplayView(menuItem); } } } Note that we have bound our ViewModel to the view's DataContext as well as the ListView's ItemsSource property.  The ViewModel is an ObservableCollection of ViewMenuItem objects.  I created the ViewMenuItem class to contain the region's name and the display text.  The ListView serves as a menu.   Here is the code for the ViewMenuItem class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace OutlookLayoutPresenter { public class ViewMenuItems : INotifyPropertyChanged { private string _regionName; private string _menuDisplayText; public string RegionName { get { return _regionName; } set { if (_regionName == value) return; _regionName = value; OnPropertyChanged("RegionName"); } } public string MenuDisplayText { get { return _menuDisplayText; } set { if (_menuDisplayText == value) return; _menuDisplayText = value; OnPropertyChanged("MenuDisplayText"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } When looking at the ViewModel, please be sure to note the public Presenter property that is used in the data binding of the ContentControl. The ObservableCollection of ViewMenuItem objects builds the ListView menu. Here's the ViewModel's code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; namespace OutlookLayoutPresenter { public class MainWindowViewModel : ObservableCollection<ViewMenuItems> , INotifyPropertyChanged { private IPresenter _presenter; public IPresenter Presenter { get { return _presenter; } set { _presenter = value; OnPropertyChanged("Presenter"); } } public MainWindowViewModel () { this.Add(new ViewMenuItems{RegionName = "RegionOne", MenuDisplayText = "Content One"}); this.Add(new ViewMenuItems{RegionName = "RegionTwo", MenuDisplayText = "Content Two"}); this.Add(new ViewMenuItems{RegionName = "RegionThree", MenuDisplayText = "Content Three"}); this.Presenter = new MainWindowPresenter(); } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } All that's left now is the MainWindowPresenter class which will dynamically load one of three user controls based on the ListView's selected item. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Windows.Controls; using OutlookLayoutPresenter.Views; namespace OutlookLayoutPresenter { /// <summary> /// This is the presenter class for the main Shell. the purpose of this /// class is to contain all of the UI event handlers for the main shell view. /// </summary> public class MainWindowPresenter : INotifyPropertyChanged, IPresenter { ContentControl _currentView = new ContentControl(); public ContentControl CurrentView { get { return _currentView; } set { _currentView = value; OnPropertyChanged("CurrentView"); } } public void DisplayView(ViewMenuItems item) { switch (item.RegionName.ToUpper()) { case "REGIONONE": this.CurrentView.Content = new ContentOne(); break; case"REGIONTWO": this.CurrentView.Content = new ContentTwo(); break; case "REGIONTHREE": this.CurrentView.Content = new ContentThree(); break; } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } There are three user controls that have a different background color and text.  I will show the markup for one of the controls for brevity. <UserControl x:Class="OutlookLayoutPresenter.Views.ContentOne" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" Background="Blue"> <Grid> <TextBlock FontWeight="Bold" Foreground="White" Text="Content One" /> </Grid> </UserControl>   As you click on each menu item, the content view will change colors and text.  I've included the source code for your reference. OutlookLayoutPresenterMVVM.zip (93.27 kb)   This concludes the tutorial.  Thanks for reading! Until next time... Buddy James kick it on DotNetKicks.com      


About the author

My name is Buddy James.  I'm a Microsoft Certified Solutions Developer from the Nashville, TN area.  I'm a Software Engineer, an author, a blogger (http://www.refactorthis.net), a mentor, a thought leader, a technologist, a data scientist, and a husband.  I enjoy working with design patterns, data mining, c#, WPF, Silverlight, WinRT, XAML, ASP.NET, python, CouchDB, RavenDB, Hadoop, Android(MonoDroid), iOS (MonoTouch), and Machine Learning. I love technology and I love to develop software, collect data, analyze the data, and learn from the data.  When I'm not coding,  I'm determined to make a difference in the world by using data and machine learning techniques. (follow me at @budbjames).  

Related links

Month List