IgorShare Thoughts and Ideas

Consulting and Training

Archive for the ‘IOC/DI’ Category

Tip: opening a MessageBox in Caliburn

Posted by Igor Moochnick on 03/27/2011

While working with Caliburn V2 I’ve noticed that there is no default View for the message box. It was a bumpy road figuring out how to add one but I’ve learned a lot.

In this post you can see my solution for this challenge, but the flexibility of the framework allows multiple solutions and you may come up with a different one.

The result of this exercise look like this:

image

In my case I wanted to warn the user during the Screen closure if the changes have not been saved. The usual place to hook the check is in “CanClose” method:

public override void CanClose(Action<bool> callback)
{
    if (HasChanges)
    {
        var result = Show.MessageBox("Current item was not saved. Do you really want to close it?",
            "Question", new[] { Answer.Ok, Answer.Cancel });

        result.Completed += (s, e) => callback(result.Answer == Answer.Ok);

        result.ExecuteWithDefaultServiceLocator();
    }
    else
    {
        callback(true);
    }
}

public static class Extensions
{
    public static void ExecuteWithDefaultServiceLocator(this IResult result)
    {
        result.Execute(new ResultExecutionContext(IoC.Get<IServiceLocator>(), null, null));
    }
}

Notice that the result of the “Completed” callback from the MessageBox is used to raise the callback reply for the “CanClose” method.

When I ran the application I’ve received an error from Caliburn that the “QuestionDialogView” was not found. After checking the source I’ve noticed that the View, in fact, is not there. I had to create one. This is my simplified take on the view:

<UserControl ...>
<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
    	<RowDefinition/>
    	<RowDefinition Height="40"/>
    </Grid.RowDefinitions>
    <ContentControl x:Name="FirstQuestion" Grid.Row="0">
        <ContentControl.ContentTemplate>
            <DataTemplate>
                <TextBlock x:Name="Text" Text="{Binding Text}" TextWrapping="Wrap" Style="{StaticResource DefaultTextBlockStyle}" />
            </DataTemplate>
        </ContentControl.ContentTemplate>
    </ContentControl>            
    <ItemsControl x:Name="Buttons" Grid.Row="1" HorizontalAlignment="Right" Margin="0,10,0,0">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Button Content="{Binding Content, Converter={StaticResource upperCase}}" cal:Message.Attach="{Binding Action}" Width="70" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
		<ItemsControl.ItemsPanel>
			<ItemsPanelTemplate>
				<StackPanel Orientation="Horizontal" />
			</ItemsPanelTemplate>
		</ItemsControl.ItemsPanel>
    </ItemsControl>
</Grid>
</UserControl>

After the view was defined – it had to be registered in the IOC to be found. This is how I did it in the bootstrapper:

            builder.With.PresentationFramework()
                .Using(x => x.ViewLocator<DefaultViewLocator>())
                    .Configured(x => x.AddNamespaceAlias("Caliburn.ShellFramework", "MyProject.Common.Views"))

BTW: in the following article you can find a full View definition for the MessageBox. When I’ve replaced my XAML with the XAML from this article – I’ve received exactly the same result:

http://caliburn.codeplex.com/wikipage?title=ISupportCustomShutdown

Advertisements

Posted in .NET, Caliburn, IOC/DI, MEF, MVVM, Tutorials | Leave a Comment »

Where is my config file if my main module is not inside the executing folder?

Posted by Igor Moochnick on 09/04/2008

Some people ask me: “What if my bootstrapper is loaded by my application from a another (preconfigured) folder and my Prism/Unity config file located in the same (non-executing) folder? How do I load it?”

It’s pretty simple. You need to take your executing assembly as the base and figure out the required path.

var assembly = Assembly.GetExecutingAssembly();
Uri uriPath = new Uri(assembly.CodeBase);
string path = Path.Combine(Path.GetDirectoryName(uriPath.AbsolutePath), "myApp.config" );
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = path  };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

unitySection = (UnityConfigurationSection)configuration.GetSection("unity");

modulesSection = (ModulesConfigurationSection)configuration.GetSection("modules");

Posted in IOC/DI, Prism, Tutorials, Unity | Leave a Comment »

Prism: File-configuration-driven bootstrapper

Posted by Igor Moochnick on 09/04/2008

If you’d like to extract all your application configuration into a config file, this is what you can do:

1. Create a config file. I suggest that you use a different file name than the App.config

2. Override ConfigureContainer method in your bootstrapper

private UnityConfigurationSection unitySection;

private void GetConfigurationSection()
{
    if  (unitySection == null)
    {
        var configMap = new ExeConfigurationFileMap { ExeConfigFilename = "myApp.config" };
        var configuration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

        unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
    }
}

protected override void ConfigureContainer()
{
    base.ConfigureContainer();

    GetConfigurationSection();

    try
    {
        unitySection.Containers["global"].Configure(Container);
    }
    catch (Exception e)
    {
        System.Diagnostics.Trace.WriteLine(e.ToString());
    }
}

3. Point the module enumerator to the same config file via ConfigurationStore

protected override IModuleEnumerator GetModuleEnumerator()
{
    string baseDir = AppDomain.CurrentDomain.BaseDirectory;
    var store = new ConfigurationStore(baseDir);
    return new ConfigurationModuleEnumerator(store);
}

 

All this is fun, but, in case you have more than one config file that contains a Modules section – the ConfigurationStore will stop reading them as soon as it’ll find a first one. It may be the file that you needed in a first place, but, as well, it may be some other file.

Here is a simple workaround:

private UnityConfigurationSection unitySection;
private ModulesConfigurationSection modulesSection;

private void GetConfigurationSections()
{
    if ((unitySection == null) && (modulesSection == null))
    {
        var configMap = new ExeConfigurationFileMap { ExeConfigFilename = "myApp.config" };
        var configuration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

        unitySection = (UnityConfigurationSection)configuration.GetSection("unity");

        modulesSection = (ModulesConfigurationSection)configuration.GetSection("modules");
    }
}

protected override void ConfigureContainer()
{
    base.ConfigureContainer();

    GetConfigurationSections();

    try
    {
        unitySection.Containers["global"].Configure(Container);
    }
    catch (Exception e)
    {
        System.Diagnostics.Trace.WriteLine(e.ToString());
    }
}

protected override IModuleEnumerator GetModuleEnumerator()
{
    GetConfigurationSections();

    return new ConfigurationModuleEnumerator(new MyConfigStore(modulesSection));
}

public class MyConfigStore : ConfigurationStore
{
    public ModulesConfigurationSection Section { get; private set; }

    public MyConfigStore(ModulesConfigurationSection section)
    {
        Section = section;
    }

    public override ModulesConfigurationSection RetrieveModuleConfigurationSection()
    {
        return Section;
    }
}

 

As you can see, by a simple overload of the ConfigurationStore, you can return exactly the modules section that you need. Note that this section is pre-retrieved by the same function that retrieves the “unity” configuration section.

Posted in IOC/DI, Prism, Tutorials, Unity, WPF | Leave a Comment »

Hosted Prism (or how to host Prism in the old projects)

Posted by Igor Moochnick on 09/02/2008

Recently I’m playing a lot with Prism and Unity and was looking for a way to gradually bring Prism to the existing projects. If you have an existing GUI project and you’d like to start using Prism (without rewriting everything from scratch) stay with me – I’m going to show a way that worked for me.

In order to work with Prism you need a “root” window, or, how they call it, a “shell” window. But what if you already have a window? There is a solution to that.

First of all create a WPF user control that will become a “shell” window to Prism. The XAML rules for this control is not different from any other Prism “shell” window. Just the root element of it is a “UserControl” and not “Window”. Let’s call it “ShellContainer”.

Then you need to attach this control to your existing application. But first you need to tell the Bootstrapper about it, but you don’t need to activate it:

   1: protected override DependencyObject CreateShell()
   2: {
   3:     return Container.Resolve<ShellContainer>();
   4: }

If your project is Windows Forms-based, you’ll need to drop on your form an ElementHost control. This control is located on the toolbox in the WPF Interoperability group. This will allow you to host a WPF User control on you non-WPF form.

   1: // Get the ShellContainer from IOC
   2: IUnityContainer container = new UnityContainer();
   3: var shellElement = container.Resolve<myLib.ShellContainer>();
   4:
   5: // Attach the WPF control to the host
   6: hostControl.Child = shellElement;

If you have a WPF form you can add this WPF User Control either manually.

   1: // Get ShellContainer from IOC
   2: IUnityContainer container = new UnityContainer();
   3: var shellElement = container.Resolve<myLib.ShellContainer>();
   4:
   5: // Add the ShellContainer UserControl to the main window
   6: this.mainGrid.Children.Add(shellElement);

From this point on you are on a home run – just follow the rest of the Prism guidelines.

TIP: I found it convenient to put the ShellContainer with the Bootstrapper in the same class library with the rest of the configuration logic. This allows a clean separation of the infrastructure from the rest of the logic of the Prism modules.

Posted in C#, IOC/DI, Prism, Tutorials, WPF | 4 Comments »

Retrieving a ShellContainer from Unity

Posted by Igor Moochnick on 09/01/2008

As I’ve mentioned in my previous post Hosted Prism, that you can add dynamically a Shell Container to your application. This time I’m going to show you how you can configure this container dynamically and have a possibility to replace it at any time without changing your code.

To do so I’m going to use a configuration file. It’s up to you to decide which one. You can use App.config, but I’ll recommend to have a separate file for your IOC, so the customers will not be exposed to a lot of nose and will not change stuff accidentally.

Create a config file (use any name you wish with .config extension – I’ll explain why in a different post).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity>
    <typeAliases>

      <!-- Lifetime manager types -->
      <typeAlias alias="singleton"
           type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
               Microsoft.Practices.Unity" />

      <!-- User-defined type aliases -->
      <typeAlias alias="UIElement" type="System.Windows.UIElement, PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

      <typeAlias alias="Shell" type="OwlHollowLib.ShellContainer, OwlHollowLib" />

    </typeAliases>

    <containers>
      <container name="global">
        <types>
          <type name="Shell" type="UIElement" mapTo="Shell">
	<lifetime type="singleton" />
          </type>
        </types>
      </container>
    </containers>
  </unity>

</configuration>

Note that in the “container[@name=”global”]” I’m associating the “ShellContainer” user control with the type “UIElement” and assigning a “Shell” name for this object. As well I’m marking this object to be a singleton, but this is not necessary if you need more than one ShellContainer in your application.

And this is how you can get a reference to the ShellContainer:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        try
        {
            var configMap = new ExeConfigurationFileMap { ExeConfigFilename = "MyApplication.config" };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

            var section = (UnityConfigurationSection) configuration.GetSection("unity");

            IUnityContainer container = new UnityContainer();
            section.Containers["global"].Configure(container);

            var shellElement = container.Resolve<UIElement>("Shell");

            this.mainGrid.Children.Add(shellElement);
        }
        catch(Exception e)
        {
            System.Diagnostics.Trace.WriteLine(e.ToString());
        }
    }
}

As you can see, you need to initialize UnityContainer from a config file. If you are using a standard App.config file – you don’t need to create an ExeConfigurationMap.

As soon as the UnityContainer is initialized – it’s available for you to start resolving objects and types. The trick in the code above is to resolve your components by their parent types and by an associated name. You can see it in the line #17. This will allow you in the future to replace one UIElement with another without recompiling the application.

Note: DO NOT use the same name (in quotes) as an existing class. The resolution doesn’t work! It looks like the default resolving is conflicted with the resolve-by-name operation.

The technique described above allows you to decouple your modules and create … a loosely coupled but cohesive application.

If you want to take this technique to the extreme and make Unity calls from WPF, you can check the series of posts by Denis Vuyka [Injecting Xaml with Unity Application Block using Markup Extensions].

Stay tuned for more Prism and Unity posts.

Posted in IOC/DI, Prism, Tutorials, WPF | 1 Comment »

CodeCamp #10 [InTENsity] – see you at my presentations

Posted by Igor Moochnick on 08/28/2008

Note: Please forward this information to anyone who is interested.

The next CodeCamp #10 will be held in Waltham, MA on weekend September 20th and 21st.

For more information check Chris Bowen’s post.

Currently there are 33 submitted (and growing number of) presentations.

I’ll be presenting the “Toolbox for Agile Projects and Developers” and will be covering the topics like:

  • Agile Development Practices
  • TDD ( Test Driven Development)
  • Unit Testing
  • Mocking
  • IOC / DI (Inversion of Control / Dependency Injection)
  • ORM (Object Relational Mapping)
  • Code Coverage
  • Source Control
  • etc …

It appears that the amount of information is enormous, so I’ve decided to split these topics into 2 separate presentations.

See you all there …

Posted in Alt.Net, C#, Community, IOC/DI, Mocking, NHibernate, ORM, Presentations, Refactoring, Tutorials, Unit Testing | Leave a Comment »

Toolbox for Agile Projects and Developers @ Hartford, CT

Posted by Igor Moochnick on 08/18/2008

image

It was Hartford’s first CodeCamp. I think it was a great success – way to go, Hartford! More to come!

My presentation had a solid attendance and people stayed until the very end. At the end I’ve ran out of time and haven’t had a time to cover in details the Inversion-of-Control and Dependency Injection tools, but, I think, I’ll prepare a separate talk only on this topic – it’s huge and requires a lot of detailed attention.

 

As I’ve promised, I’m publishing the slide deck as well as all the code iterations for you to have some fun:

 

Iteration Introduced Link
Slide deck link
0 Base solution link
1 Unit testing link
2 Source Control & Continuous Integration (CI) link
3 Mocking, Refactoring link
4 IOC (Inversion-of-Control) & DI (Dependency Injection) link

 

Please feel free to contact me for more information or leave your comments on the blog. I’m available to present this topic or any other portion of it in more details on your site – let me know.

Posted in Alt.Net, C#, Community, IOC/DI, Mocking, Presentations, Refactoring, Thoughts, Tutorials, Unit Testing, Visual Studio | Leave a Comment »

 
%d bloggers like this: