WPF and Windows Forms integration

Wed, October 10, 2007, 02:23 PM under Orcas | VisualStudio
Background
Any client developer that has seen a good Windows Presentation Foundation demo/presentation will probably be salivating at the prospect of playing with this cool technology and potentially planning in their heads how they can move their applications from Windows Forms to WPF. The fact is that you don't have to and in fact shouldn't just do that yet, despite what you may have heard from overzealous presenters. Today, WPF is a great choice for consumer applications, ideal for applications where having a WOW factor is part of the requirements and definitely the only choice for software houses that have both designers and developers working on the same projects. For the rest of us building LOB apps, Windows Forms still work great and, even better, can interop with WPF if required for specific use cases. There are many resources for bidirectional interop between WPF and WinForms as well as between WPF and Win32.

The Links
In Visual Studio 2008 we get designer support for these scenarios. If you are in a WPF project simply drag the WindowsFormHost control from the toolbox and point it to a WinForms UserControl. I am more interested in the reverse scenario, so in a Windows Forms project drag the ElementHost and point it to a WPF UserControl and then you can use that WPF control (set properties/call methods, handle events etc) from your winforms. Both of the host classes are implemented in the same namespace, in the WindowsFormsIntegration.dll assembly (part of WPF).

As you can see, other than the two aforementioned classes, there is a PropertyMap class that translates properties from winforms control to WPF elements (with help from the PropertyTranslator delegate) and you can read more about it on MSDN's aptly named Property Mapping page. In the same namespace you can also see 4 subclasses of EventArgs (ChildChanged, IntegrationException, LayoutException and PropertyMappingException) used by events.

"Hello World"
1. In VS2008, create a new WPF User Control Library project.
2. Using the designer for UserControl1.xaml create some UI or paste in the XAML section a UIElement if you already have one.
3. In the same solution, add a new Windows Forms project (in VS2008 target v3.0 or v3.5).
4. From this winforms project add a reference to the WPF User Control project
5. Rebuild all.
6. With the Form1 designer open, open the toolbox and find the UserControl1 that you created (in WPF).
7. Drag it onto the Form1, resize to your liking (it doesn't have to be docked and can coexist with WinForm controls on the form).
Notice how what it effectively did is create an ElementHost for you and set its Child property to the UserControl1? When it adds the ElementHost, it also adds references to the WindowsFormsIntegration, PresentationCore, PresentationFramework, WindowsBase and UIAutomationProvider assemblies. You can repeat the exercise by replacing step 7 with manually dragging an ElementHost onto the form and then using the ElementHost Tasks popup to select the hosted content:

8. Ctrl+F5
9. Exercise for you dear reader: Follow the links above and see what cool sample you can come up with ;-)

Releasing Source Code for the .NET Framework

Wed, October 3, 2007, 10:09 AM under dotNET
Huge announcement today: Microsoft is releasing the source code for parts of the .NET Framework (inc. BCL, WinForms, WPF, ASP.NET) under the Ms-RL license which effectively, by my interpretation, means that you can read but you cannot copy or modify.

The cool bit is not that you can just read the framework code in your favourite text editor once you download and accept the license; no, the real goodness is that when you debug your applications with Visual Studio 2008 you will have the option to debug right down into the Framework code (with an autodownload feature from an MSDN server)! Are you still debating the move to VS2008? ;-)

For more details read ScottGu's blog post or listen to ScottHa's podcast or watch ch9 interview with the man that made it happen.

FxCop rule for red bits

Wed, October 3, 2007, 04:43 AM under Orcas | VisualStudio
In my sessions I always explain the red and green bits story and then focus on describing the enhancements in the green bits – after all that is what people want to hear when attending a session on .NET Framework v3.5. I also make it clear that if you upgrade your projects to VS2008, you can leverage multitargeting to continue to target Fx v2.0.

Take those statements and combine them with my blog posts on the red bits (e.g. start here with this one). It should quickly become obvious that there are few little obscure additions at the public API surface level of v2.0 that, if you do take advantage when targeting v2.0 from VS2008, will result in your code crashing when deployed to a machine that only has v2.0 without the updates. That was a long sentence so feel free to re-read it ;).

The way Krzysztof describes it:
"But now I have to confess, there are some limitations in this design that we accepted when we made the original simplifying assumption. There is a very limited number of APIs being added to the Red assemblies and the multi-targeting system is currently not able to detect these."
To download his FxCop rule that addresses the deficiency in the VS 2008 multitargeting system for this niche scenario, visit his blog post. Note that even if you do not have VS2008, you can still download his Test.csproj and try to build to see the compiler errors in VS2005 on types/methods that do not exist. Go.

By the way, on a not so unrelated note, I found an interesting post which explains why previous versions of Visual Studio only targeted one framework version. Thought I'd share.

Migrating from .NET Framework v1.x to Visual Studio 2008

Mon, October 1, 2007, 01:38 AM under dotNET
I have no reservations in describing the move from Visual Studio 2005 to Visual Studio 2008 as a "no-brainer upgrade". The latter is a superset of the former and given framework multi-targeting and the layered approach of Framework 3.0 and 3.5, it makes perfect sense to move your development environment over and, when you are ready to change your deployment, seamlessly take advantage of a new .NET Framework 3.x

But how about those people still using VS.NET 2003 (shocking I know :) who wish to take advantage of the VS2008 enhancements and move closer to our latest platform? That's a different kettle of fish. The issue there is that: you are on a different CLR version (1.1) which has some breaking changes compared to the CLR 2.0 (which is used by Fx 2.0/3.0/3.5). You are also on a different framework version (1.1) which has some breaking changes compared to Framework v2.0 (which is also an essential part of Fx 3.0/3.5). There is no reason for you to go to VS2005 as an intermediate step, so by all means go from the IDE of 2003 to 2008, but be prepared to face all the issues people faced when they moved from Fx 1.x to Fx 2.0.

I thought I'd resurface below some links to documents that help people move from v1.x to v2.0, the first two being the most important ones IMO:
- Design time Breaking Changes in .NET Framework 2.0
- Runtime Breaking Changes in .NET Framework 2.0
- Microsoft .NET Framework 1.1 and 2.0 Compatibility
- Compatibility Testing Scenarios

Also note that if you search you'll find plenty of issues in particular for web projects since the project model fundamentally changed from VS.NET 2003 to VS2005. It was later amended via separate downloads for VS2005 but since you are moving to VS2008 you don't have to worry about that (both web site projects and web application projects are included out of the box with VS2008). So, just one extra link for you pre-ASP.NET v2.0 devs:
- Feature changes in ASP.NET 2.0

A much older blog post on the same topic may also be of use to you.

Video on Partial Methods in C# and Visual Basic

Fri, September 28, 2007, 01:30 AM under Orcas | VisualStudio
Recently I published a 15' video on a new VB9 and C# 3.0 language feature that is of course usable by projects targeting Fx v2.0 as well. The feature is called Partial Methods (not to be confused with extension methods).

Watch the screencast here.

PowerShell combined with CoreCon

Wed, September 26, 2007, 05:17 PM under MobileAndEmbedded
Loke Uei has a cool walkthrough of using PowerShell to talk to the Device Emulator via the new managed CoreCon APIs. Check it out.

Multithreaded Debugging Enhancements in Visual Studio 2008

Tue, September 25, 2007, 05:51 AM under ParallelComputing | Orcas | VisualStudio
Rather than writing or screenshoting the new multithreaded debugging enhancements in Visual Studio 2008, I thought I'd create a 15' video to demonstrate them. See if you can spot what the bug is before I "discover" it in my demo ;-).

Write your own GC Heap Viewer for NETCF

Fri, September 21, 2007, 02:30 PM under MobileAndEmbedded
Steven only posts once in a blue moon but when he does every .NET Compact Framework developer should take notice. Read the details of the GC Heap data file format.

How to go from Thread to ProcessThread

Fri, September 21, 2007, 09:27 AM under dotNET | ParallelComputing
Angelos found an interesting article via the UK MSDN Flash. If you did as well, check out more about that on the author's blog (one more reason to be sorry PDC was cancelled).

Anyway...

In a not so unrelated area, on a list that I am a member of, a question came up about affinitising a managed thread to a specific CPU. Jeffrey Richter came to the rescue by pointing out the System.Diagnostics.ProcessThread and its ProcessorAffinity property but then the harder question came along of how to associate that class with the System.Threading.Thread class. Below is the answer in C# from Mr Richter again:
      // Call this passing in 0
public static ProcessThread GetProcessThreadFromWin32ThreadId(Int32 threadId) {
if (threadId == 0) threadId = ThreadUtility.GetCurrentWin32ThreadId();
foreach (Process process in Process.GetProcesses()) {
foreach (ProcessThread processThread in process.Threads) {
if (processThread.Id == threadId) return processThread;
}
}
throw new InvalidOperationException("No thread matching specified thread Id was found.");
}
...where ThreadUtility is a class containing at least:
      [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
public static extern Int32 GetCurrentWin32ThreadId();

The code (and much more) is part the Power Threading Library which is available on the Wintellect site.

An advert for Microsoft ADCs

Thu, September 20, 2007, 01:02 AM under Links
When I get emails for support that are not directly related to my blog posts/events/screencasts I usually point the person to an appropriate free online support forum and newsgroup (e.g. for mobility questions I point them to these two and for questions in other domains I find the appropriate forum).

Occasionally the email (or phone call as the case was recently) is much more involved and for an educated answer the helper must gain a lot more context and insight into the environment. In these scenarios I recommend consultancy (not the body shop variety where people get installed in your office, but true advice from experts on a as needed basis). If the company is serious about their architectures staying up to date with where the Microsoft platform is going and about getting advice ranging from high level strategic issues down to performance optimisations in a certain implementation, then I suggest Microsoft Application Development Consulting.

As a customer you buy a set of consulting (150-2400) hours that you can use as you see fit during the year (maybe a presentation on some new technology of interest, a code review, an architectural planning meeting, help in building a proof of concept, debugging a nightmare bug etc). You are assigned an ADC that is effectively on-call for your company, (but who can decide to bring other members of the team as he sees fit – at the same rate). The ADC understands your product(s), environment(s) and people, and can be used remotely and/or on-site as the occasion dictates. To find out more about the rates, view a datasheet and get the contact email and phone number, please visit the ADC page.

As an aside, when I interviewed here at Microsoft UK 17 months ago, I got two job offers: one being the one I accepted and do today, the other being the ADC role which I am advertising on this blog post. Reasons for choosing one over the other are irrelevant here, but I did have to sleep on it for a couple of nights... As a second aside, when I joined my current team, 3 out of the 4 other guys were former ADCs...