<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Blog</title><link>http://www.baud.cz:80/blog</link><description>Blog</description><item><title>Parallel execution of multiple results in Caliburn Micro</title><link>http://www.baud.cz:80/blog/parallel-execution-of-multiple-results-in-caliburn-micro</link><description>&lt;p&gt;by Petr Ho&amp;scaron;ek&lt;/p&gt;
&lt;p&gt;While working with&amp;nbsp;&lt;a href="http://caliburnmicro.codeplex.com/" target="_blank"&gt;Caliburn Micro&lt;/a&gt;, we have came up with the need for parallel execution of multiple results. This is especially useful for concurrent load of data from multiple sources (e.g. filter content).&lt;/p&gt;
&lt;p&gt;The framework itself contains only support for sequential execution represented by the&amp;nbsp;&lt;code&gt;SequentialResult&lt;/code&gt;&amp;nbsp;class. Therefore, to add support for parallel execution, we have decided to implement our own&amp;nbsp;&lt;code&gt;ParallelResult&lt;/code&gt;&amp;nbsp;class in the similar fashion.&lt;/p&gt;
&lt;p&gt;First of all, we had to implement the&amp;nbsp;&lt;code&gt;IResult&lt;/code&gt;&amp;nbsp;interface:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class ParallelResult : IResult
{
    private readonly IEnumerator results;

    public ParallelResult(IEnumerable children)
    {
        this.results = children.GetEnumerator();
    }

    public ParallelResult(params IResult[] children)
        : this(children as IEnumerable)
    {
    }

    public event EventHandler Completed;

    public void Execute(ActionExecutionContext context)
    {
        throw new NotImplementedException();
    }

    private void OnComplete(Exception error, bool wasCancelled)
    {
        var handler = Completed;
        if (handler != null)
        {
            handler(this, new ResultCompletionEventArgs { Error = error, WasCancelled = wasCancelled });
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;Both constructors resembles the existing&amp;nbsp;&lt;code&gt;SequentialResult&lt;/code&gt;&amp;nbsp;class. Now, we need to implement the logic of this class. Our goal is to run all tasks in parallel and notify observers when all tasks have finished. To do that, we have decided to use&amp;nbsp;&lt;a href="http://msdn.microsoft.com/en-us/data/gg577609" target="_blank"&gt;Reactive Extensions for .NET&lt;/a&gt;&amp;nbsp;(Rx), library for composing asynchronous and event-based programs using observable collections.&lt;/p&gt;
&lt;p&gt;The implementation looks as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public void Execute(ActionExecutionContext context)
{
    IoC.BuildUp(this);
    var observables = Observable.Merge(Scheduler.ThreadPool, ChildObservables(context).ToArray());
    observables.Subscribe(_ =&amp;gt; { }, ex =&amp;gt; OnComplete(ex, true), () =&amp;gt; OnComplete(null, false));
}

private IEnumerable&amp;lt;IObservable&amp;gt; ChildObservables(ActionExecutionContext context)
{
    while (results.MoveNext())
    {
        IResult child = results.Current;
        yield return Observable.Create(subscribe =&amp;gt;
        {
            IoC.BuildUp(child);
            child.Completed += (sender, args) =&amp;gt;
            {
                if (args.Error != null || args.WasCancelled)
                {
                    subscribe.OnError(args.Error);
                }
                subscribe.OnCompleted();
            };
            child.Execute(context);
            return () =&amp;gt; { };
        });
    }
}
&lt;/pre&gt;
&lt;p&gt;Using the&amp;nbsp;&lt;code&gt;ChildObservables(ActionExecutionContext)&lt;/code&gt;&amp;nbsp;method, we convert each task (represented by&amp;nbsp;&lt;code&gt;IResult&lt;/code&gt;&amp;nbsp;interface) to instance of observable collection. Then, in the&amp;nbsp;&lt;code&gt;Execute(ActionExecuteContext)&lt;/code&gt;&amp;nbsp;method, we merge all observable collections and subscribe to resulting obserable collection in order to be notified of its status.&lt;/p&gt;
&lt;p&gt;When all tasks finish,&amp;nbsp;&lt;code&gt;OnComplete(Exception, bool)&lt;/code&gt;&amp;nbsp;method is called. This method notifies all the clients subscribed to&amp;nbsp;&lt;code&gt;Completed&lt;/code&gt;&amp;nbsp;event. This allows instances of&amp;nbsp;&lt;code&gt;ParallelResult&lt;/code&gt;&amp;nbsp;class to be composed in the same way as instances of&amp;nbsp;&lt;code&gt;SequentialResult&lt;/code&gt;&amp;nbsp;class.&lt;/p&gt;</description><pubDate>Fri, 08 Mar 2013 14:23:22 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/parallel-execution-of-multiple-results-in-caliburn-micro</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 2</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-2</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will create a domain model and a RIA service so that the client application will be able to access data in Coproject database.&lt;/p&gt;
&lt;p&gt;For those of you, who would like to see the code running but don't have time to write it, check &lt;a href="http://coproject.codeplex.com/"&gt;Coproject codeplex site&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;1. Create domain model&lt;/h2&gt;
&lt;p&gt;In Coproject.Web, create a new folder called Models.&lt;/p&gt;
&lt;p&gt;Add a new &lt;em&gt;Entity Data Model&lt;/em&gt; called CoprojectModel to it.&lt;br /&gt;&lt;a href="http://baud.cz/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_2.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0; margin: 0px;" title="image" src="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_thumb.png" border="0" alt="image" width="244" height="170" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In &lt;em&gt;Entity Data Model Wizard&lt;/em&gt;, choose &lt;em&gt;Generate from database&lt;/em&gt;. Choose the proper database connection (probably Database.mdf) and let VS to &lt;em&gt;Save entity connection settings in Web.Config as &lt;/em&gt;CoprojectEntities. Finally set the last wizard step as follows:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_10.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0; margin: 0px;" title="image" src="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_thumb_4.png" border="0" alt="image" width="244" height="217" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Click &lt;em&gt;Finish&lt;/em&gt; and wait for the model being created. Then rebuild the solution. Now, the server is able to access database.&lt;/p&gt;
&lt;h2&gt;2. Create RIA service&lt;/h2&gt;
&lt;p&gt;Create a folder called Services and add new &lt;em&gt;Domain Service Class&lt;/em&gt; called CoprojectService to it.&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_6.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0; margin: 0px;" title="image" src="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_thumb_2.png" border="0" alt="image" width="244" height="170" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Then, set the wizard as follows:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_8.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0; margin: 0px;" title="image" src="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_thumb_3.png" border="0" alt="image" width="201" height="244" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Two new files should be added to Services:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_12.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0; margin: 0px;" title="image" src="/Media/Windows-Live-Writer/CoProject---a-RIA-Cali.Micro-demo-part-2_117B8/image_thumb_5.png" border="0" alt="image" width="206" height="244" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The first file contains the RIA service itself. You can see functions like GetToDoItems, InsertToDoItem, etc. Their purpose should be clear.&lt;/p&gt;
&lt;h3&gt;Set metadata&lt;/h3&gt;
&lt;p&gt;The other file called CoprojectService.metadata.cs contains several classes like:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;internal sealed class ToDoListMetadata
{
	// Metadata classes are not meant to be instantiated.
	private ToDoListMetadata()
	{
	}

	public DateTime CreatedDate { get; set; }
	public string Description { get; set; }
	public string Name { get; set; }
	public Nullable&amp;lt;int&amp;gt; ProjectID { get; set; }
	public EntityCollection&amp;lt;ToDoItem&amp;gt; ToDoItems { get; set; }
	public int ToDoListID { get; set; }
	public Nullable&amp;lt;DateTime&amp;gt; UpdatedDate { get; set; }
}&lt;/pre&gt;
&lt;p&gt;These are metadata that describe what entities should be transferred to the client, what links are between them, how to localize labels for these properties or how to validate them. Take this as a configuration file for the RIA service. These settings, although written on server, are transferred by RIA Services to the client application and available there too. Now, we have to add some more metadata.&lt;/p&gt;
&lt;p&gt;Add attribute [Key] to properties ToDoItemMetadata.ToDoItemID, and ToDoListMetadata.ToDoListID and UserMetadata.UserID. This will instruct RIA Services that these properties are primary keys for these classes. This is essential for updating data and handling links between entities.&lt;/p&gt;
&lt;p&gt;Next, update other properties of ToDoItemMetadata to look like:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Include]
[Association("FK_ToDoItems_ToDoLists", "ToDoListID", "ToDoListID", IsForeignKey = true)]
public ToDoList ToDoList;

[Include]
[Association("FK_ToDoItems_Users", "UserID", "UserID", IsForeignKey = true)]
public User User;&lt;/pre&gt;
&lt;p&gt;This will make RIA services to link proper entites into the respective references. The same has to be done for ToDoListMetadata:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Include]
[Association("FK_ToDoItems_ToDoLists", "ToDoListID", "ToDoListID")]
public EntityCollection&amp;lt;ToDoItem&amp;gt; ToDoItems;&lt;/pre&gt;
&lt;p&gt;Build the solution to make sure that there are no errors. Now, the server side is ready to serve data for client.&lt;/p&gt;</description><pubDate>Tue, 04 Sep 2012 11:09:21 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-2</guid></item><item><title>Fast switching between ViewModels in Caliburn.Micro</title><link>http://www.baud.cz:80/blog/fast-switching-between-viewmodels-in-caliburn.micro</link><description>&lt;p&gt;We use &lt;a href="http://caliburnmicro.codeplex.com/"&gt;Caliburn.Micro&lt;/a&gt; on several of our projects and we are quite satisfied with it. The framework is pretty much based on what is described in &lt;a href="http://coproject.codeplex.com/"&gt;Coproject series&lt;/a&gt;. &lt;br /&gt;As one of our applications grew, we realised that changing between screens takes longer and longer time (blocking whole UI thread). The more screens had been opened the longer it took. Having profiled the application, I found out that the delay is caused by calling MeasureOverride of DataGrid and its columns. Since changing the ActiveItem property of a Conductor causes ContentControl bound to it completely change its content (to render view of the new active ViewModel), I understand it might take some time. But as all views are cached in memory, why it takes &lt;strong&gt;so much&lt;/strong&gt; time?&lt;/p&gt;
&lt;p&gt;You can see demo &lt;a href="http://www.baud.cz/media/sulc/ContentControl.html"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;I have asked several questions (&lt;a href="http://stackoverflow.com/questions/9758512/silverlight-performance-with-many-loaded-controls"&gt;StackOverflow&lt;/a&gt;, &lt;a href="http://caliburnmicro.codeplex.com/discussions/349183"&gt;C.M forum&lt;/a&gt;, &lt;a href="http://forums.silverlight.net/p/252656/630908.aspx/1?Render+performance+with+many+other+controls+loaded"&gt;Silverlight forum&lt;/a&gt;). Found no solution but at least a hint that the problem is in adding the view to visual tree.&lt;/p&gt;
&lt;p&gt;My idea was to create a custom ContentControl that would cache all views so that it can quickly switch between them. After few minutes, I came up with this:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class ContentHost : ContentControl
{
	private Grid _contentGrid;
	private UIElement _currentView;

	public ContentHost()
	{
		_contentGrid = new Grid();
		this.Content = _contentGrid;
	}

	public object CurrentItem
	{
		get { return (object)GetValue(CurrentItemProperty); }
		set { SetValue(CurrentItemProperty, value); }
	}

	public static readonly DependencyProperty CurrentItemProperty =
		DependencyProperty.Register("CurrentItem", typeof(object), typeof(ContentHost),
		new PropertyMetadata(null, (s, e) =&amp;gt; ((ContentHost)s).OnCurrentItemChanged()));

	private void OnCurrentItemChanged()
	{
		var newView = EnsureItem(CurrentItem);
		SendToBack(_currentView);
		_currentView = newView;
	}

	private UIElement EnsureItem(object source)
	{
		if (source == null)
		{
			return null;
		}

		var view = GetView(source);

		if (!_contentGrid.Children.Contains(view))
		{
			SubscribeDeactivation(source);
			_contentGrid.Children.Add(view);
		}

		BringToFront(view);
		return view;
	}

	// logic from Caliburn.Micro
	private UIElement GetView(object viewModel)
	{
		var context = View.GetContext(this);
		var view = ViewLocator.LocateForModel(viewModel, this, context);

		ViewModelBinder.Bind(viewModel, view, context);
		return view;
	}

	private void SubscribeDeactivation(object source)
	{
		var sourceScreen = source as IScreen;
		if (sourceScreen != null)
		{
			sourceScreen.Deactivated += SourceScreen_Deactivated;
		}
	}

	private void SourceScreen_Deactivated(object sender, DeactivationEventArgs e)
	{
		if (e.WasClosed)
		{
			var sourceScreen = sender as IScreen;
			sourceScreen.Deactivated -= SourceScreen_Deactivated;

			var view = GetView(sourceScreen);
			_contentGrid.Children.Remove(view);
		}
	}

	private void BringToFront(UIElement control)
	{
		control.Visibility = System.Windows.Visibility.Visible;
	}

	private void SendToBack(UIElement control)
	{
		if (control != null)
		{
			control.Visibility = System.Windows.Visibility.Collapsed;
		}
	}
}&lt;/pre&gt;
&lt;p&gt;If you now compare performance of &lt;a href="http://www.baud.cz/media/sulc/ContentControl.html"&gt;ContentControl&lt;/a&gt; with &lt;a href="http://www.baud.cz/media/sulc/ContentHost.html"&gt;ContentHost&lt;/a&gt;, you will see that it works.&lt;/p&gt;
&lt;p&gt;I still don&amp;rsquo;t know why more DataGrids causes other DataGrids to render slower.&lt;/p&gt;
&lt;p&gt;What do you think?&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.baud.cz/media/sulc/MMVMPerfTest.zip"&gt;Source code&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Tue, 27 Mar 2012 13:40:54 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/fast-switching-between-viewmodels-in-caliburn.micro</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 11</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-11</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will synchronize list after saving data and add some icons. You may continue on your work from older parts, or download updated code from &lt;a href="http://coproject.codeplex.com/"&gt;Coproject site&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Event aggregator&lt;/h2&gt;
&lt;p&gt;Usually, if you want a component of your application to notify other components about an event that occurred, you use standard .NET events. The problem with events is that you always need to access the publisher of an event from the subscriber. What&amp;rsquo;s more, you also need to unsubscribe from the event. That might be tricky in a complicated application or when the same type of event may come from more sources (for example if you would implement user events logging via events and logger subscribed to these events).&lt;/p&gt;
&lt;p&gt;Here comes (again) Caliburn.Micro and its implementation of Event Aggregator. Consider EventAggregator as a component that you subscribe to all kinds of events or that you use to publish an event.&lt;/p&gt;
&lt;p&gt;In Coproject, we will use EventAggregator to notify ToDoItemsViewModel that ToDoItem has been changed and thus it should reload data.&lt;/p&gt;
&lt;p&gt;First of all, we must create an object that will represent the event. In Coproject client project, create new folder Events and put a new class called ToDoItemUpdatedEvent into it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class ToDoItemUpdatedEvent
{
	public int ToDoItemID { get; set; }
	public ToDoItemUpdatedEvent(int toDoItemID)
	{
		ToDoItemID = toDoItemID;
	}
}&lt;/pre&gt;
&lt;p&gt;Open ToDoItemViewModel and let MEF import an EventAggregator instance:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Import]
public IEventAggregator EventAggregator { get; set; }&lt;/pre&gt;
&lt;p&gt;Then update Save as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IEnumerable&amp;lt;IResult&amp;gt; Save()
{
	(Item as IEditableObject).EndEdit();
	IsReadOnly = true;
	#region Fix DataForm bug
	IsReadOnly = false; IsReadOnly = true;
	#endregion

	yield return new SaveDataResult(_context);

	EventAggregator.Publish(new ToDoItemUpdatedEvent(Item.ToDoItemID));
}&lt;/pre&gt;
&lt;p&gt;So, after (remember coroutines and yield return) a ToDoItem is saved, we publish event notifying about it. We do not care who subscribes to this event, this is not our business here.&lt;/p&gt;
&lt;p&gt;Now, let&amp;rsquo;s write the other end &amp;ndash; an event subscriber. Open ToDoListsViewModel and edit the constructor:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[ImportingConstructor]
public ToDoListsViewModel(IEventAggregator eventAggregator)
{
	DisplayName = "To Do";
	Description = "To-do lists";

	eventAggregator.Subscribe(this);
}&lt;/pre&gt;
&lt;p&gt;Now, event aggregator will know that it should notify ToDoListsViewModel about events. But what events? It depends on what IHandle&amp;lt;T&amp;gt; interfaces the subscriber implements. Let the view model implement &lt;strong&gt;IHandle&amp;lt;ToDoItemUpdatedEvent&amp;gt;&lt;/strong&gt; and add this implementation:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public void Handle(ToDoItemUpdatedEvent message)
{
	LoadData().ToSequential().Execute(null);
}&lt;/pre&gt;
&lt;p&gt;Remember that LoadData returns iEnumerable&amp;lt;IResult&amp;gt; so we have to enumerate it to &amp;lsquo;run&amp;rsquo; it. Therefore, we wrap it into a SequentialResult and then execute this single result.&lt;/p&gt;
&lt;p&gt;The only problem is that LoadData requires a parameter &amp;ndash; filter. And this value is unknown to the handler. Fortunately, we can change the source Filter textbox binding from function parameter to property. Add this property to ToDoListsViewMode:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public string Filter { get; set; }&lt;/pre&gt;
&lt;p&gt;And the remove parameter &amp;lsquo;filter&amp;rsquo; from LoadData (take the filter value from Filter).&lt;/p&gt;
&lt;p&gt;Build the application &amp;ndash; it should run as before, but after saving of a ToDoItem, the list should refresh automatically.&lt;/p&gt;
&lt;h2&gt;Icons&lt;/h2&gt;
&lt;p&gt;Let&amp;rsquo;s give Coproject a little more style &amp;ndash; change text buttons to icon buttons.&lt;/p&gt;
&lt;p&gt;Open the zip file attached to this post and extract the five images to Assets/Icons. These icons are from &lt;a href="http://www.axialis.com/free/icons/"&gt;Axialis&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Then, open ToDoListsView and edit the LoadData button:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;Button x:Name="LoadData" Grid.Column="1" ToolTipService.ToolTip="Search"&amp;gt;
	&amp;lt;Button.Content&amp;gt;
		&amp;lt;Image Source="/Coproject;component/Assets/Icons/Search.png" Height="20" /&amp;gt;
	&amp;lt;/Button.Content&amp;gt;
&amp;lt;/Button&amp;gt;&lt;/pre&gt;
&lt;p&gt;Well, this works nicely but let&amp;rsquo;s make it a little more shorter since we will probably use these image buttons quite frequently in our application. To do this, we will create a custom control called ImageButton. Create a new folder Controls and add this control to it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class ImageButton : Button
{
	public string ImageName
	{
		get { return (string)GetValue(ImageNameProperty); }
		set { SetValue(ImageNameProperty, value); }
	}

	public static readonly DependencyProperty ImageNameProperty =
		DependencyProperty.Register("ImageName", typeof(string), typeof(ImageButton), new PropertyMetadata(OnImageNamePropertyChanged));

	public static void OnImageNamePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	{
		ImageButton button = d as ImageButton;
		string newValue = e.NewValue as string;

		if (newValue.IsNullOrWhiteSpace())
		{
			button.Content = null;
			return;
		}

		newValue = "/Coproject;component/Assets/Icons/{0}.png".FormatWith(newValue);
		ImageSource image = new BitmapImage(new Uri(newValue, UriKind.Relative));
		button.Content = new Image { Source = image };
	}
}&lt;/pre&gt;
&lt;p&gt;As you can see, we inherited original Button and added a property to it. The reason that ImageName is implemented as a dependency property is to enable it for binding, styling, etc. When the property is changed a new Image is inserted to the button. It would be great to add this image into ContentTemplate by style and just bind its Source property to ImageName, but since in template binding, you cannot use any converters, we would have to set ImageName in the raw form (/Coproject;component/Assets/Icons/Search.png) and that is not what we want. So that is why I&amp;rsquo;ve chosen this way. Now open Assets/Cosmopolitan/Custom.xaml and add this namespace to it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;xmlns:local="clr-namespace:Coproject.Controls"&lt;/pre&gt;
&lt;p&gt;And then add this to the end of the file, just above &amp;lt;/ResourceDictionary&amp;gt;:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;Style TargetType="local:ImageButton" BasedOn="{StaticResource DefaultButtonStyle}"&amp;gt;
	&amp;lt;Setter Property="Height" Value="32" /&amp;gt;
&amp;lt;/Style&amp;gt;&lt;/pre&gt;
&lt;p&gt;We are done &amp;ndash; get back to ToDoListsView, register namespace for ImageButton as in Custom.xaml and update LoadData button:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;local:ImageButton x:Name="LoadData" Grid.Column="1" ImageName="Search" ToolTipService.ToolTip="Search" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;Update buttons in Toolbar view in the same manner:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;local:ImageButton x:Name="Edit" ImageName="Pen" ToolTipService.ToolTip="Edit" Margin="0,0,5,0" /&amp;gt;
&amp;lt;local:ImageButton x:Name="Cancel" ImageName="Undo" ToolTipService.ToolTip="Cancel" Margin="0,0,5,0" /&amp;gt;
&amp;lt;local:ImageButton x:Name="Save" ImageName="Save" ToolTipService.ToolTip="Save" Margin="0,0,5,0" /&amp;gt;
&amp;lt;local:ImageButton x:Name="TryClose" ImageName="Close" ToolTipService.ToolTip="Close" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;That is all. I hope you like the new look!&lt;/p&gt;
&lt;div id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:ab923c86-e88a-42c0-9bea-c8c751c92067" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;p&gt;&lt;a href="http://www.baud.cz/Media/Windows-Live-Writer/f677e1b7409b_108D7/Icons.zip" target="_self"&gt;Icons.zip&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;</description><pubDate>Mon, 13 Feb 2012 18:30:12 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-11</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 10.5</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-10-5</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;If you watched CPU usage after implementing BusyIndicator, you might notice major increase in CPU usage on To do module after the list is loaded for the first time.&lt;/p&gt;
&lt;h2&gt;High CPU usage with BusyIndicator and ProgressBar&lt;/h2&gt;
&lt;p&gt;It is a common issue with BusyIndicator: &lt;a href="http://forums.silverlight.net/forums/p/177229/398853.aspx"&gt;Silverlight forum&lt;/a&gt;, &lt;a href="http://silverlight.codeplex.com/workitem/7372"&gt;Silverlight toolkit issue&lt;/a&gt;, &lt;a href="http://www.appsolo.com/index.php/tag/busyindicator/"&gt;Appsolo blog&lt;/a&gt; but the solution is not obvious or easy to find. So I&amp;rsquo;ve spent some time and figured out that the excessive CPU usage is caused by ProgressBar that is present in BusyIndicator. After googling for a while, I ran into &lt;a href="http://forums.silverlight.net/forums/p/105191/239947.aspx"&gt;this forum&lt;/a&gt;&amp;nbsp;but that was all about it. Fortunately, recently I saw &lt;a href="http://blogs.msdn.com/b/slperf/archive/2011/01/10/performance-on-silverlight-tv.aspx"&gt;Silveright TV episode 57&lt;/a&gt;. I strongly recommend to watch the video.&lt;/p&gt;
&lt;p&gt;Now, let's apply the new knowledge on Coproject. Edit App.xaml.cs&lt;/p&gt;
&lt;pre class="prettyprint"&gt;private void Application_Startup(object sender, StartupEventArgs e)
{
	Application.Current.Host.Settings.EnableRedrawRegions = true;
}&lt;/pre&gt;
&lt;p&gt;Run the application and reload the list (be careful if you have epilepsy!). As you can see, we have a problem.&lt;/p&gt;
&lt;p&gt;Now, let's do what was suggested in the video. So, edit ShellView to begin as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;Grid x:Name="LayoutRoot"&amp;gt;
	&amp;lt;Border Style="{StaticResource ContentBorderStyle}"&amp;gt;
		&amp;lt;ContentControl Style="{StaticResource LogoIcon}"/&amp;gt;
	&amp;lt;/Border&amp;gt;
	&amp;lt;Border Style="{StaticResource LeftBorderStyle}"/&amp;gt;

	&amp;lt;TextBlock Text="Coproject" Style="{StaticResource ApplicationTitleStyle}" /&amp;gt;
	...&lt;/pre&gt;
&lt;p&gt;And then just update LeftBorderStyle in Custom.xaml:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;Style x:Key="LeftBorderStyle" BasedOn="{StaticResource LinksBorderStyle}" TargetType="Border"&amp;gt;
	&amp;lt;Setter Property="Margin" Value="10,135,25,0"/&amp;gt;
&amp;lt;/Style&amp;gt;&lt;/pre&gt;
&lt;p&gt;Run the application again and you should see we're fine now.&lt;/p&gt;</description><pubDate>Fri, 10 Feb 2012 21:30:37 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-10-5</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 14</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-14</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In the &lt;a href="http://baud.cz/blog/coproject-ria-caliburnmicro-demo-part-13"&gt;last part&lt;/a&gt;, we created LazyScreen class so that we can load our view models into memory only when they are requested and not right after the application start. In this part, I want to create LazyConductor &amp;ndash; a conductor that will support closing of child LazyScreens and then opening new ones instead of removing them from its &lt;em&gt;Items&lt;/em&gt; collection.&lt;/p&gt;
&lt;p&gt;Please note that this is just a simple demo of an idea I had about lazy screens/conductors and using it in production might need additional code. But if you use it, please let me know (I plan to use it on a real project too, so this post might be updated later according to my experience).&lt;/p&gt;
&lt;h2&gt;LazyConductor&lt;/h2&gt;
&lt;p&gt;In the Framework folder, create a new file called &lt;em&gt;LazyConductorWithCollectionOneActive.cs&lt;/em&gt; and put the following into it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public partial class LazyConductor&amp;lt;TScreen, TMetadata&amp;gt;
{
	public partial class Collection
	{
		public class OneActive : Conductor&amp;lt;LazyScreen&amp;lt;TScreen, TMetadata&amp;gt;&amp;gt;.Collection.OneActive
		{
		}
	}
}&lt;/pre&gt;
&lt;p&gt;From now, every time I refer to &lt;em&gt;LazyConductor&lt;/em&gt;, I mean the OneActive class.&lt;/p&gt;
&lt;p&gt;Since the difference between the original conductor and our lazy conductor is in the way they close their children, we will override functions dealing with closing/deactivating stuff. When a child is closed, the original conductor removes it from its children collection. Lazy conductor should only call Reset() on the child and activate another one.&lt;/p&gt;
&lt;p&gt;Add overriden &lt;em&gt;DeactivateItem&lt;/em&gt; function:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public override void DeactivateItem(LazyScreen&amp;lt;TScreen, TMetadata&amp;gt; item, bool close)
{
	if (item == null)
	{
		return;
	}

	if (close)
	{
		CloseStrategy.Execute(new[] { item }, (canClose, closable) =&amp;gt;
			{
				if (canClose)
				{
					CloseItemCore(item);
				}
			});
	}
	else
	{
		ScreenExtensions.TryDeactivate(item, false);
	}
}&lt;/pre&gt;
&lt;p&gt;If you compare it to Caliburn.Micro source code, you will notice that there is no change. The reason for that is that we just need to alter &lt;em&gt;CloseItemCore&lt;/em&gt; function and since it is private, there is no other way.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;private void CloseItemCore(LazyScreen&amp;lt;TScreen, TMetadata&amp;gt; item)
{
	if (item.Equals(ActiveItem))
	{
		var next = DetermineNextItemToActivate(item);
		ChangeActiveItem(next, true);
	}
	else
	{
		ScreenExtensions.TryDeactivate(item, true);
	}

	item.Reset();
}&lt;/pre&gt;
&lt;p&gt;The last line is why we did that &amp;ndash; original conductor said &amp;lsquo;Items.Remove(item)&amp;rsquo;. To make the solution build again, we must add one more function:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;protected LazyScreen&amp;lt;TScreen, TMetadata&amp;gt; DetermineNextItemToActivate(
	LazyScreen&amp;lt;TScreen, TMetadata&amp;gt; currentItem)
{
	var next = Items.FirstOrDefault(x =&amp;gt; x != currentItem &amp;amp;&amp;amp; x.IsScreenCreated);
	return next;
}&lt;/pre&gt;
&lt;p&gt;Finally add these functions:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public override void CanClose(Action&amp;lt;bool&amp;gt; callback)
{
	var openedItems = Items.Where(x =&amp;gt; x.IsScreenCreated);
	CloseStrategy.Execute(openedItems, (canClose, closable) =&amp;gt;
		{
			closable.Apply(CloseItemCore);
			callback(canClose);
		});
}

protected override LazyScreen&amp;lt;TScreen, TMetadata&amp;gt; EnsureItem(LazyScreen&amp;lt;TScreen, TMetadata&amp;gt; newItem)
{
	var node = newItem as IChild;
	if (node != null &amp;amp;&amp;amp; node.Parent != this)
	{
		node.Parent = this;
	}

	return newItem;
}&lt;/pre&gt;
&lt;p&gt;The first line of &lt;em&gt;CanClose&lt;/em&gt; is quite important here &amp;ndash; we want to check only already opened children.&lt;/p&gt;
&lt;h2&gt;ShellViewModel&lt;/h2&gt;
&lt;p&gt;To use our new lazy conductor, update definition of ShellViewModel as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class ShellViewModel : LazyConductor&amp;lt;IModule, IModuleMetadata&amp;gt;.Collection.OneActive, IShell&lt;/pre&gt;
&lt;p&gt;Finally, I want to add the possibility to close opened modules. Add this to ShellViewModel:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public bool CanCloseActiveItem
{
	get
	{
		return ActiveItem != null;
	}
}

public void CloseActiveItem()
{
	DeactivateItem(ActiveItem, true);
}&lt;/pre&gt;
&lt;p&gt;To get the guard property updated, put this code into the class constructor:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;this.PropertyChanged += (s, e) =&amp;gt;
	{
		if (e.PropertyName == "ActiveItem")
		{
			NotifyOfPropertyChange(() =&amp;gt; CanCloseActiveItem);

		}
	};&lt;/pre&gt;
&lt;h2&gt;ShellView&lt;/h2&gt;
&lt;p&gt;The last thing to do is to add a close button to ShellView. Open ShellView, add this definition into its beginning:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;xmlns:local="clr-namespace:Coproject.Controls"&lt;/pre&gt;
&lt;p&gt;and put this control to the end of the &lt;em&gt;LayoutRoot&lt;/em&gt; grid:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;local:ImageButton x:Name="CloseActiveItem" ImageName="Close" ToolTipService.ToolTip="Close current module"
					Margin="20" HorizontalAlignment="Right" VerticalAlignment="Top" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;And we are done! Open To Do module, edit an item and then try to close the whole module &amp;ndash; you will see a warning that you have unsaved changes in the module.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://baud.cz/Media/Windows-Live-Writer/Coproject---a-RIA-Cal.Micro-demo-part-14_C2B0/image_4.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://baud.cz/Media/Windows-Live-Writer/Coproject---a-RIA-Cal.Micro-demo-part-14_C2B0/image_thumb_1.png" border="0" alt="image" width="244" height="168" /&gt;&lt;/a&gt;&lt;/p&gt;</description><pubDate>Thu, 07 Jul 2011 10:57:26 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-14</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 13</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-13</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;By now, you are probably using &lt;a href="http://caliburnmicro.codeplex.com/"&gt;Caliburn.Micro&lt;/a&gt; for your applications and hopefully Coproject helped you to learn it. But if you are creating large business applications as we do, you have probably realized that you need to tweak and extend C.M a little bit. That&amp;rsquo;s why I would like to continue on this &lt;a href="http://coproject.codeplex.com/"&gt;Coproject series&lt;/a&gt; while focusing on these advanced features.&lt;/p&gt;
&lt;p&gt;As you probably know, ordinary ViewModels hierarchy and thus whole application structure is loaded on the application startup. This is OK for small applications but with larger ones, there might be a memory issue having all ViewModels initialized and not being able to close them. In this part, I would like to describe and test an idea about having LazyScreens.&lt;/p&gt;
&lt;h2&gt;Lazy screen&lt;/h2&gt;
&lt;p&gt;The core idea is to have LazyScreen &amp;ndash; a sort of a wrapper around ordinary Screens that can be seen in application menu but will load the inner screen only after requested. Possibility to close the inner screen would be also useful to free some memory. Yes, you can close ordinary screens too but then, they are removed from their parent screen (and therefore from its menu), which is not what we want here. If these LazyScreens work, they will be used for main application parts &amp;ndash; modules, module navigation screens, etc.&lt;/p&gt;
&lt;h2&gt;ModuleMetadata&lt;/h2&gt;
&lt;p&gt;So, let&amp;rsquo;s open the Coproject source code and see what can we do. First of all, since we want our modules (Home, Messages, To Do , Milestones) be lazy loaded only when requested, their titles cannot be set in their code (DisplayName property) but must be set in metadata. So, open &lt;em&gt;IModuleMetadata&lt;/em&gt; and add Title property:&lt;/p&gt;
&lt;p&gt;(btw: do you know that you can hit CTRL+, to quickly navigate to any class in the solution? You can even use only capital letters, so write IMM to look for IModuleMetadata).&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public interface IModuleMetadata
{
	int Order { get; }
	string Title { get; }
}&lt;/pre&gt;
&lt;p&gt;Next, update &lt;em&gt;ExportModuleAttribute&lt;/em&gt; so that it implements the updated interface:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ExportModuleAttribute : ExportAttribute, IModuleMetadata
{
	public int Order { get; private set; }
	public string Title { get; private set; }

	public ExportModuleAttribute(int order, string title)
		: base(typeof(IModule))
	{
		Order = order;
		Title = title;
	}
}&lt;/pre&gt;
&lt;p&gt;Finally, update all module definitions so that the new attribute constructor is used (Home module example follows):&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[ExportModule(10, "Home")]
public class HomeViewModel : Screen, IModule&lt;/pre&gt;
&lt;p&gt;The solution should now build again.&lt;/p&gt;
&lt;h2&gt;LazyScreen&lt;/h2&gt;
&lt;p&gt;Having metadata prepared we have to implement the LazyScreen class. Put it into the Framework folder and make its signature as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class LazyScreen&amp;lt;TScreen, TMetadata&amp;gt; : Screen&lt;/pre&gt;
&lt;p&gt;In order to have LazyScreen create a new instance of the inner ViewModel (Screen) when requested, we will use MEF class named ExportFactory. This works just as its name suggests &amp;ndash; it gives you an export when you request one. What&amp;rsquo;s more, it provides metadata without creating a new export. So, let&amp;rsquo;s add a constructor to the class.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;private ExportFactory&amp;lt;TScreen, TMetadata&amp;gt; _factory;

public LazyScreen(ExportFactory&amp;lt;TScreen, TMetadata&amp;gt; factory)
{
	_factory = factory;
}&lt;/pre&gt;
&lt;p&gt;Next, add the most important functionality:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;private TScreen _screen;
private ExportLifetimeContext&amp;lt;TScreen&amp;gt; _export;
private object _lock = new object();

public TMetadata Metadata
{
	get
	{
		return _factory.Metadata;
	}
}

public bool IsScreenCreated
{
	get
	{
		return _export != null;
	}
}

public TScreen Screen
{
	get
	{
		lock (_lock)
		{
			if (!IsScreenCreated)
			{
				_export = _factory.CreateExport();
				_screen = _export.Value;
			}
			return _screen;
		}
	}
}&lt;/pre&gt;
&lt;pre class="prettyprint"&gt;public void Reset()
{
	if (!IsScreenCreated)
	{
		return;
	}

	lock (_lock)
	{
		_export.Dispose();
		_export = null;
		_screen = default(TScreen);
	}
	NotifyOfPropertyChange(() =&amp;gt; IsScreenCreated);
	NotifyOfPropertyChange(() =&amp;gt; Screen);
}&lt;/pre&gt;
&lt;p&gt;Now, let&amp;rsquo;s check, whether this might work. To use this new class, we must update our Shell. First, open ShellViewModel and update it like this:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Export(typeof(IShell))]
public class ShellViewModel : Conductor&amp;lt;LazyScreen&amp;lt;IModule, IModuleMetadata&amp;gt;&amp;gt;.Collection.OneActive, IShell
{
	[ImportingConstructor]
	public ShellViewModel([ImportMany]IEnumerable&amp;lt;ExportFactory&amp;lt;IModule, IModuleMetadata&amp;gt;&amp;gt; moduleHandles)
	{
		var modules = from h in moduleHandles orderby h.Metadata.Order 
						select new LazyScreen&amp;lt;IModule, IModuleMetadata&amp;gt;(h);
		Items.AddRange(modules);
	}
}&lt;/pre&gt;
&lt;p&gt;You should notice that we only updated constructor parameter type (from &lt;em&gt;Lazy&lt;/em&gt; to &lt;em&gt;ExportFactory&lt;/em&gt;), added new LazyScreens from these exports into &lt;em&gt;Items&lt;/em&gt; property, and updated base class generic parameter accordingly.&lt;/p&gt;
&lt;p&gt;Finally, we must update ShellView too:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Change binding of the TextBlock in the Items ListBox from &lt;em&gt;DisplayName&lt;/em&gt; to &lt;em&gt;Metadata.Title&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;Change name of &lt;em&gt;ActiveItem_Description&lt;/em&gt; to &lt;em&gt;ActiveItem_Screen_Description&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;Change name of &lt;em&gt;ActiveItem&lt;/em&gt; to &lt;em&gt;ActiveItem_Screen&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Meaning of these changes should be obvious &amp;ndash; since there is another layer between shell and modules (our new lazy screen), we must point the controls to the inner view models.&lt;/p&gt;
&lt;p&gt;If you now run the application, it should work just as it did before all these changes. Ok, I know that this does not seem like a great achievement :-) but take it as a proof that the original idea might work.&lt;/p&gt;
&lt;h2&gt;Simplify generics&lt;/h2&gt;
&lt;p&gt;There is one line in the code I really don&amp;rsquo;t like &amp;ndash; the repeating of generic parameters in &amp;lsquo;select new LazyScreen&amp;hellip;&amp;rsquo; in ShellViewModel constructor. We could make a use of generic functions to get rid of it. Add the following class into LazyScreen.cs:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public static class LazyScreen
{
	public static LazyScreen&amp;lt;TScreen, TMetadata&amp;gt; Create&amp;lt;TScreen, TMetadata&amp;gt;(
		ExportFactory&amp;lt;TScreen, TMetadata&amp;gt; factory)
	{
		return new LazyScreen&amp;lt;TScreen, TMetadata&amp;gt;(factory);
	}
}&lt;/pre&gt;
&lt;p&gt;We can update the ShellViewModel constructor:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;var modules = from h in moduleHandles orderby h.Metadata.Order select LazyScreen.Create(h);&lt;/pre&gt;
&lt;p&gt;No big deal but I like it much better now.&lt;/p&gt;
&lt;h2&gt;Finish LazyScreen&lt;/h2&gt;
&lt;p&gt;Having proven that LazyScreen works as expected, we should finalize its implementation (mainly delegate actions called on LazyScreen to its inner screen). Here are functions for screen activation and deactivation:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;protected override void OnActivate()
{
	ActivateScreen();
}

protected override void OnDeactivate(bool close)
{
	DeactivateScreen(close);
}

private void ActivateScreen()
{
	var activatableScreen = _screen as IActivate;
	if (activatableScreen != null)
	{
		activatableScreen.Activate();
	}
}

private void DeactivateScreen(bool close)
{
	var deactivatableScreen = _screen as IDeactivate;
	if (deactivatableScreen != null)
	{
		deactivatableScreen.Deactivate(close);
	}
}&lt;/pre&gt;
&lt;p&gt;There are functions for closing too:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public override void CanClose(Action&amp;lt;bool&amp;gt; callback)
{
	var closableScreen = _screen as IGuardClose;
	if (closableScreen != null)
	{
		closableScreen.CanClose(callback);
	}
	else
	{
		base.CanClose(callback);
	}
}

public new void TryClose()
{
	var closableScreen = _screen as IClose;
	if (closableScreen != null)
	{
		closableScreen.TryClose();
	}
	base.TryClose();
}&lt;/pre&gt;
&lt;p&gt;And for Parent/Child relationship:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public override object Parent
{
	get
	{
		return base.Parent;
	}
	set
	{
		base.Parent = value;

		if (IsScreenCreated)
		{
			SetScreenParent();
		}
	}
}

private void SetScreenParent()
{
	var childScreen = _screen as IChild;
	if (childScreen != null)
	{
		childScreen.Parent = this.Parent;
	}
}&lt;/pre&gt;
&lt;p&gt;Then update getter for Screen property:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;if (!IsScreenCreated)
{
	_export = _factory.CreateExport();
	_screen = _export.Value;

	SetScreenParent();
	if (IsActive)
	{
		ActivateScreen();
	}
}&lt;/pre&gt;
&lt;p&gt;And add this line just to the beginning of the lock statement in &lt;em&gt;Reset()&lt;/em&gt;:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;DeactivateScreen(true);&lt;/pre&gt;
&lt;p&gt;So, our LazyScreen is ready. It loads its content only when needed and the rest of the application works properly. In the next part of this series, we will implement LazyConductor so that we can close (reset) LazyScreens.&lt;/p&gt;
&lt;p&gt;What do you think about this solution? Have you already solved similar problems?&lt;/p&gt;</description><pubDate>Thu, 07 Jul 2011 09:44:49 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-13</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 12</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-12</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, I would like to use RIA Services a little more and then show you how to customize Caliburn.Micro conventions. Remember to visit &lt;a href="http://coproject.codeplex.com/"&gt;Coproject Codeplex site&lt;/a&gt; for latest news.&lt;/p&gt;
&lt;h2&gt;Display metadata&lt;/h2&gt;
&lt;p&gt;If you remember &lt;a href="http://baud.cz/blog/coproject-ria-caliburnmicro-demo-part-2"&gt;Part 2&lt;/a&gt;, RIA Services use metadata to describe what data should be transferred to the client. But that is not all &amp;ndash; you can add things like label text or validation. So, open Coproject.Web/Services/CoprojectService.metadata.cs.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s say we want to change labels in ToDoItem detail:&lt;br /&gt;&lt;a href="http://www.baud.cz/Media/Windows-Live-Writer/8da7bf03af91_8C05/image_2.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://www.baud.cz/Media/Windows-Live-Writer/8da7bf03af91_8C05/image_thumb.png" border="0" alt="image" width="244" height="152" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So in ToDoItemMetadata, update the following properties:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Display(Name="Task", Description="Describe the To-do task.")]
public string Content { get; set; }

[Display(Name = "Deadline", Description = "The latest possible date the task must be finished.")]
public Nullable&amp;lt;DateTime&amp;gt; DueDate { get; set; }

[Include]
[Association("FK_ToDoItems_Users", "UserID", "UserID", IsForeignKey = true)]
[Display(Name="Assigned user")]
public User User;&lt;/pre&gt;
&lt;p&gt;If you run the application now you will see the metadata applied:&lt;br /&gt;&lt;a href="http://www.baud.cz/Media/Windows-Live-Writer/8da7bf03af91_8C05/image_4.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://www.baud.cz/Media/Windows-Live-Writer/8da7bf03af91_8C05/image_thumb_1.png" border="0" alt="image" width="244" height="179" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Note that you could use other named parameters of [Display] to modify auto-generation of DataForms: AutoGenerateField, Order, Groupname. There are other useful parameters &amp;ndash; you can check them on &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx"&gt;MSDN&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Validation metadata&lt;/h2&gt;
&lt;p&gt;Matadata can be also used for setting validation restrictions. Update the following:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Display(Name = "Task", Description = "Describe the To-do task.")]
[Required]
[StringLength(40)]
public string Content { get; set; }

[Range(typeof(DateTime), "1.1.2010", "31.12.2019")]
[Display(Name = "Deadline", Description = "The latest possible date the task must be finished.")]
public Nullable&amp;lt;DateTime&amp;gt; DueDate { get; set; }&lt;/pre&gt;
&lt;p&gt;And now, when you run the application, you can see something like that (note that the Save button is disabled as there are validation errors):&lt;br /&gt;&lt;a href="http://www.baud.cz/Media/Windows-Live-Writer/8da7bf03af91_8C05/image_6.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="http://www.baud.cz/Media/Windows-Live-Writer/8da7bf03af91_8C05/image_thumb_2.png" border="0" alt="image" width="244" height="192" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;You should look into System.ComponentModel.DataAnnotations for other useful attributes. For example if we set this on DueData:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Editable(false)]&lt;/pre&gt;
&lt;p&gt;The field will be disabled for editing even in edit mode. That is how you set your domain on the server so that there is as little as possible of specific code concerning your domain in your presentation layer.&lt;/p&gt;
&lt;h2&gt;Shared code&lt;/h2&gt;
&lt;p&gt;As you can see, the User field shows only last name of the user and that is not what we want. This a great opportunity to show you how to use shared code between server and client. All you need to do is to call the file you want to be shared as *.shared.cs. So in Coproject.Web project, create a new file Models/User.shared.cs and set its content as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;namespace Coproject.Web.Models
{
	public partial class User
	{
		public string FullName
		{
			get
			{
				return string.Format("{0} {1}", this.FirstName, this.LastName);
			}
		}
	}
}&lt;/pre&gt;
&lt;p&gt;It is especially important to use this namespace (so that you can extent the partial class created by RIA Services) and to remove using of System.Web (since tis file is copied to the client as-is and there is no reference to this assembly). Now, we can edit ToDoItemView as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;dataForm:DataField PropertyPath="User"&amp;gt;
	&amp;lt;TextBlock Text="{Binding User.FullName}" /&amp;gt;
&amp;lt;/dataForm:DataField&amp;gt;&lt;/pre&gt;
&lt;p&gt;Note that you can share validators and other logic this way.&lt;br /&gt;&lt;a href="http://www.baud.cz/Media/Windows-Live-Writer/8da7bf03af91_8C05/image_8.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://www.baud.cz/Media/Windows-Live-Writer/8da7bf03af91_8C05/image_thumb_3.png" border="0" alt="image" width="244" height="192" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Filter on Enter&lt;/h2&gt;
&lt;p&gt;Another thing I would like to tweak a little bit would be to start filtering right when user hits Enter in the filter text box in ToDoListsView. The easiest way you are probably thinking of would be to add this handler to the Filter text box:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;cal:Message.Attach="[KeyDown] = [HandleKeyInFilter($eventargs)]"&lt;/pre&gt;
&lt;p&gt;and then add this to view model:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IEnumerable&amp;lt;IResult&amp;gt; HandleKeyInFilter(System.Windows.Input.KeyEventArgs eventargs)
{
	if (eventargs.Key == System.Windows.Input.Key.Enter)
	{
		yield return LoadData().ToSequential();
	}

	yield break;
}&lt;/pre&gt;
&lt;p&gt;Although this approach would work prefectly, it might not be a good idea to make view model dependent on KeyEventArgs. The best approach would be to customize Caliburn.Micro.Parser.CreateTrigger to support other action s than Event (like EnterPressed, or Gesture Key: Enter that is supported by original Caliburn). But I don&amp;rsquo;t want to change C.M source here. The last solution I can think of would be to create ExtendedTextBox and add EnterKeyDown event to it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;namespace Coproject.Controls
{
	public class ExtendedTextBox : TextBox
	{
		public event EventHandler EnterKeyDown;

		protected override void OnKeyDown(KeyEventArgs e)
		{
			base.OnKeyDown(e);

			if (e.Key == Key.Enter)
			{
				OnEnterKeyDown();
			}
		}

		protected void OnEnterKeyDown()
		{
			var handler = EnterKeyDown;
			if (handler != null)
			{
				handler(this, EventArgs.Empty);
			}
		}
	}
}&lt;/pre&gt;
&lt;p&gt;In order to have the default text box style applied to this new control too, we also have to add this to Custom.xaml:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;Style TargetType="local:ExtendedTextBox" BasedOn="{StaticResource DefaultTextBoxStyle}" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;And then we can easily use this new text box in ToDoListsView:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;local:ExtendedTextBox x:Name="Filter" Style="{StaticResource FilterTextBoxStyle}" 
						cal:Message.Attach="[EnterKeyDown] = [LoadData]" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;I, personally, like this way more because view and view models don&amp;rsquo;t have any clue about views implementation.&lt;/p&gt;
&lt;h2&gt;Customizing Caliburn.Micro conventions&lt;/h2&gt;
&lt;p&gt;Since we created a new control, we would like to save some configuration about attaching actions to it and use C.M convention instead. So, open AppBootstrapper, add a call to InitializeConvention() into Configure() and implement it as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;private void InitializeConventions()
{
	ConventionManager.AddElementConvention&amp;lt;BusyIndicator&amp;gt;(BusyIndicator.IsBusyProperty, "IsBusy", "Loaded");
	ConventionManager.AddElementConvention&amp;lt;ExtendedTextBox&amp;gt;(ExtendedTextBox.TextProperty, "Text", "EnterKeyDown");
}&lt;/pre&gt;
&lt;p&gt;The first argument configures to what property should be the respective view model property bound to. So if we name a BusyIndicator &amp;lsquo;Busy&amp;rsquo;, its IsBusy property will be bound to (viewModel).Busy.&lt;/p&gt;
&lt;p&gt;The second arguments describes what property of the control should be taken if this control is set as an action parameter. If you remember LoadData(string filter) then this argument is responsible that the Text property of &amp;lsquo;Filter&amp;rsquo; text box was passed.&lt;/p&gt;
&lt;p&gt;The third argument configures the default event to start actions.&lt;/p&gt;
&lt;p&gt;Now, we can update these two controls in ToDoListsView as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;local:ExtendedTextBox x:Name="Filter" Style="{StaticResource FilterTextBoxStyle}" cal:Message.Attach="LoadData" /&amp;gt;&lt;/pre&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;toolkit:BusyIndicator x:Name="Busy_IsBusy"  Grid.RowSpan="2" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;Note: I am not saying that this is exactly what you should do in your projects, it was just a great example for showing how these things work. You have to think about it and decide yourself &amp;ndash; concrete decision depends on many factors.&lt;/p&gt;
&lt;h2&gt;Opened details counter&lt;/h2&gt;
&lt;p&gt;I found this quite useful when experimenting with details opening and closing so if you want to, add this code to ToDoListsView, above Toolbar:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,-25,0,0"&amp;gt;
	&amp;lt;TextBlock Text="Opened details: " Style="{StaticResource StatusTextBlockStyle}" /&amp;gt;
	&amp;lt;TextBlock x:Name="Items_Count" Style="{StaticResource StatusTextBlockStyle}" /&amp;gt;
&amp;lt;/StackPanel&amp;gt;&lt;/pre&gt;
&lt;p&gt;I think that by now, you are so familiar with the concept that there is no need to describe what this does.&lt;/p&gt;</description><pubDate>Tue, 21 Jun 2011 13:56:43 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-12</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 1</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-1</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, I would like to describe the Coproject application, overview its architecture, and prepare its database.&lt;/p&gt;
&lt;h2&gt;What will Coproject do&lt;/h2&gt;
&lt;p&gt;If you know &lt;a href="http://basecamphq.com/"&gt;BaseCamp&lt;/a&gt;, the idea of Coproject should be familiar to you. For others, let&amp;rsquo;s say we want to create a simple project management tool. It should help you track current state and progress of a project. We want it to have four modules: Home and overview, Messages, To-Do lists, and Milestones.&lt;/p&gt;
&lt;p&gt;Since I want this tutorial to be as simple and clear as possible, we will focus on To-Do lists only. We want the application to show list of To-Do items, filter the list, show detail of selected To-Do item, and edit the item. I believe that for now, it is enough to keep you focused on our goal and I hope I will be able to show how to handle many issues that you usually encounter while developing business applications.&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/ca245fdba608_F210/mockup_2.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0;" title="mockup" src="/Media/Windows-Live-Writer/ca245fdba608_F210/mockup_thumb.png" border="0" alt="mockup" width="244" height="171" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Architecture&lt;/h2&gt;
&lt;p&gt;Based on the analysis illustrated in the &lt;a href="http://www.slideshare.net/petrh/rapid-ria-development"&gt;original presentation&lt;/a&gt;, Coproject will be a three layered application based on a SQL database, ADO.NET Entity Framework 4, WCF RIA Services and Silverlight 4.&lt;/p&gt;
&lt;h3&gt;Data source&lt;/h3&gt;
&lt;p&gt;In this tutorial. we will use a simple SQL database for data storage because this is probably the typical case. Nevertheless, you may use any other data source that is supported by Entity Framework 4. The most important part of the database schema is shown below:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/ca245fdba608_F210/image_2.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0; margin: 0px;" title="image" src="/Media/Windows-Live-Writer/ca245fdba608_F210/image_thumb.png" border="0" alt="image" width="244" height="220" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To make it a little more complicated than simple list of items, ToDoItems are grouped by ToDoLists.&lt;/p&gt;
&lt;h3&gt;Web server&lt;/h3&gt;
&lt;p&gt;On the application server side, we will use Entity Framework 4 to access data source. If you are not familiar with it, check &lt;a href="http://msdn.microsoft.com/en-us/data/aa937723"&gt;this&lt;/a&gt; site.&lt;/p&gt;
&lt;p&gt;To make the data available for the Silverlight client, we will use WCF RIA Services. You can learn more about it &lt;a href="https://www.silverlight.net/getstarted/riaservices/"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The client itself and the services will be hosted in an ASP.NET Web application and thus the client application will be accessible via browser. However, we will also support out-of-browser running.&lt;/p&gt;
&lt;h3&gt;Client&lt;/h3&gt;
&lt;p&gt;The client will be implemented as a Silverlight 4 application. It will follow &lt;a href="http://johnpapa.net/silverlight/5-minute-overview-of-mvvm-in-silverlight/"&gt;M-V-VM design pattern&lt;/a&gt; using &lt;a href="http://caliburnmicro.codeplex.com/"&gt;Caliburn.Micro&lt;/a&gt; framework. It should handle typical business scenarios like: asynchronous loading of data, loading indication, opening and editing of more than one entity at a time, validation, dirty checking, etc.&lt;/p&gt;
&lt;h2&gt;Getting ready for development&lt;/h2&gt;
&lt;p&gt;We need to create a database for Coproject. Although you can create a database file in Visual Studio, it is not possible to execute a script on a database through VS. So you can either create an ordinary database on your server (or local Express server) and execute Create script attached to this article, or download already prepared database file Database.mdf and put into App_Data folder of web server that we created last time.&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/ca245fdba608_F210/image_4.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0; margin: 0px;" title="image" src="/Media/Windows-Live-Writer/ca245fdba608_F210/image_thumb_1.png" border="0" alt="image" width="244" height="226" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;You should be able to double-click it and have it opened in &lt;em&gt;Server Explorer&lt;/em&gt;:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/ca245fdba608_F210/image_6.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px; border: 0; margin: 0px;" title="image" src="/Media/Windows-Live-Writer/ca245fdba608_F210/image_thumb_2.png" border="0" alt="image" width="153" height="244" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Rebuild the solution to make sure there are no errors.&lt;/p&gt;
&lt;p&gt;That&amp;rsquo;s all for now. The next time, we&amp;rsquo;ll create a RIA service.&lt;/p&gt;
&lt;div id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:2f62b228-1814-4f02-bb57-a0bc7bdb9a22" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;div&gt;&lt;a href="http://www.baud.cz/Media/Windows-Live-Writer/ca245fdba608_F210/Database_2.zip" target="_self"&gt;Script and Database&lt;/a&gt;&lt;/div&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;/div&gt;</description><pubDate>Tue, 21 Jun 2011 13:50:12 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-1</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 9</title><link>http://www.baud.cz:80/blog/coproject-a-ria-caliburnmicro-demo-part-9</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will add a toolbar and handle data saving.&lt;/p&gt;
&lt;h2&gt;Toolbar&lt;/h2&gt;
&lt;p&gt;It is a typical scenario that screens have toolbars. These are usually shown somewhere else in the application than their respective view model&amp;rsquo;s views. In this case, we will benefit from Caliburn.Micro&amp;rsquo;s feature of having more than one view attached to a view model. You can describe what view you want to show by setting &amp;lsquo;context&amp;rsquo; of the view.&lt;/p&gt;
&lt;p&gt;So, open the Coproject solution where we finished the last time or download source codes from &lt;a href="http://coproject.codeplex.com/"&gt;Coproject site&lt;/a&gt;. Add this control to root grid in ToDoListsView:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;ContentControl Grid.Column="1" Grid.Row="0" Margin="10,0,0,0" HorizontalContentAlignment="Stretch" 
				cal:View.Model="{Binding ActiveItem}" cal:View.Context="Toolbar" /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Important is the second line. Since there is already a control called ActiveItem and we want to bind this control to the active item too, we have to use cal:View.Model structure. Even more important is cal:View.Context because it instructs C.M not to use the default view (ToDoItemView in this case) but Toolbar view.&lt;/p&gt;
&lt;p&gt;C.M&amp;rsquo;s default logic for locating context views is: take the default view location (e.g., Views.ToDoItemView), trim &amp;lsquo;View&amp;rsquo; from the end, add &amp;lsquo;.&amp;rsquo; + context. So it would end up with Views.ToDoItem.Toolbar. And that&amp;rsquo;s where we have to put our new &lt;em&gt;Silverlight User Control&lt;/em&gt;. Then replace its original LayoutRoot with the following:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;Border Style="{StaticResource FilterPanelStyle}"&amp;gt;
	&amp;lt;StackPanel Orientation="Horizontal" HorizontalAlignment="Right"&amp;gt;
		&amp;lt;Button x:Name="Edit" Content="Edit" Margin="0,0,5,0" /&amp;gt;
		&amp;lt;Button x:Name="Cancel" Content="Cancel" Margin="0,0,5,0" /&amp;gt;
		&amp;lt;Button x:Name="Save" Content="Save" Margin="0,0,5,0" /&amp;gt;
		&amp;lt;Button x:Name="TryClose" Content="Close" /&amp;gt;
	&amp;lt;/StackPanel&amp;gt;
&amp;lt;/Border&amp;gt;&lt;/pre&gt;
&lt;p&gt;So the structure of the client project should be like:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/Coproject---a-RIA-Cali.Micro-demo-part-9_A51C/image_2.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/Coproject---a-RIA-Cali.Micro-demo-part-9_A51C/image_thumb.png" border="0" alt="image" width="126" height="244" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Context views are bound to view models the same way as default views, so it is not a surprise that now we are going to implement Edit, Cancel, and Save functions (TryClose is already implemented in Screen base class).&lt;/p&gt;
&lt;h2&gt;ViewModel behavior&lt;/h2&gt;
&lt;p&gt;We want the detail to be in read-only mode with buttons Cancel and Save disabled. When Edit is clicked, the detail should change to edit mode and disable edit button. This will be done by adding another property IsReadOnly to the view model. So, open ToDoItemViewModel.&lt;/p&gt;
&lt;p&gt;First of all, we will add the IsReadOnly property. Since we want it to automatically raise NotifyPropertyChanged, we cannot use the one-line definition, so write this:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;private bool _isReadOnly;
public bool IsReadOnly
{
	get
	{
		return this._isReadOnly;
	}
	set
	{
		this._isReadOnly = value;
		NotifyOfPropertyChange(() =&amp;gt; IsReadOnly);
	}
}&lt;/pre&gt;
&lt;p&gt;Implementation of Edit function is very lightweight:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public void Edit()
{
	IsReadOnly = false;
}&lt;/pre&gt;
&lt;p&gt;Cancel will be only a little bit longer because we need to cancel changes before switching back to read-only mode. We will benefit from the fact that RIA Services entities implement IEditableObject interface. In order to fix a DataForm bug I mention &lt;a href="http://baud.cz/blog/coproject-ria-caliburnmicro-demo-part-8"&gt;last time&lt;/a&gt;, we have to switch to read-only, then back to edit, and finally again to read-only mode:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public void Cancel()
{
	(Item as IEditableObject).CancelEdit();
	IsReadOnly = true;
	#region Fix DataForm bug
	IsReadOnly = false; IsReadOnly = true;
	#endregion
}&lt;/pre&gt;
&lt;p&gt;In order to implement Save(), we will need SaveDataResult. It is wuite similar to LoadDataResult we implemented earlier. So create new class SaveDataResult into the Framework folder:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;namespace Coproject.Framework
{
	public class SaveDataResult : IResult
	{
		public DomainContext Context { get; private set; }
		public SubmitOperation Result { get; private set; }

		public event EventHandler&amp;lt;ResultCompletionEventArgs&amp;gt; Completed;

		public SaveDataResult(DomainContext context)
		{
			Context = context;
		}

		public void Execute(ActionExecutionContext context)
		{
			Context.SubmitChanges(SaveDataCallback, null);
		}

		private void SaveDataCallback(SubmitOperation data)
		{
			Result = data;
			OnCompleted();
		}

		private void OnCompleted()
		{
			var handler = Completed;
			if (handler != null)
			{
				handler(this, new ResultCompletionEventArgs());
			}
		}
	}
}&lt;/pre&gt;
&lt;p&gt;Now, we can use it ToDoItemViewModel.Save() implementation:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IEnumerable&amp;lt;IResult&amp;gt; Save()
{
	(Item as IEditableObject).EndEdit();
	IsReadOnly = true;
	#region Fix DataForm bug
	IsReadOnly = false; IsReadOnly = true;
	#endregion

	yield return new SaveDataResult(_context);
}&lt;/pre&gt;
&lt;p&gt;Finally, bind the DataForm on ToDoItemView to the IsReadOnly property:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;dataForm:DataForm CurrentItem="{Binding Item}" IsReadOnly="{Binding IsReadOnly}" HorizontalAlignment="Stretch"&amp;gt;&lt;/pre&gt;
&lt;p&gt;If you now run the application, you will notice that switching modes works and savings works too (you must refresh the list). There still some issues: opened detail is already in edit mode, all buttons are enabled.&lt;/p&gt;
&lt;p&gt;Fixing the first issue is trivial &amp;ndash; add this row to the beginning of Setup(int toDoItemID):&lt;/p&gt;
&lt;pre class="prettyprint"&gt;IsReadOnly = true;&lt;/pre&gt;
&lt;h2&gt;Guard methods&lt;/h2&gt;
&lt;p&gt;To fix the other issue, we will use &amp;lsquo;guards&amp;rsquo;. These are another part of Caliburn.Micro&amp;rsquo;s &amp;lsquo;Convention over configuration&amp;rsquo; system. If there is a control bound to any function of a view model and the view model also contains property or function called CanXXX, it will use this CanXXX function to determine whether it is possible to run the bound function itself. These 'CanXXX&amp;rsquo; properties are called guards. Note that C.M will also update availability of invoking controls. So as you can guess, we will implement properties CanEdit, CanCancel, and CanSave:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public bool CanEdit
{
	get { return IsReadOnly; }
}
		
public bool CanCancel
{
	get { return !IsReadOnly; }
}

public bool CanSave
{
	get { return Item.HasChanges &amp;amp;&amp;amp; !Item.HasValidationErrors; }
}&lt;/pre&gt;
&lt;p&gt;We also need to notify when these properties change. So update set of IsReadOnly as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;set
{
	this._isReadOnly = value;
	NotifyOfPropertyChange(() =&amp;gt; IsReadOnly);
	NotifyOfPropertyChange(() =&amp;gt; CanEdit);
	NotifyOfPropertyChange(() =&amp;gt; CanCancel);
}&lt;/pre&gt;
&lt;p&gt;CanSave property depends on the state of Item, so add this line at the end of the Setup function:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;Item.PropertyChanged += (s, e) =&amp;gt; NotifyOfPropertyChange(() =&amp;gt; CanSave);&lt;/pre&gt;
&lt;p&gt;You can now run the application and see how the buttons get disabled and enabled as appropriate.&lt;/p&gt;
&lt;h2&gt;Dirty checking&lt;/h2&gt;
&lt;p&gt;As Close button works too, we should add dirty-checking logic so that we don&amp;rsquo;t lose unsaved changes when closing detail. This is done using CanClose virtual function. This function is closed when C.M wants to close the screen. It is then up to the implementation what happens but when it is resolved, the CanClose function should call callback with information whether it can be closed or not. Add this function to ToDoItemViewModel:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public override void CanClose(Action&amp;lt;bool&amp;gt; callback)
{
	if (Item.HasChanges)
	{
		var result = MessageBox.Show("Current item was not saved. Do you really want to close it?", 
			"Coproject", MessageBoxButton.OKCancel);
		callback(result == MessageBoxResult.OK);
	}
	else
	{
		callback(true);
	}
}&lt;/pre&gt;
&lt;p&gt;I know that the question in the message is not ok for buttons OK or Cancel but that&amp;rsquo;s all we get from Silverlight out of the box. You definitely should implement custom message box (I will talk about it in later posts).&lt;/p&gt;
&lt;p&gt;There is one more thing I want to implement: if the detail is closed and its entity is edited, it would be better to cancel the changes. Implementation is very straightforward:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;protected override void OnDeactivate(bool isClosing)
{
	if (isClosing &amp;amp;&amp;amp; CanCancel)
	{
		Cancel();
	}
}&lt;/pre&gt;
&lt;p&gt;That is all for toolbar and dirty-checking. It was quite easy, wasn&amp;rsquo;t it?&lt;/p&gt;
&lt;h2&gt;UpdateSourceOnChange&lt;/h2&gt;
&lt;p&gt;I bet you noticed that when editing Content, you have to click somewhere else to enable the Save button. The reason for that is that TextBox in Silverlight updates its binding source only when it loses focus and this cannot be changed as in WPF by setting UpdateSourceTrigger=PropertyChanged. Fortunately, this can be achieved in Silverlight too, but we will need this helper class in Coproject/Helpers:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public static class BindingHelper
{
	public static bool GetUpdateSourceOnChange(DependencyObject obj)
	{
		return (bool)obj.GetValue(UpdateSourceOnChangeProperty);
	}

	public static void SetUpdateSourceOnChange(DependencyObject obj, bool value)
	{
		obj.SetValue(UpdateSourceOnChangeProperty, value);
	}

	public static readonly DependencyProperty UpdateSourceOnChangeProperty =
		DependencyProperty.RegisterAttached("UpdateSourceOnChange", typeof(bool), 
		typeof(BindingHelper), new PropertyMetadata(false, OnPropertyChanged));

	private static void OnPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
	{
		var textBox = obj as TextBox;
		if (textBox != null)
		{
			if ((bool)e.NewValue)
			{
				textBox.TextChanged += TextBox_TextChanged;
			}
			else
			{
				textBox.TextChanged -= TextBox_TextChanged;
			}
		}
	}

	private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
	{
		var textBox = sender as TextBox;
		if (textBox != null)
		{
			var binding = textBox.GetBindingExpression(TextBox.TextProperty);
			if (binding != null)
			{
				binding.UpdateSource();
			}
		}
	}
}&lt;/pre&gt;
&lt;p&gt;Your &lt;em&gt;Solution Explorer&lt;/em&gt; should show this:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/Coproject---a-RIA-Cali.Micro-demo-part-9_A51C/image_4.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/Coproject---a-RIA-Cali.Micro-demo-part-9_A51C/image_thumb_1.png" border="0" alt="image" width="242" height="244" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Lastly, we need to use this helper in our views. Open ToDoItemView and register this namespace in it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;xmlns:helpers="clr-namespace:Coproject.Helpers"&lt;/pre&gt;
&lt;p&gt;Then update the TextBox in DataField bound to Content as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;TextBox Text="{Binding Content,Mode=TwoWay}" TextWrapping="Wrap" Height="auto"
			helpers:BindingHelper.UpdateSourceOnChange="True"/&amp;gt;&lt;/pre&gt;
&lt;p&gt;And that is really all for this part. Run the application and experiment!&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/Coproject---a-RIA-Cali.Micro-demo-part-9_A51C/image_6.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/Coproject---a-RIA-Cali.Micro-demo-part-9_A51C/image_thumb_2.png" border="0" alt="image" width="244" height="179" /&gt;&lt;/a&gt;&lt;/p&gt;</description><pubDate>Sat, 19 Feb 2011 15:52:22 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-a-ria-caliburnmicro-demo-part-9</guid></item><item><title>Unity/EntLib interceptors in MEF</title><link>http://www.baud.cz:80/blog/unity-entlib-interceptors-in-mef</link><description>&lt;p&gt;By Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In one of our applications, we use MEF for discovery of component exports. To make it more complicated, we also wanted to use Enterprise Library interceptors for advanced logging, error handling and caching (from Policy Injection Application Block) so we needed to use Unity as well. &lt;a href="http://mefcontrib.codeplex.com/"&gt;MEFContrib&lt;/a&gt; was a great helper for us so we were able to use (in simplified words) MEF for exports and Unity for imports. Although there were some &lt;a href="http://mefcontrib.codeplex.com/discussions/227677"&gt;problems&lt;/a&gt; it worked. With the new version of MEFContrib, things became even easier as support for &lt;a href="http://pwlodek.blogspot.com/2010/11/introduction-to-interceptingcatalog.html"&gt;interception&lt;/a&gt; and &lt;a href="http://pwlodek.blogspot.com/2010/12/introduction-to-interceptingcatalog.html"&gt;open generics&lt;/a&gt; was added to MEF.&lt;/p&gt;
&lt;p&gt;The current MEFContrib interceptor implementation uses Castle&amp;rsquo;s &lt;a href="http://www.castleproject.org/dynamicproxy/index.html"&gt;Dynamic Proxy 2&lt;/a&gt; or &lt;a href="http://code.google.com/p/linfu/"&gt;LinFu&lt;/a&gt; as intercepting proxies. But as we wanted to use the original EntLib interceptors that were meant for Unity, I had to add support for Unity&amp;rsquo;s &lt;em&gt;InterfaceInterceptor&lt;/em&gt; to MEFContrib.&lt;/p&gt;
&lt;h2&gt;Unity Interceptor&lt;/h2&gt;
&lt;p&gt;To implement UnityInterceptor for MEFContrib, I suggest to download the latest &lt;a href="https://github.com/MefContrib/MefContrib"&gt;source codes&lt;/a&gt; for MEFContrib and build it yourself as the interception and generics support have been extended since the 1.0 release.&lt;/p&gt;
&lt;p&gt;Supposing you already have MEFContrib running, reference it in your project and then add this class to your project:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class UnityInterceptor : IExportedValueInterceptor
{
	public object Intercept(object value)
	{
		var interfaces = value.GetType().GetInterfaces();
		var proxyInterface = interfaces.FirstOrDefault();
		var additionalInterfaces = interfaces.Skip(1).ToArray();

		var interceptor = new InterfaceInterceptor();

		CurrentInterceptionRequest request = new CurrentInterceptionRequest(interceptor, proxyInterface, value.GetType());
		InjectionPolicy[] policies = new InjectionPolicy[] { new AttributeDrivenPolicy() };
		PolicyInjectionBehavior behaviour = new PolicyInjectionBehavior(request, policies, null);

		var proxy = Microsoft.Practices.Unity.InterceptionExtension.Intercept.ThroughProxyWithAdditionalInterfaces(
			proxyInterface,
			value,
			interceptor,
			new[] { behaviour },
			additionalInterfaces);

		return proxy;
	}
}&lt;/pre&gt;
&lt;p&gt;I will send this code to the MEFContrib team so hopefully it will be integrated into MEFContrib bits.&lt;/p&gt;
&lt;p&gt;Then, add the following code to your MEF container initialization:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;var catalog = new DirectoryCatalog(System.Web.Hosting.HostingEnvironment.MapPath("~/Bin")); // create your original MEF catalog

var interceptionConfiguration = new InterceptionConfiguration()
	.AddInterceptionCriteria(new PredicateInterceptionCriteria(
		new UnityInterceptor(),
		predicate); // predicate that filters to what export components should be interceptors applied (you will probably use some metadata filtering or omit it)
var interceptingCatalog = new InterceptingCatalog(catalog, interceptionConfiguration);
//use interceptingCatalog (initialize MEF with it)&lt;/pre&gt;
&lt;p&gt;You are done &amp;ndash; now you can use EntLib attributes, for example, &lt;em&gt;[LogCallHandler]&lt;/em&gt; on your components and they will work as expected!&lt;/p&gt;</description><pubDate>Fri, 18 Feb 2011 10:10:35 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/unity-entlib-interceptors-in-mef</guid></item><item><title>E-mail protection on your site</title><link>http://www.baud.cz:80/blog/email-protection-on-your-site</link><description>&lt;p&gt;by M&amp;iacute;&amp;scaron;a H&amp;aacute;jkov&amp;aacute;&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s imagine following situation. You create new modern website and because you are looking for some feedback from your potential customers, your new e-mail address shouldn&amp;rsquo;t missed. But after some time, you receive first offer for some blue pills, and then next and next and&amp;hellip; - and then you&amp;rsquo;re doing nothing else than deleting spam. That&amp;rsquo;s because your e-mails are not protected and can be easily harvested by specialized robots called spambots.&lt;/p&gt;
&lt;p&gt;What spambots do? It&amp;rsquo;s easy, they get html of your web page and search for e-mails. Here is small example how spambot should work:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("website_url");&lt;br /&gt;request.Method = "GET";&lt;br /&gt;using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())&lt;br /&gt;{&lt;br /&gt; StreamReader stream = new StreamReader(response.GetResponseStream());&lt;br /&gt; string html = stream.ReadToEnd();&lt;br /&gt; foreach (Match m in Regex.Matches(html, @"\w[\w\.-]+?@(?:[\w-]+\.)+[\w]{2,4}"))&lt;br /&gt; {&lt;br /&gt;  Console.WriteLine(m.Value);&lt;br /&gt; }&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;As you see, it&amp;rsquo;s really very easy to get your e-mail addresses from your website. You can harvest links from your page in similar way and then harvest e-mails from all of Internet &amp;ndash; except pages, where e-mails are protected. Let&amp;rsquo;s take a look, how to do it.&lt;/p&gt;
&lt;p&gt;First question is: Where is the best place for code? Your e-mail protecting code can be placed into overridden &lt;code&gt;Render&lt;/code&gt; method of your page or into the same method of base class of your page, or master page. But if you want to protect more websites, or protect non-aspx files such as html, the best way is to use &lt;code&gt;ResponseFilter&lt;/code&gt; in new (or maybe your existing) HTTP Module. This HTTP Module can be used in as many sites as you want, you simply copy compiled files into bin directory of your site and register this module in web.config. If you are really brave and want to protect whole your IIS, you can copy your files to GAC and register it in machine.config. Base information about HTTP Modules can be found here: &lt;a title="http://msdn.microsoft.com/en-us/library/zec9k340(v=VS.71).aspx" href="http://msdn.microsoft.com/en-us/library/zec9k340(v=VS.71).aspx"&gt;http://msdn.microsoft.com/en-us/library/zec9k340(v=VS.71).aspx&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s show how to create our custom HTTP Module protecting e-mail addresses being harvested by spambots.&lt;/p&gt;
&lt;p&gt;First, we need to create basic HTTP Module functionality:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class EmailFilter : IHttpModule&lt;br /&gt;{&lt;br /&gt; public void Init(HttpApplication app)&lt;br /&gt; {&lt;br /&gt;  app.PostRequestHandlerExecute += new EventHandler(app_PostRequestHandlerExecute);&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; private void app_PostRequestHandlerExecute(object sender, EventArgs e)&lt;br /&gt; {&lt;br /&gt;  &lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; public void Dispose() { }&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;Methos &lt;code&gt;Init&lt;/code&gt; and &lt;code&gt;Dispose&lt;/code&gt; must be presented in every class implementing &lt;code&gt;IHttpModule&lt;/code&gt; interface. Inside &lt;code&gt;Init&lt;/code&gt; method, you see declaration of new &lt;code&gt;PostRequestHandlerExecute&lt;/code&gt; handler. It fires right after page is executed and before it is send to the client. This is the right time to modify generated content and send to the client this modified code. Inside &lt;code&gt;PostRequestHandlerExecute&lt;/code&gt; we append our new e-mail protecting &lt;code&gt;ResponseFilter&lt;/code&gt; to the response stream.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;private void app_PostRequestHandlerExecute(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt; HttpResponse response = ((HttpApplication)sender).Response;&lt;br /&gt; string rawUrl = ((HttpApplication)sender).Request.RawUrl.ToLower();&lt;br /&gt; if (String.Equals(response.ContentType, "text/html"))&lt;br /&gt; {&lt;br /&gt;  response.Filter = new EmailStreamFilter(response.Filter, response.ContentEncoding);&lt;br /&gt; }&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;As you see, we check mime type of response. It isn&amp;rsquo;t good idea to replace some strings in images, documents or other files non-text files. We want to modify only html. If you want, you can add another conditions, for example if you have some private part of your website (i.e. admin subweb) where e-mail protecting is not necessary, or even unwanted, you can check url of request and pass only wanted parts of website. Inside condition, you see unknown class &lt;code&gt;EmailStreamFilter&lt;/code&gt;. That is our next step &amp;ndash; create this stream filter.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class EmailStreamFilter : Stream&lt;br /&gt;{&lt;br /&gt; Stream stream;&lt;br /&gt; &lt;br /&gt; public EmailStreamFilter(Stream sourceStream, Encoding sourceencoding)&lt;br /&gt; {&lt;br /&gt;  stream = sourceStream;&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; public override void Write(byte[] buffer, int offset, int count)&lt;br /&gt; {&lt;br /&gt;  stream.Write(buffer, offset, count);&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; public override int Read(byte[] buffer, int offset, int count)&lt;br /&gt; {&lt;br /&gt;  return stream.Read(buffer, offset, count);&lt;br /&gt; }&lt;br /&gt; public override bool CanRead&lt;br /&gt; {&lt;br /&gt;  get { return stream.CanRead; }&lt;br /&gt; }&lt;br /&gt; public override bool CanSeek&lt;br /&gt; {&lt;br /&gt;  get { return stream.CanSeek; }&lt;br /&gt; }&lt;br /&gt; public override bool CanWrite&lt;br /&gt; {&lt;br /&gt;  get { return stream.CanWrite; }&lt;br /&gt; }&lt;br /&gt; public override void Flush() { }&lt;br /&gt; public override long Length&lt;br /&gt; {&lt;br /&gt;  get { return stream.Length; }&lt;br /&gt; }&lt;br /&gt; public override long Position&lt;br /&gt; {&lt;br /&gt;  get { return stream.Position; }&lt;br /&gt;  set { }&lt;br /&gt; }&lt;br /&gt; public override long Seek(long offset, SeekOrigin origin)&lt;br /&gt; {&lt;br /&gt;  return 0;&lt;br /&gt; }&lt;br /&gt; public override void SetLength(long value) { }&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;As you see, Stream Filter is based on &lt;code&gt;Stream&lt;/code&gt; object, and it must contain implementation of it&amp;rsquo;s base abstract methods and properties. Maybe it looks little complicated, but we won&amp;rsquo;t work with all of this members. All we need is only to declare some new members and modify constructor and &lt;code&gt;Write&lt;/code&gt; method, as you see bellow.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class EmailStreamFilter : Stream&lt;br /&gt;{&lt;br /&gt; Stream stream;&lt;br /&gt; Encoding encoding;&lt;br /&gt; string html;&lt;br /&gt; &lt;br /&gt; public EmailStreamFilter(Stream sourceStream, Encoding sourceencoding)&lt;br /&gt; {&lt;br /&gt;  stream = sourceStream;&lt;br /&gt;  encoding = sourceencoding;&lt;br /&gt;  html = "";&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; public override void Write(byte[] buffer, int offset, int count)&lt;br /&gt; {&lt;br /&gt;  html += encoding.GetString(buffer, offset, count);&lt;br /&gt; &lt;br /&gt;  if (html.IndexOf("&amp;lt;/html&amp;gt;") &amp;gt; 0)&lt;br /&gt;  {&lt;br /&gt;   //secure e-mails&lt;br /&gt;   byte[] data = encoding.GetBytes(html);&lt;br /&gt;   stream.Write(data, 0, data.Length);&lt;br /&gt;  }&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; #region implementation of abstract members of base Stream object&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;As you see in &lt;code&gt;Write&lt;/code&gt; method, we simply collect response data as long as we find end of html represented by &lt;code&gt;&amp;lt;/html&amp;gt;&lt;/code&gt; tag. This is weak part of this solution, but problem is we don&amp;rsquo;t now size of response data of current page. Valid html is really necessary.&lt;/p&gt;
&lt;p&gt;Our &lt;code&gt;EmailStreamFilter&lt;/code&gt; is almost complete now. Only we need is replace comment &lt;code&gt;//secure e-mails&lt;/code&gt; with some code which will do it :) First we need is some method to find e-mail inside html. You can use, for example, following regular expression:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;\b(\w[\w\.-]+?@(?:[\w-]+\.)+[\w]{2,4})\b&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;It&amp;rsquo;s easy, and what is more important, it&amp;rsquo;s fast. Imagine very very large page &amp;ndash; you really don&amp;rsquo;t need some complex expression used in for example in validators, you need combination of reliability but also great speed . Now, what shall we do with captured e-mails? We can simply replace dots and at-signs with their text representation (dot) and (at). After it, all of our e-mails on our page are secured. There are not any e-mails, there are only text representations which can be understood by humans, but not by spambots. If it&amp;rsquo;s not enough, you can use any other replacement, for example &lt;em&gt;mail &amp;ndash; here is at &amp;ndash; domain &amp;ndash; here is dot &amp;ndash; com&lt;/em&gt;. Or &amp;ndash; you can use images or links to special page with CAPTCHA code. There are many ways to fight with spambots (almost as many, as they know to fight with us).&lt;/p&gt;
&lt;p&gt;In this example, we use first method and simple replace dots and at-sign with their text representation.&lt;/p&gt;
&lt;p&gt;But because it&amp;rsquo;s not so comfortable to rewrite this encoded e-mails to real e-mails, we also use javascript to replace text representation of our secured e-mails back to original e-mails. Spambots, as far I now, don&amp;rsquo;t execute javascript. And why they should? There are many unprotected sites on the Internet and it&amp;rsquo;s easier to harvest e-mails from them, than lost time with programming script executing spambot.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;script type="text/javascript"&amp;gt;var body = document.getElementsByTagName('body')[0]; body.innerHTML = body.innerHTML.replace(/\(dot\)/gm, '.').replace(/\(at\)/gm, '@');&amp;lt;/script&amp;gt;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;This small script replace all of our secured e-mail addresses to their original format. But only for those clients with enabled javascript, which is now majority of human users. We replace this only in &lt;code&gt;body&lt;/code&gt; of html but if you want, you can replace also in &lt;code&gt;head,&lt;/code&gt; or you can link external more sophisticated script. You have many possibilities again. Now let&amp;rsquo;s look to our completed &lt;code&gt;EmailStreamFilter&lt;/code&gt;.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class EmailStreamFilter : Stream&lt;br /&gt;{&lt;br /&gt; Stream stream;&lt;br /&gt; Encoding encoding;&lt;br /&gt; string html;&lt;br /&gt;  &lt;br /&gt; bool isEmailFound = false;&lt;br /&gt; static Regex _regEmail = new Regex(@"\b(\w[\w\.-]+?@(?:[\w-]+\.)+[\w]{2,4})\b", RegexOptions.Compiled);&lt;br /&gt; &lt;br /&gt; public EmailStreamFilter(Stream sourceStream, Encoding sourceencoding)&lt;br /&gt; {&lt;br /&gt;  stream = sourceStream;&lt;br /&gt;  encoding = sourceencoding;&lt;br /&gt;  html = "";&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; public override void Write(byte[] buffer, int offset, int count)&lt;br /&gt; {&lt;br /&gt;  html += encoding.GetString(buffer, offset, count);&lt;br /&gt; &lt;br /&gt;  if (html.IndexOf("&amp;lt;/html&amp;gt;") &amp;gt; 0)&lt;br /&gt;  {&lt;br /&gt;   MatchEvaluator emailEvaluator = new MatchEvaluator(EmailEvaluator);&lt;br /&gt;   html = _regEmail.Replace(html, emailEvaluator);&lt;br /&gt;   if (isEmailFound) html = html.Insert(html.IndexOf("&amp;lt;/body&amp;gt;"), @"&amp;lt;script type=""text/javascript""&amp;gt;var body = document.getElementsByTagName('body')[0]; body.innerHTML = body.innerHTML.replace(/\(dot\)/gm, '.').replace(/\(at\)/gm, '@');&amp;lt;/script&amp;gt;");&lt;br /&gt;    &lt;br /&gt;   byte[] data = encoding.GetBytes(html);&lt;br /&gt;   stream.Write(data, 0, data.Length);&lt;br /&gt;  }&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; private string EmailEvaluator(Match m)&lt;br /&gt; {&lt;br /&gt;  isEmailFound = true;&lt;br /&gt;  string noScriptEmail = m.Groups[1].Value.Replace("@", "(at)").Replace(".", "(dot)");&lt;br /&gt;  return noScriptEmail;&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; #region implementation of abstract members of base Stream object&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;And that&amp;rsquo;s almost all. Last step is registering your new HTTP Module inside appropriate section of your web.config and work is done.&lt;/p&gt;
&lt;p&gt;At the end, before comments :), I have one small icing on the cake. Maybe protecting e-mails is not enough, maybe you want to create links from e-mails not inside &amp;lt;&lt;code&gt;a&amp;gt;&lt;/code&gt; tag. In that case, only you need is find right regular expression. For example this one:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;\b(?![^&amp;lt;]*&amp;gt;)(?!.*&amp;lt;/head&amp;gt;)(\w[\w\.-]+?@(?:[\w-]+\.)+[\w]{2,4})\b(?![^&amp;lt;]*(&amp;lt;[^a][^&amp;lt;]*)*&amp;lt;/a&amp;gt;)&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;This ugly string above is regular expression, which find e-mails not inside &lt;code&gt;head&lt;/code&gt;, not inside tag attribute and not inside &amp;lt;&lt;code&gt;a&amp;gt;&lt;/code&gt; tag (and of course abbr, and other tags beginning with a &amp;ndash; yes it&amp;rsquo;s not perfect, but it may be sufficient for your purposes). All you need then is inserting these two lines of code into right place, and work is done.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;static Regex _regNoLinkEmail = new Regex(@"\b(?![^&amp;lt;]*&amp;gt;)(?!.*&amp;lt;/head&amp;gt;)(\w[\w\.-]+?@(?:[\w-]+\.)+[\w]{2,4})\b(?![^&amp;lt;]*(&amp;lt;[^a][^&amp;lt;]*)*&amp;lt;/a&amp;gt;)", RegexOptions.Compiled);&lt;br /&gt;html = _regNoLinkEmail.Replace(html, "&amp;lt;a href=\"mailto:$1\"&amp;gt;$1&amp;lt;/a&amp;gt;");&lt;/pre&gt;
&lt;p&gt;Enjoy it.&lt;/p&gt;</description><pubDate>Tue, 08 Feb 2011 12:55:19 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/email-protection-on-your-site</guid></item><item><title>Optimizing size of public websites based on Sharepoint</title><link>http://www.baud.cz:80/blog/optimizing-size-of-public-websites-based-on-sharepoint</link><description>&lt;p&gt;By M&amp;iacute;&amp;scaron;a H&amp;aacute;jkov&amp;aacute;&lt;/p&gt;
&lt;p&gt;Sharepoint is generally very good platform for intranet applications. But you can meet more and more public web applications based on Sharepoint. Despite my humble opinion, that Sharepoint really isn&amp;rsquo;t the best choice for this purpose, some of our customers web presentations are based on it.&lt;/p&gt;
&lt;p&gt;The biggest problem, I was faced, is many many&amp;hellip;. really many parts I don&amp;rsquo;t need. Default master page in Publishing site contains lot of controls and referenced files, which are useful in intranet, and some of them are also useful for editing content, but visitors of your site really don&amp;acute;t need them &amp;ndash; they don&amp;acute;t edit pages, don&amp;acute;t approve them, they only browse pages.&lt;/p&gt;
&lt;p&gt;Here is image taken from Firebug showing the overall amount of data visitor&amp;rsquo;s browser download from our site before it was optimized:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.baud.cz/Media/Windows-Live-Writer/5bf2dcc42e4e_C6D6/net-before_2.gif"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="net-before" src="http://www.baud.cz/Media/Windows-Live-Writer/5bf2dcc42e4e_C6D6/net-before_thumb.gif" border="0" alt="Firebug data - before" width="640" height="347" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you see, user download almost 700 KB of data. And most of them are Sharepoint data which are useless on read-only sites.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;core.js &amp;ndash; good for editing and administrating site, but visitors doesn&amp;rsquo;t need it; &lt;/li&gt;
&lt;li&gt;core.css &amp;ndash; our website use it&amp;rsquo;s own stylesheet, we don&amp;acute;t need another 80 KB which is not used anywhere; &lt;/li&gt;
&lt;li&gt;init.js &amp;ndash; our read only site doesn&amp;rsquo;t need it, why visitors must download it?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I check some of sites presented on &lt;a title="http://www.topsharepoint.com" href="http://www.topsharepoint.com"&gt;http://www.topsharepoint.com&lt;/a&gt; and few of them are optimized and relatively small, but most of them has really terrible overall size of landing page and all referenced files. Average is about 1 MB, but there are some 3 MB or 4 MB! Yes, most of these files are stored in cache after first load, but problem is mentioned first load. Many users has only limited bandwidth (mobile connection is more and more common). They probably don&amp;rsquo;t wait five minutes for loading landing page, they close browser&amp;rsquo;s tab and find another (probably faster) page.&lt;/p&gt;
&lt;p&gt;If your website is based on Sharpeoint, don&amp;rsquo;t be sad, here is solution of this pain.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Important information: This solution works and is tested in MOSS 2007&lt;/strong&gt;, but similar technics can be used in other versions.&lt;/p&gt;
&lt;p&gt;First of all, I recommended&amp;nbsp; you to use minimal master page (&lt;a title="http://msdn.microsoft.com/en-us/library/aa660698(v=office.12).aspx" href="http://msdn.microsoft.com/en-us/library/aa660698(v=office.12).aspx"&gt;http://msdn.microsoft.com/en-us/library/aa660698(v=office.12).aspx&lt;/a&gt;), similar minimal master page exists also for MOSS 2010. It&amp;rsquo;s first step to wipe out Sharepoint things, you don&amp;rsquo;t need in Publishing web.&lt;/p&gt;
&lt;p&gt;In next step, you must modify &lt;code&gt;Render&lt;/code&gt; method of your master page. It can be done in &lt;code&gt;&amp;lt;script runat=&amp;rdquo;server&amp;rdquo;&amp;gt;&lt;/code&gt; block or in code behind file referenced in &lt;code&gt;&amp;lt;%@ Master %&amp;gt;&lt;/code&gt; directive.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;protected override void Render(HtmlTextWriter writer)
{
	string html = string.Empty;
	using (StringWriter sw = new StringWriter())
	{
		using (HtmlTextWriter tw = new HtmlTextWriter(sw))
		{
			base.Render(tw);
			html = sw.ToString();
		}
	}

	// Do something with html

	writer.Write(html);
}&lt;/pre&gt;
&lt;p&gt;As you see, you can take html right before it&amp;rsquo;s send to client. And what&amp;rsquo;s better, you can modify it. And that&amp;rsquo;s right what we need. We use regular expressions to find and remove references to scripts and style sheets, we don&amp;rsquo;t need, and also remove Sharepoint hidden fields and script blocks:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;protected override void Render(HtmlTextWriter writer)
{
	string html = string.Empty;
	using (StringWriter sw = new StringWriter())
	{
		using (HtmlTextWriter tw = new HtmlTextWriter(sw))
		{
			base.Render(tw);
			html = sw.ToString();
		}
	}
	if (_isPublicWeb)
	{
		// removing of all hidden MSO... and __SPCEditMenu fields for page editing
		html = Regex.Replace(html, @"&amp;lt;input type=""hidden"" name=""(MSO|__SPSCEditMenu).*?/&amp;gt;\s*", String.Empty);
		// removing of MOSS client scripts for page editing
		html = Regex.Replace(html, @"&amp;lt;script&amp;gt; var MSOWebPartPageFormName.*?&amp;lt;/script&amp;gt;\s*", "");
		html = Regex.Replace(html, @"&amp;lt;script[^&amp;gt;]*src=""/_layouts/1029/.*?&amp;gt;&amp;lt;/script&amp;gt;\s*", "");
		html = Regex.Replace(html, @"&amp;lt;script type=""text/javascript""&amp;gt;\s*//&amp;lt;\!\[CDATA\[\s*var __wpmExportWarning=.*\s*&amp;lt;/script&amp;gt;\s*", "");
		// removing of MOSS body and form scripts
		html = html.Replace(@"&amp;lt;body onload=""javascript:_spBodyOnLoadWrapper();""&amp;gt;", "&amp;lt;body&amp;gt;");
		html = Regex.Replace(html, @"(&amp;lt;form.*?)onsubmit="".*?""(.*?&amp;gt;)", "$1$2");
		// removing references to MOSS styles
		html = Regex.Replace(html, @"&amp;lt;link rel=""stylesheet"".*?href=""/_layouts/1029.*?/&amp;gt;", "");
		// removing of (not html valid) ms-action table
		html = Regex.Replace(html, @"&amp;lt;!-- Begin Action Menu Markup --&amp;gt;(.|\s)*?&amp;lt;!-- End Action Menu Markup --&amp;gt;", "");

		// if we don't use WebResource.axd, we can remove it
		html = Regex.Replace(html, @"&amp;lt;script[^&amp;gt;]?src=""/WebResource.axd.*?&amp;gt;&amp;lt;/script&amp;gt;\s*", "");
	}
	writer.Write(html);
}&lt;/pre&gt;
&lt;p&gt;Variable &lt;code&gt;_isPublicWeb&lt;/code&gt; contains information, whether this site is public (read only) or not. We assign it with value stored in web.config, but you can choose different approach (for example check rights).&lt;/p&gt;
&lt;p&gt;After these steps our site look much better:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.baud.cz/Media/Windows-Live-Writer/5bf2dcc42e4e_C6D6/net-after_2.gif"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="net-after" src="http://www.baud.cz/Media/Windows-Live-Writer/5bf2dcc42e4e_C6D6/net-after_thumb.gif" border="0" alt="net-after" width="640" height="248" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now, overall amount of downloaded data is only 113 KB and after optimization of our stylesheet it can be plus minus 100 KB, which is acceptable for site visitors and also for site creators :) Difference between site before optimization and after it is half of megabyte.&lt;/p&gt;
&lt;p&gt;At the end, you can improve your &lt;code&gt;Render&lt;/code&gt; to lower size of your aspx files:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;html = Regex.Replace(html, @"[ \t]{2,}", " "); // all tab sequences are replaced with space
html = Regex.Replace(html, @"(\r\n(\s*)){2,}", "\r\n"); // removing all of empty rows
if (IsPublicWeb) ...&lt;/pre&gt;
&lt;p&gt;This method is also useful for validating HTML (if you need it), or other activities, if you need modify Sharepoint pages before sending them to client . If you are not sure if you can remove some fields or references, don&amp;rsquo;t afraid. You can try it row by row, or create own regular expression.&lt;/p&gt;
&lt;p&gt;And that&amp;rsquo;s all. I hope this article can help someone :)&lt;/p&gt;</description><pubDate>Fri, 04 Feb 2011 18:10:59 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/optimizing-size-of-public-websites-based-on-sharepoint</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 10</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-10</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will add a busy indicator.&lt;/p&gt;
&lt;p&gt;As you know, communication with server takes some time. Even in our small project loading might take several seconds so it would be a good idea to notify the user that something is happening in background.&lt;/p&gt;
&lt;p&gt;So, open your solution from &lt;a href="http://baud.cz/blog/coproject-ria-caliburnmicro-demo-part-0"&gt;part 9&lt;/a&gt; or grab source codes from &lt;a href="http://coproject.codeplex.com/"&gt;Coproject site&lt;/a&gt; and let&amp;rsquo;s start.&lt;/p&gt;
&lt;h2&gt;BusyIndicator&lt;/h2&gt;
&lt;p&gt;First of all, add a BusyIndicator control to ToDoListsView. So, add this namespace using:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" &lt;/pre&gt;
&lt;p&gt;and paste this control to the end of LayoutRoot (below ActiveItem and Toolbar):&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;toolkit:BusyIndicator IsBusy="{Binding IsBusy}"  Grid.RowSpan="2" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;Then we must implement the IsBusy property on ToDoListsViewModel.&lt;/p&gt;
&lt;h2&gt;IsBusy property&lt;/h2&gt;
&lt;p&gt;The easiest way to implement busy indication would be to add IsBusy property to ToDoListsViewModel:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;private bool _isBusy;
public bool IsBusy
{
	get
	{
		return this._isBusy;
	}
	set
	{
		this._isBusy = value;
		NotifyOfPropertyChange(() =&amp;gt; IsBusy);
	}
}&lt;/pre&gt;
&lt;p&gt;Then, we just set it to true at the beginning of LoadData function and to false at the end. Try it, it should work well.&lt;/p&gt;
&lt;p&gt;Note: if the loading is too fast so you cannot see the BusyIndicator, open CoprojectService and add Thread.Sleep(1000); above &amp;lsquo;return&amp;rsquo; statement to the proper GetXXX function (GetToDoListsWithItems to be exact).&lt;/p&gt;
&lt;h2&gt;BusyWatcher&lt;/h2&gt;
&lt;p&gt;Although this approach works, you can see problems if more than one loading is done at a time:&lt;/p&gt;
&lt;p&gt;- the first action starts and sets IsBusy to true&lt;br /&gt;- the other action starts and sets IsBusy to true&lt;br /&gt;- the first action completes and sets IsBusy to false&lt;br /&gt;- the other action is still running but IsBusy is already set to false&lt;/p&gt;
&lt;p&gt;So, it would be a good idea to have something like BusyWatcher &amp;ndash; a class that has a hidden counter inside, actions just increment or decrement it as they start or finish, and IsBusy property returns whether the counter is greater than 0 or not. One of possible implementations is as follows. Put it into Framework/BusyWatcher.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class BusyWatcher : PropertyChangedBase
{
	int _counter;

	public bool IsBusy
	{
		get
		{
			return _counter &amp;gt; 0;
		}
	}

	public void AddWatch()
	{
		if (Interlocked.Increment(ref _counter) == 1)
		{
			NotifyOfPropertyChange(() =&amp;gt; IsBusy);
		}
	}

	public void RemoveWatch()
	{
		if (Interlocked.Decrement(ref _counter) == 0)
		{
			NotifyOfPropertyChange(() =&amp;gt; IsBusy);
		}
	}
}&lt;/pre&gt;
&lt;p&gt;Next, extract interface IBusyWatcher from it (IsBusy, AddWatch, RemoveWatch) and make BusyWatcher export this interface:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public interface IBusyWatcher
{
	bool IsBusy { get; }

	void AddWatch();
	void RemoveWatch();
}&lt;/pre&gt;
&lt;pre class="prettyprint"&gt;[Export(typeof(IBusyWatcher))]
public class BusyWatcher : PropertyChangedBase, IBusyWatcher
...&lt;/pre&gt;
&lt;p&gt;Now, let&amp;rsquo;s use this watcher in our view model. Replace the IsBusy property in ToDoListsViewModel with the following:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Import(RequiredCreationPolicy = CreationPolicy.NonShared)]
public IBusyWatcher Busy { get; set; }&lt;/pre&gt;
&lt;p&gt;And setting of IsBusy in LoadData change to their respective equivalents of Busy.AddWatch/RemoveWatch.&lt;/p&gt;
&lt;p&gt;Finally change binding of BusyIndicator int ToDoListsView to:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;toolkit:BusyIndicator IsBusy="{Binding Busy.IsBusy}"  Grid.RowSpan="2" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;OK, this looks much better but what if an exception occurs between AddWatch and RemoWatch calls? BusyWatcher would stay in as busy forever. Of course, we could wrap actions with a try block and put RemoveWatch into a finally statement.&lt;/p&gt;
&lt;h2&gt;BusyTicket&lt;/h2&gt;
&lt;p&gt;Another way is to make use of &amp;lsquo;using&amp;rsquo; statement. The trick is that we create a disposable ticket for the using statement. And when the ticket gets disposed of, it will RemoweWatch.&lt;/p&gt;
&lt;p&gt;Add this class into BusyWatcher:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class BusyWatcherTicket : IDisposable
{
	IBusyWatcher _parent;

	public BusyWatcherTicket(IBusyWatcher parent)
	{
		_parent = parent;
		_parent.AddWatch();
	}

	public void Dispose()
	{
		_parent.RemoveWatch();
	}
}&lt;/pre&gt;
&lt;p&gt;Also add this function into BusyWatcher and put its definition into IBusyWatcher too:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public BusyWatcherTicket GetTicket()
{
	return new BusyWatcherTicket(this);
}&lt;/pre&gt;
&lt;p&gt;Now, we can use it as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IEnumerable&amp;lt;IResult&amp;gt; LoadData(string filter)
{
	using (Busy.GetTicket())
	{
		CoprojectContext context = new CoprojectContext();

		...&lt;/pre&gt;
&lt;pre class="prettyprint"&gt;		Lists = result.Result.Entities;
		NotifyOfPropertyChange(() =&amp;gt; Lists);
	}
}&lt;/pre&gt;
&lt;p&gt;Note that in this scenario, you have separate BusyWatcher for every screen (i.e., separate BusyIndicator for every view). But if you, for example, wanted to have one BusyIndicator for the whole application (e.g., in a status bar), we could use a shared BusyWatcher for all view models and add a BusyIndicator into ShellView and bind it to this BusyWatcher. No big deal.&lt;/p&gt;</description><pubDate>Wed, 26 Jan 2011 09:29:22 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-10</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 6</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-6</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will load data from database and start using Caliburn.Micro coroutines. Remember that you can get latest news and source code from &lt;a href="http://coproject.codeplex.com/"&gt;Coproject Codeplex site&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;ToDoListsView&lt;/h2&gt;
&lt;p&gt;Create a new Silverlight User Control called ToDoListsView in the Views folder. Then replace the original LayoutRoot grid with this one:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;Grid x:Name="LayoutRoot"&amp;gt;
	&amp;lt;Grid.ColumnDefinitions&amp;gt;
		&amp;lt;ColumnDefinition Width="6*" /&amp;gt;
		&amp;lt;ColumnDefinition Width="5*" /&amp;gt;
	&amp;lt;/Grid.ColumnDefinitions&amp;gt;
	&amp;lt;Grid.RowDefinitions&amp;gt;
		&amp;lt;RowDefinition Height="auto" /&amp;gt;
		&amp;lt;RowDefinition Height="*" /&amp;gt;
	&amp;lt;/Grid.RowDefinitions&amp;gt;

	&amp;lt;Button x:Name="LoadData" Content="Load" /&amp;gt;

	&amp;lt;ItemsControl x:Name="Lists" Grid.Row="1"&amp;gt;
		&amp;lt;ItemsControl.ItemTemplate&amp;gt;
			&amp;lt;DataTemplate&amp;gt;
				&amp;lt;StackPanel&amp;gt;
					&amp;lt;TextBlock Text="{Binding Name}" FontWeight="Bold" 
								Style="{StaticResource DefaultTextBlockStyle}" /&amp;gt;
					&amp;lt;TextBlock Text="{Binding Description}" TextWrapping="Wrap" 
								Style="{StaticResource DefaultTextBlockStyle}" /&amp;gt;
				&amp;lt;/StackPanel&amp;gt;
			&amp;lt;/DataTemplate&amp;gt;
		&amp;lt;/ItemsControl.ItemTemplate&amp;gt;
	&amp;lt;/ItemsControl&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;
&lt;p&gt;As we already know, Caliburn.Micro will automatically bind Lists ItemsControl to &amp;lsquo;Lists&amp;rsquo; property of respective view model. Therefore, you can guess that pressing LoadData button will execute function called LoadData, and you would be right. So let&amp;rsquo;s implement the view model.&lt;/p&gt;
&lt;h2&gt;ToDoListsViewModel&lt;/h2&gt;
&lt;p&gt;Open ToDoListsViewModel and add this code to it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IEnumerable&amp;lt;ToDoList&amp;gt; Lists { get; private set; }&lt;/pre&gt;
&lt;pre class="prettyprint"&gt;public void LoadData()
{
	CoprojectContext context = new CoprojectContext();
	EntityQuery&amp;lt;ToDoList&amp;gt; query = context.GetToDoListsQuery().OrderByDescending(l =&amp;gt; l.CreatedDate);
	context.Load(query, LoadDataCallback, null);
}

private void LoadDataCallback(LoadOperation&amp;lt;ToDoList&amp;gt; data)
{
	Lists = data.Entities;
	NotifyOfPropertyChange(() =&amp;gt; Lists);
}&lt;/pre&gt;
&lt;p&gt;&lt;span style="font-family: 'Courier New';"&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;In Silverlight, all data loading is done asynchronously. It is good for keeping user interface responsive but programming asynchronous tasks requires more coding than working synchronously. To load data from a RIA Services service, you need to instantiate a context (created on compile time by RIA services), get default query from it, modify the query and then pass it back to the context to load it. You should also provide a callback that gets called when the data are loaded.&lt;/p&gt;
&lt;p&gt;If you build the project and click Load, after a while, data should appear.&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/678a4276c2c4_CEC1/image_2.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="/Media/Windows-Live-Writer/678a4276c2c4_CEC1/image_thumb.png" border="0" alt="image" width="244" height="176" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Coroutines&lt;/h2&gt;
&lt;p&gt;You probably noticed that if we wanted to do some other work after data are loaded, we would have to put it into LoadDataCallback. And if we wanted to load some other data, another callback would have to be created. This could easily become a a nightmare to maintain and debug. Happily, Caliburn.Micro comes to help with &lt;a href="http://devlicio.us/blogs/rob_eisenberg/archive/2010/08/21/caliburn-micro-soup-to-nuts-part-5-iresult-and-coroutines.aspx"&gt;coroutines&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Caliburn coroutines are based on objects that implement IResult interface. Purpose of these objects is to execute some action and fire an event when the action is done. C.M then sequentially enumerates results returned from methods like LoadData, executes a result, waits for it to complete and then execute next one. This is achieved by yield return C# keyword. You probably see similarity to &lt;a href="http://www.abhisheksur.com/2010/10/c-50-asynchronous-made-easy.html"&gt;new keywords&lt;/a&gt; &amp;lsquo;async&amp;rsquo; and &amp;lsquo;await&amp;rsquo; planned for C# 5.&lt;/p&gt;
&lt;h3&gt;LoadDataResult&lt;/h3&gt;
&lt;p&gt;So, let&amp;rsquo;s implement result that would load data from a RIA Services context. Create LoadDataResult in Framework as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class LoadDataResult&amp;lt;TEntity&amp;gt; : IResult where TEntity : Entity
{
	public EntityQuery&amp;lt;TEntity&amp;gt; Query { get; set; }
	public DomainContext Context { get; set; }
	public LoadOperation&amp;lt;TEntity&amp;gt; Result { get; private set; }

	public event EventHandler&amp;lt;ResultCompletionEventArgs&amp;gt; Completed;

	public LoadDataResult(DomainContext context, EntityQuery&amp;lt;TEntity&amp;gt; query)
	{
		Query = query;
		Context = context;
	}

	public void Execute(ActionExecutionContext context)
	{
		Context.Load(Query, LoadDataCallback, null);
	}

	private void LoadDataCallback(LoadOperation&amp;lt;TEntity&amp;gt; data)
	{
		Result = data;
		OnCompleted();
	}

	private void OnCompleted()
	{
		var handler = Completed;
		if (handler != null)
		{
			handler(this, new ResultCompletionEventArgs());
		}
	}
}&lt;/pre&gt;
&lt;p&gt;Although it might seem complicated, most of the code is just initialization and obvious definitions. The only functions worth attention are Exxecute and LoadDataCallback and these are the same as in the LoadData function. When this result is passed to C.M, it will run Execute and then wait until Completed event is raised. Then it will enumerate next result and so on.&lt;/p&gt;
&lt;p&gt;We can replace LoadData and LodDataCallback in ToDoListsViewModel with this function:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IEnumerable&amp;lt;IResult&amp;gt; LoadData()
{
	CoprojectContext context = new CoprojectContext();
	EntityQuery&amp;lt;ToDoList&amp;gt; query = context.GetToDoListsQuery().OrderByDescending(l =&amp;gt; l.CreatedDate);
	var result = new LoadDataResult&amp;lt;ToDoList&amp;gt;(context, query);
	yield return result;

	Lists = result.Result.Entities;
	NotifyOfPropertyChange(() =&amp;gt; Lists);
}&lt;/pre&gt;
&lt;p&gt;Now, although LoadDataResult loads data asynchronously, execution of this function will stop at yield return and continue once the result completes. Workflow of LoadData function is obvious now and can be easily edited later.&lt;/p&gt;
&lt;h2&gt;Include ToDoItems&lt;/h2&gt;
&lt;p&gt;We still need to add ToDoItems under their parent ToDoLists. First, we must tell RIA Services to include ToDoItems with lists. Open Services/CoprojectService.cs in Coproject.Web project and this function below GetToDoLists function:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IQueryable&amp;lt;ToDoList&amp;gt; GetToDoListsWithItems()
{
	return this.ObjectContext.ToDoLists.Include("ToDoItems");
}&lt;/pre&gt;
&lt;p&gt;ObjectContext is an Entity Framework context, so we instruct EF to include nested ToDoItems when querying underlying database. If these properties are set, RIA Services will automatically include these into metadata transferred to the client ([Include] attribute on respective properties in CoprojectService.metadata.cs that we added in &lt;a href="http://baud.cz/blog/coproject-ria-caliburnmicro-demo-part-2"&gt;Step 2&lt;/a&gt;). Now rebuild the solution in order to have RIA Services recreate context on the client.&lt;/p&gt;
&lt;p&gt;Next, point query creation in ToDoListsViewModel.LoadData from context.GetToDoListsQuery to context.GetToDoListsWithItemsQuery.&lt;/p&gt;
&lt;p&gt;Finally, edit ToDoListsView and add the following control below the two TextBlocks in ItemTemplate of the &amp;lsquo;Lists&amp;rsquo; control:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;ListBox ItemsSource="{Binding ToDoItems}"
				Margin="5,0,0,0" ScrollViewer.HorizontalScrollBarVisibility="Disabled"&amp;gt;
	&amp;lt;ListBox.ItemTemplate&amp;gt;
		&amp;lt;DataTemplate&amp;gt;
			&amp;lt;StackPanel Orientation="Horizontal"&amp;gt;
				&amp;lt;TextBlock Text="{Binding DueDate,StringFormat='\{0:d\}'}" 
						   FontWeight="Bold" Margin="0,0,5,0" /&amp;gt;
				&amp;lt;TextBlock Text="{Binding Content}" /&amp;gt;
			&amp;lt;/StackPanel&amp;gt;
		&amp;lt;/DataTemplate&amp;gt;
	&amp;lt;/ListBox.ItemTemplate&amp;gt;
&amp;lt;/ListBox&amp;gt;&lt;/pre&gt;
&lt;p&gt;Now you can run the application. The list will probably run off the screen, so let&amp;rsquo;s wrap Lists control with ScrollViewer:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;ScrollViewer Grid.Row="1" Style="{StaticResource ListsScrollViewerStyle}"&amp;gt;
	&amp;lt;ItemsControl x:Name="Lists"&amp;gt;
		...
	&amp;lt;/ItemsControl&amp;gt;
&amp;lt;/ScrollViewer&amp;gt;&lt;/pre&gt;
&lt;p&gt;That is all for this step. The application should look like that:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/678a4276c2c4_CEC1/image_4.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/678a4276c2c4_CEC1/image_thumb_1.png" border="0" alt="image" width="244" height="176" /&gt;&lt;/a&gt;&lt;/p&gt;</description><pubDate>Mon, 24 Jan 2011 14:14:34 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-6</guid></item><item><title>The first official release of T4RIA</title><link>http://www.baud.cz:80/blog/the-first-official-release-of-t4ria</link><description>&lt;p&gt;by Petr Ho&amp;scaron;ek&lt;/p&gt;
&lt;p&gt;During the&amp;nbsp;&lt;a href="http://baud.cz/blog/prezentace-rapidni-vyvoj-ria-aplikaci-pomoci-net-technologii"&gt;Rapid RIA development using .NET&lt;/a&gt; presentation, we have presented our own T4 template for WCF RIA Service called T4RIA. T4RIA is a T4 template that generates domain services, metadata and localization for WCF RIA Services from ADO.NET Entity Data Model.&lt;/p&gt;
&lt;p&gt;We have promised to release T4RIA under open-source license. Today, I would like to announce the &lt;a href="http://riaservicescontrib.codeplex.com/releases/view/59261"&gt;first official release&lt;/a&gt;&amp;nbsp;which is part of&lt;a href="http://riaservicescontrib.codeplex.com/"&gt; WCF RIA Contrib&lt;/a&gt; project. This project&amp;nbsp;is a collection of tools for WCF RIA Services and therefore presents a perfect home for T4RIA.&lt;/p&gt;
&lt;h2&gt;Usage&lt;/h2&gt;
&lt;p&gt;T4RIA supports &lt;a href="http://go.microsoft.com/fwlink/?LinkID=177508"&gt;WCF RIA Services 1.0&lt;/a&gt;, ADO.NET Entity Framework 4.0 and requires &lt;a href="http://t4toolbox.codeplex.com/releases/view/41443"&gt;T4 Toolbox&lt;/a&gt; for its run.&lt;/p&gt;
&lt;p&gt;To use it, simply &lt;a href="http://riaservicescontrib.codeplex.com/releases/view/59261"&gt;download&lt;/a&gt;&amp;nbsp;the official zip file and copy both T4RIA.tt and T4RIA.settings.t4 to the root of your WCF RIA Services web application. You might need to customize the settings in T4RIA.settings.t4 to fit your environment and conventions. Then, by running T4RIA.tt (simply save the file or use &lt;a href="http://chirpy.codeplex.com/"&gt;Chirpy&lt;/a&gt;&amp;nbsp;extension), you will generate all the necessary files.&lt;/p&gt;
&lt;p&gt;The code in generated files can then be customized to fit your needs e.g. add additional domain service operations, add additional model metadata, localize your model.&lt;/p&gt;
&lt;h2&gt;Resources&lt;/h2&gt;
&lt;p&gt;To find out more about T4RIA, please visit the &lt;a href="http://riaservicescontrib.codeplex.com/wikipage?title=T4RIA"&gt;official page&lt;/a&gt;. To ask questions or make suggestions regarding improvements and new functionality, please use the&amp;nbsp;&lt;a href="http://riaservicescontrib.codeplex.com/discussions"&gt;official&amp;nbsp;discussion&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Developers wishing to help are welcomed to join the effort. Source code can be obtained on &lt;a href="http://riaservicescontrib.codeplex.com/SourceControl/changeset/changes/56219"&gt;CodePlex&lt;/a&gt;. For&amp;nbsp;T4 templates&amp;nbsp;development support in Visual Studio 2010, I recommend&amp;nbsp;&lt;a href="http://www.visualt4.com/"&gt;Visual T4&lt;/a&gt; editor from Clarius. To learn more about T4 as well as T4 Toolbox, its usage and advanced techniques, read &lt;a href="http://www.olegsych.com/tag/t4/"&gt;Oleg Sych's blog&lt;/a&gt;&amp;nbsp;which contains many useful information.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description><pubDate>Sun, 23 Jan 2011 19:54:34 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/the-first-official-release-of-t4ria</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 8</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-8</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will create ToDoItem detail.&lt;/p&gt;
&lt;h2&gt;Context lifetime&lt;/h2&gt;
&lt;p&gt;The main question when considering lists and details is whether to share context among all screens or create a new context per screen. Both ways have their pros and cons and you will probably have to choose depending on the situation. But most likely, you will use both of them depending on the scope of entities.&lt;/p&gt;
&lt;h3&gt;Shared context&lt;/h3&gt;
&lt;p&gt;In this case, you would probably create a service in the application and all screens would access it to get and save data. It is useful when some entities are used across the whole application.&lt;/p&gt;
&lt;p&gt;+ You can pass entities across application&lt;br /&gt;+ No need to synchronize data when an entity gets updated &amp;ndash; all parts of the application use the same entity.&lt;br /&gt;+ Lower memory consumption if entities are shared across application.&lt;br /&gt;+ Centralized data access.&lt;br /&gt;- Entities stay in memory until detached or context disposed. So if you use a shared context to load hundreds of entites (e.g, in a grid) and do not detach them, memory consumption will be a problem.&lt;br /&gt;- Even unsaved state of entities affect other parts of application (sharing the same entity).&lt;br /&gt;- Harder saving. If you save whole context, you might save currently edited entities of other screens.&lt;br /&gt;- Harder to maintain, especially with current &lt;a href="http://baud.cz/blog/memory-leak-in-silvelright-with-inotifydataerrorinfo"&gt;memory leaks&lt;/a&gt; in Silverlight.&lt;/p&gt;
&lt;h2&gt;Context per screen&lt;/h2&gt;
&lt;p&gt;Every screen creates its own context and loads and saves data on its own. This is probably better for scenarios with editing detail screens and large lists/grids.&lt;/p&gt;
&lt;p&gt;+ Easier to see consequences of changing entity properties.&lt;br /&gt;+ Memory management. You can easily dispose of context (and thus all entities it loaded).&lt;br /&gt;+ Easier saving. If you save context, you don&amp;rsquo;t save currently edited entities of other screens.&lt;br /&gt;- Need to pass IDs across application and every screen must load the entity itself.&lt;br /&gt;- Duplicate entities might exist in the application.&lt;br /&gt;- Need to synchronize changes throughout application when entity is updated.&lt;br /&gt;- Possible concurrency errors while saving.&lt;/p&gt;
&lt;h2&gt;ToDoItemViewModel&lt;/h2&gt;
&lt;p&gt;In Coproject, we will use Context per screen for ToDoItem entity. So, let&amp;rsquo;s start. I hope you have done all the steps described so far. If you haven&amp;rsquo;t, just download source code from &lt;a href="http://coproject.codeplex.com/"&gt;Coproject Codeplex site&lt;/a&gt;. Note that source codes are branched for every tutorial part so you can start in any stage.&lt;/p&gt;
&lt;p&gt;First of all, we should create an interface for ToDoItem detail. So, create interface ViewModels.Interfaces.IToDoItemEditor:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public interface IToDoItemEditor
{
	ToDoItem Item { get; }
	IEnumerable&amp;lt;IResult&amp;gt; Setup(int toDoItemID);
}&lt;/pre&gt;
&lt;p&gt;Then, add ToDoItemViewModel to ViewModels:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Export(typeof(IToDoItemEditor))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ToDoItemViewModel : Screen, IToDoItemEditor
{
	public ToDoItem Item { get; private set; }

	private CoprojectContext _context;

	public IEnumerable&amp;lt;IResult&amp;gt; Setup(int toDoItemID)
	{
			_context = new CoprojectContext();

			var dataResult = new LoadDataResult&amp;lt;ToDoItem&amp;gt;(
				_context,
				_context.GetToDoItemsQuery().Where(x =&amp;gt; x.ToDoItemID == toDoItemID));
			yield return dataResult;

			Item = dataResult.Result.Entities.First();
			NotifyOfPropertyChange(() =&amp;gt; Item);
	}
}&lt;/pre&gt;
&lt;p&gt;As you can see, the detail screen expects ToDoItemID and loads the proper entity itself. We want to store the context because we will use it for saving. Since there will be single instance of view model for every ToDoItem detail opened, we need it to be of a NonShared creation policy.&lt;/p&gt;
&lt;p&gt;Now, let&amp;rsquo;s add the logic that will open the detail screen. There are ListBoxes in DataTeplates for every ToDoList in ToDoListsView so we could probably use the same trick as for modules to track the selected item, but as there are more ListBoxes, sharing SelectedItem would lead at least to a binding error.&amp;nbsp; Moreover, I want to show how to use custom binding to events.&lt;/p&gt;
&lt;p&gt;Firstly, open ToDoListsViewModel and change its base class from Screen to&lt;/p&gt;
&lt;pre class="prettyprint"&gt;Conductor&amp;lt;IToDoItemEditor&amp;gt;.Collection.OneActive&lt;/pre&gt;
&lt;p&gt;and add the following function to it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IEnumerable&amp;lt;IResult&amp;gt; OpenItemDetail(ToDoItem item)
{
	var editor = Items.FirstOrDefault(x =&amp;gt; x.Item.ToDoItemID == item.ToDoItemID);
	if (editor == null)
	{
		editor = IoC.Get&amp;lt;IToDoItemEditor&amp;gt;();
		yield return editor.Setup(item.ToDoItemID).ToSequential();
	}

	ActivateItem(editor);
	yield break;
}&lt;/pre&gt;
&lt;p&gt;Finally, we need to execute this function in appropriate time. Open ToDoListsView and add new xmlns definition to the top of the file:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;xmlns:cal="http://www.caliburnproject.org"&lt;/pre&gt;
&lt;p&gt;Now, we want to attach the OpenItemDetail function to the SelectionChanged event of the ListBox bound to ToDoItems. It the most fluent way, it would be done like this:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;ListBox ItemsSource="{Binding ToDoItems}" 
			cal:Message.Attach="[Event SelectionChanged] = [Action OpenItemDetail($this.SelectedItem)]" ...&lt;/pre&gt;
&lt;p&gt;But since SelectionChanged is the default event of ListBox, Action is the default behavior and SelectedItem is the default property of ListBox for binding, we can use this shortcut with the same result:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;ListBox ItemsSource="{Binding ToDoItems}" cal:Message.Attach="OpenItemDetail($this)"&lt;/pre&gt;
&lt;p&gt;Note the argument $this. This is a special C.M argument name. Other special words are $datacontext and $eventargs. Their meaning is exactly what you would expect from their names. You can read more about C.M actions &lt;a href="http://devlicio.us/blogs/rob_eisenberg/archive/2010/07/17/caliburn-micro-soup-to-nuts-pt-3-all-about-actions.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;We also must add a place for the detail to be displayed in. So add this control below the ScrollViewer containing the Lists ItemsControl:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;ContentControl x:Name="ActiveItem" Grid.Column="1" Grid.Row="1" Margin="10,0,0,0" 
				HorizontalContentAlignment="Stretch" /&amp;gt;&lt;/pre&gt;
&lt;h2&gt;ToDoItemView&lt;/h2&gt;
&lt;p&gt;Next, we have to create the respective view. So add a new &lt;em&gt;Silvelright User Control&lt;/em&gt; named ToDoItemView to Views. Add these two namespaces to it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;xmlns:dataForm="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"
xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"&lt;/pre&gt;
&lt;p&gt;Then add this DataForm to LayoutGrid:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;dataForm:DataForm CurrentItem="{Binding Item}" HorizontalAlignment="Stretch"&amp;gt;
	&amp;lt;StackPanel&amp;gt;
		&amp;lt;dataForm:DataField PropertyPath="DueDate"&amp;gt;
			&amp;lt;controls:DatePicker SelectedDate="{Binding DueDate,Mode=TwoWay}" /&amp;gt;
		&amp;lt;/dataForm:DataField&amp;gt;
		&amp;lt;dataForm:DataField PropertyPath="Content"&amp;gt;
			&amp;lt;TextBox Text="{Binding Content,Mode=TwoWay}" TextWrapping="Wrap" Height="auto" /&amp;gt;
		&amp;lt;/dataForm:DataField&amp;gt;
		&amp;lt;dataForm:DataField PropertyPath="User"&amp;gt;
			&amp;lt;TextBlock Text="{Binding User.LastName}" /&amp;gt;
		&amp;lt;/dataForm:DataField&amp;gt;
	&amp;lt;/StackPanel&amp;gt;
&amp;lt;/dataForm:DataForm&amp;gt;&lt;/pre&gt;
&lt;p&gt;If you run the application, you will see this:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/03bac6b09b47_12C0E/image_4.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/03bac6b09b47_12C0E/image_thumb_1.png" border="0" alt="image" width="244" height="179" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;DataFields automatically added labels to proper places. You should note that there are no DataForm buttons. The reason is that in Assets/Custom.xaml, we have a default style that disables it. DataForm is still kind of a buggy control so I want to use as little of its features as possible.&lt;/p&gt;
&lt;p&gt;Let me mention four DataForm bugs we could encounter in Coproject:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Even though Commit and Cancel buttons are disabled, they sometimes appear when changing edit mode.&lt;/li&gt;
&lt;li&gt;When switching between DataForms, it sometimes hide the first label in it (DueDate).&lt;/li&gt;
&lt;li&gt;When setting ReadOnly mode after editing a TextBox inside the DataForm, controls inside the DataForm are still enabled.&lt;/li&gt;
&lt;li&gt;Switching to edit mode with BusyIndicator on the same page causes the indicator to constantly use 100% CPU.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;All of them, except for the second can be avoided / fixed.&lt;/p&gt;
&lt;p&gt;You probably noticed that &lt;em&gt;User&lt;/em&gt; is still empty. The cause is that this nested entity is not included in ToDoItem. So open Services/CoProjectService.cs in the server project, find GetToDoItems() and edit it as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;return this.ObjectContext.ToDoItems.Include("User");&lt;/pre&gt;
&lt;p&gt;Build and run the application. Detail should be complete:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/03bac6b09b47_12C0E/image_6.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/03bac6b09b47_12C0E/image_thumb_2.png" border="0" alt="image" width="244" height="179" /&gt;&lt;/a&gt;&lt;/p&gt;</description><pubDate>Thu, 20 Jan 2011 08:28:20 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-8</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 7</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-7</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will add filtering to ToDo list and create several useful extension methods.&lt;/p&gt;
&lt;h2&gt;Extension methods&lt;/h2&gt;
&lt;p&gt;In the client project root, create a new static class called Extensions and put following functions into it:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public static bool IsNullOrWhiteSpace(this string value)
{
	return string.IsNullOrWhiteSpace(value);
}

public static string FormatWith(this string formatString, params object[] args)
{
	return string.Format(formatString, args);
}

public static IResult ToSequential(this IEnumerable&amp;lt;IResult&amp;gt; results)
{
	return new SequentialResult(results.GetEnumerator());
}&lt;/pre&gt;
&lt;p&gt;The last function is interesting. What it does is that it wraps a collection of IResults (remember coroutines from the &lt;a href="http://baud.cz/blog/coproject-ria-caliburnmicro-demo-part-6"&gt;last part&lt;/a&gt;?) into one result. This is particularly useful when you want to yield return a collection of results, maybe other coroutine function.&lt;/p&gt;
&lt;h2&gt;Filtering&lt;/h2&gt;
&lt;p&gt;To add filtering capabilities to our ToDoListView, we must add a textbox to it. In order to make look Coproject look nice, add some more styling, so replace LoadData button from the view with the following:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;Border Style="{StaticResource FilterPanelStyle}"&amp;gt;
	&amp;lt;Grid&amp;gt;
		&amp;lt;Grid.ColumnDefinitions&amp;gt;
			&amp;lt;ColumnDefinition Width="*" /&amp;gt;
			&amp;lt;ColumnDefinition Width="auto" /&amp;gt;
		&amp;lt;/Grid.ColumnDefinitions&amp;gt;

		&amp;lt;TextBox x:Name="Filter" Style="{StaticResource FilterTextBoxStyle}" /&amp;gt;
		&amp;lt;Button x:Name="LoadData" Grid.Column="1" Content="Search" /&amp;gt;
	&amp;lt;/Grid&amp;gt;
&amp;lt;/Border&amp;gt;&lt;/pre&gt;
&lt;p&gt;In fact, we just added a TextBox called Filter. Now, we have to make use of it. Update LoadData function in ToDoListsViewModel:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public IEnumerable&amp;lt;IResult&amp;gt; LoadData(string filter)
{
	CoprojectContext context = new CoprojectContext();
	EntityQuery&amp;lt;ToDoList&amp;gt; query = context.GetToDoListsWithItemsQuery().OrderByDescending(l =&amp;gt; l.CreatedDate);

	if (!filter.IsNullOrWhiteSpace())
	{
		query = query.Where(x =&amp;gt; x.Name.Contains(filter));
	}

	var result = new LoadDataResult&amp;lt;ToDoList&amp;gt;(context, query);
	yield return result;

	Lists = result.Result.Entities;
	NotifyOfPropertyChange(() =&amp;gt; Lists);
}&lt;/pre&gt;
&lt;p&gt;As you can see, we only added parameter and filter query according to the parameter. Btw: this filter is transferred via RIA services and Entity Framework to database server and executed there (so the SQL statement is &lt;em&gt;where Name like &amp;lsquo;%anyText%&amp;rsquo;&lt;/em&gt;). Using this way of filtering, you can easily chain multiple filter criteria. You probably won&amp;rsquo;t be surprised that the filter parameter is set by Caliburn.Micro according to the content of the TextBox called Filter.&lt;/p&gt;
&lt;p&gt;Depending on database configuration, the comparison might be case sensitive or in-sensitive. If it is case sensitive, you will need to change the criteria to:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;query = query.Where(x =&amp;gt; x.Name.ToLower().Contains(filter.ToLower()));&lt;/pre&gt;
&lt;p&gt;That is all for this part about filtering.&lt;/p&gt;</description><pubDate>Mon, 17 Jan 2011 17:17:03 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-7</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 4</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-4</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will dig a little bit into &lt;a href="http://caliburnmicro.codeplex.com/"&gt;Caliburn.Micro&lt;/a&gt; and create application modules.&lt;/p&gt;
&lt;p&gt;Note: some information are intentionally simplified to make the whole concept easier to understand. Once you master it, go ahead and read more &lt;a href="http://devlicio.us/blogs/rob_eisenberg/archive/tags/Caliburn/default.aspx"&gt;detailed articles&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Screens&lt;/h2&gt;
&lt;p&gt;As I indicated in the &lt;a href="http://baud.cz/blog/coproject-ria-caliburnmicro-demo-part-3"&gt;last part&lt;/a&gt;, we will describe Coproject structure and hierarchy of application screens via ViewModels. And then, we will let C.M to take care of wiring it to views and showing it to the user. You will see that this approach helps keep the solution clean and easy to manage.&lt;/p&gt;
&lt;p&gt;For this purpose, Caliburn.Micro has several useful classes already prepared.&lt;/p&gt;
&lt;h3&gt;Screen&lt;/h3&gt;
&lt;p&gt;Screen is a simple base class for all ViewModels. Not that it already implements INotifyPropertysChanged, it also contains virtual functions that you can use in scenario of nested ViewModels:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;OnInitialize
OnActivate
OnDeactivate
TryClose&lt;/pre&gt;
&lt;h3&gt;Conductor&lt;/h3&gt;
&lt;p&gt;Conductors are basically screens with other nested screens. Therefore, their additional functions are like:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;ActivateItem
DeactivateItem
GetChildren&lt;/pre&gt;
&lt;h3&gt;Conductor.Collection.OneActive&lt;/h3&gt;
&lt;p&gt;To save you as much time as possible, there is an even more specific base class for you to use. It contains property Items and helps you to manage collection of nested viewmodels.&lt;/p&gt;
&lt;p&gt;In Coproject, we will this third base class as Shell contains a collection od Modules and, for example, ToDoLists module will contain a collection of opened ToDoItem details.&lt;/p&gt;
&lt;p&gt;As I don&amp;rsquo;t want to duplicate this &lt;a href="http://devlicio.us/blogs/rob_eisenberg/archive/2010/10/08/caliburn-micro-soup-to-nuts-part-6a-screens-conductors-and-composition.aspx"&gt;great article&lt;/a&gt;, you should read it if you want to get more information about screens in C.M.&lt;/p&gt;
&lt;h2&gt;Modules&lt;/h2&gt;
&lt;p&gt;Ok, let&amp;rsquo;s use all the screens and conductors and write some code!&lt;/p&gt;
&lt;p&gt;First of all, we should create interface for modules (as seen &lt;a href="http://baud.cz/blog/coproject-ria-caliburnmicro-demo-part-1"&gt;there&lt;/a&gt; &amp;ndash; Home, Messages, To do, and Milestones will be modules of Coproject). Create interface ViewModels.Interfaces.IModule as follows:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;namespace Coproject.ViewModels.Interfaces
{
	public interface IModule
	{
		string Description { get; }
	}
}&lt;/pre&gt;
&lt;p&gt;Then, under ViewModels, create HomeViewModel:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Export(typeof(IModule))]
public class HomeViewModel : Screen, IModule
{
	public string Description { get; private set; }

	public HomeViewModel()
	{
		DisplayName = "Home";
		Description = "Project overview &amp;amp; activity"; 
	}
}&lt;/pre&gt;
&lt;p&gt;As you can see, no magic here. We just set some text properties and notifies MEF that this is a module. The DisplayName property is already implemented in Screen.&lt;/p&gt;
&lt;p&gt;Do the same for other modules (don't forget to export):&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Class name] - [DisplayName] - [Description]
MessagesViewModel - Messages - All messages
ToDoListsViewModel - To Do - To-do lists
MilestonesViewModel - Milestones - string.Format("Milestones (today is {0:D})", DateTime.Today)&lt;/pre&gt;
&lt;p&gt;If you&amp;rsquo;ve done it right, your &lt;em&gt;Solution Explorer&lt;/em&gt; should look like this:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_2.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image" src="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_thumb.png" border="0" alt="image" width="244" height="212" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Next, we need to import those exported modules into the shell.&lt;/p&gt;
&lt;p&gt;Change ShellViewModel&amp;rsquo;s base class from Screen to&lt;/p&gt;
&lt;pre class="prettyprint"&gt;public class ShellViewModel : Conductor&amp;lt;IModule&amp;gt;.Collection.OneActive, IShell&lt;/pre&gt;
&lt;p&gt;And add this constructor:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[ImportingConstructor]
public ShellViewModel([ImportMany]IEnumerable&amp;lt;IModule&amp;gt; modules)
{
	Items.AddRange(modules);
}&lt;/pre&gt;
&lt;p&gt;That is all we need to do to make MEF import all IModule implementations it has into our shell.&lt;/p&gt;
&lt;p&gt;Put a breakpoint into the constructor and run debugging to see that it works. Note that we didn&amp;rsquo;t listed or even mentioned modules anywhere in the application. So if you want to add a new module, just create ViewModel and let it export IModule. That&amp;rsquo;s all! You can read more about importing in MEF &lt;a href="http://blogs.microsoft.co.il/blogs/bnaya/archive/2010/01/02/mef-for-beginner-part-5-import.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Tips for Silverlight debugging&lt;/h2&gt;
&lt;p&gt;Sometimes people have difficulties to debug Silverlight applications. Let me give you a hint to make it easy. The key thing is to understand that there are two applications (processes) you might want to debug &amp;ndash; server and client. If you typically hit F5 sometimes only server gets debugged. That&amp;rsquo;s why I do it another way:&lt;/p&gt;
&lt;p&gt;1. At the beginning, &lt;em&gt;Start Without Debugging&lt;/em&gt;:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_4.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_thumb_1.png" border="0" alt="image" width="244" height="63" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This will run the server and open the client in your default browser. Because of easier finding of the right process, I close the browser and open client URL in Internet Explorer, since I don&amp;rsquo;t use it for other tasks (you will see in a minute). You don&amp;rsquo;t have to start it again as long as the ASP.NET Development Server is running.&lt;/p&gt;
&lt;p&gt;2. Then, before you want to debug your application, you just need to build the solution (in larger applications, rebuilding of the affected project should be enough).&lt;/p&gt;
&lt;p&gt;3. &lt;em&gt;Attach to Process&lt;/em&gt; (or press CTRL+ALT+P)&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_6.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_thumb_2.png" border="0" alt="image" width="244" height="71" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;4. If you want to debug server, attach to process called WebDev.WebServer40.EXE (press keys w,e,b and the listbox will find it for you):&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_8.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_thumb_3.png" border="0" alt="image" width="244" height="166" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If you want to debug client, attach to process of your browser (make sure to choose the process of &lt;em&gt;Type&lt;/em&gt; Silverlight!). In my case, it is iexplore.exe:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_10.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_thumb_4.png" border="0" alt="image" width="244" height="166" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So, if you want to debug your client app opened in the only Internet Explorer instance running, press: CTRL+ALT+P, i, e, ENTER. Just don&amp;rsquo;t forget to build the solution and refresh your browser (so that the latest version of client gets loaded).&lt;/p&gt;
&lt;h2&gt;Show menu&lt;/h2&gt;
&lt;p&gt;So, modules are loaded into shell but nothing is shown in the application &amp;ndash; we have to update ShellView to show nested modules.&lt;/p&gt;
&lt;p&gt;Open ShellView.xaml and add the following ListBox just below the TextBlock with text &amp;lsquo;Coproject&amp;rsquo;:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;ListBox x:Name="Items" Style="{StaticResource NavigationMenuStyle}"&amp;gt;
	&amp;lt;ListBox.ItemTemplate&amp;gt;
		&amp;lt;DataTemplate&amp;gt;
			&amp;lt;TextBlock Text="{Binding DisplayName}" /&amp;gt;
		&amp;lt;/DataTemplate&amp;gt;
	&amp;lt;/ListBox.ItemTemplate&amp;gt;
	&amp;lt;ListBox.ItemsPanel&amp;gt;
		&amp;lt;ItemsPanelTemplate&amp;gt;
			&amp;lt;StackPanel Orientation="Horizontal" /&amp;gt;
		&amp;lt;/ItemsPanelTemplate&amp;gt;
	&amp;lt;/ListBox.ItemsPanel&amp;gt;
&amp;lt;/ListBox&amp;gt;&lt;/pre&gt;
&lt;p&gt;Tip: You can press CTRL+K, D to have Visual Studio reformat the code.&lt;/p&gt;
&lt;p&gt;This is just a ListBox that shows DisplayName of some items it is bound to. But if you run the application, you will see that it is already bound to the Items property of ShellViewModel:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_12.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_thumb_5.png" border="0" alt="image" width="244" height="171" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This is caused by convention imposed by Caliburn.Micro &amp;ndash; because the ListBox is called &amp;lsquo;Items&amp;rsquo;, C.M tries to bind its ItemsSource property to property Items of respective ViewModel. And since ShellViewModel is a conductor with collection of child modules, it has one. Of course, you could bind ItemsSource by hand, C.M would not overwrite it.&lt;/p&gt;
&lt;h2&gt;Show module content&lt;/h2&gt;
&lt;p&gt;Below the Items ListBox, add the following controls:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;&amp;lt;TextBlock x:Name="ActiveItem_Description" Style="{StaticResource CurrentPageTitleStyle}" /&amp;gt;
&amp;lt;ContentControl x:Name="ActiveItem" Style="{StaticResource MainContentStyle}" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;As you can guess, the first will show Description of currently selected module, the second one will show its content. But if you run the application, you will see that it works right away.&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_14.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/84d9ff8317ec_98FE/image_thumb_6.png" border="0" alt="image" width="244" height="170" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This is caused by Items ListBox again. There is another convention in C.M &amp;ndash; if a control supports SelectedItem property, C.M will try to add Active, Current, or Selected to its singularized name and check whether there is respective property in ViewModel. And if successful, it will create a TwoWay binding. Conductors in C.M have ActiveItem property.&lt;/p&gt;
&lt;p&gt;This binding over naming conventions has one flaw &amp;ndash; it does not work in design time, co if you want to have some data bound to the controls on design time, you will have to use standard {Binding} syntax.&lt;/p&gt;
&lt;h2&gt;View location&lt;/h2&gt;
&lt;p&gt;If you select a module, you might see 'Coproject,Views.MessagesView not found&amp;rsquo;. It is a C.M error message that it could not locate proper view for your ViewModel. This convention works as that to get View name, it just removes &amp;lsquo;Model&amp;rsquo; from the full name of ViewModel. Of course, you can customize this logic, but it is usually sufficient.&lt;/p&gt;
&lt;p&gt;Although it might not seem like, it is very flexible. You can have a simple structure like we do:&lt;br /&gt;/ViewModels/MessagesViewModel + /Views/MessagesView&lt;/p&gt;
&lt;p&gt;But you can also add structure for modules:&lt;br /&gt;/MessagesModule/ViewModels/ListViewModel + /MessagesModule/Views/ListView&lt;br /&gt;or&lt;br /&gt;/ViewModels/MessagesModule/ListViewModel + /Views/MessagesModule/ListView&lt;/p&gt;
&lt;h2&gt;Get the source&lt;/h2&gt;
&lt;p&gt;You can download Coproject source codes from its &lt;a href="http://coproject.codeplex.com/"&gt;Codeplex site&lt;/a&gt;. Feel free to experiment!&lt;/p&gt;
&lt;p&gt;That is all for this part.&lt;/p&gt;</description><pubDate>Thu, 13 Jan 2011 21:48:32 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-4</guid></item><item><title>Coproject - a RIA Caliburn.Micro demo, part 5</title><link>http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-5</link><description>&lt;p&gt;by Augustin &amp;Scaron;ulc&lt;/p&gt;
&lt;p&gt;In this part, we will add some module metadata. Note that you can get the most recent Coproject source codes from its &lt;a href="http://coproject.codeplex.com/"&gt;Codeplex site&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Metadata&lt;/h2&gt;
&lt;p&gt;As you probably noticed, modules are not loaded into shell in any specified order. And since we don&amp;rsquo;t want the modules be in arbitrary order, we need to add some metadata. You can read more about MEF metadata &lt;a href="http://blogs.microsoft.co.il/blogs/bnaya/archive/2010/01/20/mef-for-beginner-metadata-part-8.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The easiest way is to use ExportMetadataAttribute. We would update HomeViewModel as:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Export(typeof(IModule))]
[ExportMetadata("Order", 10)]
public class HomeViewModel : Screen, IModule&lt;/pre&gt;
&lt;p&gt;and the other ViewModels in the same manner. Next, must update ShellViewModel constructor. Instead of IModule directly, we will request Lazy&amp;lt;IModule, IModuleMetadata&amp;gt; from MEF. This will make MEF to provide lazy reference to requested instance and also metadata of type IModuleMetadata. You might read an introduction to Lazy &lt;a href="http://sankarsan.wordpress.com/2009/10/04/laziness-in-c-4-0-lazyt/"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s create IModuleMetadata in new folder /Framework/:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;namespace Coproject.Framework
{
	public interface IModuleMetadata
	{
		int Order { get; }
	}
}&lt;/pre&gt;
&lt;p&gt;Finally, ShellViewModel&amp;rsquo;s constructor:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[ImportingConstructor]
public ShellViewModel([ImportMany]IEnumerable&amp;lt;Lazy&amp;lt;IModule, IModuleMetadata&amp;gt;&amp;gt; moduleHandles)
{
	var modules = from h in moduleHandles orderby h.Metadata.Order select h.Value;
	Items.AddRange(modules);
}&lt;/pre&gt;
&lt;p&gt;The code should be self-describing. Now, run the application. You may experiment with order numbers and see that the order in application menu changes respectively.&lt;/p&gt;
&lt;h2&gt;Strongly typed metadata&lt;/h2&gt;
&lt;p&gt;Although this solution works, you probably don&amp;rsquo;t like the idea of writing magic strings like &amp;ldquo;Order&amp;rdquo;. So we should make these metadata strongly typed. To do this, add new class ExportModuleAttribute to the Framework folder. Application structure should look like this:&lt;br /&gt;&lt;a href="/Media/Windows-Live-Writer/Coproject---a-RIA-Cali.Micro-demo-part-5_B979/image_6.png"&gt;&lt;img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="/Media/Windows-Live-Writer/Coproject---a-RIA-Cali.Micro-demo-part-5_B979/image_thumb_2.png" border="0" alt="image" width="171" height="244" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Add this implementation of the created class:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public class ExportModuleAttribute : ExportAttribute, IModuleMetadata
{
	public int Order { get; private set; }

	public ExportModuleAttribute(int order)
		: base(typeof(IModule))
	{
		Order = order;
	}
}&lt;/pre&gt;
&lt;p&gt;As you can see, we simply extend the original ExportAttribute to accept order integer. In this case, we can add default export type (IModule). The first attribute [MetadataAttribute] is very important because it tells MEF to also load metadata from ExportModuleAttribute. Finally, we can merge the two attributes on each module viewmodel:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Export(typeof(IModule))]
[ExportMetadata("Order", 10)]&lt;/pre&gt;
&lt;p&gt;into one:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[ExportModule(10)]
public class HomeViewModel : Screen, IModule&lt;/pre&gt;
&lt;p&gt;Do this for all module view models and run the application.&lt;/p&gt;
&lt;h2&gt;PartCreationPolicy&lt;/h2&gt;
&lt;p&gt;Talking about MEF exports, you might wonder what happens when you import a component more than once &amp;ndash; will MEF provide you the same instance or will it create a new one? The answer is: It depends on configuration. You can specify this behavior on the places. Either on export:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[ExportModule(10)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeViewModel : Screen, IModule&lt;/pre&gt;
&lt;p&gt;Or on import:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;[Import(typeof(IShell), RequiredCreationPolicy=CreationPolicy.Shared)]
public IShell Shell { get; set; }&lt;/pre&gt;
&lt;p&gt;CreationPolicy enum has three options:&lt;br /&gt;&lt;strong&gt;Shared&lt;/strong&gt; &amp;ndash; MEF will return always the same instance (singleton pattern)&lt;br /&gt;&lt;strong&gt;NonShared&lt;/strong&gt; &amp;ndash; MEF will always create a new instance&lt;br /&gt;&lt;strong&gt;Any&lt;/strong&gt; &amp;ndash; not specified, depends on the other side of contract (export/import). This is default and if not set to other, this will act as Shared by default.&lt;/p&gt;
&lt;p&gt;You can read more about this topic &lt;a href="http://blogs.microsoft.co.il/blogs/bnaya/archive/2010/01/09/mef-for-beginner-part-creation-policy-part-6.aspx"&gt;here&lt;/a&gt;. I suggest reading whole series &lt;a href="http://blogs.microsoft.co.il/blogs/bnaya/archive/2010/01/09/mef-for-beginner-toc.aspx"&gt;MEF for Beginner&lt;/a&gt;&amp;nbsp;or &lt;a href="http://mef.codeplex.com/wikipage?title=Guide&amp;amp;referringTitle=Documentation"&gt;MEF Programming Guide&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Thu, 13 Jan 2011 21:13:38 GMT</pubDate><guid isPermaLink="true">http://www.baud.cz:80/blog/coproject-ria-caliburnmicro-demo-part-5</guid></item></channel></rss>