Hello WPF World, part 2 – Why XAML?

Let’s continue poking around with a first WPF “hello world” application.  We’ll continue comparing our bare bones wizard-generated WPF project with an equivalent Win Forms application.  And we’ll look at how XAML fits into our application architecture.

Last time, we compared the Win Forms Program class with its parallel in WPF–an App class, which inherits from System.Windows.Application.  The application framework in Win Forms was pretty lightweight–we just had a simple class that instantiated a form and called the Application.Run method.  WPF was just a bit more complicated.  If we count the generated code, we have an App class split across a couple of files, as well as a .xaml file that defines applicaton-level properties (like the startup window).

Now let’s compare the main form in our Win Forms application with the main window generated for us in WPF.  (The fact that WPF calls it a window, rather than a form, hints at the idea that GUI windows aren’t meant to be used just for entering data in business applications).

In Windows Forms, we have two files for each form–the form containing designer-generated code (e.g. Form1.Designer.cs) and the main code file where a user adds their own code (e.g. Form1.cs).  These two source files completely define the form and are all that’s required to build and run your application.  In Windows Forms, the designer renders a form in the IDE simply by reading the Form1.Designer.cs file and reconstructing the layout of the form directly from the code.  (The IDE does create a Form1.resx resource file, but by default your form is not localizable and the resource file contains nothing).

When you think about it, this approach is a bit kludgy.  The designer is inferring the form’s layout and control properties by parsing the code and reconstructing the form.  Form1.Designer.cs is meant to contain only designer-generated code, so with partial classes, we can keep designer-generated code in a single file and it only contains designer code.  But it’s clumsy to use procedural code to define the static layout of a form.

Here’s a picture of how things work in Win Forms:

In this model, the Form1.Designer.cs file contains all the procedural code that is required to render the GUI at runtime–instantiation of controls and setting their properties.  We could dispense with the designer in Visual Studio—it’s just a convenient tool for generating the code.  (I’m ashamed to admit that I’ve worked on projects that broke the designer and everyone worked from that point on only in the code–ugh)!

Now let’s look at WPF.  Here’s a picture of what’s going on:

Note the main difference here is–our designer works with XAML, rather than working with the code.  This is the big benefit of using XAML–that the tools can work from a declarative specification of the GUI, rather than having to parse generated code.  This also means that it’s easier to allow other tools to work with the same file–e.g. Expression Blend, or XamlPad.

Then at build time, instead of just compiling our source code, the build system first generates source code from the XAML file and then compiles the source code.

But this isn’t quite the whole story.  It’s not the case in WPF that the Window1.g.cs file contains everything required to render the GUI at runtime.  If we look at the Window1.g.cs file, we don’t find the familiar lines where we are setting control properties.  Instead, we see a call to Application.LoadComponent, where we pass in a path to the .xaml file.  We also find a very interesting method called Windows.Markup.IComponentConnector.Connect(), which appears to be getting objects passed into it and then wiring them up to private member variables declared for each control.  If we add a single button to our main window, the code looks something like:

But then the obvious question is–what happened to all those control properties?  Where do the property values come from at runtime?

Enter BAML–a binary version of the original XAML that is included with our assembly.  Let’s modify the above picture to more accurately reflect what is going on:

Note the addition–when we build our project, the contents of the XAML file–i.e. a complete definition of the entire GUI–is compiled into a BAML file and stored in our assembly.  Then, at runtime, our code in Window1.g.cs simply loads up the various GUI elements (the logical tree) from the embedded BAML file.  This is done by the Connect method that we saw earlier, in conjunction with a call to Application.LoadComponent:

MSDN documentation tells us, for LoadComponent, that it “loads a XAML file that is located at the specified uniform resource identifier (URI) and converts it to an instance of the object that is specified by the root element of the XAML file”.  When we look at the root element of the XAML file for our application, we discover that it is an object of type Window, with the specific class being HelloWPFWorld.Window1.  Voila!  So we now see that the code in Window1.g.cs which was generated at build time just contains an InitializeComponent method whose purpose it is to reconstitute a Window and all its constitutent controls from the GUI definition in the XAML file.  (Which went along for the ride with the assembly as compiled BAML).

So what is BAML and where is it?  BAML (Binary Application Markup Language) is nothing more than a compiled version of the corresponding XAML.  It’s not procedural code of any sort–it’s just a more compact version of XAML.  The purpose is just to improve runtime performance–the XAML is parsed/compiled at build time into BAML, so that it does not have to be parsed at runtime when loading up the logical tree.

Where does this chunk of BAML live?  If you take a look at our final .exe file in ILDASM, you’ll see it in the manifest as HelloWPFWorld.g.resources.  Going a tiny bit deeper, the Reflector tool shows us that HelloWPFWorld.g.resources contains something called window1.baml, which is of type System.IO.MemoryStream.  (I found something that indicated there was also a BAML decompiler available from the author of Reflector, which would allow you to extract the .baml from an assembly and decompile back to .xaml–but I couldn’t find the tool when I went looking for it).

So there you have it.  We haven’t quite yet finished our “hello world” application, but we’re close.  We’ve now looked in more depth at the structure of the application and learned a bit about where XAML fits into the picture.  Next time, we’ll add a few controls to the form and talk about how things are rendered.

It’s a WPF World, part 2

Let me continue my ramble about Microsoft technologies leading up to WPF.  Last time, I ended by talking about the .NET technologies and why I think they are so important.  .NET has become the de facto standard for developing applications for the Windows platform (thick clients).  And although ASP.NET likely doesn’t have nearly as big a chunk of market share as Windows Forms, it feels like the WISA stack (Windows, IIS, SQL Server, ASP.NET) is gradually overtaking the LAMP stack (Linux, Apache, MySQL, PHP).  And with the rise of RIAs (Rich Internet Applications), ASP.NET Ajax will likely encourage the continued adoption of the ASP.NET technologies.

Going back to my list of the most important benefits of the .NET world from last time, I realized that I’d like to add a final bullet item.  (In the list–what’s so special about .NET):

  • Programmer Productivity — with things like intellisense and code snippets in Visual Studio, you can be incredibly productive, whether working in Win Forms or ASP.NET

I make the claim about productivity without having had experience with other development environments (at least since doing OWL development with Borland tools).  But the rise in productivity is true even just of Microsoft tools.  They just continue to get better and better.  And though “real programmers” might pooh-pooh all this intellisense nonsense in favor of hand coding in Textpad, I have to believe that even these guys would be more productive if they truly leveraged the tools.

When .NET first came out, I remember reading the marketing materials and being a little misled about where ASP.NET fit into things.  It seemed like Microsoft was touting convergence of Windows vs. web development, by talking up the similarities of the dev experience, working in Windows Forms vs. Web Forms.  Developing with ASP.NET was ostensibly very similar to developing Win Forms applications–you started with an empty design surface, dragged visual controls onto it, and double-clicked to bring up an editor where you wrote your code-behind.  (Nevermind that this model encouraged low quality architectures as people wrote monolithic chunks of event handler code–perpetuating bad habits that we learned with VB6).

But the web model was still very, very different from the thick client model.  On Windows, we were still working with an event-driven model, using the same old Windows message loop that we’d always used.  But users interact with a web-based interface in a completely different way.  We used server-side controls in ASP.NET to hide some of the complexity, but we were still just delivering a big glob of HTML to the client and then waiting for a new HTTP request.

The ASP.NET development environment also felt a bit kludgy.  I remember being a bit dismayed when I wrote my first ASP.NET application.  In the classic Win Forms development environment, there were two separate views of your application, where a developer lived–the design surface and the code behind.  The ASP.NET environment has three–the design surface, the code behind, and the HTML content.  So now instead of a developer jumping back and forth between two views, you end up jumping around in all three.

Spoiler–this web application architecture gets a lot cleaner with Silverlight 2.0.  There seems to be actual convergence between thick vs. thin clients as we use WPF for thick clients, Silverlight 2.0 for thin.  But more on that later.

So along comes WPF (Windows Presentation Foundation) and XAML (Extensible Application Markup Language).

I remember when I first read about XAML and WPF (Avalon at the time).  My first reaction was to be mildly frustrated.  At first glance, XAML seemed to be an arbitrary switch to a new syntax for defining GUIs.  And it seemed cryptic and unnecessary.  In the effort to be able to define a user interface declaratively rather than procedurally, it looked like we were ending up with something far messier and garbled than it needed to be.  It felt much easier to understand an application by reading the procedural code than by trying to make sense of a cryptic pile of angle brackets.

But I’ve come to realize that the switch to defining GUIs declaratively makes a lot of sense.  With XAML, thick clients move a bit closer to web applications, architecturally–the GUI is built from a static declaration of the UI (the XAML), a rendering engine, and some code behind.  And the layout of a user interface (rather than the behavior) is implicitly static, so it makes sense to describe it declaratively.  [As opposed to Windows Installer technology, which converts the dynamics of the installation process to something declarative and ends up being far messier].

Why does it make sense to separate the markup from the code like this?

  • Architecturally cleaner, separating the what (XAML declaraction of GUI) from the how (code-behind).  (Separating the Model from the View)
  • Enables broad tool support–tools can now just read from and write to XAML, since the GUI is now defined separately from the application itself.  (Enabling separate tools for designers/devs, e.g. Expression Blend and Visual Studio).
  • Cleaner for web apps — because we can now serialize a description of the GUI and send it across the wire.  This just extends the ASP.NET paradigm, using a similar architecture, but describing a much richer set of elements.

Another of my earlier reactions to XAML was that it was just a different flavor of external resource (.resx) files.  It looked similar–using angle brackets to describe GUI elements.  But XAML goes far beyond .resx files.  Resource files are used to externalize properties of UI controls that are potentially localizable.  E.g. Control sizes, locations and textual elements.  But the structure is flat because a resource file is nothing more than a big collection of keyword/value pairs.  Nothing can be gleaned about the structure of the UI itself by looking at the .resx file.  XAML, on the other hand, fully describes the UI, hierarchically.  It is far more than a set of properties, but it is logically complete, in that it contains everything required to render the GUI.

XAML is a big part of what makes WPF so powerful.  But there are a number of other key features that differentiate WPF from Windows Forms.

  • Totally new rendering engine for the GUI, based on Direct3D.  This enables better performance in rendering of the GUI, because everything in your GUI is described as 3D objects.  So even apparent 2D user interfaces can take advantage of hardware acceleration on the graphics card.  [The new NVidia GT200 GPU has 1.4 billion transistors, compared with original Core 2 Duo chips, which were in the neighborhood of 300 million].
  • Vector graphics.  The GUI is now entirely defined in vector graphics, as opposed to bitmapped/raster.  This is huge, because it means that you can define the GUI geometry indepedent of the target machine’s screen resolution.  This should mean–no more hair-pulling over trying to test/optimize at various screen resolutions and DPI settings.  (Gack)!
  • Bringing other APIs into the .NET fold.  E.g. 3D, video, and audio are now accessible directly from the .NET Framework, instead of having to use APIs like DirectX.
  • Focus on 3D graphics.  All of the above technologies just make it easier to develop stunning 3D graphical user experiences.  Powerful/cheap graphics hardware has led to 3D paradigms like Apple’s “cover flow” showing up more and more often in the average user interface.  (Battleship Grey, you will not be missed))

So where does WPF fit into the rest of the .NET world?  Is WPF a complete replacement for Windows Forms?

Adopting WPF will not be nearly as big a learning curve as adopting .NET was, originally.  WPF is a full-fledged citizen of the .NET world, existing as a series of .NET namespaces.  So .NET continues to be the premiere Microsoft development technology.

WPF is definitely a replacement for Windows Forms.  It is the new presentation layer, meant to be used for creation of new Windows-based applications (thick clients).  Microsoft is probably hesitant to brand WPF purely as a Windows Forms replacement, not wanting to dismay development shops that have invested a lot in learning .NET and Windows Forms.  But it’s clearly the choice for new Windows-based UI development, especially as the number of WPF controls provided by the tools, and shipped by 3rd party vendors, increases.

WPF is also highly relevant to web development (thin clients).  Silverlight 2 allows a web server to deliver browser-based RIAs containing a subset of the widgets found in WPF.  (Silverlight 2 used to be called Windows Presentation Foundation/Everywhere).  With WPF and Silverlight, Windows and web development are definitely converging.

So we clearly now live in a WPF world.  WPF will rapidly become more widely adopted, as it is used for more and more line-of-business applications, as well as serving as the underlying engine for the new Silverlight 2 RIAs that are starting to appear.  And the best news is that we also still live in a .NET world.  We get all of the .NET goodness that we’ve learned to love, with WPF being the shiniest new tool in our .NET toolbox.