Atlanta Silverlight Firestarter 2009

Hello everyone!

Tommorrow I will be speaking at the Atlanta Silverlight Firestarter event and boy am I excited!  I will be presenting “Beyond the Plugin and into the Browser”.  This topic will show how we can utilize the browser from within Silverlight and also how the browser can utilize items from inside of the Silverlight application its hosting.

I also wrote the Silverlight application used to show information about the event.  You can see it at http://www.silverlightatlanta.net/Firestarter/minisite.html

Tim Heuer, the Senior Program Manager at Microsoft for Silverlight will be down to speak.  We are all very excited to get an opportunity to meet and talk with him.

I will be blogging and posting my session at a later time, so if you dont get a chance to come out to the event you can still view my topic information!

And as always, Happy Coding!

No Comments

VisualStateManager in WPF 4.0 and MVVM

Hello everyone!

Its been a bit since I last blogged, so I wanted to give y’all some insight into the VisualStateManager in WPF 4.0 and how we can use it with the MVVM design pattern.

I’ve been looking at ways to use the VSM for things like Forms State in addition to using it for custom control development.  To set up the scenario, Imagine you have a SearchView with a SearchViewModel.  This SearchView contains an area for SearchCriteria, an area for SearchResults, and an overlay screen with a progress bar that shows the status of the search or a processing animation of some sort.  The SearchView could have a SearchStates VisualStateGroup containing states called SearchInitialized, SearchStarted and SearchCompleted.

Now in our SearchInitialized state we dont want to show the results area, the SearchStarted state we want to show the processing animation, and the SearchCompleted state we want to stop the processing animation and show the SearchResults area.  So far this makes logical sense, but lets see how the VisualStateManager can handle this.

First to setup the MVVM portion.  Were going to use the style of MVVM that injects a View into the ViewModel. (ex.  public SearchViewModel(SearchView view)).  The reason we use this is because when we work with the VSM we have to pass it a Visual that has the VisualStateGroups defined.  This already presents one limitation in the VSM, its not a terrible limitation, but it does exist.  Now we can have commands in the normal MVVM way that work with setting states.  A command handler may look like so.

   1: public void OnSearchStarted(object parameter)
   2: {
   3:     VisualStateManager.GoToState(View, "SearchStartedState", false);
   5:     //start your background process for searching here
   4:  
   6: |

Then you have a completed handler on your background process that would look like this

   1: public void OnSearchCompleted(object sender, EventArgs e)
   2: {
   3:     VisualStateManager.GoToState(View, "SearchCompletedState", false);
   4:     //handle setting the results appropriately in the ViewModel
   5: }

So you see we have a cool, abstracted way to define which state you want to go to without having to know what Visuals are in the View you are working with.  I think this is great in concept but I have found some limitations with the VSM that makes it complicated to actually use it in this way.

The biggest issue is that a VisualState object can only have an Animation defined.  This by default tells us we cant expand expanders with booleans, we cant set Visibility states, and a whole other slew of properties that we cant set.  I was able to get around the Visibility issue by creating a VisibilityAnimation.  It does nothing more than animate the Visibility property to a VisibilityState that you define in XAML in 0 seconds.  I tried creating a BooleanAnimation that does the same for expanders, but got some weird side-effects.

What we need is for the VSM to support a collection of Setters.  If we had this then we could define visual states that actually set properties on controls and reduce the requirement of an animation.  If you look at the default ControlTemplate for the Silverlight CheckBox (which uses VSM), in the CheckedState it animates the Opacity of the check mark from 0 to 1 in 0 seconds.  This to me calls into the animation API when it does not need to.

I have built a demo that shows how we can work with what we have in the VSM to accomplish this Forms visual state functionality.  You can download it here.

I hope everyone learns from this and as always have a good day!

1 Comment

Update to SortableCollection

Hello Everyone!

I udpated the SortableCollection code at http://sortablecollection.codeplex.com.

The sorting operation has taken out all of the Reflection invocation and replaced it with DynamicMethod creations.  DynamicMethod is used to cause direct IL emitting of things like MethodBody from a reflection call.  You can then create a delegate out of the DynamicMethod to make a call to a compiled method.  This implementation has proved to execute much much faster since it is technically invocating a compiled method versus making a pure reflection invocation.  The new performance metric is as follows:

150,000 items sorted on 2 columns in 400-600 milliseconds.

As you can see the performance has improved drastically over the reflection calls.  If any of you are looking at doing heavy reflection and are leaning against it because of the known performance issues I would definatly look into DynamicMethod and direct IL emitting.

For a great example you can check out the DynamicMethodHandle component of the CSLA framework at http://www.lhotka.net/ .  This code is owned and Copyright 2009 Marimer LLC.  So make sure to take note of the license agreement if you decide to use it.

And as always happy coding!

No Comments

MVP Award!!

Hello Everyone!

Last wednesday July 1st I received the MVP Award from Microsoft in Client App Dev!  I am very happy and excited about this achievement and thank everyone who supported me in this.  Its been a wild ride building up my community involvement to this level.  I look forward to writing and presenting many more times and sharing my knowledge of .NET.

If you would like to check out my profile you can see it here!

Thanks again everyone and I hope to provide more content soon!

No Comments

SortableObservableCollection using LINQ and reflection

Hello Everyone!

So im taking a break on WPF today to blog about LINQ and sorting stuff.  We’ve all had to perform sorting at some point in time and sometimes a lot of adhoc, on the fly mechansims get built.  So I wanted to come up with a way to provide sorting functionality for any collection using some of the new powerful technologies like LINQ.

I have posted the code and release on Codeplex at http://sortablecollection.codeplex.com

The component makes use of a SortDescription class with a PropertyName and Direction properties.  The property name supports pointing to a value type, reference type (requires the implementation of IComparable) and also supports dot notation down your object graph to sort on child values.  You can also add multiple sort descriptions to sort by different properties.  The order in which the SortDescriptions are in the collection relates to a LINQ orderby description1, description2 so that you get a true By ThenBy calculation mechanism.

The meat of the processing is built into an extension method called BuildSorts(IEnumerable<SortDescription> sortDescriptions).  This follow most of the LINQ extension method pattern and works along with queries.  The following code is an example of how you may use the extension method

   1: List<SortDescription> sorts = new List<SortDescription>();
   2:  
   3: sorts.Add(new SortDescription() { PropertyName="LastName", Direction=SortDirection.Ascending });
   4: sorts.Add(new SortDescription() { PropertyName="FirstName", Direction=SortDirection.Ascending });
   5:  
   6: List<Person> people = dataLayer.GetPeople();
   7:  
   8: var query = from person in people
   9:             select person;
  10:  
  11: query = query.BuildSorts(sorts);
  12: //append .AsQueryable() when working with Linq to SQL
  13:  
  14: List<Person> sortedPeople = query.ToList();

 

You can use the extension method in building your master query to provide dynamic order by’s in them.

Also provided is a SortableObservableCollectionClass.  This class encapsulates the setup and usage of the extension method to provide a collection that will sort itself and also adhere to binding notification.

Here is an example of how you would use this class.

   1: SortableObservableCollection<Person> people = dataLayer.GetSortablePeople();
   2:  
   3: people.SortDescriptions.Add(new SortDescription() { PropertyName="FirstName", Direction=SortDirection.Ascending });
   4:  
   5: people.RefreshSorts();

Image that this was a property we are binding to.  By adding a sort description and calling RefreshSorts we cause the collection to re-order itself based on the sort descriptions provided.

The mechanism uses Func and Reflection behind the scenes but I have tested the performance pretty extensively and are happy with the results.

10,000 items with 2 sort descriptions takes 1-3 seconds

340,000 items with 2 sort descriptions takes 6-8 seconds

It also properly handles type sorting so strings are compared as strings, ints and ints, datetimes as datetimes and so forth.  If you are sorting on an object that doesnt have a proper default IComparable then you will need to implement that and this mechanism will use it.

I hope everyone enjoys this and have a good day!

No Comments

MVVM, providing the Association of View to ViewModel

Hello everyone!

As stated in my previous post, today I will be talking about the different ways we can associate a ViewModel (or any other type of middle object in the MV? design patterns) to the View.

When we look at the UI design patterns we almost always have a View and a middle object, whether it be a ViewModel, Presenter, Controller, Presentation Model, or other newly thought up facilitators, their has to be some sort of association between them.  Today I will show two different ways that we can associate a View to a ViewModel.

The first is my personal favorite and that is using a DataTemplate.  A DataTemplate is a way we can provide a visual representation of any object.  The object in our case is the ViewModel.

   1: <DataTemplate DataType="{x:Type vms:PersonViewModel}">
   2:     <vws:PersonView />
   3: </DataTemplate>

What this does is allows us to use a ViewModel as content and have it resolve the PersonView as the visual to be used.  The cool thing about this is that because the View is the representation of the DataTemplate the View will automatically have a DataContext set to the ViewModel that was set as Content.  So inside the View we can <TextBlock Text=”{Binding PersonModel.FirstName}”/> and the binding will work.  This to me is the way to keep the most separation of visuals and behavior.  The View knows nothing directly about the ViewModel and the ViewModel knows nothing directly about the View.  If you create a new View you can just inject a new DataTemplate targeted to the same type and you will have a new Visual for your ViewModel.

The drawback to this is that you do have a full separation so if you need a few coupled items you may have to utilize some other concepts or break the separation by having references back and forth between the View and ViewModel.

The second way to provide the association is using Constructor Injection to the ViewModel and instance of the View.  The code may look something like this.

   1: public class PersonViewModel
   2: {
   3:     private IPersonView _view;
   4:  
   5:     public IPersonView View
   6:     {
   7:         get
   8:         {
   9:             return _view;
  10:         }
  11:     }
  12:  
  13:     public PersonViewModel(IPersonView view)
  14:     {
  15:         _view = view;
  16:  
  17:         _view.DataContext = this;
  18:     }
  19: }

 

What this does is allows the ViewModel to contain an instance of the View so that it can do things like utilizing events to it, making method calls and such.  The way we would utilize this is by using either concrete instantiation or Dependency Injection resolution.

   1: PersonViewModel viewModel = UnityContainer.Resolve<PersonViewModel>();
   2:  
   3: NavigationManager.NavigateTo(viewModel.View);

Whichever view is registered with the container is the View that will get used so we can still provide different Views for the same ViewModel in this case.  This gives us more access to things on the View but also tightly couples us a little more.  This is not a bad thing but it may be too much for your needs depending on the project.  This also “looks” more like a Presenter than a ViewModel at this point.

The key to the semantics of these different interactions is the difference between a ViewModel and a Presenter.  Generally the second way looks more like a Presenter, but we call is a ViewModel.  I do not think it really matters what we call it as long as certain guidelines are followed.  Things like using Binding.  We can call it a Controller with Binding if we want as along as we adhere to utilizing Binding.

I hope this information is useful and have a good day!

No Comments

MV? and WPF, some possible Answers?

Hello Everyone,

So me and a co-worker of mine James Ashley have been discussing UI patterns as they related to WPF and Silverlight and really trying to find the one good fit that covers what people need from a pattern.  We found ourselves discussing not so much the implementation of a pattern to fit the needs, but rather looking at existing patterns and discussing the semantics of what each pattern represents.  They all have their pros and cons like anything in the world does but what we need is one good solid foundation for building WPF applications so that people aren’t trying to stick to an existing purist pattern and giving up something they need or is powerful to make sure they dont break the rules of a pattern.  James Ashley did a great post discussing the differences and utilizations of the different patterns called MVVM: UI design patterns in the wild.  I suggest reading this post first becuase it is a pre-cursor to what I am going to talk about today.  Today I am going to try to provide some opinions on answers to the situation we run into with patterns associated with a technology like WPF.

So first of all in WPF and Silverlight we definitely want to make use of DataBinding.  Its so powerful and robust in WPF that it makes the choice very simple in that we should use it.  So any ui patterns that do not make use of DataBinding should be thrown out to start of with.

So now lets discuss semantics a little but.  MVVM has become a very popular pattern to use with WPF but in my opinion it has a few drawbacks.  All of the patterns include a M for model and a V for View but its that middle object that ends up with drastic changes to a pattern.  In MVVM its a ViewModel.  So what is a ViewModel.  If you think about the semantical term it’s a Model representation of your View.  To me this sounds like it should be a direct description of the View, meaning 1 to 1 field mapping.  If you have a PersonView that has a FirstName and LastName text boxes then in your ViewModel you would have a FirstName property and a LastName property to bind to.  Then your ViewModel would contain a Person object (your model) that would have their properties be routed to through the ViewModel properties.  This code might look something like this.

   16         private Person PersonModel;

   17 

   18         public string FirstName

   19         {

   20             get

   21             {

   22                 return PersonModel.FirstName;

   23             }

   24             set

   25             {

   26                 PersonModel.FirstName = value;

   27                 OnPropertyChanged("FirstName");

   28             }

   29         }

 

So the first thing that people probably notice is that we have duplicated our fields.  This is where the MVVM pattern gets a little sticky.  Why would we want to make our code harder to maintain by duplicating our properties from a Model to a ViewModel.  What we could do is provide binding straight to the model.  Lets say we have our PersonModel but as a property instead of a private field.  We can now specify our fields in our model and also our validation at the model level.  Instead of binding to FirstName, we bind to PersonModel.FirstName.  But if we provide this sort of binding are we now out of the semantics of using a ViewModel since our class no longer directly describes our View?  Also if we bind straight to our model we have to provide validation at the model.  What if different views have to work with different validation rules?  This can be a little tricky with binding straight to our model, but a bit easier with the pure VM way.  in the pure VM way each VM describes its own validation rules, but now once again we have to duplicate our common validation rules accross many VM’s going back to a maintenance problem.  The answer to this is to provide boolean flags for our validation rules in our Model.  Properties are expendable so i do not think it would be bad to have 1 boolean per validation rule.  Then the VM can have the responsibility of configuring the validation rules for the model its working with.  Something like this.

   31         public PersonViewModel()

   32         {

   33             PersonModel.IsFirstNameRequired = true;

   34             PersonModel.IsLastNameRequired = false;

   35         }

 

So now we have our models containing re-usable fields and re-usable validation rules while our middle object (not a VM at this point?) factilitates pass-through binding to our model and configuration of our rules.  Our middle object would still adhere to the commanding structure described in James Ashleys post.  So our middle object now becomes what i would like to just plainly call a Facilitator.  It facilitates the bindings to the model, it facilitates the configuration of validation rules and it facilitates the commanding to run our non-ui functionality.  It doesnt seem like a ViewModel to me because it doesnt directly describe the View.  It doesnt seem like a Presenter because it doesnt know, nor care about the View and isnt making any decisions on which view should be used.  It doesnt seem like a Controller because it directly utilizes binding.  Do we now have a new pattern called Model-View-Facilitator? (MVF). 

There is another piece to all of this that includes how a View and middle object are tied together.  Some use Dependency Injection so the middle object knows about itself and the View, or Dependency Injection into the View with the middle object, and then there is a DataTemplate scenario.  Regardless of which pattern we use this concept shouldn’t matter.  Generally MVP might be directly tied to the DI injection of a View into a Presenter, but we can use this for many different patterns.  It still all comes back to semantics and trying to figure what we are trying to achieve.  In my next post i will be discussing these different integration points as they relate to the semantics of a pattern and how they can be utilized.

Hope this helps and have a good day!

No Comments

MVVM: UI design patterns in the wild. By James Ashley

Hello everyone!

There is an excellent blog from James Ashley yesterday talking about the MVVM design pattern.

You can read it here.

This is a topic we have been discussing for about a week now, trying to figure out exactly what pieces the different patterns represent when we come to a robust DataBinding technology like WPF and Silverlight.  What we found was that all them applied in their different ways and we ended up discussing nothing more than semantics.  This post does a great job of really explaining what can be considered when thinking of utilizing a UI design pattern in a DataBinding scenario.

Please read and enjoy!

No Comments

Introduction to Prism and the MVVM design pattern in WPF

Hello All!

So it looks like my user group presentation went very well with lots of very good questions being asked and a general feeling that people learned some good stuff.  I had a lot of information to cover in a fairly deep topic so it was challenging at best, but still a lot of fun to present.

Highlights for the presentation include

Prism:

  • Bootstrapper
  • Modularity (IModule)
  • ConfigurationModuleCatalog with ConfigSettings example
  • IRegionManager
  • IEventAggregator
  • DelegateCommand<>

MVVM:

  • ViewModel design and implementation
  • View design and implementation
  • Tieing the two together via DataTemplate
  • Themeing
  • Designer/Developer interaction

Materials from the presentation can be found here.

I hope everyone enjoys the materials and if you have questions please feel free to email me!

No Comments

Prismand MVVM in WPF tonight!

Hello everyone!

Just a short blog post today.  I am going to speaking at the Atlanta MSPros User Group tonight on using Prism and the MVVM pattern in WPF.  The talk will be going over a brief explanation of what Prism and MVVM can be used for followed by many code samples and demonstrations show how to technically utilize Prism and MVVM.  Info for the location and meeting can be found here. Hope to see you all there!

No Comments