Category Archives: Windows Presentation Foundation

Hosting Winforms in Firefox

Standard

 image

I have a strange fascination with hybrids.  Combining old and new technologies in bizarre and interesting ways.   Why must developers make “the choice” between a web or native technology? It would be great to build applications that would increase or decrease in features depending on the platform they were run on.

 

clip_image002

Do you have a Winforms application that you’d like to host in a web browser?  There’s an interesting technique you can use to do this enabled by .net Framework 3.5.

The .net framework provides the ability to create WPF web applications (commonly called XBAP).  WPF has the ability, in turn, to host Winforms. 

Security

It appears that in order to do this effectively, it’s necessary to deploy your XBAP application as a “Full Trust” application.

image

The code

To use this, create an XBAP project, then a page a “WinformHost” control on it.   The XAML could look like this:

<Page x:Class="Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1">
    <DockPanel LastChildFill="True">
        <Button Name="Button1"  DockPanel.Dock="Bottom"  >This is a WPF Button</Button>
        <WindowsFormsHost Name="WinformHost"   />
    </DockPanel>
</Page>

Then, create some code to instantiate your winform and show it on the Winform host:

Class Page1

    Private Sub Page1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        Dim loForm As New HelloWorldWinform

        WinformHost.Child = WinformToUserControl.GetWrapper(loForm)
        loForm.Show()

    End Sub
End Class

Here’s the subroutine:

Public NotInheritable Class WinformToUserControl

    Public Shared Function GetWrapper(ByVal form As System.Windows.Forms.Form) As System.Windows.Forms.Control
        Dim loPanel As New System.Windows.Forms.Panel
        loPanel.Dock = Forms.DockStyle.Fill
        ShowFormInControl(loPanel, form)
        Return loPanel
    End Function

    Private Shared Sub ShowFormInControl(ByVal ctl As System.Windows.Forms.Control, ByVal frm As System.Windows.Forms.Form)

        frm.TopLevel = False
        frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
        frm.AutoScaleMode = Forms.AutoScaleMode.Dpi
        ctl.Controls.Add(frm)

        frm.Dock = Forms.DockStyle.Fill

    End Sub
End Class

   

Interesting bits and pieces

We found that in order for the items inside the control to scale properly, the AutoScaleMode property on the Winform must be set to Dpi instead of the default, which is Font.  I have a feeling this is because Dpi is the mode preferred for WPF, but I am uncertain.

In the sample WinformToUserControl class I found it better to contain the Winform inside a panel rather than exposing the Winform directly.  It seemed to make it more stable.  Feel free to experiment with taking it off.

Gotchas

As of time of writing, Firefox on my Windows 7 64 bit machine steadfastly refuses to run xbap.  It appears the “Windows Presentation Foundation” addin has not been automatically installed.  I have no idea how to install it.  There’ appears to be no information about how to do so.  So if you have it, good for you.  If you don’t….try re-installing the .net framework 3.51 (which didn’t work for me…)

I do know there was some controversy about this addin being temporarily blacklisted by Mozilla due to security concerns last month, but that’s all over now isn’t it?  

 

Download

You can download a sample project here.

image

Links

Sketchflow – “Duplicate” Bug

Standard

 

image

 

The Problem

At the moment I’m trialling Sketchflow for Expression Blend.  There’s an annoying bug that happens when you use the “Duplicate” action on a node:

image

If you use this action, sooner or later you’ll end up with this error:

‘InitializeComponent’ is not a member of ‘xxxxxxxxxx.xxxxxxxxxxxxxx’

This can be very frustrating if you are trying to advocate Sketchflow as a prototyping tool for non wpf savvy analysts.

The Workaround

The simplest workaround is to delete the code-behind file.  To do this, go to the project pane and choose “Delete”.

image

 

At first I tried hard to ensure that the xaml filenames and classnames were correct.  This just causes a cascading comedy of errors.

Upgrading Sketchflow prototype projects to real code is a pipe-dream at the moment.

If you know of a better way of handling this situation (and fixing the errors) more quickly, feel free to comment.  I just want get on with the prototyping.

Silverlight 3 style NavigationContext in WPF

Standard

 image

At the moment I’m experimenting with various user interface technologies.  Because the prototypes are working in parallel, I want to reuse code where possible.  With this in mind, I’ve created a couple of useful wrapper functions for navigation in both Silveright 3 and WPF that I thought I’d share.

 

In case you don’t know the Silverlight 3 Beta now has a navigation framework that works in a similar way to WPF’s Frame navigation feature.   To learn more about it, check our Jeff Poise’s great article Silverlight 3’s New Navigation Framework.

 

I brief, to navigate to a new page and pass a parameters you use a syntax like this in the code behind:

 

Me.NavigationService.Navigate(New Uri(String.Format(“/SomePage.xaml?someparameter={0}”,somevalue), UriKind.Relative))

 

In the loaded event of the page you’re navigating to, you use code like this:

 

Private Sub MyPage_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
     txtSomeTextbox.Text =  Me.NavigationContext.QueryString("someparameter")
End Sub

 

Nicer Navigating

I found the Navigate method above a little awkward, so in Silverlight I created a little helper function called “NavigateTo”, on page that makes the code a bit nicer.

 

Me.NavigateTo(“/SomePage.xaml”,”someparameter”,somevalue)

 

Here’s the implementation:

 

Imports System.ComponentModel
Public Module PageHelper
    <System.Runtime.CompilerServices.Extension()> _
   Public Sub NavigateTo(ByVal page As System.Windows.Controls.Page, ByVal navigationUrl As String, ByVal ParamArray arguments() As String)
        Dim lsUrl As String = navigationUrl & "?"
        Dim lbIsParamName As Boolean = True
        For Each lsArg As String In arguments
            lsUrl &= lsArg
            If lbIsParamName Then lsUrl &= "="
            lbIsParamName = Not lbIsParamName
        Next

        page.NavigationService.Navigate(New Uri(lsUrl, UriKind.Relative))
    End Sub

End Module

 

Nicer NavigationContext

 

I found Silverlight3’s NavigationContext quite nice to use.  Unfortunately this is not available in WPF.  I set about creating a helper function that would emulate this functionality in WPF.

 

WPF Navigation Helper

 

Here’s a WPF version of PageHelper that allows a compatible syntax with Silverlight3.  

 

Imports System.ComponentModel
Public Module PageHelper

    Private WithEvents moCurrentNav As NavigationService
    <System.Runtime.CompilerServices.Extension()> _
   Public Sub NavigateTo(ByVal page As System.Windows.Controls.Page, ByVal navigationUrl As String, ByVal ParamArray arguments() As String)

        '  Update Navigation Args
        Dim loNavigationUri As New NavigationContext

  If arguments.Length > 0 Then
            For i As Integer = 0 To arguments.Length - 1 Step 2
                 loNavigationUri.QueryString.Add(arguments(i), arguments(i + 1))
            Next

            End If

           
        loNavigationUri.Uri = New Uri(navigationUrl, UriKind.Relative)

        ' Strip the Xaml extension 
        Dim lsClassName As String = navigationUrl.Substring(0, navigationUrl.Length - 5) 
        ' Make my class name 
         Dim lsName As String = page.GetType.Namespace & "." & lsClassName 
        ' Instantiate the class 
        Dim loPage As Page = page.GetType.Assembly.CreateInstance(lsName) 
        ' Do the Navigation 
         page.NavigationService.Navigate(loPage, loNavigationUri)
    

        ' Store the current NavigationService so we can complete
        moCurrentNav = page.NavigationService

    End Sub
    <System.Runtime.CompilerServices.Extension()> _
Public Function NavigationContext(ByVal page As System.Windows.Controls.Page) As NavigationContext
        Return moLastNavContext
    End Function
    Private Sub moCurrentNav_Navigated(ByVal sender As Object, ByVal e As System.Windows.Navigation.NavigationEventArgs) Handles moCurrentNav.Navigated
        moLastNavContext = e.ExtraData
        moCurrentNav = Nothing
    End Sub
    Private moLastNavContext As New NavigationContext

End Module
Public Class NavigationContext
    Public QueryString As New Dictionary(Of String, String)
    Public Uri As Uri
End Class

 

I also have provided primitive support for cross-assembly navigation.

 

I hope someone found this useful, let me know.

 

 

Share this post :

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

WPF and the Supervising Controller/Presenter Pattern

Standard

image

I’ve previously stated that the MVP pattern could be advantages for XAML based applications.  I haven’t provided WPF examples yet as I fear that these may compromise the design-ability of the XAML layout.  

Florian Krusch describes the beginnings of an MVP style pattern for WPF (and Silverlight) applications in his article:

WPF – DM-V-VM or M-V-P – WTF?

He states that the pattern described by Martin Fowler  “Supervising Controller Pattern” (still under development at time of writing) may be relevant in this case.  (The term Controller and Presenter are used interchangeably in Fowler’s article)

This pattern has been created in order to facilitate frameworks such as WPF that have a data binding capability.   I understand however that it expects one-way data binding (read) with the view look at the model directly.  Updates to fields are delegated to the controller, which in turn updates the model.  This sortve neuters the 2-way data binding in WPF.

The true objective of these architectures is testability, with the assumption of the view being difficult to work with in the unit test environment.

An architecture that may work is something like the diagram below:

 

image 

In this proposal both the View and Model could be mocked successfully.

In future posts I’ll endeavour to  create some code to show how this may work in the real world.

Share this post :

Weird Science – Defining Winforms in XAML

Standard

image

I like to think of XAML as an “object instantiation script”.  According the to the main books on the subject it should be possible to utilise XAML to create any kind of .net object. 

Practical examples include WWF (Windows Workflow Foundation) , which allows the storage of definition in XAML, which is nothing to do WPF.  WPF (Windows Presentation Foundation) was the original reason XAML was created, but XAML was designed to be independent.

So I was thinking, why not see if I can define a traditional “Winform” in XAML.    Why would I want to?   I thought it might be fun.   As it turns out, it may actually be useful in some scenarios.  (With a great stretch of the imagination)

So does it work?  Oh yes it works and it works well.   “Well” means that VS2008 provides full intellisense for tags within the Xaml designer, as well as “code behind”.  Now that, my friends, is cool.  Imagine being able to create form layouts using XML tags instead of that oh-so-last year winforms designer!  The result is surprisingly WPF like, which I find intriguing.

To create the example below, I created a WPF project, then removed the default WPF “Window1.xaml” and replaced it with my own “Form1.xaml”:

<Form Name="Form1" x:Class="Form1"  Text="Hello" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        >
    <Form.Controls>
        <FlowLayoutPanel>
            <FlowLayoutPanel.Controls>
                <TextBox Name="txtName" x:Name="txtName" />
                <Button Name="cmdSayHello" Text="Say Hello" Click="Button_Click" /> 
            </FlowLayoutPanel.Controls>
        </FlowLayoutPanel>
    </Form.Controls>
</Form>

Please note that features such as code behind (partial classes), event hooks and most things in the “x” namespace work fine.

Creating XAML from an existing Winform

For even more fun and games, you can feed a running instance of a Winform into XAML Writer and get XAML source.  Sadly winforms incorporates read-only properties, so without massaging the Xml you’re not going to be able to clone a Winform using XAML serialization just yet.

The code would look something like this:

Dim loWinform As Form = Me ' Some Winform
Dim lsWinformXaml As String = XamlWriter.Save(loWinForm)
Dim loClonedForm As Form = XamlReader.Load(new XmlTextReader(new StringReader(xaml)))

 

See this Mike Hillberg’s object cloning article for more information.

 

So where from here?

What’s the use of it?  Well for me it proved that Xaml can be used to create any sort of object graph.  

Possible uses for this:

  • Embedding Winforms instantiation code within a WPF XAML document (something I haven’t tried)
  • Streaming Winforms form definitions from a server down to a client (effectively allowing a WebServer to render Winforms just like it renders HTML pages)
  • Providing a good interim step in creating a Winforms to WPF Converter

 

Any Comments?

If you find this topic interesting, ask questions or download a sample project, write some comments on the blog.  If I can see interest in the topic I may develop it further.

Share this post :

kick it on DotNetKicks.com

Seeing is Believing – Using Powerpoint as a UI Design Tool

Standard

Image that provides a visual metaphor about how different owls see things differently

When talking about “interaction design”, designers talk about the practice of “Wire Framing”. 

In the past this “Wire Framing” involved creating fairly primitive mock-ups of user interfaces on paper, arranged to make a “Story Board”, much in the same way as makers of animated cartoons always have.

The use of these story boards has allowed designers to “run through” prospective designs with real users as well as developers.  A useful tool.

Although paper is certainly a useful tool (I use it alot myself).  I can’t help wondering if there’s a way of doing this on a computer effectively.  You’d think there would be wouldn’t you?

Draw It!

One approach is to use a graphics editor such as Photoshop or the ubiquitous MS Paint (for goodness sake use Paint.NET at least….).    This is good in that it helps the stakeholders understand what it is that the new product will look like.  It’s bad in that it isn’t interactive and it usually takes lots of time, sometimes with a mediocre result.  It’s good if you have a Graphic Artist to help.  (The difference between a developer and a Graphic Artist producing a piece of work is that although they will probably both take ages to produce something, at least the Graphic Artist produces something worth looking at).

Prototypes

Another approach is to create a prototype using the actual development tools.  In the Microsoft World, run up Visual Studio and start churning out miracles.  Sadly however this approach is still development and developers can get bogged down in the detail.

There’s also the “scary” side to an operational prototype.  That nightmare scenario where development budgets are reduced and the boss says “why don’t we just put the prototype into production”……Enough said.

So the trick, in my opinion is to create something that looks as real as possible (ie as impressive as possible), but clearly is not the “real thing”.

 

Enter – Expression Blend

The era of User Experiences ushers in another alluring alternative.  Microsoft for example offer designer-oriented products such as “Expression Blend” that allow designers to create WPF and Silverlight based user interfaces without having to run the equivalent development tool “Visual Studio”. 

Allegedly Expression Blend will allow designers to create user interfaces.  At last designers have the power to wireframe in a rich way, creating user experiences that behave like prototypes.   Like the craftsman in his workshop, the designer has created a beautiful puppet, which dances for his appreciative masters.  But what if Pinnochio wants to become a “real boy”?

When it comes time to create real software the developers add the code, like Blue Faerie’s pixie dust and bring the user interfaces to life.

A pretty story indeed.  But will it happen?  In the Microsoft world it’s something that was promised with web frameworks such as ASP.Net in the early days, the dream of separating  ui design from programming content.

Sometimes creating the desired ui experience does take a while, even for someone proficient in Expression Blend.   (Happy to be howled down on this point)  A lot longer than doing a hand sketch or using MS Paint anyway.

Powerpoint Magic

A technique that has been used in my team is to use PowerPoint to do our Ui concept demos.      It has proven to be so believable, I’ve had stakeholders ask me to click on ui elements that are not part of the demo, despite repeatedly telling them “it’s only powerpoint”. 

We create different slides for each ui state.  In it’s simplest form we press enter to advance to the next ui state. 

This does NOT involve complex animation and transitions.  This sort of thing, even in a normal powerpoint presentation just wastes time.

If there’s time we’ll add “Custom Actions” (Mouse Hover or Click) to some UI elements to advance to the next slide, but that’s it.

To create the slides, we usually begin with a base (in the case of a browser based app this may be a screenshot of a webbrowser frame).  Take screenshots of various UI elements from other applications using screen capture software.  (this is built in to Vista….I recommend using Gadwin if you’re running XP)  The more of these you have the more realistic your concept will look.  Use the built-in powerpoint text boxes for more conceptual work.

The screenshot below a screenshot of a proposed PDA application.   It uses a screenshot of Visual Studio’s emulator as a base:

Sample PDA Application Screenshot

 

Using this approach can have these advantages:

  • It can look exactly like the real thing
  • It’s easy to do
  • It’s fast
  • You can add annotations
  • You can add limited interactivity
  • It works for any kind of application, not just Microsoft Wpf/Silverlight
  • You can use any Powerpoint-like tool

Conclusion

The “User Experience” is a becoming a key differentiator in many software markets.  Creating prototypes can be an important technique in creating compelling Ui experiences.  Perhaps more of this would be done if people realised that even a tool like PowerPoint can be used to do this.

Links

 

Share this post :

Visual Studio 2008 Released to RTM

Standard

 

A little while ago Microsoft announced via the MSDN news feed (first time I actually found the “Start” page useful).  So it’s time for you MSDN subscribers to start your download managers.

What’s New?

Visual Studio 2008 finally provides a fully supported developer experience for the .Net 3.0 technologies, namely Windows Presentation Foundation, Windows Workflow Foundation and Windows Communication Foundation.

It also supports the hyped up LINQ feature, which will be implemented in tandem with the .NET 3.5 runtime which is being released at the same time.

An interesting feature is the ability to target .NET 2.0, 3.0 or 3.5 applications.   It’s different to previous attempts in that some language features will work across all versions of the .NET Framework.

Compact Framework

Unit Testing is now available “out of the box” along with the Compact Framework 3.5.

The Compact Framework 3.5 includes LINQ and an implementation of WCF that uses Exchange ActiveSync as a transport.  Nice, but not anything I’m particularly interested in.

Silverlight

Scot Guthrie says “Two popular add-ins to Visual Studio are not yet available to download for the final VS 2008 release, These are the Silverlight 1.1 Tools Alpha for Visual Studio and the Web Deployment Project add-in for Visual Studio. Our hope is to post updates to both of them to work with the final VS 2008 release in the next two weeks.”

I’ll be looking forward to that!

Links

E Week Article – http://www.eweek.com/article2/0,1895,2219239,00.asp

Cross Thread User Interface updating in WPF

Standard

Recently I tried to update a WPF Dependency property from a System.Timer thread and received a “Cross Threading” error.  This wasn’t entirely unexpected, as I’d encountered similar issues in Winforms in the past.

In Winforms, methods such as Invoke, BeginInvoke and InvokeRequired are used in order to force code to run on the UI thread.

The absence of these methods (but not the error message) in WPF was disconcerting.  Fortunately those methods (and many more) do exist, via an extra object called the “Dispatcher” object that hangs off all Ui Elements.  

image

Links

Forum Post – http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=328693&SiteID=1

WPF Threads: Build More Responsive Apps With The Dispatcher — MSDN Magazine, October 2007

ThoughtEx – State of the Art Mind Mapping

Standard

Recently I had a discussion with Joseph Cooney, one of the creators of Thoughtex Mind Mapping application.

This application  has many unique user features such as:

  • Graphical Concept Maps
  • Rich editing within nodes 
  • Contextual Internet search
  • Simplified approach to file management

It’s also very interesting technically, as it utilises RIA technologies such as:

  • Windows Presentation Foundation
  • Click Once

This sort of thing shows how powerful Click Once can be.

Joseph told me the contextual search utilised the Yahoo mashup Apis for searching as they had quite a good licence.  If you want to do something similar check them out.

Responding To Events From DataTemplate Controls in WPF

Standard

WPF provides the ability to create templated items for controls such as the list and grid.

These item templates allow any WPF controls including labels, text areas and buttons.  My problem was knowing how to create code that responds to the clicks of these buttons.  Wasn’t terribly obvious to me. 

Here’s an example:


  <DataTemplate x:Key="SomeListItemTemplate">
    <StackPanel>
     <TextBlock Text="{Binding Subject}" Width="188" Height="45.277"/>
      <Button x:Name="cmdDeleteItem" Width="59" Height="21.277" Content="Delete" >    
    </StackPanel>
  </DataTemplate>

The trick  appears to be to create “CommandBindings”.  These are an input mechanism in WPF that allows developers to define commands centrally and have them processed by the one piece of logic.

It appears this isn’t supported visually in Expression Blend unfortunately.

In order to solve my problem I had to do four things.

Firstly I defined a Window.CommandBindings section in my xaml file

<Window.CommandBindings>
<CommandBinding Command="local:MyCommands.DeleteItem" Executed="OnDeleteItem" />
</Window.CommandBindings>

(For this to work, add the ‘xmlns:local=”clr-namespace:MyProject” ‘ attribute against the Window Tag)

Secondly I created a class to host my custom command:


Public Class MyCommands
    Public Shared DeleteItem As New RoutedCommand("DeleteItem", GetType(MyTasksWPF.Main))
End Class

Thirdly I created the “OnDeleteItem” method to receive my event:

Public Sub OnDeleteItem(ByVal sender As Object, ByVal args As ExecutedRoutedEventArgs)
System.Windows.MessageBox.Show("So you wanted to delete " & CStr(args.Parameter) & " punk? Well didja?")
End Sub

Finally I updated the button definition to specify the command I defined:

<Button x:Name="cmdDeleteItem" Width="59" Height="21.277" Content="Delete"
Command="local:MyCommands.DeleteItem" CommandParameter="{Binding Id}"/>

Find the SDK docummentation on the subject here:

http://www.eggheadcafe.com/software/aspnet/29895215/commandbindings-in-blend.aspx

A full example demonstrating types of using CommandBinding:

http://adoguy.com/2007/03/28/WPF_Command_Example.aspx