IgorShare Thoughts and Ideas

Consulting and Training

Archive for March, 2011

Tip: Showing a Main view as a tray app with Caliburn.Micro

Posted by Igor Moochnick on 03/31/2011

The trick here is to make sure that the main view doesn’t pop-up right away in a visible form. After creation and resolving all the binding rules – the main view should be in a Hidden form.

This can easily be achieved with customizing the WindowManager by sub-classing it and adding one extra method:

[Export]
public class CustomWindowManager : WindowManager
{
    public Window MainWindow(object rootModel, object context = null)
    {
        return CreateWindow(rootModel, false, context);
    }
}

As soon as you’ll have the new WindowManager – the logic for the root view creation in the Boostrapper should be adjusted accordingly:

protected override void DisplayRootView()
{
    var viewModel = IoC.Get<IShell>();

    var windowManager = IoC.Get<CustomWindowManager>();

    _mainWindow = windowManager.MainWindow(viewModel);
    _mainWindow.Hide();
}

Here is a simple ShellView that uses a WPF TrayIcon implementation from CodeProject:

<UserControl ...
             xmlns:tb="clr-namespace:Hardcodet.Wpf.TaskbarNotification;assembly=Hardcodet.Wpf.TaskbarNotification"
             xmlns:cal="http://www.caliburnproject.org"
             Visibility="Hidden">
    <Grid>
        <tb:TaskbarIcon
            Visibility="Visible"
            x:Name="MyNotifyIcon"
            IconSource="/Resources/Images/Bulb.ico"
            MenuActivation="LeftOrRightClick" PopupActivation="DoubleClick">
            <!-- Set a simple context menu  -->
            <tb:TaskbarIcon.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Exit" cal:Message.Attach="AppExit" />
                </ContextMenu>
            </tb:TaskbarIcon.ContextMenu>
        </tb:TaskbarIcon>
    </Grid>
</UserControl>

The View Model for this view is very straight forward:

[Export(typeof(IShell))]
public class ShellTrayViewModel : Screen, IShell
{
    public void AppExit()
    {
        Application.Current.Shutdown();
    }
}

That’s it.

Posted in .NET, C#, Caliburn, MVVM, WPF | 5 Comments »

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

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

Installing a second TeamCity build agent on the same server

Posted by Igor Moochnick on 03/27/2011

1. Install a new build agent (uncheck the Windows service) on a different port and a different path.

Ex: ownPort = 9092

2. Change the buildAgent.properties file:

Ex: name=BuildAgent2

3. Add a Windows service for the build agent:

sc create TCBuildAgent2 DisplayName= "TeamCity Build Agent Service2" start= auto binPath= "C:\TeamCity\buildAgent2\launcher\bin\TeamCityAgentService-windows-x86-32.exe -s C:\TeamCity\buildAgent2\launcher\conf\wrapper.conf wrapper.ntservice.account=

If you’ve installed the agent to run under non-System credentials your password will be written in the registry in plain text. Don’t forget to remove it from there.

Posted in Continous Integration, TeamCity | Leave a Comment »

Office Applications via Prism of Unity

Posted by Igor Moochnick on 03/19/2011

This article was submitted to the MSDN magazine for publication 2 years ago. It wasn’t published due to budget cuts in the magazine and my small disagreement with Glen Block on the way I’ve used the bootstrappers. Glen was busy this time with MEF and we didn’t have time to resolve our differences.

So, for what it worth, it’s a great article and helped me and my teams in a lot of ways.

Now you’ll be the judge of that if you’ll keep on reading.

This article discusses:

  • VSTO – Visual Studio Tools for Office system
  • Prism v2 – December 19 drop 8 – Composite Application Guidance for WPF and Silverlight
  • Unity Application Block 1.2 – October 2008 drop
  • WPF
  • Visual Studio 2008 Sp1
  • Introduction

    Adding integration with Office suite was always a sweet fruit that only the daring people were willing to touch. This is mostly due to a different development model that the Office suite demands – you have to specifically target your functionality to work with Office applications and develop it separately from your main application. Office integration is based on COM knowledge. At the beginning, it was hard to wrap your head around the Office COM object model, but, with the release of the VSTO (Microsoft Visual Studio Tools for Office System), it became much easier to develop the integration for the .NET applications. The use of VSTO PIA (Primary Interpol Assemblies) makes it easier but does not change the paradigm very much: it is still necessary to develop separate application components that integrate into the Office suite. Until today, it has been hard to reuse and integrate parts of a primary product with the Office suite. We need a way to create GUI applications that can be easily decomposed into separate parts and components, and re-hosted in different ways and configurations. In other words: we need a way to create composite GUI blocks that can be hosted by Office applications and Windows applications equally.

    Note that the biggest benefits of creating composite applications in general, and for Office suite in particular, are maintainability and testability. Your components can be developed separately from each other by distributed teams and tested outside of the Office applications while maintaining high quality levels of the code. This greatly reduces the complexity of the development process.

    The Office Suite applications are, by nature, composite ones. They consist of a lot of different parts and services that have to intercommunicate and coexist in a common environment. Let us take Outlook as an outstanding example. It consists from many different parts, like folder trees, explorers (folder views), inspectors (item views), ribbons, form regions, configuration tabs, etc. All of those components have to be loaded, initialized and composed in a certain way. And do not forget that, after they are loaded, they have to communicate with each other and change their views and representations in reaction to the changes in the state of their peers.

    Let us see a simplified workflow of what happens when we change an active folder in Outlook to another one:

  • A new folder is selected in a folder tree
  • Toolbar is updated to enable or disable actions that are allowed in the selected folder
  • An active Explorer clears its current items list and populates it with the list of items from the new selected folder
  • A first item in the list is automatically selected, which causes the explorer to:
  • Update the toolbar to reflect actions that can be applied to the selected item
  • Locate an appropriate inspector that knows how to render the selected item and render it in an adjoined pane (to the explorer)
  • Locate the appropriate form regions that are associated with the selected item, create appropriate custom task panes and render them
  • Note how complex the described workflow is, and adding your own functionality into it brings certain challenges.

    Outlook is not alone in this case – all the other applications from the Microsoft Office Suite, in their own different contexts, have similarly complex workflows. All of them have menu bars, ribbons tool bars, panes, regions, etc. This leads us to the question: is there a way to solve these different complexities in a common way? The answer is Yes!

    Recently released Prism (i.e. the Composite Application Guidelines for WPF) is a perfect candidate to untangle such a tight logic knot and help us create simple composite applications that can play nicely with the applications from the Office suite. It describes how we can create composite applications from modular blocks and assemble then however we need. Furthermore, this broadens the horizons of the hosting solutions. This article will take you step by step through the implementation of an application that can be executed equally as a standalone or as a hosted one. We will see how it can be hosted within an Office application as well.

    Read the rest of this entry »

    Posted in Composite Applications, Office API, Prism, Tutorials, Unity, VSTO, WPF | 2 Comments »

    Adding custom credentials to the SVN activity in TFS build workflow

    Posted by Igor Moochnick on 03/14/2011

    Other posts in the series:

    1. Can TFS be useful if the sources are in Subversion (SVN)? Or how to run integration and nightly builds on TFS from SVN?
    2. Teaching TFS custom activity to work with the Svn, Cvs, Git and other source control command line tools

    Obviously you don’t want to expose your password to everyone who can see the build definitions. For this I can suggest 2 separate solutions – the simple one and the right one.

    If you want it quick – implement Password as a string workflow parameter but do not put the value in the build definition (this is visible to everyone) but, in the metadata, set it’s availability to “Always Show the Parameter”. By this you’ll ensure that the password will be available for you to set not only during the build definition but, as well, when anyone will be scheduling it for the execution.

    The better way, as I found out, is to create a custom “credentials” construct (type). This allows you to have your own editor for the password (where you can have it masked) and to control how it appears on the build definition.

    The final result should look like this (notice the “Credentials” parameter):

    image

    Continue reading for the implementation details …

    Read the rest of this entry »

    Posted in Agile, ALM, Source Control, Subversion, Svn, TFS, Tutorials | Leave a Comment »

     
    %d bloggers like this: