Archive

Posts Tagged ‘MVVM’

eBook Giveaway

October 29, 2012 Leave a comment

Congratulations to Thomas Griffin and Chris Bordeman for winning a free copy of MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF.

Hope enjoy the book!

Advertisements
Categories: English Tags: , , , , , ,

Win a free copy of Packt’s Silverlight book

October 9, 2012 3 comments

I am pleased to announce that I have teamed up with Packt Publishing and we are organizing a give away especially for you. All you need to do is just comment below the post and win a free copy of MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF. Two lucky winners stand a chance to win an e-copy of the book. Keep reading to find out how you can be one of the Lucky One’s.

Overview of MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF

  • Build an enterprise application using Silverlight and WPF, taking advantage of the powerful MVVM pattern.
  • Customize the MVVM pattern for your projects’ needs by comparing the various implementation styles.

Read more about this book and download free Sample Chapter: http://www.packtpub.com/mvvm-survival-guide-for-enterprise-architectures-in-silverlight-and-wpf/book

How to Enter?

All you need to do is head on over to this page and look through the product description of these books and drop a line via the comments below to let us know what interests you the most about these books. It’s that simple.

In one week, I will randomly select two lucky winners.

Categories: English Tags: , , , ,

MVVM Survival Guid for Enterprise Architectures in Silverlight and WPF

August 24, 2012 1 comment

I finished just reading this book and I thought I would do a review while it is still fresh in my head.  I believe the book has good content and is a great reference for building application architectures using Silverlight or WPF.

Chapter 1 takes us through the various Presentation Patterns.  We first are introduced with a brute force monolithic approach and then look at MVC and MVP while evaluating any issues or concerns.  Its primary focus is to demonstrate the power of these patterns and enforce separation of concern (SoC).

Chapter 2 introduces us to MVVM and the benefits it offers do to Silverlight and WPF’s rich data binding.  The user is presented with strategies for sharing code between both Silverlight and WPF.  I was surprised that there is no mention of Prism or Caliburn.Micro or any other framework besides MVVM Light.  I think that MVVM Light is a great framework but I don’t agree that Microsoft leaves you without any direction as was mentioned in the book when they have an excellent guidance using Prism.

Chapter 3 uses the Northwind database as the primary data storage throughout the book.  It uses Entity Framework and also introduces Unit Tests for testing.  We are exposed to a new pattern, “Service Locator Pattern” and how it interacts with View and ViewModel.

Chapter 4 goes a step further with our Northwind database and discusses services and persistence ignorance.  It basically follows the best practices as established by Martin Fowler with regards to using a “Service Layer” to remove tight coupling.  Transaction Script, Domain-Driven Design, and Service-Oriented Architecture and presented in this chapter as well.  We then look at persistence ignorance and custom models and the pros and cons for each.

Chapter 5 is all about Commands and User Input dealing with the Northwind database.  It does a good job of demonstrating the commanding API supported in both Silverlight and WPF.  It also deals with InputBindings such as KeyBinding and MouseBinding.  We then discuss attached behaviors.  I did not see any true behaviors or actions that are also supported by both Silverilght and WPF.  Neither did I see any examples of EventAggregation which is very important when trying to communicated across projects or classes.

Chapter 6 handles hierarchical view models and inversion of control.  We are presented with master/detail scenarios and also take a look at the ObservableCollection<> object.  With IoC, we are presented again the Service Locator pattern.  Next we are presented with StructureMap.  I am again surprised in that we are not presented with Unity or MEF as these two come straight from Microsoft.  I would also like to have seen others like Ninject but we are at least presented with IoC best practices.  I do like that they introduce the Single Responsibility Principle (SRP) and give the reader a good idea of how it works works and how to use it.

Chapter 7 is all about dialogs and MVVM.  Dialogs can be a tricky part of an application architecture in that it is easy to break all the hard work we established by using MVVM.  We are presented three options for using dialogs:  Dialog Service, Mediators, and Attached behaviors.  With dialog services, we are presented with data templates and the flexibility they provide as well as some common conventions to give us one of my favorite patterns, convention over configuration.  With mediators, we are finally introduced Event Aggregation and Messaging.  Finally with attached behaviors we see a way to controls dialogs via XAML.

Chapter 8 this chapter is a nice surprise in that it discusses Windows Work Flow and building MVVM applications.  We discuss several patterns in this chapter, “Unity of Work” and “Memento“.  Next we are shown how these patterns are supported and implemented using WF and how they support handling application flow.

Chapter 9 is all about validation and error handling.  IDataErrorInfo, INotifyDataErrorInfo, and ValidationSummary are a few of the objects presented in this chapter.  We also discuss the Enterprise Library Validation Application Block and how it interacts with both WPF and Silverilght.

Chapter 10 talks about using non MVVM third party controls.  It deals with strategies for incorporating controls such as the WebBrowser control and still achieve rich data binding using MVVM with these controls.  We look again at the power of attached behaviors and a technique such as exposing a binding reflector to help with our data binding.  Another technique is to use the adapter pattern and leverage inheritance to expose and surface the functionality we want to support MVVM as well.

Chapter 11 focus on MVVM and application performance.  For WPF applications, we look asynchronous bindings.  Another area of performance concerns with controls is the concept of virtualization and paging.  Not a lot is addressed here but at least the concepts are presented.  The BackgroundWorker object is presented to facilitate work being done on a separate thread.

Appendix A claims to evaluate other MVVM libraries but I only see a list and not much discussion as to the power or differences among them.

Appendix B is titled “Bindings at a Glance” but I really only see a glossary of terms and now real good examples of bindings or real-world examples.

All in all, this seems to be a good book.  It doesn’t answer all the questions but it does present you with enough information to give you a good direction as to where you need to go when building out your own architectures.

Microsoft Silverlight 5 Data and Services Cookbook

I wanted to continue on reviewing books related to Silverlight 5 and development.  Microsoft Silverlight 5 Data and Services Cookbook states that it has over 100 practical recipes for creating rich, data-driven, business applications in Silverlight 5.  As with my last review, I will go over each chapter and add any gut reactions towards the content it provides.

The book is broken down into 13 chapters as well as an appendix.  On the whole, the book has a lot of content to absorb.  It is broken down into a collection of tips and tricks and common scenarios for using Silverlight in building line of business applications.  I like the concept and idea behind the approach to this book but I find that a lot of corners were cut in getting the book out the door.  I wish that the book had a better quality of code snippets as well as accompanying images as the code samples lack syntax highlighting of any sort and the images are very poor in quality.

Chapter 1 is all about learning the nuts and bolts of Silverlight 5.  This chapter is necessary if you have never written a Silverlight application and need to understand what is required in order to get started using Visual Studio 2010.

Chapter 2 jumps right into covering Data Binding.  This is also a core concept to any XAML technology and I like that they cover it soon so as to get you exposed to the whole data binding programming paradigm.  You are exposed to the classical non-data binding approach and then launch into the concept of a DataContext and how the data binding mechanism works.  We exposed how to create bindings both in XAML as well as in code which is sometimes necessary.  Binding to other elements, and collections is also discussed.  Next, is introduced the interface, INotifyPropertyChanged.  This is by far one of the most important aspects of XAML programming as it facilitates two-way data binding.  We finally come to one of the first instances of a new feature of Silverlight 5, debugging data binding expression.  This is one of the coolest features of Silverlight 5 and makes developing in Silverlight 5 a joy.

Chapter 3 takes our knowledge that we learned from data binding and goes into some advanced topics.  Namely, we are presented with converters, data templates, validating.  Converters are required in most line of business applications as your data binding alone will not satisfy all of your business logic and requirements.  We are also presented TargetNullValue, StringFormat, and FallbackValue as alternatives for using converters.  Another important part of any line of business application is validating user input.  We are presented with NotifyOnValidationError and ValidatesOnExceptions.  In the UI, we are introduced the ValidationSummary control that will automatically receive any BindingValidationError events.  This is nice in that we can present all errors in one concerted location and effort back to the user.  Data Annotations are presented as a means for providing validation rules on your domain objects.  INotifyDataErrorInfo and IDataErrorInfo interfaces are introduced to show how you can validate user input without throwing exceptions.  We finally move away from validation and review data templates.  This is an important concept with any XAML technology and we find good examples of usage here.  With Silverlight 5, we get the ability to use implicit templates and this is covered as well.  For scenarios where we need to binding something different than our current element in the visual tree, we are presented with Ancestor RelativeSource binding now available in Silverlight 5.  Another powerful feature of Silverlight 5 is the ability to create custom markup extensions.  Finally, as with INotifyPropertyChanged works on a single object, we are presented with the INotifyCollectionChanged interface for dealing with change aware collections.

Chapter 4 is completed dedicated to the Data Grid.  The one aspect that I was curious about was how they demonstrated binding combo boxes to the a column in the data grid.  The sample was very primitive and would not be something you would really be able to use in most data driven scenarios.  I am hoping that as we move to MVVM, we will see better scenarios on this.

Chapter 5 is about Isolated Storage.  This chapter does a good job on covering Isolated Storage and the limitations of Silverlight applications and their security sandbox.  I also liked that they also showed how you could use the Sterling database.

Chapter 6 covers MVVM.  The chapters covers the basics of MVVM as well as introducing MVVM Light and MEF as tools to use with MVVM.  I would have like an introduction on Prism and Caliburn.Micro as well as these are two important frameworks and libraries.  With Caliburn.Micro, they could have provided a nice introduction to architecting rich user interfaces without explicit data binding in your XAML.

Chapter 7 covers services.  Most all line of business applications will require data and since you cannot create a direct connection to the database in Silveright, you will need to access a service.  You presented with services such as ASMX, WCF, REST, and RSS.  I also liked that they also had a section on socket communication in Silverlight as well.  The one complaint I have is that I wished they would have also introduced SignalR as section as this is gaining a lot of popularity in the .NET community.

Chapter 8 takes what we were introduced in the previous chapter and focuses strictly on WCF and ASMX services.  We are exposed with using services that expose data, using Bing as a service.  We get presented with performance tuning by using binary XML.  We also cover a personal favorite of mine, the infamous, “Server Not Found” exception and how to provide more information to the Silverlight client.  Integrating with ASP.NET Authentication is also covered.  Finally, we are presented with uploading files using WCF.

Chapter 9 takes us one step further in our discovery with ASMX and WCF.  Mainly, we cover duplex communication, data encryption, message-based security, using Windows Identity Foundation and, finally, using a ChannelFactory with Silverlight.  Most of these sections are very high level and don’t go any further than a quick sample.  It at least points you in the right direction for further investigation.

Chapter 10 talks about using REST and WCF Data Services.  With REST we cover both XML and JSON formats.  Another sections discusses the limitations to the Silverlight browser stack.  We are then presented with the ClientHttp stack and how we can use the common REST verbs.  Next, we are presented with using WCF Data Services.  We also get presented with Flickr and Twitter and how to use their REST services.

Chapter 11 is dedicated to presenting WCF RIA Services.  While I am not a big fan of WCF RIA Services this chapter does a good job at showing you what you can do with WCF RIA Services.  It walks you through using the class library, getting your data, using a LoadBehavior, server-side queries, sorting, filtering, paging, and finally persisting your data and dealing with transactions and concurrency.

Chapter 12 continues on the WCF RIA Services and shows us some advanced features.  We are shown how to get a user’s identity either by Windows authentication or a custom means.  Next, we are presented with using Windows Identity Foundation and WCF RIA Services.    We then move from authentication to authorization in our services.  We also review how WCF RIA Services supports data annotations and validating user input.  Finally, we are presented with exposing our data via OData endpoints as well as SOAP or a JSON/REST endpoint.

Chapter 13 introduces Windows Phone 7.  This chapter walks you through the WP7 architecture from a developer’s perspective and then concentrates on getting data to the device.  A lot of the same patterns presented in the previous chapters are applicable.  Using push notifications with the cloud is demonstrated.  Local storage using a SQL CE database is presented.  Finally, a sample on using background transfer service is covered for uploading and downloading files in the background.

Appendix.  The appendix walks you through how to find any of the dependencies mentioned in the book.

If you are looking for a book that covers a lot of scenarios in Silverlight concerning data and services than this seems like a good reference for you to have.  At times, I feel that the samples were overly verbose and cluttered but I believe this is more to be the fault of poor publishing.  It would have been nice to have a better rendering of the code snippets and a better quality of the sample images throughout the book.  All in all, I found the book to be a good reference and it will definitely go in my toolbox as a go to book when I am working on a particular scenario.

Implementing View First using a ViewModelLocator

May 17, 2010 3 comments

A while back I did a post on a way to use dependency injection (DI) to handle View first approach to your MVVM development. Today, I am going to be talking about another approach that is Blend friendly if you are wanting to go View first and still have your VieModel created with dependencies. For this example, I am going to use a simple data entry screen that will be composed of DataEntryView and corresponding DataEntryViewModel.

Before we get started, I want to show you the most common approach for implementing the View first in Xaml:

<UserControl 
    x:Class="CodeCamp2010.Calc.Views.DataEntryView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:l="clr-namespace:CodeCamp2010.Calc"
    >
    <UserControl.DataContext>
        <l:DataEntryViewModel />
    </UserControl.DataContext>
    <Grid x:Name="LayoutRoot">
        ...
    </Grid>
</UserControl>

Here is a sample of the ViewModel:

public class DataEntryViewModel
{

    #region ctor
    public DataEntryViewModel()
    {
    }
    #endregion

    Property Bindings...

};

If you only need to use your default constructor of the ViewModel, this is a quick and easy way to wire you View and ViewModel together. This does have its limitations since it will only work with the default constructor.

Now let’s examine how we would go about facilitating dependency injection in the ViewModel. I will be using Unity as my container since I am using Prism. I will also be use the ServiceLocator from Prism. Let’s look at what it takes to register these two objects in Unity.

public class CalcModule : IModule
{
    private IUnityContainer _container;
    private IRegionManager _regionManager;
    private IEventAggregator _eventAggregator;

    #region ctor
    public CalcModule(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator)
    {
        _container = container;
        _regionManager = regionManager;
        _eventAggregator = eventAggregator;
    }
    #endregion

    public void Initialize()
    {
        _container.RegisterType<DataEntryView>();
        _container.RegisterType<DataEntryViewModel>();       

        _regionManager.RegisterViewWithRegion("MainRegion", typeof(DataEntryView));
    }
};

In Prism, every separate module or assembly that you create needs to have a class that implements IModule. This interface requires a single Initialize() method. It is in this method that I am registering and also requesting the view to be displayed.

Now let’s look at the DataEntryView:

<UserControl 
    x:Class="CodeCamp2010.Calc.Views.DataEntryView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:l="clr-namespace:CodeCamp2010.Calc"
    >
    <UserControl.Resources>
        <l:ViewModelLocator x:Key="ViewModelLocator" />
    </UserControl.Resources>
    <UserControl.DataContext>
        <Binding Path="DataEntryViewModel" Source="{StaticResource ViewModelLocator}" />
    </UserControl.DataContext>
    <Grid x:Name="LayoutRoot">
        ...
    </Grid>
</UserControl>

We see that we have a new entry compared to the previous view example. We now have a UserControl.Resources entry and it is providing a ViewModelLocator resource. We then see how the DataContext uses this new Resource and requests the DataEntryViewModel as its path.

Let’s now look at the ViewModelLocator class:

public class ViewModelLocator
{
    private IUnityContainer _container;
    private IUnityContainer Container
    {
        get
        {
            if (_container == null)
                _container = ServiceLocator.Current.GetInstance<IUnityContainer>();
            return _container;
        }
    }

    public DataEntryViewModel DataEntryViewModel
    {
        get
        {
            return Container.Resolve<DataEntryViewModel>();
        }
    }
};

This class is very simple. It basically is your one-stop shopping for all of your ViewModels that need to be referenced by your Views in your module. It uses the ServiceLocator to get an instance of IUnityContainer. Then it simple uses the Container to resolve for the corresponding type that you need.

Finally, here is an exmple of the DataEntryViewModel with an overloaded constructor:

public class DataEntryViewModel
{
    private IUnityContainer _container;
    private IRegionManager _regionManager;
    private IEventAggregator _eventAggregator;

    #region ctor
    public DataEntryViewModel(IUnityContainer container, 
        IRegionManager regionManager, 
        IEventAggregator eventAggregator)
    {
        _container = container;
        _regionManager = regionManager;
        _eventAggregator = eventAggregator;
    }
    #endregion

    Property Bindings...

};

Hopefully, this gives you an idea as to another alternative to implementing your View first approach and still using the power of dependency injection.

Categories: English Tags: , , ,