Showing posts with label PRISM. Show all posts
Showing posts with label PRISM. Show all posts

Tuesday, June 1, 2010

how to build an outlook style application with prism v2 – Part 2

how to build an outlook style application with prism v2 – Part 2: "

A while ago, I put an example application on my blog on how to build an outlook style application.


The last couple of weeks, I’ve been working on a new version of this app. I’ve done some bugfixes, but also included support for opening use cases in a popup window. It’s turning out to be quite an advanced demo of what’s possible with Prism. But while I’m playing with it, I can’t help but be amazed with the things I can push Prism into doing :)


<Outlook style app>


You will need the following references to make the solution work:



So there are a couple of things I didn’t explain in my previous blog:



  • How to do ViewModel first development?

  • How to open a Use Case in a popup?

  • Why I’m using ObservableObject in my ViewModels?

So here goes:


ViewModel first development


I’m a big van of ViewModel first development. So what does that mean?



  1. I create my ViewModels before i create my Views. This allows me to create testable viewmodels that absolutely don’t rely on any visual aspects.

  2. My application code programs against ViewModels, not Views. Most of my code doesn’t need to know about the views. Only when a ViewModel needs to be displayed should you load up the view to display it.

There are a couple of big advantages to this approach:



  • You can easily unit test your UI logic, without relying on visual elements.

  • I can easily reskin my app.

  • You don’t have to forward data from your views to your view models. This is something I have always found annoying with a View First approach. For example, if you have a view that displays a person and needs a PersonID to do it. With view first, your code has to talk to the view. So the view needs a PersonID property. But actually, the logic of your view needs that PersonID, so it needs to be forwarded to your ViewModel. Annoying, tedious, error prone!!!

I wanted to be able to put ViewModels into my regions and to have some code that would provide the visualization onto it. So the code I want to be able to write is:


// 1: Setup visualizations (typically in Module.Initialize)
// Whenever an EmailMainViewModel is displayed, visualize it with an EmailMainView
modelVisualizationRegistry.Register<EmailMainViewModel, EmailMainView>();

// 2: Add ViewModels to region (view discovery, view injection or any other method)
region.Add(new EmailMainViewModel());



ViewModel First internals


If you’re interested in how I built the ViewModel First code? here it is:


ModelVisualizer


The first step into creating the view model first appraoch was to create a ModelVisualizer class. The reason for this was: 'The prism region adapters will put the content of the regions directly into the control that hosts the region (for example, a contentcontrol). There is no extensionpoint to sit in between that.


So I created something that I could put in a region, that would hold BOTH the View and the ViewModel. It would be the glue between the view and the viewmodel and:



  • Set the View as the content in the Visual Tree.

  • Set the ViewModel as the datacontext for the View.

  • Forward common information between the ViewModel and the View (such as the RegionContext or the IsActive values)

The following diagram explains my ModelVisualizer.


image


The ModelVisualizer IS a ContentControl. So it can be placed inside the Visual Tree. It will set the View as the content. It will also set the ViewModel as the datacontext of the view (so the view can bind to all the information in the ViewModel). Lastly, the IModelVisualizer implements the IRegionContextAware and IActiveAware interfaces, and will synchronize these interfaces with the View and ViewModel if they implement the interfaces.


Visualizing Region


The ModelVisualizer worked great. However, it demanded that all my code knew about the ModelVisualizer. I didn’t want to do that, because I wanted to make it implicit. There were some issues with that though, because due to the current implementation the region adapters, I didn’t have an extension point to create my visualizations implicitly. I couldn’t change the type of region that was created by adapters and I couldn’t change how the adapters set the content of the region to the hostcontrol. But I solved that with a little trick, that I call my VisualizingRegion.


The trick was: while I couldn’t change what type of region was being created, I could control what type of region was registered to the RegionManager (because there is a regionbehavior that does the registration. So I just wrapped the Region that was created by the regionadapters in my own region (the visualizing region) and registered my own visualizing region to the regionmanager.


The only way a consumer can get access to the Region is through the RegionManager, so that solved the problem :)


Easier Solution to region context


In Prism V2, we introduced the concept of RegionContext. The RegionContext is a way that a view that hosts a region can share some of it’s information with any childviews that are loaded into it’s region. While I really liked the concept of RegionContext, I didn’t really like the implementation of it.


So I created the IRegionContextAware interface. It has one property (the regioncontext as an ObservableObject) and the RegionContextAwareRegionBehavior that would sync the context of the region with the RegionContextAware properties.




Opening a Use Case (or ViewModel) in a popup


One thing I thought was an interesting challenge was opening a viewmodel in a (non modal) popup. So why would this be challenging:



  • You can have many instances of the same popup open at the same time.

  • Viewmodels shouldn’t know if they are opened in the main window (perhaps in several tabs) or in a popup. This should be decided by the designer, preferably in XAML.

The code I wanted to be able to write is:



   1: // Create an UseCase to write new email messages
   2: NewEmailUseCase newEmailUseCase = ApplicationModel.CreateObjectInScopedRegionManager<NewEmailUseCase>();
   3:  
   4: // Add some data to the Email message use case (in this case, a blank new email)
   5: newEmailUseCase.Message = new EmailMessage();
   6:  
   7: // Show the email (in a popup, but the consumer doesn't know that)
   8: ApplicationModel.ShowUseCase(newEmailUseCase);

The problem with opening several instances of the same popup is: Regions are identified by name in the regionmanager. If you have several popups of the same type open, each popup needs it’s own RegionManager, or else the region names will collide. In my scenario, I decided that the Popup has most of the same region names as the main shell. That way, any ViewModel or use case could be loaded in either the popup or the main window.


Creating use cases in a scoped regionmanager


Ok, so i need to create a scoped regionmanager. That’s not to hard, just do: RegionManager.CreateRegionManager() and you have one. However, I wanted the consuming code NOT to have to think about this. It should be blissfully ignorant about the fact that it’s in a scoped regionmanager or not.


Since all most of my objects are created by a DI Container, and it injects all of the dependencies to my object, I decided to use that to solve this problem. So I created a scoped Container and registered the scoped regionmanager with that. Then I created my use case from the newly created scoped container, and if it needs a regionmanager, it would automatically get the scoped regionmanager. Pretty neat huh.


So schematic, that looks like this:


image


So when the use case (in green) get’s created, it and it’s dependencies would get the scoped regionmanager injected. Without knowing about the scoped containers or scoped regionmanager.


Adding use cases to popups


Adding the use case to a popup (in the application model) works like this:


image



  1. Create the use case.
    Your code creates a new use case instance, for example new NewEmailUseCase(); The application model has a method to create a use case within a new RegionManager scope (as described before).

  2. Show use case.
    Your code calls the Application model to show the use case.

  3. Add to region.
    The application model (which is logic) doesn’t even know if the use case is displayed in a popup or not. It just adds the use case to a region. The region itself is defined in the Shell.XAML.

  4. Visualize the Use case
    Just as a visualization (view) can be registered for ViewModels, i’ve also registered a visualization for Use Cases. In this case, I’ve registered a window (called Popup.XAML) as visualization.

  5. Show /Close the popup on activate.
    Now that the visualization is there, I had to create some code to show and close the popup. I decided that, if i Activate() the use case, the popup should be displayed. If I deactivate Use case, the popup should be closed and the use case should be removed from the region. This functionality I put in a RegionBehavior, because it can easily monitor if something is added or removed from a region.

  6. Assign scoped region manager to the popup
    Lastly, the popup window needs to know the RegionManager that the Use Case wants to use. So I’ve created the IRegionManagerAware interface. If a usecase implements that interface, anything that’s placed inside the region will get this region manager assigned.

As you can see, there are quite a lot of moving bits for showing a use case into a popup. Of course, it would have been A LOT easier to give ‘your code’ (an other use case or something) the knowledge that a view can be opened in popup.


ObservableObject for easier binding


If you look at my viewmodels, you’ll see that I make use of the ObservableObject a LOT. It’s a very simple object, one that just takes a type and wraps it in a INotifyPropertyChanged. The nice thing about this is, that I don’t have to add any INotifyPropertyChanged code in my ViewModels anymore. That makes it soooo much easier to do 2 way databinding in WPF.


The only problem is, that to get to the value, you often have to do: viewModel.MyProperty.Value to get to the actual value of MyProperty. But I thought that’s worth it since now I don’t have to write INotifyPropertyChanged code for my properties anymore.





Conclusion


Like I mentioned, before, this outlook style app has become quite an advanced demo of what’s possible with Prism. But I hope it gives you some idea’s on what’s possible with it. I’m also in the process of creating a video walkthrough of this application. But I’ll let you know when that’s done!


Keep practicing!


_Erwin


[UPDATE]


If you get an System.Threading.SynchronizationLockException from Unity: Don’t worry! I had turned on ‘break on all exceptions’ so the debugger is also breaking on these handled exceptions. Just continue and the app will run fine, or change that debug setting.

"

how to build an outlook style application – part 1

how to build an outlook style application – part 1: "

[Update] This is part 1 of this post. Read the second post here.

At the end of building prism V2, we have played around with different application styles to see how easy it is to consume our own libraries. In this blog post, I’m going to describe my attempt at creating an outlook style application. My implementation shows the following aspects:

  • How to create application parts that can be activated and deactivated, can be put in a list, and are very lightweight.
  • How to use an Application Model?
  • How to do pure ViewModel first development. In WPF, you can apply implicit Data Templates to visualize objects, but in silverlight that doesn’t work. So I’ll demonstrate two ways to do this.
  • How to handle RegionContext in a more direct way.

You can download the Source Code here:

<Outlook style app>

You will need the following references to make the solution work:

Download prism, compile it, and place the binaries in the lib folder. Also, place the Unity binaries in the lib folder.

Requirements

So what are my requirements for the outlook style app.

  • Be able to show a list of buttons that can activate parts of an application (like the outlook buttons for Mail, calendar, contacts, etc.)
  • It should be possible to activate and deactivate ‘Application parts’. If an application part becomes active, It’s initial view should show up in the main area.
  • Only one ‘application part’ can be active at any point in time.
  • When a view or an application part becomes active or inactive, other views might also have to be added or removed, such as toolbars.
  • Show a list of available ‘application parts’, without really instantiating all their views immediately. Only instantiate the views the first time you show them.

Solution

So this is my Outlook style app:

image

With a little bit of imagination, I hope you can see how this app could resemble outlook ;)

The following diagram shows the overall structure of the application and the most important pieces.

image

My shell has several regions, each brightly colored to make it clear where they are.

The ApplicationModel defines that the application has a list of UseCases. The ButtonBar (in red) is bound to the list of use cases. Each use case is represented as a button. When you click that button, the ActivateUseCase command is fired which will activate the selected UseCase.

An UseCase (like the MainEmailUseCase) implements the IActiveAwareUseCaseController and likely inherits from ActiveAwareUseCaseController. This makes it activatable (I know, it’s not a word). Lastly, the EmailUseCase itself defines which views it needs and where those views should go.

In the following paragraphs, i’m going to describe some of the moving pieces of this design.

Application model

The approach I took when creating the OutlookStyle app is to have a central ‘application model’ that knows how the application is structured. The modules also know a bit about this application model, through the IApplicationModel interface.

The ApplicationModel has a list of Main Usecases (more on usecases later), that I could bind my list of buttons to. It also has a command that can activate a UseCase when one of the buttons is clicked.

Using an ApplicationModel is kind of a double edged sword. It ties you somewhat down to a specific style of application. This makes your modules less portable, but it also makes the interaction between your modules and your shell more explicit and thus easier to understand. Using an application model is only one approach to creating an outlook style application and there are many others. But I thought it was an elegant solution and since we weren’t showing how to create an ApplicationModel in the Prism RI or the Quickstarts I thought it would be nice to show it here.

Internally, the application model uses a SingleActiveRegion to store the UseCases. This might seem strange, but a Region is nothing more than a model that can store a collection of objects that can be added, removed and activated. The SingleActiveRegion is ideal for this purpose, because it will make sure only one usecase is active at a given time. I choose not to add the region to a regionmanager, because I want the ApplicationModel to control access to this region.

Showing application parts: UseCaseControllers.

My implementation for the ‘application parts’ that can be activated and deactivated are called ‘UseCaseControllers’. This were my requirements for them:

  • I want to be able to put it in a list bind a collection of buttons to
  • I want to be able to activate and deactivate it.
  • It should be very lightweight, because all available controllers will be activated at once.

Motivations for naming the ‘application parts’

It was quite hard to find a right name for the ‘application parts’:

  • It’s not a module, because a module will likely contain many application parts. Also, a module should be viewed as a unit of deployment.
  • It’s not a view, because it’s more likely a set of views, working together to fulfill a single use case. These views, can be main views, tool bars, etc..
  • I considered the term ‘feature’ for a while. However, if you have ever built installers, you’ll know that a feature is also an overloaded term. It also refers more to a unit of deployment than what we’re looking for here.

So called my ‘Application parts’ UseCaseControllers. In my example, the main buttons on the outlook app kind of map to the ‘main’ or initial UseCases in my application.

Why call it controller? Controller is quite an overloaded term, because of the Model View Controller pattern. However, controllers are also commonly used to coordinate some kind of process and couple several pieces together to form a single unit. So because the controller hooks several controls together to perform a single use case, I called it a UseCaseController.

ActiveAwareUseCaseController

The ActiveAwareUseCaseController is a handy base class that you can use to fulfill the IActiveAwareUseCaseController interface. It does the following things for you:

  • BeforeFirstActivation Method. Have a handy place for the first time you activate this controller. In this method (BeforeFirstActivation), you can create all your Views or ViewModels and perform any eventwiring. For example, tie any toolbar commands to your ViewModels. The ObjectFactory also helps with this.
  • ViewToRegionBinder. One of the things you are very likely to do is to add views to some regions when the UseCase becomes active, and remove them again when it becomes inactive. Instead of having to put region.Add(view) and matching region.Remove(view) calls in the activate and deactivate methods, I figured it would be handy to create one registration method that takes care of this.

Using the ViewToRegionBinder to add and remove views to and from regions

Adding and removing views from a region whenever something becomes active or inactive can be quite tedious. Whenever a view or usecase (or anything else that implements IActiveAware) becomes active, you probably have to find the right regions, add the views to the regions. And the same if the usecase is deactivated (but then remove the views)

To make this a bit easier, I have created the ViewToRegionBinder. This object can monitor an IActiveAware object (such as a IActiveAwareUseCaseController or a view or a ViewModel). You can register a list of objects (views or viewmodels) against names of regions so that, when the object you are monitoring becomes active, the views will be added to the right regions and removed when the object becomes inactive.

   1: // Make sure the Toolbar and the mainregion get displayed when this use case is activated


   2: // and removed again when it becomes inactive. 


   3: this.ViewToRegionBinder.Add("ToolbarRegion", this.emailToolBarViewModel);


   4: this.ViewToRegionBinder.Add("MainRegion", this.emailViewModel);




Using the ObjectFactory to delay creation of your views until you actually need them



Another interesting challenge I ran into was:I wanted to shows a list of buttons for each usecase in my system. But only when I click one of these buttons do I want my views to be created and initialized. You can imagine, if you have 20 of these ‘main’ usecases and each creates a bunch of views when the application starts, application load time would be dramatic.



This was one of the motivations for creating the UseCaseControllers in the first place. They are very lightweight and I could create the views I needed in the Activate() method. But then I faced an other issue. I really like to create my views and my viewmodels using Constructor Injection. However, since the objects injected the constructor would be created before the usecase would be created, not after, i had to put in some level of indirection.



This is what the ObjectFactory<Type> solves. You can express the dependency on an object in the constructor, and create the object when you need it, by calling the ObjectFactory.CreateInstance() method. You can access the instance created by the objectfactory using the ObjectFactory.Value property.



Now I didn’t want to create member variables for the ObjectFactories, because that would mean that every time I needed to access the view, i would have to go through the ObjectFactory.Value property. I really wanted to have variables of the type of the views. So I created the AddInitializationMethod, where you can add a lambda expression that will set the member variable for the views. The ActiveAwareUseCaseController will call these lambda’s just before the UseCase becomes active for the first time.



The following code snippet shows how this works in the MainEmailUseCase





   1: // The references to these viewmodels will be filled when the app is initialized for the first time. 


   2: private EmailMainViewModel emailViewModel;


   3: private EmailToolBarViewModel emailToolBarViewModel;


   4:  


   5: public EmailMainUseCase(


   6:     // Get the ViewToRegionBinder that the baseclass needs


   7:     IViewToRegionBinder viewtoToRegionBinder


   8:     // Get the factories that can create the viewmodels


   9:     , ObjectFactory<EmailMainViewModel> emailViewFactory


  10:     , ObjectFactory<EmailToolBarViewModel> emailToolBarFactory) : base(viewtoToRegionBinder)


  11: {


  12:     // Just before the view is initialized for the first time


  13:     this.AddInitializationMethods(


  14:             // Create the emailViewModel and assign it to this variable


  15:         () => this.emailViewModel = emailViewFactory.CreateInstance()


  16:             // Create the toolbarViewModel and assign it to this variable


  17:         , () => this.emailToolBarViewModel = emailToolBarFactory.CreateInstance());


  18: }




Why do I like Constructor Injection? It expresses very clearly what the dependencies of my object are, in a single place. Take the previous code snippet. You can clearly see that the EmailUseCase has a dependency on the IViewToRegionBinder, the EmailMainViewModel and the EmailToolBarViewModel. Those are the only objects this class interacts with. Sure, in some cases it might seem easier to get a reference to the service locator and resolve types when you need them, but that makes it very unclear what other types your class depends on and also makes unit testing a lot harder.





Bootstrapper



As usual, the bootstrapper is the glue for all the individual pieces. In the bootstrapper, all the infrastructure pieces are registered in the right way, so the application can use them. You can see that I’m registering the types i need to the container and some of the default regionbehaviors to the RegionBehaviorFactory





What’s next?



In the Outlook style application, i’m also showing a bunch of other things:




  • How to do ViewModel First development in an elegant way.


  • How to use RegionContext in a bit easier way


  • How to show views in a popup in a robust way. Note, in the current version, this is still work in progress.



Since I’ve already spent way to much time on this blogpost, i’m going to address these things in future posts.



As always, I really appreciate your feedback. Any comments or questions are more than welcome.



Happy coding!



_Erwin



[Update: Also read part 2 of this post. ]

"

Learning Prism (Composite Application Guidance for WPF & Silverlight). How do I start?

Learning Prism (Composite Application Guidance for WPF & Silverlight). How do I start?: "

A question we get asked frequently is: “How do I start learning Prism? Is there a particular order for the Quickstarts? What other web resources do you recommend to start learning?”. If you are in this situation, or just want to have some more insight on a particular Prism topic, this is the post for you (I always wanted to say that, just like TV announcements :))


The basic question: “How do I start learning Prism?”


The first thing you should do to start learning Prism (assuming you know WPF/Silverlight), is begin with the documentation. It is really clear in what it tries to explain, provides great samples and explains a lot of the common doubts when starting to develop applications with Prism. There is not a particular order to learn Prism, so you should tackle it in the way you feel comfortable. Pay special attention to the Technical Concepts section, as it really helps understand how things come together.








Tip 1: Read the Prism documentation.

If while reading the documentation you have any doubts, or want to dig deeper into any particular topic you have many different options (and search queries in your favorite search engine). However, there are some things I believe you should take a look at:



  • Prism KB. There you will find links on many different topics (you can find a picture of them below), that could be videos, sample applications or blog post which will help you better understand some of Prism concepts.

  • Watch videos. There are lots of video tutorials going around, but these two collections are particularly good. Videos from P&P team & 10 Things to Know About Silverlight Prism.








Tip 2: Use the Prism KB and watch videos (these and also these particularly).

image


Prism KB site


But, what if I have some doubts while learning?


That is why developer communities were created, and as any other p&p asset Prism has its own forum at Codeplex where you can ask questions about any topic (technical concepts, how do I?, etc). The forum has a really active community, and is also monitored by the p&p Client Sustained Engineering Team (which we are part of). So if you have a question that has been bugging you for some time, and have not found the answer anywhere you can always drop by the forum.








Tip 3: Ask questions in the Prism Codeplex forum.

Last, but definitely not least…


There are some frequent Prism bloggers that you should follow, as they have some really interesting posts about how to use Prism and its insides. Below I will provide the list of those I follow (which is probably really short in comparison to the one I should be following), and for some the most interesting/requested post in my opinion:



As an extra, you can also follow the clientdev twitter, in which we tweet about the latest news about different .Net Client Development technologies (mostly Silverlight & WPF) and can be really useful when learning about Prism.








Tip 4: Read tons of articles about Prism.

I hope this article will help your Prism learning process, and please provide any feedback you might have so I can improve this guidance, like comments on the bloggers.


Shout it


kick it on DotNetKicks.com


"

Learning Prism (Composite Application Guidance for WPF & Silverlight) MVVM Fundamentals

Learning Prism (Composite Application Guidance for WPF & Silverlight) MVVM Fundamentals: "

On a previous post in this series I talked about a possible approach to take when starting to learn Prism as a whole (the Tip numbering is resumed from the previous post). In this post I will get more specific and talk about one of the most used (if not the most used) pattern when developing Prism applications (either for WPF & Silverlight): MVVM.


Most people are familiar with this pattern (if you are not great places to read about it are here for WPF and over here for Silverlight), so I will not go deep into what is the main idea of it. Instead I will try to go over some core concepts that usually lead to different levels of confusion.


What’s the difference between MVVM and PresentationModel?


The above question is one asked a lot, as people tend to get confused when they hear all the talk about MVVM and then open some Prism Quickstarts or RI and find most of them “implement the PresentationModel pattern”.


Well, there is not a certain answer (and if there was I probably wouldn’t be the one who came up with it), but as far as Prism development is concerned they are synonyms. There is no difference between them, except for the coined term. As Martin Fowler explains in his PresentationModel article: “The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window, but without any of the controls used to render that UI on the screen. A view then simply projects the state of the presentation model onto the glass.”, so if you think about it, the way to “project the state of the PresentationModel (or ViewModel) onto the glass is WPF/Silverlight DataBinding in our case (or as Julian likes to explain it: “the ViewModel is a bindable Presenter”).


Always remember the main objective, testability and decoupling.








Tip 5: MVVM and Presentation Model are synonyms.

How do I do pure MVVM?


This is another point of confusion as people tend to relate MVVM with DataTemplates and no View code behind, so they get the idea that the only way to implement the pattern is that one.


In my opinion there is no pure MVVM, it is a design pattern, so it can have many different implementations which will depend mainly on who implements it and what his requirements are. In this particular topic I would like to “branch you” to Glenn’s post “The spirit of MVVM (ViewModel), it’s not a code counting exercise.” as I agree with his point of view in this topic, so there is no point in duplicating the information.


Now that you have finished reading Glenn’s post, I hope you understand what I am trying to explain (not necessarily agree). I for once like the “View First” (you “talk” to the view) implementation to relate the View to its ViewModel in Prism could be the following (using DI):


public class MyView

{

public MyView(IMyViewModel viewModel)

{

this.DataContext = viewModel;

InitializeComponent();

}

}


In the code above, Unity’s DI provides the decoupling between the View and the ViewModel, so the ViewModel “does not have to know anything about the view” and allows you to test the VM in isolation (of course this is just one of the ways to do it).








Tip 6: There is no Silver Bullet MVVM implementation. Use the one that you like best.

How should I manage my View/ViewModel?


This question addresses both creation/destruction of View and ViewModels as well as its interaction with other components in the application. Often it is not “clear” which component should handle a specific action.


Say that when a button is clicked an event should be published. Where should this be done? Well, without information about the application and its patterns it is hard to say. It could be done in the ViewModel or it could be done in a module level controller that manages interaction with other modules, but this depends on how your application is structured.


Instead of expanding on this topic, I would like to branch you (yet again), to these posts from Ward Bell which talk about these common questions and provide some really interesting and thought answers:



Should I always use commands to communicate with the ViewModel?


Before using a command, I usually stop and think: “Can this be done in another way?, Can I achieve this same functionality with binding?”. Well, sometimes the answer is yes, and that is when I think commands are not necessary. The most common example is binding a command to execute every time and item in a Listbox is selected. This same behavior can be achieved by binding the SelectedItem property of the Listbox to your ViewModel (most of the times), and executing the required action on the setter.


Having thought of the above, what if I do need a command? Well, my first recommendation would be understanding how do Commands with attached Behaviors work, a topic explained by Julian in this great post. After that you can use the code snippet I created some time ago to help you with the tedious task of creating the classes required for this to work.








Tip 7: Before using commands, think if there is another option.

Things to add to your reading list


To help you comply with Tip 4, you can find below a couple of articles about MVVM and MVVM with Prism that I think might be of use to better understand this topic (the ones mentioned above would be in this list, but there is not need in duplicating them):



Hopefully, this post has helped you understand a little more about MVVM and how to use it with Prism. As always, your feedback is appreciated, so if you believe any link should be added or anything of the sort, just drop a comment.


Shout it


kick it on DotNetKicks.com


"

Memory Leak removing View with child regions in Prism-v2

Memory Leak removing View with child regions in Prism-v2: "

About a week ago in the Prism forum we got a question about an issue in the scenario displayed below.



The Issue


When the MainView was removed from the MainRegion, the RightOne and RightTwo regions were not removed from the RegionManager and the views were still being referenced by the region. We were able to reproduce this issue “successfully” both using scoped regions and without them so we started thinking on a possible fix for this.


The Fix


After trying different things out, we took Julian’s suggestions and created a RegionBehavior that would be in charge of this. You can find the complete code for this class below:


public class ClearChildViewsRegionBehavior : RegionBehavior
{
public const string BehaviorKey = “ClearChildViews”;

protected override void OnAttach()
{
this.Region.PropertyChanged +=
new System.ComponentModel.PropertyChangedEventHandler(Region_PropertyChanged);
}

void Region_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == “RegionManager”)
{
if (this.Region.RegionManager == null)
{
foreach (object view in this.Region.Views)
{
DependencyObject dependencyObject = view as DependencyObject;
if (dependencyObject != null)
{
dependencyObject.ClearValue(RegionManager.RegionManagerProperty);
}
}
}
}
}
}

When the RegionManager property of a Region changes to null, the behavior removes the view’s RegionManager attached property of all views in the region. Adding this behavior by overriding the bootstrapper’s ConfigureDefaultRegionBehaviors will enable this behavior for all regions:


protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
{
var regionBehaviorTypesDictionary = base.ConfigureDefaultRegionBehaviors();
regionBehaviorTypesDictionary.AddIfMissing
(ClearChildViewsRegionBehavior.BehaviorKey, typeof(ClearChildViewsRegionBehavior));
return regionBehaviorTypesDictionary;
}

The Outcome


I have created a sample application showing how the fix works. You can download it from here. The code is provided “AS IS” with no warranties and confers no rights. I hope you can find this behavior useful if you have a similar kind of situation in your application.


As I probably won’t blog anymore until after the holidays, have a merry Christmas and a happy new year :) .


Shout it


"

Creating a multi-shell application in Prism-v2

Creating a multi-shell application in Prism-v2: "

This thread from the Prism forum presents the following question (this is not an actual quote but a summary): Are there any examples with multiple Shell windows, as the Prism documentation mentions?


First I re-read this article from the Prism documentation so I could get in the same page as the user. I’m not going to quote it here, but the “Implementing a Shell” section is the one where it is explained. Once I read that, the popular Popup Region from the Prism-v2 RI was out of the table so with Ezequiel Jadib we decided to create a small spike to see what changes needed to be done.


Creating Multiple Shells


As in a regular Prism application, using the CreateShell method to create the new Shell seemed like a good approach. However, as the RegionManager is set to the DependencyObject returned by this method, this had to be done manually for any other Shell window.


protected override DependencyObject CreateShell()
{
Shell1 shell = new Shell1();
Shell2 shell2 = new Shell2();
shell.Show();
shell2.Show();
shell.Activate();

RegionManager.SetRegionManager(shell2, this.Container.Resolve<IRegionManager>());
RegionManager.UpdateRegions();

return shell;
}

When to close the application?


Another thing to determine is when to close the application. This is not something “Prism specific” as WPF provides this option for any application. Since there are multiple Shell Windows, choosing the ShutdownMode=”OnLastWindowClose” seemed like the best approach.


<Application x:Class=HelloWorld.App
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xamlShutdownMode=OnLastWindowClose>

Sample Application


I created a small sample application which publishes an event in one of the Shell views and subscribes to it in the other. You can download it from here. The code is provided “AS IS” with no warranties and confers no rights.


image


Shout it


"

Saturday, May 29, 2010

Prism Template Pack for Visual Studio 2010

Prism Template Pack for Visual Studio 2010: "

Now that we have Release Candidate versions of Visual Studio 2010, as well as WPF and Silverlight 4.0, I’ve updated the Prism Templates so that you can more easily develop Prism applications that target these latest releases.

The templates themselves are similar to those I released a while back – there are templates for Shell and Module projects, as well as ‘QuickStart Solution’ templates that provide a complete, pre-configured, multi-module solution that you can use as a starting point for a complete Prism application. All templates are available for both WPF and Silverlight. They are all in C# at the moment. I’ll work on VB.NET versions soon…

I’ve modified the templates a little to use some of the features that have been introduced since Silverlight 2.0. In particular, I updated the QuickStart Solution to use the Silverlight PagedCollectionView class so that the ViewModel can keep track of the current selection automatically.

The biggest change, though, is that the templates now come in a VSIX package and use the Visual Studio 2010 Extension Manager. This dramatically simplifies the installation and management of the templates!! You can download the VSIX package herenote that you will have to change the file extension from .zip to .vsix in order to install it – or you can find it in the Visual Studio Code Gallery. You can also read the Getting Started release notes here.

You can install the VSIX package by simply double-clicking it (once you’ve changed the file extension to .vsix). You’ll be prompted to accept the license but two clicks is pretty much all it takes. When you run Visual Studio 2010 and open the Extension Manager (from the Tools menu) you’ll see the Prism Template Pack is installed. You can uninstall it or disable it from here too.

ExtensionManager

The templates show up in the Visual Studio 2010 New Project dialog under the Prism category. There are Shell and Module project templates, as well as the QuickStart Solution templates, for Silverlight and WPF.

NewProject

Once you’ve created a project using the templates, a ReadMe file will be shown that details the remaining steps you will need to take before the solution will compile and run. This mainly involves updating the project’s references to point to the Prism assemblies on your system. In some cases, you might also have to add Silverlight App References to the Web project so that the projects are linked together properly. I haven’t yet figured out how to do this automatically without requiring some kind of complicated Visual Studio automation but I’m still working on it…

These templates target the Release Candidate versions of Visual Studio 2010, and WPF and Silverlight 4.0. Once they are fully released, I will update the templates with any changes that are required. I’m also hoping that templates like these will be included ‘in the box’ for Prism 4.0.

In the meantime, I hope you find them useful. Let me know what you think!

"