Caliburn.Micro and SimpleContainer

If you don’t want to use a fully fledged IoC container, then you can use the simple one Caliburn.Micro contains. It’s needed to support the Windows Phone development, but works with WPF, which is my interest.  It’s a source release, and you can get from Nuget, as Caliburn.Micro.Container.


Of course, Caliburn.Micro has it’s own direct access to any IoC, like this in a ViewModel ctor:-

public ShellViewModel()
{
windowsmgr = Caliburn.Micro.IoC.Get<IWindowManager>();
}

But it makes testing difficult and this direct use should be avoided.

What SimpleContainer allows you to do is this:-

public ShellViewModel(IEventAggregator events, IWindowManager wm)
{ 
this.events = events;
this.windowsmgr = wm;
}

Where SimpleContainer will inject the EventAggregator and WindowManager automatically, if set up in the Bootstrapper.

I’m attaching two examples, which work with CM 1.4.1, and for VS2012 and Net4.5.
One I wrote myself, and the other was added as a sample within Caliburn.Micro’s discussions, which I’ve updated.

It’s easier for you to read the code in the examples than for me to write any more here.

Have fun!

CM-SimpleContainerDemo.zip (2.81 mb)

CM-SimpleContainer-Sample.zip (2.81 mb)

EventAggregator Comparison Demo

Ever since I started using Caliburn.Micro I was puzzled why the EventAggregator used an interface in the ViewModel signature, like this

public class ShellViewModel : Screen, IShell, IHandle<YourMessageOne>, IHandle<YourMessageTwo>{}

Agreed, the documentation is clear, in that you can Cast to see if the view model supports messaging, and if so automatically subscribe. But is that the only advantage? In the few EventAggregators I describe here it’s the only one using this technique. Anyway, a quick search showed that I was not the only person to wonder if it could be used without IHandle, as Thomas Oosterkamp shows. I created a small demo to test the idea, and decided I’d go a bit further to make a comparison with a few others. In fact, once you start searching there are many implementations of the Publish/Subscribe paradigm. I was also interested in publishing a message which was subscribed to in an independently loaded MEF module.
So attached is my simple demo of six EventAggregators. If your’s is not shown, do say and I’ll include it!

The demo is very basic. Each EventAggregator publishes your message when you press Send, and it is subscribed to in the same ShellViewModel and an MEF loaded module. The MEF module then re-publishes a new message with the same content, which is subscribed to back in the ShellViewModel. By the way, the MEF module is copied into the demo’s bin/Debug folder by a Build Event and so is entirely idependent. If your EventAggregator is shown, do let me know of any idea to enhance the demo to show off the best feature(s) of your implementation!

To be continued…

EventAggregatorDemo.zip (573.36 kb)

AvalonDock v2 and Caliburn Micro

 AvalonDockCaliburnMicro.zip (2.16 mb)

A new version of AvalonDock is due to be released early March. See  http://avalondock.codeplex.com/.
I thought I would attempt to integrate with Caliburn Micro, which should be easier now, as v2 of AvalonDock is MVVM compatible.

To integrate there are two ways that I know of,

(a.) to create a Custom Attached Property or Behaviour as suggested by Felice Pollano, http//www.felicepollano.com/Trackback.aspx?guid=9dcc8717-eb83-45b5-ac89-2f0d0cf05bde

(b.) to create a Custom Convention along the lines that Valeriu Caraulean has done for Telerik controls,
http://blog.caraulean.com/2011/06/05/integration-of-caliburn-micro-and-teleriks-silverlight-controls/

I thought I’d do both. I’ve used the same test program that Valeriu created.

In the attached Zip, I have included both the associated Caliburn.Micro sources and AvalonDock as at 28th Feb, 88810, which is why the Zip might be a bit big. But I hope it means you can compile and test the solution without fishing for other components.

(a.) Works very well. Simple Activate and Deactivate Message Boxes enable you to track how the Conductor OnActive tracks the usage of the tabs.

(b.) Has a bug I can’t find! The Active ViewModel is Deactivated twice when the application closes down.
In certain circumstances, it can cause the app to crash on shutdown. Solution (a.) does not suffer from this.

I hope you find it useful and interesting. Perhaps you can fix the bug!
I’ll attempt to keep this updated as newer versions of AvalonDock are released

Updated 6th March
I've updated AvalonDock to 89121.
Also updated the Zip with an improved version of how Tab Closing is handled in the Caliburn Convention version.
Still has the closedown problem however.

Updated 8th March
I've changed TestBehaviour to hold a collection of ViewModels instead of Views as in the original.
It's brought out the Style and Template for the Header to the Tab View to better handle the closing.
I've made a small change to Screen.cs to prevent the double Deactivate on shutdown of the app.

John

Upgrade to BlogEngine 2.5.0.32 and new Hosting Provider

This time all went very smoothly. Storage of post attachments is built in, and BlogML worked like a dream...
Lets hope the testing goes smoothly too!

File attachments via the new File Manager and SQL tables works, but alas the link into the post does not. So you won't be able to access this file.

 

It does now because I've manually changed the link because urlrewriting is not working.

TestTextFile.txt (65.00 bytes)

TestTextFile.txt (65.00 bytes)

Quick test post after restoring the database

Am I going to be lucky.....
This blog was reporting that the transaction log was full and nothing could be posted. As with anything to do with SQL Server, there is a huge amount of documentation to plough through and Google searches didn't seem to show up a solution quickly. I couldn't even backup the database, as that was what was showing me the error message. So I tried the Import and Export Data tool. This is a great tool just copy to a new database on my local PC, create a new database using my hosting control panel and copy the data back. Then edit the web.config and hay presto it's working again...
Well it will be if you see this post!

Well, it seems that it was, but there were two issues. The second one what that the hosting company had enabled .Net v4, and this resulted in the error message, "A potentially dangerous Request.Form value was detected from the client".  Another quick Google search gave the answer, add the following "<httpRuntime requestValidationMode="2.0" />" to the web.config.

And it turns out there was a third issue. One caused by my copying of the database above. I created a blank database and copied in the data using the Import and Export Data tool. Well, it sort of worked, but there were various SQL errors trying to post to ID fields. So I guessed I should have created the database with the BlogEngine sql script. I did so, but then the Import and Export Data tool wouldn't move the data. To my rescue came EMS's Data Comparison and Synchronisation tool, http://www.sqlmanager.net/en/products/mssql/dbcomparer. I pointed the tool at the two databases and it miraculously did the job.

Phew!

Custom EFDAL generator for nHydrate

nHydrateis a model first ORM code generator on codeplex, and can be used to generate Entity Framework DAL layer. But unlike the designer in Visual Studio it is text based, but this is not a disadvantage as nHydrate offers greater features such as built in row auditing and incremental database management. As any development team knows version 1 of your application is easy, but version 2 is likely to have database schema changes. The incremental database management keeps a track of all SQL used to modify the database so you can migrate the schema changes to your production database with ease.

In the application I’m building the database connection string is only known at runtime, and in trying nHydrate I found the generated code did not support this for the audit system. I needed to make a change to the code generation to allow me to add my runtime connection string.

Also, in this application I want to use CSLA.net for the business layer, and want to use the CSLA code T4csla generatoron codeplex which uses T4 generation from the Entity Framework designer edmx file.  Now nHydrate does not have a edmx file because it does not need one. The EFDAL generator does generate the three csdl, ssdl and msl files, which Entity Framework generates from the edmx file.

So I have added a EFEDMX Generator Item to create this file using the same generators that produce the three files. Once you have edmx file you can right-click on the design surface when the file is open in Visual Studio and using the Add Generation Item to add the CSLA template. At present the cslaextension.tt and the resulting csla class files will be in the wrong class library – they’ll be sharing the same as the EFDAL code. I hope to resolve this later.

The attached Zip is self contained class libraries from 56617 on codeplex, the only changes I’ve made is to the links for the AssembyCommon.cs and the SNK files. Once built copy the EFDAL dll to your normal nHydrate install.

Edit: I didn’t anticipate what would happen to T4Csla’s properties when nHydrate was regenerated. The VSIX from T4Csla adds new properties to the graphic EF designer which are used to for the Csla class generation. Of course, when the edmx file is regenerated the values of those properties is lost. The obvious place for the Csla properties is within the nHydrate model, but that’s a lot of work and ongoing maintenance. I need to think of a better solution!

have fun!

nHydrate-EFGenerator.zip (1.48 mb)

Entity Framework Starter Kit alternative

 

The Entity Framework 4 has superb  features for custom code generation and there are now quite a few different T4 code generators being released. You can see them easily in VS2010 Extension Manager, and include the ADO.NET C# POCO and C# Web Site POCO Entity Generators and the one I particularly like, Rob Hallett’s method of Unit testing Entity Framework classes, see  http://blogofrab.blogspot.com/2010/08/unit-testing-entity-framework-40.html

To start writing your own generator, a Entity Framework Starter Kit is available, as documented here http://code.msdn.microsoft.com/DesignerExtStartKit  and here http://msdn.microsoft.com/en-us/library/ee373851.aspx.  However  I could not get the starter kit to show and assume it’s due to it being written for VS2010 RC and the VSIX is set up for a version of VS2010 I don’t have.

I decided therefore to recreate the starter kit and to enhance it to include a do nothing T4 template.
I’ve based the mode of operation from the VSIX available at http://t4csla.codeplex.com/.  and so thanks to that team as it proved very helpful.

The Zip is the source of the project and is not a project template, so you’ll need to download and compile it. It’s set up to debug in the experimental instance, so you’ll need the VS2010 SDK installed. Once you have VS2010 running add a Class Library project and a Entity Framework blank model.  Add an Entity from the toolbox, click on the design surface and notice the additional property called, “StarterKit design surface property”. Click on the Entity and notice the two Example properties.

Now right click on the design surface and select Add Code Generation Item….  In the Add Item dialogue that opens the StarterKit item template should now show. It will only show on the top Visual C# menu. Select it and it will add StartupExtention.tt to the project and when the model is save the t4 code will run to create a related cs file.

In developing this starter kit, the thing that caught me out was the item template’s VsTemplate must have a filename starting with, ADONETArtifactGenerator.

Hope you find this useful as a basis for your own work.
John

Update 7th May 2013
I have upgraded the VS2010 VSIX to VS2012 and it worked without issue.
Below are the Starter Kits for VS2010 and VS2012 (they will only install on their respective versions)
The VS2012 is already built and you can find the VSIX in the bin/Debug directory.
The third zip is a test program for you to see the added Properties in the Entity Designer.
Have fun!

StarterKitExtensionVS2010.zip (67.90 kb)

StarterKitExtensionVS2012.zip (300.68 kb)

StarterKitTest2ForAfterYouHaveInstalledTheVSIX.zip (2.79 mb)

At the moment the attachment links are broken.
Try getting files from my GitHub repository, https://github.com/jradxl?tab=repositories

 

Customising csproj build scripts

Here’s an item I need to blog about because in a few months I will have forgotten the details.

First, the verbosity of Visual Studio MSBuild messages. Go to Tools > Options > Project and Solutions > Build and Run. Set the build output verbosity to Normal. Would appear that the VS install default is Minimal.

Now you’ve done that, you can edit your csproj file to add some custom targets where you’ll actually see any messages in the output window, for example:-

<Target Name="BeforeBuild">
    <Message Text="My Before Build message..." />
</Target>

Finally, I found this post enhancing the AfterClean target which I thought was most helpful.
http://www.ademiller.com/blogs/tech/2007/12/deep-clean-your-build/

  <Target Name="AfterClean">
    <Message Text="Deep cleaning..." />
    <CreateItem Include="$(OutDir)*.*;$(IntermediateOutputPath)**\*.*">
        <Output TaskParameter="Include" ItemName="Clean_FilesToDelete"/>
    </CreateItem>
    <Delete Files="@(Clean_FilesToDelete)" />
    <RemoveDir Directories="$(OutDir);$(OutDir)..\;$(IntermediateOutputPath);$(IntermediateOutputPath)..\" />
  </Target>

have fun!
John

Caliburn Micro, MEF and multiple modules

I’ve been looking at the Caliburn Micro Framework for a new WPF desktop application I need to write. This app is to replace another I wrote in 2006 using the Composite Application Block. So I was reviewing some of the more recent frameworks such as Prism and discovered both Caliburn and Caliburn Micro on Codeplex.

Caliburn Micro is a very lightweight framework for helping you build MVVM applications by handling all the plumbing between the View and the ViewModel. It does this by requiring you to adopt some naming conventions – the View must be named the same as the ViewModel with the Model removed, then it will bind together any properties it finds on the View and ViewModel that have the same name.

This technique dramatically reduces the amount of code you need to write, and indeed the View’s code behind needs no extra code other than the default.

As you look at the many Caliburn Micro demo programs on Codeplex and the web in general I found they were all single solution. Before committing to using this framework I wanted to be sure I understood the basic concepts in particular how I would work with multiple modules with no hard references, in a standard Prism/MEF fashion. So the obvious question is, without Prism, how can a Module find a the place in the Shell where it should be displayed. If you know Prism it has the concept of Regions and a RegionManager that allows the Shell to specify a name for a Region and a Module to find that named Region all without references between the Module and the Shell. Clearly, MEF will instantiate the Module for you, but it isn’t going to do the binding for you.

I concluded (wrongly as it turns out) that I would have to manually bind the Module’s View and ViewModel into the correct place in the Shell or write a simple Region/RegionManager concept. If fact I did write a simple “control finder” that the Module can use once it imports a reference to the Shell.

Anyway I posted a question on Codeplex  requesting some help on this and to cut a story short, the originator of Caliburn Micro, Rob Eisenberg, kindly stepped in with an example.

The way the example works to bind a Module’s View into a place in the Shell is so simple that it’s worth documenting here.

I assume you know MEF, and so it will be no surprise to you that you can have a property in the ShellViewModel that imports a Module’s ViewModel. In the code fragment below, the interface IView1Model is in a Contracts class and the actual implementation is in a class library called Module1. Module1 has the conventional Post Build copy task to the program’s bin/Debug directory.

//ShellViewModel fragment
[Export(typeof(IShell))]
public class ShellViewModel : Screen, IShell
{
    IView1Model one;

    [Import(typeof(IView1Model), AllowDefault = true)]
    public IView1Model One 
    {
        get { return one; }
        set {
            one = value;
            NotifyOfPropertyChange(() => One);
        }
    }

The import is standard MEF, and AllowDefault = true is needed to ensure the Shell is instantiated by MEF even if the Module cannot be found.

So far so good. Now look at the Xaml fragment of the Shell’s view.

<StackPanel>
    <TextBlock x:Name="Title" TextAlignment="Center" FontWeight="Bold" />
    <GroupBox Height="100">
        <GroupBox.Header>Module1, View1Model here</GroupBox.Header>
        <ContentControl x:Name="One" />
    </GroupBox>

Caliburn Micro will then bind the name of the ContentControl to the ShellViewModel’s One property, which happens to be the Module’s ViewModel and magically the View appears in the Shell.

Now depending on how much of a Prism purist you are, if you are willing for the Shell to use an interface name from the Module, Caliburn Micro will do it for you. But,  if you really want the Shell to be kept clear of any  connection with your Module, you’ll have to use the Region concept from Prism.

Update:
In the discussion on Codeplex, Richard posts a solution using two buttons to load different Modules into a place in the Shell. His solution uses cal:View.Model in the Xaml, which based on Robert’s example is not really necessary as it can be done with only properties. I’ve added that to the solution attached.

Notes:
MEF has now been incorporated into .Net 4 and Silverlight 4 , so the Codeplex site is out of date in only referring to the early development.


MultipleModulesDemo.zip (692.89 kb)

Free Software Project Hosting with Version Control

I’ve decided to try a hosted version control solution for a new private software project, instead of the local file based solution I have presently. My first criterion is that private project hosting is available, and for convenience multiple projects should be possible. Which version control system was not particularly important but likely to be SVN, and of course I use TortoiseSVNon my PC.

Google is of course the first stop in the search for the hosting, and it quickly points you to http://en.wikipedia.org/wiki/Comparison_of_open_source_software_hosting_facilities. I sorted the list to find all identified as offering private space and started looking at each in turn.

My first was to look for Origo, that I had found some months ago but which currently has been removed from the list. This free service provides both open and closed projects, and has many features such as a wiki, forum and blog together with an SVN repository. I found the web site confusing at first, it kept switching between the Origo main site and my project site. It also has ftp upload and a release feature which I can’t see how are supposed to be used. The actual project you request appears to be set up manually, but even on a Saturday evening, was quite quick. You get a number of URLs, http://your-project.origo.ethz.ch, https://svn.origo.ethz.ch/your-project and ftp://upload.origo.ethz.ch/your-project . Whereas the features were good, I decided to look at some others.

I next looked at www.bettercodes.org,  This is an impressive site and you can create multiple project and repositories within your account. For private projects it says that there is a 300MB limit, but you can ask for more. The site is clearly attempting to create a social community in a Facebook like manner but works well. The SVN repository https://svn.bettercodes.org/mytestproject1 took some moments to create as I thought at first it wasn’t working. They have a TortoiseSVN video which I found very helpful in showing the basics.

And finally, I looked again at www.assembla.com.  I did look at software project hosting some months ago and was rather put off by the obvious commercialisation. If you look though it they do offer free, private hosting and out of the three, it is probably the easiest to start with. As you might expect all the extras need you to upgrade, but if you want just SVN it’s fine. However each project’s space is a very reasonable 2GB which should be amble since most of the storage will be source code.

Well there it is a little summary of three software project hosting offerings. Not sure which one I’ll go with yet, but I’ll blog again when I’ve decided and used one for some time.