Updated In the Box MVVM Training

December 1, 2010

I’ve posted an update to In the Box, MVVM Training:

http://visualstudiogallery.msdn.microsoft.com/en-us/3ab5f02f-0c54-453c-b437-8e8d57eb9942

The update corrects WPF data binding issues when the current culture is not en-US.

  • Corrected two spelling errors
  • Corrected the SearchView user controls, changing the data format string to {0:d}
  • Added code to each App.xaml.cs Startup method to set WPF data binding culture to the current culture.  This corrects the DatePicker data binding problems.

Many thanks to those that posted comments and suggestions.

Have a great day,

Just a grain of sand on the worlds beaches.


Removing Repetitive Boiler Maker Code From View Models

November 17, 2010

While I was writing the BBQ Shack, I noticed that view model code calling into the business layer was repetitive across view models. The pattern I used was simple and widely accepted; background worker to make the asynchronous calls to the business layer.

The below code snippet was typical.  Background worker, exception checking, call to business layer, successful result code path, and exception result code path.

Old Pattern

void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
    e.Result = _iBLLItemCategory.Select(Convert.ToInt32(e.Argument));
}


void BackgroundWorker_RunWorkerCompleted(object sender, 
    System.ComponentModel.RunWorkerCompletedEventArgs e) {
    if (e.Error == null) {
        if (e.Result != null) {
            this.ic_ItemCategory = (ic_ItemCategory)e.Result;

        } else {
            _iViewModelUIService.MessageDialog("Data Error", 
                "Record Not Found",     
                string.Format("Item Category key: {0} not found", _objLoadKey.ToString));
        }

    } else {
        _objIViewModelUIService.ExceptionDialog(e.Error);
    }
}

I kept thinking about this, always looking for a better pattern.  I also wanted a pattern that only required a single line of code and still gave me all of the same benefits of the above code.

New Pattern

All of the above code condenses nicely down to one line of code that provides all of the above “old pattern” features.

The below repository method signatures describe the pattern.  The pattern for the method signatures is zero or more parameters, followed by the same last two; Action<T> resultCallback and Action<Exception> errorCallback.

public interface IItemRepository {

    void GetAll(Action<IEnumerable<Item>> resultCallback, Action<Exception> errorCallback);

    void Get(Int32 itemId, Action<Item> resultCallback, Action<Exception> errorCallback);

    Item Create();
}

The successful result of the method call is always calls the resultCallback delegate.

The unsuccessful result of the method call is always calls the errorCallback delegate.

This pattern is incredibly simple and leads to much cleaner code in the view model.  The errorCallback is a method in the view model base class.  This method can use a variety of techniques for displaying the error message to the user.

void LoadItems() {
    _itemRepository.GetAll(result => { this.DataItems.Source = result; }, this.DisplayException);
}

Repository Implementation – Bring on the Task Parallel Library (TPL)

The below implementation leverages the TPL Futures pattern.  Use of the TPL is optional, I’m using it here in this WPF application.  The TPL is not available in Silverlight 4 applications yet.  For Silverlight applications, change the implementation to use the common Silverlight asynchronous pattern.

The “pattern” is described in the above IItemRepository interface.  Like all interface contracts, implementation specifics can be platform specific and up to the developer.

Strongly recommend you read this book on MSDN: Parallel Programming with Microsoft .NET.  The book can also be purchased from Amazon here.  There is a book and Kindle version available.

[Export(typeof(IItemRepository))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ItemRepository : IItemRepository {

    readonly ThePhoneCompanyEntities _dataService;

    [ImportingConstructor]
    public ItemRepository(DataServiceFacade dataServiceFacade) {
        _dataService = dataServiceFacade.DataService;
    }

    void IItemRepository.GetAll(Action<IEnumerable<Item>> resultCallback,
        Action<Exception> errorCallback) {

        // This code can be refactored into a generic method
        // I left it this way to help with the learning process 
        Task<RepositoryResult<IEnumerable<Item>>> task =
            Task.Factory.StartNew(() => {
                try {
                    return new RepositoryResult<IEnumerable<Item>>(
                                _dataService.Items.ToList(), null);
                } catch(Exception ex) {
                    return new RepositoryResult<IEnumerable<Item>>(null, ex);
                }
            });

        task.ContinueWith(r => {
            if(r.Result.Error != null) {
                errorCallback(r.Result.Error);
            } else {
                resultCallback(r.Result.Package);
            }
        }, CancellationToken.None, TaskContinuationOptions.None,
            TaskScheduler.FromCurrentSynchronizationContext());
    }

    void IItemRepository.Get(Int32 itemId, Action<Item> resultCallback, 
        Action<Exception> errorCallback) {

        if(itemId != 0) {

            // This code can be refactored into a generic method
            // I left it this way to help with the learning process 
            Task<RepositoryResult<Item>> task =
                Task.Factory.StartNew(() => {
                    try {
                        return new RepositoryResult<Item>(
                            _dataService.Items.Where(
                                i => i.ItemID == itemId).FirstOrDefault(), null);
                    } catch(Exception ex) {
                        return new RepositoryResult<Item>(null, ex);
                    }
                });

            task.ContinueWith(r => {
                if(r.Result.Error != null) {
                    errorCallback(r.Result.Error);
                } else {
                    resultCallback(r.Result.Package);
                }
            }, CancellationToken.None, TaskContinuationOptions.None,
                TaskScheduler.FromCurrentSynchronizationContext());
        } else {
            resultCallback(((IItemRepository)this).Create());
        }
    }

    // I always create my entity objects in the business layer and never in the presentation layer
    Item IItemRepository.Create() {
        return new Item();
    }
}

Key Points

  • Call that does the actual work is wrapped in a try catch block.
  • The result of the asynchronous operation is wrapped in a RepositoryResult object.
  • The RepositoryResult is used to drive invoking the resultCallback or the errorCallback on the calling thread. The TaskScheduler.FromCurrentSynchronizatikonContext method call in the task.ContinueWith ensures the two callbacks are invoked on the calling thread. 

Download

This code is from one of my presentations at the patterns & practices 2010 Symposium. 

The article and video is here: http://blogs.msdn.com/b/kashiffl/archive/2010/10/21/patterns-and-practices-2010-symposium-content.aspx

This code can be downloaded from the article.

Close

I hope that this short post encourages you to look for possible refactorings in your own code and to take a look at the TPL. 

Have a great day,

Just a grain of sand on the worlds beaches.


Prism 4.0 For Visual Studio 2010, .NET Framework 4.0, WPF & Silverlight 4

November 12, 2010

 pnp_logo

The Microsoft patterns & practices team is excited to announce the release of:

Prism 4

For Visual Studio 2010, .NET Framework 4.0, WPF & Silverlight 4

Prism provides guidance designed to help you more easily design and build rich, flexible, and easy to maintain Windows Presentation Foundation (WPF) desktop applications, Silverlight Rich Internet Applications (RIAs) and Windows Phone 7 applications. Using design patterns that embody important architectural design principles, such as separation of concerns and loose coupling, Prism helps you to design and build applications using loosely coupled components that can evolve independently but which can be easily and seamlessly integrated into the overall application. Such applications are known as often referred to as composite applications.

Links

Audience

Prism is intended for software developers building WPF or Silverlight applications that typically feature multiple screens, rich user interaction and data visualization, and that embody significant presentation and business logic. These applications typically interact with a number of back-end systems and services and, using a layered architecture, may be physically deployed across multiple tiers. It is expected that the application will evolve significantly over its lifetime in response to new requirements and business opportunities. In short, these applications are “built to last” and “built for change.” Applications that do not demand these characteristics may not benefit from using Prism.

Key Benefits

  • Provides guidance and a re-usable library to help you develop flexible, easy to maintain WPF and Silverlight composite applications
  • Helps you to understand, implement and use key design patterns, such as MVVM and Dependency Injection
  • Supports the development of modular applications, allowing parts of your application to be fully developed and tested by separate teams
  • Helps you re-use application code and components across WPF and Silverlight, allowing you to create multi-targeted client experiences
  • Allows you to build a designer-friendly, dynamically composed user interface for your application
  • Includes reference implementations, quick-starts, hands-on-labs, as well as a comprehensive developers guide to get you up to speed quickly
  • Includes full source code to support code re-use or customization or for reference and education

In this Release

  • Prism Library for WPF, Silverlight and Windows Phone 7
    • Signed binary assemblies
    • Full source code
  • Example Applications and Hands-on-Lab Source Code
    • Reference Implementations (2)
    • QuickStarts (12)
    • Hands on Labs (2)
  • Documentation
    • Comprehensive developers guide showing how to use Prism within your application
    • A printable PDF of the developers guide – available on CodePlex

About patterns & practices

The Microsoft patterns & practices team provides a wide range of guidance to help customers save time and reduce risk on their software development projects by incorporating proven patterns and practices.  This applied engineering guidance includes both production quality source code and in-depth documentation.

The guidance is designed to help software development teams:

  • Make critical design and technology selection decisions by highlighting the appropriate solution architectures, technologies, and Microsoft products for common scenarios
  • Understand the most important concepts needed for success by explaining the relevant patterns and prescribing the important practices
  • Get started with a proven code base by providing thoroughly tested software and source code that embodies the recommendations

For more information: http://msdn.microsoft.com/practices


In the Box – MVVM Training

November 7, 2010

Updated 12 Nov 2010

InTheBox

What is In the Box?

In the Box is a high quality, multi-media training that is consumed within Visual Studio 2010.  Content is navigated and delivered using a next generation computer based training (CBT) experience, the Visual Studio 2010 Feature Extension.

In the Box, is a brand name for a series of CBT Feature Extensions I’ll release that are listed in the Visual Studio 2010 Add New Project dialog; see below image.  This release is MVVM Training, the next will be Prism Training.

In the Box features:

  • Visual Studio 2010 Feature Extension
  • Content delivered as text, code, images, diagrams, video, or hyperlinks to the Internet
  • Hierarchical navigation tool window for content navigation
  • Content is viewed inside Visual Studio 2010 tool windows
  • No additional downloads or dependencies; all content is in the box.  (except online videos)
  • Installed and updated from the Visual Studio Gallery
  • Managed (disabled or uninstalled) using Visual Studio Extensions Manager (see bottom of this page)
  • Authored using Microsoft Word and the Instant Feature Builder

What is in this release of In the Box?

Please watch this video as it will answer most of your questions.

This installment of In the Box contains in-depth MVVM Training that includes an eleven assembly example solution with projects targeting developers at different levels of experience

Who is the target audience?

  • If you have never used MVVM before, this training is for you. 
  • If you have been using MVVM for a while and want to learn more, this training is for you. 
  • If you are an expert, you will enjoy the MVVM Technical Description and MVVM Scenarios content.

What are the requirements to install In the Box?

Visual Studio 2010 Professional, Premium, or Ultimate.

Expression Blend 4 WPF SDK – Free download (see below comment on SDK) (Note: this is installed with Blend also)

For those developers using Visual Studio 2010 Express or Visual Studio 2008, you can use the links in the below download section to download a .mht version of the content along with the sample solution source.  The .mht file can be viewed in your browser by double clicking the file in Windows Explorer.

Please note: I have not tested this solution with the Express version.

Windows XP and Windows Server 2003 Users

In order to run Feature Builder on either XP or Server 2003 you must create an environment variable named LocalAppData (set by default on Windows Vista and Windows 7).

How to Add LOCALAPPDATA variable in Windows XP:

  • Right-click on the My Computer icon and choose Properties
  • Click Advanced
  • Click Environment Variables
  • Under User variables section, click New
  • In the Variable name: field, type LOCALAPPDATA
  • In the Variable value: field, type %USERPROFILE%\Local Settings\Application Data

How do I install In the Box?

Click on this Visual Studio Gallery Link and install from there.

After I install it, how do I get started?

Open Visual Studio 2010; File, New Project, Visual C#, In the Box, MVVMTraining.

NewProject

Videos

In the Box – MVVM Training Introduction video

You can view the above video using the web browser plug in, or you can download and watch an HD version of the video.  To download the HD version of the video, locate the, “About this video” section (lower right side of web page) and join Vimeo; it’s free and very quick to join.

Vimeo

Downloads

In the Box – MVVM Training on the Visual Studio Gallery

Visual Studio Express and Visual Studio 2008 Developers download the written content and sample application from my:

SkyDrive click here to download.

Note the link is to a folder; you will want to download both .zip files in the folder.

Expression Blend 4 SDK Requirement

I received a report from a developer having a problem with two references to the Expression Blend 4 SDK in two of the included projects.

I thought for awhile about including just these two DLL’s, but thought that would be a disservice, only providing two DLL’s.  I have opted to add the Expression Blend 4 SDK as a requirement because a high percentage of developers already have the SDK installed by Blend or by downloading it.

Have a great day,

Just a grain of sand on the worlds beaches.


Karl’ Roadmap Nov – Dec 2010

October 31, 2010

While my blog has been a little on the quiet side, I’ve been going like a rabbit with his tail on fire.  Metaphorically speaking, “What lies beneath the water line of the iceberg is about to be unveiled.”

I’ve been getting emails, Tweets, and blog comments asking me about XAML Power Toys, Ocean, Mole 2010, my upcoming cruise, Prism, In the Box, patterns & practices 2010 Symposium code; so I thought a short roadmap post is in order.

Prism 4

Prism 4 will RTW either this Thursday, 4 November 2010 or early the following week.

The patterns & practices Prism team has invested a lot of resources in the Prism Library and written guidance.  The documentation has been completely rewritten with new topics added such as MVVM, MEF and navigation.

Once released, I’ll blog regularly on the features and content of the Prism guidance.  Additionally, I’m researching the possibility of conducting three Prism events; I’m thinking of using the two day event model, holding the sessions over a Friday and Saturday.  Once the dates and locations are firmed up, I’ll provide plenty of lead time to plan and register.

patterns & practices 2010 Symposium Code

On the day Prism v4 ships, I’ll post the MVVM Training that was package using In the Box.  In the Box is explained below.

This Friday, 5 November 2010 I’ll publish a blog post and video covering the Prism Region Navigation sample application that also demonstrated the Task Parallel Library Futures pattern that streamlines view model code.

XAML Power Toys

I was hoping to get to the next release in November but am putting this work off until early December.  I’ll release a new version with the suggestions and performance fix on 19 December 2010.  If you have a suggestion or requested fix, please leave a comment here.

Mole 2010

Team Mole has put in several hundred hours in this new release.  We have been cautious with our release, wanting to provide the very best product.  Mole 2010 is code complete, has a great new UI and many new features you’ll love.  Team Mole is completing the documentation and videos and hopes to ship very soon.

You can follow Josh Smith’s blog and my blog for the release announcement.

We can also be followed on Twitter:

Ocean

I’ve already ported Ocean to C#, Windows Phone 7 and released it here.

I’m currently porting Ocean for WPF and Silverlight to C#.

While on my cruise over Thanksgiving, I’ll write a reference implementation that shows Ocean v3 in action.

Expect this to be released on Sunday, 5 December 2010.

Mexican Riviera Cruise

It has been a year and the time has come to set sail again; this time to the Mexican Riviera.  With three full days at sea and each night spent at sea, kdawg will have plenty of coding time!  No email, no phone, no Internet, just heads down coding.  The sounds and scent of the ocean breeze; gentle rolls of the ship and room service grill cheese, sets the stage for a week of creativity and productivity.

I’ve been wanting to update my Stuff application to consume Amazon.com data and to support many more item types.

The core scenario is to be able to look up movies, books, games, music and software I currently own using a phone.  This would allow me to see what I own, if I don’t have it, quickly check the price at Amazon.com and either purchase it at the store (automatically adding to my database) or put the item in my Amazon.com shopping cart.

To accomplish this, I’ll be taking these three patterns & practices assets out for a test drive, Prism, Windows Phone 7 Developer Guidance, and Unity Application Block.  To those, I’ll add Ocean v3 to the supporting cast.

The application will have an oData cloud services component with WPF, Silverlight, Windows Phone 7 and ASP.NET MVC3 front ends.  The cloud services component will be hosted on my Discount ASP.NET site.  Each developer wanting to have their own live service, will need to deploy the backend to their own hosted web server.

Developers will be able to compile and run the application locally on their system.  For Amazon.com access you’ll need a free developer account.  Again, to use the application remotely, you’ll need to host the cloud component on your web server.

What is exciting to me is the notion of a single cloud service consumed by the very cool UI stacks offered by Microsoft .NET.

It will a lot of fun working with the technologies that are new to me, Windows Phone 7 and ASP.NET MVC3.  When coding, I’ll be looking for code-reuse opportunities when writing the WPF and Silverlight applications powered by the above patterns & practices assets.  All-in-all, a very relaxing and fun vacation.

Just so you don’t think I’m insane and never stray from my keyboard, I’ve signed up for a 7 hour dolphin training experience and a day on the jet ski during my cruise.

The 7 hours with Flipper is one of those bucket list goals I can finally check off and is the main reason for visiting the Mexican Riviera.  The day on the jet ski will be one big nasty adrenalin rush.  The other day in port will be spent shopping for some cool shirts, a sombrero and tasting the local cuisine.

Expect this application to be released on Sunday, 5 December 2010.

In the Box

InTheBox_Large

At the patterns  & practices 2010 Symposium and at the post PDC 2010 Windows Phone 7 Lab Day, I previewed, “In the Box” and the first training package, MVVM Training.

So far response to this format and the content has been very favorable.

The training is unique because it’s consumed within Visual Studio 2010.  The interface is pictured below.

To create the content, I followed the training videos presented on Channel9 here.  For more information you can also follow Michael Lehman’s blog.

This will ship from the Visual Studio Code Gallery on the same day Prism v4 ships, either Thursday, 4 Nov or the following week.  My next planned training package for In the Box will be Prism v4.  Remember, every thing comes “In the Box.”

NewSolution

Click the image to view full size

Date Summary

Check my blog or follow me on Twitter for these announcements:

  • 4 Nov – Prism v4 (could possibly ship the following week)
  • 4 Nov – In the Box (could possibly ship the following week)
  • 5 Nov – Prism Region Navigation with Task Parallel Library Futures example  (could possibly ship the following week)
  • 5 Dec – Ocean v3, and the vastly upgrade Stuff application with multiple UI front ends
  • 19 Dec – XAML Power Toys update

Close

WOW – what a way to close down 2010!  Looking to power down after the 19th of December; then crank back up January 2011.

Have a great day,

Just a grain of sand on the worlds beaches.


Prism v4 Beta2 Drop 10 Released

October 14, 2010

The Microsoft Patterns & Practices Prism Team has just released Prism v4 Beta 2, Drop 10.  This will be the last drop until Prism v4 RTM’s in early November 2010.

New assets in this drop include documentation on Model-View-ViewModel, Composing the User Interface, and Extending Prism.  Overall, documentation is still in edit but we have made much progress.

You can read about the code changes in Drop 10 as well as updated information on the two region navigation blog posts I did here.

Still time to register and attend the Patterns & Practices Symposium is 18 – 22 Oct.  You can get information and register here.

Prism guidance can help you grow as a developer.

Have a great day,

Just a grain of sand on the worlds beaches.


Prism v4 Beta 1 Drop 9 Released

October 5, 2010

The Microsoft Patterns & Practices Prism Team has just released Prism v4 Beta 1, Drop 9.

Many new assets in this drop including for the first time, signed Prism Library binaries.  Included is a script to register your signed Prism binaries so that you can now use the Visual Studio 2010, Add References dialog to add a reference to a Prism assembly.

I’ve also started a new MSDN .NET Developer Guidance blog where I’ll blog all my P & P related posts.

I’ve just added my first post to the new blog Prism v4 Region Navigation Pipeline.  This post covers the new Prism v4 Region Navigation API’s.

I think you’ll like the libraries, samples and guidance in this drop.

The documentation is still a work in progress but we hope to have it completed over very close to completion by our next drop on 14 Oct 2010  (next Thursday).

Remember, the Patterns & Practices Symposium is 18 – 22 Oct.  You can get information and register here.

Prism is not just a set of libraries, it is developer guidance for building .NET applications. 

Prism is supported, has dedicated engineers to assist with questions or issues.  Prism is also backed by a large advisory board of industry experts.

The guidance that will be release next week on 14 Oct will be fantastic.  In addition to being published on MSDN in early November, it will be released in a book. 

Want to learn about M-V-VM?  We have it.  Want to learn about Commands?  We have it.  Want to learn about loosely coupled applications?  We have it.  Want to learn about Navigation?  We have it.  Want to learn about testing?  We have it.  Want to see MEF or Unity in real-world applications?  We have it. 

Prism guidance can help you grow as a developer.

Have a great day,

Just a grain of sand on the worlds beaches.


Follow

Get every new post delivered to your Inbox.

Join 241 other followers