Kello’s Code Corner

August 17, 2009

ExecutionEngineException when trying to open WPF Window a second time in a WinForms application

Filed under: .NET,C#,VB.NET,WPF — jonaskello @ 19:34

The problem:

Today when I was coding away on an application which is based on WinForms but contains WPF UserControls I had to add a WPF Window to show a modal dialog. This worked fine until I tried to open the WPF window, close it and then open it again. The second time I tired to open the WPF window I ran into a System.ExecutionEngineException.

I found this very strange at first but it is actually totally logical! It all became clear to me when I found this post. Since I am using both WinForms and WPF there are two Application objects (I blogged about creating the WPF application object in a WinForms application to use application level WPF resources). The problem is that the WPF application object that is created has a defult setting of ShutdownMode = OnLastWindowClose. So what happens is:

  1. The WinForms application is started and creates an WPF application object to enable application level resources.
  2. A WPF window is opened. This is now the first and only WPF window running in the context of the WPF Application object.
  3. The WPF window is closed, this causes the WPF Application object to execute its Shutdown method because of its default setting of ShutdownMode = OnLastWindowClose.
  4. An attempt is made to open a second WPF window but since the WPF Application has been shutdown the result is a System.ExecutionEngineException.

The solution:

It is very simple to solve this actually. Using the code I presented in the aformentioned post I made the following modifications:

  Sub Main()

    'This will create the WPF Application object but it will only
    'be used for WPF application-level resources since the
    'real application uses the WinForms Application object
    If System.Windows.Application.Current Is Nothing Then
      Dim wpfApp As New WpfControlLibrary1.App
      'Use OnExplicitShutdown instead of the default OnLastWindowClose
      'because otherwise WPF will shutdown when a WPF window is opened
      'and then closed and we will not be able to open it a second time
      wpfApp.ShutdownMode = ShutdownMode.OnExplicitShutdown
    End If

    Application.Run(Form1)

    'Now that the WinForms application is done we explicitly shutdown the WPF application
    If System.Windows.Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown Then
      System.Windows.Application.Current.Shutdown()
    End If

  End Sub

May 5, 2009

Why I don’t choose to use NHibernate

Filed under: .NET,NHibernate — jonaskello @ 21:30

If my job was to retrieve data from the database I would never choose NHibernate!

DataSets and DataReader are much more useful for this.

But my job is not to retrieve data from the database. It is to build a system that solves a complex problem.

If my job was to build a system that solves a complex problem I would never choose NHibernate!

I would choose an approach that can handle complex problems. I would choose to build a Domain Model!

If I choose to build a Domain Model I would make sure that it was built to have a long lifespan.

If I wanted a long lifespan for my Domain Model I would make sure we only need to change it when the business domain changes, not when software technologies for data access and other such concerns change.

To give my Domain Model a long lifespan I would base it on the technology that is the least likely to change. This would be something that have not changed in a long time and have a lot of other software built on it so it cannot change for a long time.

The way basic classes work in object models have not changed since the ideas were formed in the 1960s. In the Microsoft world, classes/objects have not changed since Microsoft.NET framework 1.0 was introduced.  The whole Microsoft.NET framework is built on Common Language Runtime (CLR) classes/objects.

I would base my Domain Model on just basic classes, also known as Plain Old CLR Objects (POCO). PCOO objects are classes that does not inherit from or are in any way are associated with anything “special” such as a Microsoft DataSet base class. This way POCO classes can stay 100% focused on business problems and don’t have to change when data access technologies change.

Some of the POCO objects in the Domain Model would have to be saved to a database. In order to do this and not involve any of the technology to do it in the Domain Model I would have to use Persistence Ignorance (PI). PI means that the object in the Domain Model have no idea how they are being saved and loaded from the persistent medium (the database).

To use PI I would have to use an existing persistence framework that supports PI or build my own data access framework that supports PI.

I would choose to use an existing persistence framework to save time. I would want to use the framework that does not depend on a small vendor and does not infer extra cost on the project. I would want to use a framework that are used in a lot of other systems and have a lot of documented credibility.

The only framework that currently matches these criteria is NHibernate.

I do not choose to use NHibernate but I use it as a consequence of my other more important choices!

DotNetKicks Image

March 26, 2009

Model-View-ViewModel and naming conventions for bound data objects in lists (ViewItems)

Filed under: .NET,C#,Model-View-ViewModel,Naming Convention,WPF — jonaskello @ 21:02

The problem

When designing Views and ViewModels for M-V-VM (or Presentation Model if you prefer) I often find myself in a situation where I need a ListView or ListBox in the View which is bound to a list of objects exposed from the ViewModel. For several reasons I don’t want to put the domain/business object directly in that list. They may not have all properties I want to display because some extra properties would be calculated for screen only use or represent some visual state. Also I don’t want to force the domain/business objects to fit the screen since that should not be their design goal.

An example scenario

As an simple example imagine a read-only master-details screen for an order and its order lines. The order information such as address etc. is displayed in labels and the order lines are displayed in a ListView. Just for the sake of argument we should also display a running sum for each order line in the ListView and we want to do this by calculating the running sum first and storing it in an extra property that is not available in the domain/business object.  At first I used to handle this kind of scenario by creating the View and ViewModel for the Order and an extra ViewModel class for the order lines. That would give us the following files:

  1. OrderView.xaml
  2. OrderViewModel.cs
  3. OrderLineViewModel.cs

The OrderLineViewModel holds information for each order line including the running sum and the OrderViewModel exposes a property of List<OrderLineViewModel> that the ListView is bound to. The OrderLineViewModel does not have a corresponding View since it is not needed in order to display them in the ListView. After doing this for a while I discovered that this naming convention would make it hard to find the “real” ViewModels that has a corresponding XAML View among the other files. So now we get to the reason for this post, namely what we should name that OrderLineViewModel class!

Reasoning and current solution

The first thing to consider would be to have no suffix at all for this kind of classes. Then the name would be OrderLine, very simple and describing. The problem with that however is that the domain/business object probably also would be named OrderLine but would reside in a different namespace. Now this would work but we would have to qualify the namespaces and it would be hard to distinguish them when reading the code.

Now considering the following:

  1. This kind of classes exists only in order to bind to something on the screen.
  2. They represent only a part of the screen/view not the whole screen/view like a ViewModel class does.

I first considered the following suffixes:

  1. ScreenDataObject
  2. ScreenElement
  3. PresentationObject

Thinking further I realized the following:

  1. This kind of classes often wind up as items in something that inherits from ItemsControl (like ListView or ListBox). So “item” would be more appropriate than “element” to signal it is only a part of the screen.
  2. If we wanted to do some advanced styling for each item in the list we would probably create an separate UserControl to use as a DataTemplate. This UserControl would then of course become a View for the Item and the item then would be upgraded/renamed as a “real” ViewModel. So “view” would probably be better than “screen” in the first place.

Adding my thoughts up I came up with the suffix “ViewItem” which I am fairly satisfied with for the time being. Actually “ViewModelItem” would probably be more correct but I decided it was too long. So for the original example we would now have:

  1. OrderView.xaml
  2. OrderViewModel.cs
  3. OrderLineViewItem.cs

Going further with ViewItems

Now I am currently considering if these ViewItem classes should wrap (contain) a domain/business object or if they should have their own members and become a copy of the domain/business object. Obviously they can not derive all their information through a contained business/domain object if they should also contain extra calculated properties. Then they would have to have a reference to the domain object and also some other members for calculated values. I will try to do another post about some reasoning around this soon.

DotNetKicks Image

January 13, 2009

VB.NET lambda expressions intellisense not working for Repository(Of T)

Filed under: .NET,C#,VB.NET — jonaskello @ 21:54
Tags: , ,

When designing an IRepository(Of T) implementation with lambda expressions in VB.NET I found out that there is a bug in the VB.NET intellisense of Visual Studio 2008 SP1.

The problem

When trying to get a list of members for an type-inferred lambda parameter in VB.NET (Visual Studio 2008 SP1) there are no members shown in the intellisense drop down list. It does however work in C#. See illustrations below:

C# is working

Lambda intellisense in C# is working

VB.NET is not working

Lambda intellisense in VB.NET is not working
Status

Known bug said to be resolved in next Visual Studio. It is reported here and here and is said to resolved in next visual studio. I guess next version means VS.NET 2010 which seems far away. Too bad.

Work-arounds

The only work-around I have found is to explicitly declare the parameter’s type like “Function(c As Customer) c.Name = “Donald”. Then it works as shown below:

Lambda intellisense in VB.NET works when type declaring generic parameter

Steps to reproduce

Step 1, VB.NET is not working

Create a new VB.NET WinForms project and add these classes:

Person.vb

Public Class Customer

  Private _name As String

  Public Property Name() As String
    Get
      Return _name
    End Get
Set(ByVal value As String)
      _name = value
    End Set
  End Property

End Class

Repository.vb

Public Class Repository(Of T)

Public Function Find(ByVal predicate As
System.Linq.Expressions.Expression(Of Func(Of T, Boolean))) As List(Of T)
    Return Nothing
  End Function

End Class

Form1.vb code-behind

Public Class Form1

  Private Sub Form1_Load(ByVal sender As System.Object, 
ByVal e As System.EventArgs) Handles MyBase.Load

    Dim r As New Repository(Of Customer)()
    r.Find(Function(c) c.Name = "Donald")

  End Sub

End Class

Now trying to get intellisense on the “Name” member of Customer in the “Function(c) c.Name” lambda will not work and it looks like this:

Lambda intellisense in VB.NET is not working

Step 2, C# is working

Now Create a new C# WinForms project and add these classes:

Person.cs

namespace WindowsFormsApplication3
{
  class Customer
  {
    public string Name { get; set; }
  }
}

Repository.vb

using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace WindowsFormsApplication3
{
  class Repository<T>
  {
public List<T> Find(Expression<Func<T, bool>> predicate)
    {
      return null;
    }
  }
}

Form1.cs code-behind

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
  public partial class Form1 : Form
  {
    public Form1()
    {
InitializeComponent();
    }

private void Form1_Load(object sender, EventArgs e)
    {
      Repository<Customer> r = new Repository<Customer>();
      r.Find(c => c.Name == "Donald");
    }
  }
}

Now trying to get intellisense on the “Name” member of Customer in the “c=> c.Name” lambda will work and it looks like this:

Lambda intellisense in C# is working

kick it on DotNetKicks.com

January 12, 2009

Application level resources for WPF UserControls hosted in WinForms

Filed under: .NET,C#,VB.NET,WinForms — jonaskello @ 21:00
Tags: , , ,

I am working on an application that was originally written in framework 2.0 with WinForms where one application shell window is host to multiple MDI child windows. Now after upgrading it to framework 3.5 I wanted to add some MDI child windows with WPF features. I don’t think there is a way to open a WPF Window as a child of a WinForms MDI parent (well, maybe there is but it didn’t seem like a good idea) and the application is far too big to convert to pure WPF.

Therefore I created a WinForms MDI child form with a ElementHost covering it to act as a container for my WPF “Forms”. I also added a separate project for the WPF UserControls to be contained in the WinForm. This way I can add several UserControls to the separate project and reuse my WinForms container window for showing them. Now everything was nice until I wanted to add some application-level resources for the WPF UserControls. Since the main project (the project that compiles to an executable) is a WinForms project it does not have the App.xaml that WPF application projects have (or Application.xaml as is seems to be named now-days when creating new projects in VS 2008 SP1). This leads us to:

The problem

How do I provide application-level resources when I host WPF UserControls in an WinForms application?

The solution

As usual Dr. WPF is the doctor with all the right prescriptions for my problems and he has a post about several approaches to this problem. I will describe the one that I decided to use and how I got it working since the changes to the proj file that the doctor prescribes did not work in my case.

What I wanted was an App.xaml file in the WPF UserControl library project that could act just like it does in a WPF Application project. I think that approach would provide an easy upgrade path if the main application ever makes it to pure WPF. To achive this we can use a WPF Page to emulate the App.xaml file like this: 

1. Add a new WPF Page to the WPF UserControl library project and name it “App.xaml”.

2. The contents of the App.xaml now have a root tag of <Page>. Replace all the contents of this file with this:

<Application x:Class="App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns: x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Application.Resources>

  </Application.Resources>
</Application>

NOTE: Remove the space between xmlns: and x below, I had to add it so the blog would not make a smiley of it.

3. Now in your main WinForms project make sure you start from “Sub Main” or some other entry point that you can add code to and add the following:

  Sub Main()

    'This will create the WPF Application object but it will only
    'be used for WPF application-level resources since the
    'real application uses the WinForms Application object
    If System.Windows.Application.Current Is Nothing Then
      Dim wpfApp As New WpfControlLibrary1.App
    End If

    Application.Run(Form1)

  End Sub

4. Now you should be able to reference the resources that are added to the App.xaml file from the UserControls.

I attach a sample project demonstrating this concept here. NOTE: Rename file suffix to ZIP to make it work.

kick it on DotNetKicks.com

January 11, 2009

Model-View-ViewModel and InputBindings for ICommand

Filed under: .NET,C#,Model-View-ViewModel,VB.NET,WPF — jonaskello @ 20:55
Tags: , , , ,

The problem

When using the Model-View-ViewModel pattern best practice is currently to expose properties of type ICommand from the ViewModel and map them to the Command property on Buttons, MenuItems etc. in the view. Using this approach is considered better than using RoutedCommands but we loose InputBindings becuase there is no ICommand.InputBindings like there is RoutedCommand.InputBindings. Instead we have to map KeyBindings at some level to the commands, for example at the Window or UserControl level. I tried to do this in XAML like this:

<Window>
  <Window.InputBindings>
    <KeyBinding Command="{Binding Path=SetViewCommand}" 
                     CommandParameter="Right" Key="Ctrl+R" />
    <KeyBinding Command="{Binding Path=SetViewCommand}" 
                     CommandParameter="Left" Key="Ctrl+L" />
  </Window.InputBindings>
</Window>

This syntax seemed so natural to me that I intuitively tried it without thinking too much but it didn’t work. There must be some other simple solution I thought and started searching. Oh boy, was I wrong… Below is my tale of researching this issue.

Why it does not work

I came across this post where this issue is discussed by people who understand WPF far better than me. It seems that the problem is two-fold:

  1. The KeyBinding.Command is not a DependencyProperty so it does not support data binding.
  2. Even if it was a DependencyProperty the KeyBinding is not part of the WPF element tree and therefore has no access to the DataContext (which is usually set to the ViewModel that exposes the ICommand we want to bind to).

The solution …err.. I mean the work-arounds

I have found two work-around solutions worth mentioning:

  1. This solution uses a “virtual branch“. But the XAML syntax gets very complex.
  2. Here is another solution that I like better. It uses a markup extension and the XAML syntax gets a litte bit less complicated.

But I didn’t like the work-arounds enough to use them. Mainly because advanced concepts such as virtual branches and markup extensions are not likely to be easily understood by all developers on a team and certainly not by the maintainers that would have to figure out how it all works later on.

RoutedCommand you have InputBinding… Why will you not be my friend?

This is where I turned back to look at RoutedCommand again because it actually has an InputBindings collection built-in. I knew that exposing RoutedCommands in ViewModel were considered bad and we should use ICommand instead but I did not fully understand why. So I read this article that explains a lot about RoutedCommand. In the section  “Routed Command Challenges” it also explains why RoutedCommands only complicates things for the M-V-VM pattern.

I don’t fully understand it all but it seems like one thing that makes RoutedCommands complicate things is that they are hard-wired to trigger things according to which control that have focus in the UI and then bubble up from that control. When we have many controls working together in a Window it then becomes hard to predict which handler the RoutedCommand will invoke. In contrast, mapping a Button.Command property to an ICommand on the ViewModel we get a very clear and direct understanding of what command handler will be invoked (the bound ICommand’s Execute method of course). Also since I am having a hard time fully understanding all implications of RoutedCommands they cannot be any good ;-).

So the problem is in the framework classes? Then why don’t you rewrite the framework…

Looking further at the badness of RoutedComands I also found this interesting post where the whole idea behind commanding in WPF is being rethought. I don’t understand it all so maybe I have gotten the wrong idea but I think what is proposed is something like this:

  • RoutedCommands and CommandBinding classes should be obsoleted so we work only with ICommand.
  • Instead of RoutedCommand there would be VerbGesture. A VerbGesture would be an abstract representation of something that can be invoked in the application like Save, Cut, Close etc. It would be treated as the other InputGestures so we would have KeyGesture, MouseGesture, and VerbGesture. Because of this a VerbGesture would be routed like other InputGestures.
  • The VerbGestures could be added to a control’s InputBindings so we would have KeyBinding, MouseBinding and VerbBinding. This way we could bind a VerbGesture to an ICommand.
  • VerbGestures could be mapped to other InputGestures so we could map a KeyGesture to a VerbGesture. For example pressing a key would trigger the KeyGesture which in turn would trigger the VerbGesture.
  • When a VerbGesture is triggered an associated VerbBinding is sought and when it is found it’s associated ICommand is executed. So it would work just like KeyGesture and MouseGesture.

This seems nice to me and I hope Microsoft implements something like this in the future. Anyway it seems like the consensus is that RoutedCommands complicate things so the thing I take away from all this is that I should avoid RoutedCommands and CommandBinding altogether. If I only knew this before it could have saved me a lot of reading up on how RoutedCommand works ;-).

Oh well, the framework rewrite would take me too long… Looks like it would have to be code-behind then..

But now back to present time. The way I solve this in my current project is to add the InputBindings in the code-behind file. It is not as nice as to have it in XAML but on the other hand it does not require advanced concepts like virtual branch or markup extensions. So to emulate the XAML in the beginning of this post I would have this for a view called MyView in the code-behind file MyView.xaml.vb:

Partial Public Class MyView   
  
  Public Sub New(ByVal viewModel As MyViewModel)   
  
    'This call is required by the Windows Form Designer.   
    InitializeComponent()   
  
.. Other code ...   
  
    'Create KeyBindings so the menus have shortcuts   
    CreateKeyBinding(_viewModel.SetViewCommand, "Right",   
Key.R, ModifierKeys.Control)   
    CreateKeyBinding(_viewModel.SetViewCommand, "Left",   
Key.L, ModifierKeys.Control)   
  
  End Sub  
  
  Protected Sub CreateKeyBinding(ByVal command As ICommand,   
ByVal commandParameter As Object,   
ByVal gestureKey As Key, ByVal modifiers As ModifierKeys)   
  
    Dim kb As New KeyBinding(command, gestureKey, ModifierKeys.Control)   
    kb.CommandParameter = commandParameter   
    InputBindings.Add(kb)   
  
  End Sub  
  
End Class

One thing that gets me is the fact that I have to add InputGestureText to each MenuItem like this.

<MenuItem Header="Right" Command="{Binding Path=SetViewCommand}"  
                CommandParameter="Right" InputGestureText="Ctrl+R" />  
<MenuItem Header="Left" Command="{Binding Path=SetViewCommand}"  
                CommandParameter="Left" InputGestureText="Ctrl+L" />  

The InputGestureText property is just a string that gets displayed to the right of the MenuItem and has nothing to do with mapping to keyboard shortcuts as it had in earlier GUI platforms such as WinForms. Now imagine what would happen if we change the KeyBinding’s KeyGesture in the code-behind file from Ctrl+R to Ctrl+W. The MenuItem.InputGestureText would still display Ctrl+R to the user but this keyboard shortcut would no longer trigger the ICommand in the MenuItem.Command property because it is now bound to the Ctrl+W KeyGesture.

RoutedCommand you are not my friend but you give InputGestureText a meaning…

When a MenuItem’s Command property is set to a RoutedCommand the InputGestureText is “automatically” set. I checked the code for this in the MenuItem class with Reflector and it actually tries to cast the Command property to RoutedCommand and if it succeds then it reads the InputBindings and uses the first KeyBinding it finds to set the InputGestureText:

private static object CoerceInputGestureText(DependencyObject d, object value)
{
RoutedCommand command;
MenuItem item = (MenuItem) d;
if ((string.IsNullOrEmpty((string) value)
&& !item.HasNonDefaultValue(InputGestureTextProperty))
&& ((command = item.Command as RoutedCommand) != null))
{
InputGestureCollection inputGestures = command.InputGestures;
if ((inputGestures == null) || (inputGestures.Count < 1)) { return value; } for (int i = 0; i < inputGestures.Count; i++) { KeyGesture gesture = ((IList) inputGestures)[i] as KeyGesture; if (gesture != null) { return gesture.GetDisplayStringForCulture(CultureInfo.CurrentCulture); } } } return value; } [/sourcecode] Too bad that it casts to a concrete implementation instead of an interface. This makes the MenuItem class tightly coupled to the RoutedCommand class. If instead it would cast to an interface like IInputGestureTextProvider we could provide our own implementation that could look for a parent KeyBinding in the element tree or something like that. Now there is nothing I can do to make MenuItem sync it's InputGestureText with the KeyBindings that are mapped to my ICommands? Perhaps I could make my DelegateCommand inherit from RoutedCommand and then shadow all the methods and properties including the InputBindings collection. It does not seem like a clean solution though so for now I suppose I have to keep my InputGestureTexts in sync with the KeyBindings manually. But I hope I will have time to get back to this later and find a better solution. kick it on DotNetKicks.com

January 10, 2009

Getting code formatting with syntax highlighting to work on wordpress.com

Filed under: syntax highlighting — jonaskello @ 19:36
Tags:

After making two posts on my blog at blogger.com I realized that I had outgrown that blogging platform and moved to wordpress.com ;-). Now I need a a way to get code examples to display nice at my wordpress.com blog. I would like to use syntaxhighligeter on wordpress.com like I did on blogger so I looked for a way to customize the blog template to include the needed syntaxhighligter css and javascript snippets like in my previous post.

I soon realized that wordpress.com does not support template customization and you have to pay for CSS changes. Bummer :-(…. So I googled some more and finally found out that wordpress.com has built-in support for syntaxhighliter for free :-). All you have to do is wrap your code in sections starting with

[sourcecode language=’css’]

your code here

[/sourcecode]

Any of the following can be used for the language parameter (using one is required):

  • cpp
  • csharp
  • css
  • delphi
  • html
  • java
  • jscript
  • php
  • python
  • ruby
  • sql
  • vb
  • xml

And you don’t have to HTML encode your code! It’s all explained in detail at this wordpress.com support page. I knew wordpress.com would be better than blogger!

January 8, 2009

Printing WPF Visuals that are created in code and not displayed

Filed under: .NET,C#,WPF,WPF Printing — jonaskello @ 20:23
Tags: , , ,

Today I had to print some WPF visuals (actually multiple views of a 3D model) that were not rendered to the screen but only existed in memory. If you try this you will notice it is not obvious how to do it. For example to print a simple button with a text you could assume the following code would do it but it won’t work.

      // This code will result in an empty page
      PrintDialog pd = new PrintDialog();
      if (pd.ShowDialog().GetValueOrDefault())
      {
        Button buttonToPrint = new Button();
        buttonToPrint.Content = "My Button";
        pd.PrintVisual(buttonToPrint, "Printing button");
      }

Why does it not work? Well if we put a breakpoint at the PrintVisual() line and check values for the button’s size in the immediate window we get this:

?buttonToPrint.Width
NaN
?buttonToPrint.Height
NaN
?buttonToPrint.ActualHeight
0.0
?buttonToPrint.ActualWidth
0.0

Aha! So we need to give our button a size, lets try this:

      // This code will also result in an empty page
      PrintDialog pd = new PrintDialog();
      if (pd.ShowDialog().GetValueOrDefault())
      {
        Button buttonToPrint = new Button();
        buttonToPrint.Content = "My Button";
        buttonToPrint.Width = 100;
        buttonToPrint.Height = 100;
        pd.PrintVisual(buttonToPrint, "Printing button");
      }

Hmm.. Still an empty page, let’s check the properties in the immediate window again:

?buttonToPrint.Height
100.0
?buttonToPrint.Width
100.0
?buttonToPrint.ActualWidth
0.0
?buttonToPrint.ActualHeight
0.0

The ActualWidth and ActualHeight is zero hence the button is not displayed on the printed page. Why is this? According to the doctor WPF layout engine does a 2-pass layout in which it first calls the Measure() method and then the Arrange() method on all Visuals recursively. When using PrintDialog.PrintVisual() it seems this is not done automatically so we need to do it ourselves using code like this:

      // This code will actually make the button appear on the page!
      PrintDialog pd = new PrintDialog();
      if (pd.ShowDialog().GetValueOrDefault())
      {
        Button buttonToPrint = new Button();
        buttonToPrint.Content = "My Button";

        // Do Measure and Arrange passes before printing so the button is layed out correctly
        buttonToPrint.Measure(new Size(double.MaxValue, double.MaxValue));
        buttonToPrint.Arrange(new Rect(buttonToPrint.DesiredSize));

        pd.PrintVisual(buttonToPrint, "Printing button");
      }

What happens in the Measure() and Arrange() calls that make this work? In the Measure() call the button checks how big it has to be in order to display all of it’s text and checks if this size is available within the size we pass in. This will always be the case since we pass in an “infinite” size. It then sets it’s DesiredSize to this size. Then in the second pass we call Arrange() which will layout the Button according to it’s DesiredSize property. Now we have simulated the layout engine’s work and the button is printed!

kick it on DotNetKicks.com

January 7, 2009

Getting code formatting with syntax highlighting to work on blogger

Filed under: syntax highlighting — jonaskello @ 22:56
Tags:

When blogging about coding I want to be able to show code with some nice formatting. I found a this site that will convert your code to HTML. It was somewhat nice but looking further I found syntaxhighlighter which is much nicer. It uses javascript to do the formatting dynamically so you will not have to include formatted HTML in your posts.

It was not obvious how to make syntaxhighlighter work with blogger but I found this post that was very helpful.

Basically it involves these steps:

1. In the HTML template (Layout->Edit HTML) include this before </head>

<link href='http://syntaxhighlighter.googlecode.com/svn/trunk/Styles/SyntaxHighlighter.css' 
rel='stylesheet' 
type='text/css'/>  
<script language='javascript' 
src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js'/>  
<script language='javascript' 
src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js'/> 

2. Put this before </body>

<script language="javascript">  
dp.SyntaxHighlighter.BloggerMode();  
dp.SyntaxHighlighter.HighlightAll('code')  
</script> 

3. Paste your code into your posts like this.

<pre name="code" class="CSharp">  
if(!working)   
{  
  FixIt();  
} 
</pre>

Tips
All reserved HTML chars in your code must be encoded before you paste them. An easy way to do this is to use this site.

This is an list of the languages that syntaxhighlighter supports and the aliases that can be used in the class attribute of the code tag.

To use a language you muse include it’s “brush” which is the highlighting script for a specific language. You will find a list of brushes in the syntaxhighlighter source code trunk.

Create a free website or blog at WordPress.com.