MDC 2010 Takeaways

I attended the Minnesota Developers Conference (MDC 2010) yesterday in Bloomington, MN.  A nice dose of conference-motivation–some good speakers talking about great technologies.  In the FWIW category, here are my lists of takeaways for the talks that I attended.

1.       Keynote – Rocky Lhotka (Magenic)

General overview of development landscape today, especially focused on cloud computing and the use of Silverlight.  Takeaways:

  • We’re finally getting to a point where we can keep stuff in “the cloud”, access anywhere, from any device
  • Desire to access application data in the cloud, from any device, applies not just to consumer-focused stuff, but also to business applications
  • Smart client apps, as opposed to just web-based, are important/desired – intuitive GUI is how you differentiate your product and what users now expect
  • HTML5 is on the way, will enable smart client for web apps
  • Silverlight here today, enables smart clients on most devices (not iPhone/IOS)
  • Silverlight/WPF is ideal solution.  You write .NET code, reuse most GUI elements on both thick clients (WPF) running on Windows, and thin clients (Silverlight) running web-based or on mobile devices
  • I didn’t realize that I have in common with Rocky: working on teletypes, DEC VAX development, Amiga development. :O)
  • http://www.lhotka.net/weblog/ , @RockyLhotka (Twitter)

2.       WPF with MVVM From the Trenches – Brent Edwards (Magenic)

Practical tips for building WPF applications based on MVVM architecture.  What is the most important stuff to know?  Excellent talk.  Takeaways:

  • MVVM excellent pattern for separating UI from behavior.  Benefits: easier testing, clean architecture, reducing dependencies
  • MVVM is perfect fit for WPF apps, very often used for WPF/Silverlight
  • MVVM perfect fit for WPF/Silverlight, makes heavy use of data binding
  • Details of how to do data binding in MVVM, for both data and even for command launching
  • How to use: data binding, DataContext, Commanding, data templates, data triggers, value converters.  (Most often used aspects of WPF)
  • Showed use of message bus, centralized routing of messages in typical MVVM application.  Reduces coupling between modules.  (aka Event Aggregator).   Used Prism version.
  • Slide deck – http://www.slideshare.net/brentledwards/wpf-with-mvvm-from-the-trenches
  • http://blog.edwardsdigital.com/, @brentledwards (Twitter)

3.       Developer’s Guide to Expression Blend – Jon von Gillern (Nitriq)

Demoing use of Expression Blend for authoring UI of WPF/Silverlight apps.  Also demoed Nitriq/Atomiq tools.  Takeaways:

  • Blend not just for designers; developers should make it primary tool for editing GUI—more powerful than VStudio
  • Lots of tricks/tips/shortcuts – he handed out nice cheatsheet – http://blog.nitriq.com/content/binary/DevelopersGuidetoBlend.pdf
  • Very easy to add simple effects (e.g. UI animations) to app elements to improve look/feel, just drag/drop
  • Nitriq – tool for doing basic code metrics, summaries, visualize code, queries that look for style stuff.  (Free for single assembly, $40 for full )
  • Atomiq – find/eliminate duplicate code, $30
  • http://blog.nitriq.com/, @vongillern (Twitter)

4.       Introduction to iPhone Development – Damon Allison (Recursive Awesome)

Basic intro to creating iPhone app, showing the tools/language/etc.  From a .NET developer’s perspective.  Takeaways:

  • You have to do the dev work on a Mac—no tools for doing the work on Windows
  • The tools are archaic, hard to work with, much lower level than .NET.  (E.g. no memory management)
  • In many cases, consider creating web-baesd mobile app, rather than native iPhone.  But then you wrestle with CSS/browser issues
  • Worth considering creation of native iPhone app for the best user experience
  • Lots of crestfallen-looking .NET developers in the audience
  • http://www.recursiveawesome.com/blog/ , damonallison (Twitter)

5.       A Lap Around Prism 4.0 – Todd Van Nurden (Microsoft)

Showing Prism—a free architectural framework written by Microsoft, came out Patterns and Practices group.  Good for creating extensible apps, with plug-in model.  Takeaways:

  • Leverages MEF (Microsoft Extensibility Framework)
  • Good for apps where you have the idea of a lot of “tools” that plug into main application architecture.  Or for applications made up of various building blocks.
  • You write application modules that are decoupled from main app framework, loaded on demand.
  • Prism on Codeplex – http://compositewpf.codeplex.com/
  • http://www.spoke.com/info/p5rAVze/ToddVanNurden
Advertisements

Silverlight 4 Project Types part III – Silverlight Class Library

Last time, I looked at the Silverlight Navigation Application choice in Silverlight’s New Project wizard.  Next, I’d like to look at the Silverlight Class Library choice.  This is next on the list, out of the six different project types that are listed in the New Project wizard when you pick Silverlight as a project type.

Creating a Class Library

What exactly is a class library?  Well, simply put, it’s a library containing the implementation of one or more classes, implemented as a .NET DLL.  The basic idea is to move basic functionality that you’d likely use in more than one place out to a common library that one or more applications can use.

Silverlight lets us easily create a class library that we can then deploy with our actual Silverlight application.  The class library would contain code that we could invoke from our Silverlight application.

Let’s create a basic Silverlight Class Library using the New Project wizard.  Here’s what the dialog looks like:

Once you enter your project name and click OK, you see the dialog shown below.  This is where you get to decide which version of Silverlight you’re targeting. We saw something similar when creating a Silverlight Navigation Application.

For this project, we’ll stick with version 4 of Silverlight.  Keep in mind that if you author a Silverlight 4 project, the client will need to download Silverlight 4.  If you’re curious about what specific changes were made between Silverlight 3 and Silverlight 4, you can take a look at the article:  Ensuring that Your Silverlight Applications Work with Silverlight 4.  Note the “quirks” mode, in which the Silverlight 4 runtime can behave like Silverlight 3, to avoid breaking applications that targeted version 3.

Here’s what the solution looks like, after the wizard creates it.  Pretty simple.

The obvious question is: how is this different from a standard class library, that you might use with Win Forms or a WPF application?  If we just create a standard class library and then compare the project that we get with our Silverlight Class Library,we see basically the same thing–an empty DLL containing a single class.

One real difference that you’ll notice is related to which assembly references are included in the project by default.  Take a look at the projects shown below.  On the left is a standard C# class library.  On the right is a Silverlight Class Library.  (Nevermind that I’ve changed the default class from “Class1” to “Cat”.

You’ll see some similarities and some differences.  The main thing to remember is that the Silverlight project is built against the Silverlight versions of all of these libraries, rather than the standard .NET Framework versions.  You can convince yourself that there is more than one set installed one your machine by looking at the directory “C:\Program Files\Reference Assemblies\Microsoft\Framework”.  Make note of the .NET Framework and Silverlight sub-directories, with various version numbers under each sub-directory.  If you drill down into the sub-directories, you’ll see the actual .NET Framework or Silverlight DLLs.  There is a completely different set of DLLs for each platform.  As an example of the differences, note that there is a System.Windows.Forms.dll in the .NET Framework directories, but not in the Silverlight directories.

One other thing to remember is that even when you see the same file in both .NET Framework and Silverlight directories, the content of the file may be different.  For example, the Silverlight version of System.Core doesn’t include the System.Diagnostics namespace, because for Silverlight, it’s implemented in mscorlib instead.

There is another important difference between the different versions of the framework–the Silverlight versions are much smaller than their full .NET Framework counterparts.  Remember that Silverlight needs to be deployed over the web, so its copy of the Framework is considerably smaller than the full .NET Framework.  If you just look on a system that has both and compare total size of the files in each directory, you’ll see:

  • Version 3.0 of the .NET Framework = 84.4MB
  • Version 4.0 of the .NET Framework = 189MB
  • v3.0 of Silverlight framework = 20.6MB
  • v4.0 of Silverlight framework = 24.6MB

So the Silverlight runtime is only about 13% of the size of the full .NET 4.0 Framework.  Pretty amazing.

Adding Some Code

Now let’s add some functionality to our Silverlight class library.  We’ll create a Cat class that we can later use in our Silverlight application.  Here’s the implementation:

public class Cat
{
    public string Name { get; set; }
    public string Motto { get; set; }
    public uint NumLives { get; set; }

    public Cat() { NumLives = 9; }

    public void Die()
    {
        if (NumLives > 0)
            NumLives--;
        else
            throw new Exception("This cat is already dead");

        return;
    }
}

Building the Library

What do we get when we build the library that contains an implementation of our Cat class?  As it turns out, we just get a regular .NET DLL.  Let’s take a look at what shows up in our \bin directory:

Take a look at what’s in this directory.  Using the IL DASM tool (Intermediate Language Disassembler, which can be found in Windows 7 at C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin), crack open the DLL and you’ll see:

We could also look at the manifest for our Silverlight class library and compare it with manifest for a .NET 4.0 version.  If you did this, you’d see that the main difference is the version of mscorlib that they reference.  .NET 4.0 class libraries reference version 4.0.30319 of mscorlib and Silverlight 4 class libraries reference version 2.0.50727.  This could be because of the timing of the Silverlight and .NET 4.0 releases–Silverlight 4 just ended up using the version of mscorlib that shipped with .NET 3.5.  Or maybe it’s the case that Silverlight doesn’t make use of any of the new functionality added to .NET 4.0.

The bottom line here is that both class libraries (.NET 4.0 and Silverlight) are structurally the same–just .NET DLLs.  But they are not interchangeable, because they depend on different versions of various .NET DLLs.

Using Our Class

Now let’s actually use the class that we just created.  We’ll go back to our SilverlightClassLibrary1 solution and add a Silverlight Application project.  We leave the option turned on that automatically generates an ASP.NET Web Application project.

The solution now looks like this:

So we have a web project that loads our Silverlight application and we now want to change the application to make use of our class library.  Specifically, we’ll add some code that makes use of our Cat class.

On the MainPage control in the Silverlight application, we switch to the Events tab in the Properties window and double-click to the right of the Loaded event, to generate an event handler for Loaded.

Next, we add a reference to SilverlightClassLibrary1 in the Silverlight application.  In the Solution Explorer, we right-click the References folder in the SilverlightApplication1 project and select Add Reference.  Then we just click on the Project tab and select SilverlightClassLibrary1.  Now we see the class library show up as a reference in the Silverlight application.

Next, we open MainPage.xaml.cs in the code editor and add a using statement at the top for our class library.   Then we add code to the Loaded event to create a new instance of a Cat.  MainPage.xaml.cs now looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightClassLibrary1;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        Cat _garfield;

        public MainPage()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _garfield = new Cat();
            _garfield.Name = "Garfield Arbuckle";
            _garfield.Motto = "Carpe Catnip";
        }
    }
}

Now let’s do something with our cat.  We go back to the design surface for the main window, add a new button, change the Content property to “Kill” and then double-click on the button to create an instance of the button’s Click event.  The code for the Click event is pretty simple–we just tell Garfield to die.

private void button1_Click(object sender, RoutedEventArgs e)
{
    _garfield.Die();
}

Now we’ve created a Cat and we have a button that lets us kill the cat (repeatedly).  As a next step, let’s just add a label on the main page that indicates how many lives the cat has left.  After you drag the label onto the design surface, it will look like this:

Let’s think about the best way to display the number of lives.  One way would be to add a line in button1_Click() that resets the label’s Content property every time we invoke the Die method.  But the drawback of this is that if we have other places in our code that cause our cats # lives to decrement (or increment), we’d have to remember to add code to all of those places to also update the label.  Better than manually updating the label would be to just “bind” it to Garfield’s NumLives property.  We’d like the label to change automatically whenever Garfield’s NumLives property changes.

Doing the data binding involves two main steps.  The first is to specify the binding of the label’s Content property.  We can set up the binding in XAML, specifying the binding Path, which indicates which property of the Cat object we want to bind this label to.  Below is the XAML for our main page, showing both the Button and the Label.  Note the value of the label’s Content property, with the binding path specified.

<Grid x:Name="LayoutRoot" Background="White">
    <Button Content="Kill" Height="23" HorizontalAlignment="Left" Margin="153,69,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    <sdk:Label Height="28" HorizontalAlignment="Left" Margin="165,26,0,0" Name="label1" VerticalAlignment="Top" Width="63" Content="{Binding Path=NumLives}" />
</Grid>

(For more info on data binding in Silverlight, see this Silverlight Data Binding article in MSDN).

There’s one more thing that we have to do to get the binding to work.  We need to also specify the object that we’re binding to.  In our case, the object is the instance of the Cat that we created in the Load event–Garfield.  We do this by setting the DataContext property of our main page.  Really, we want to set the DataContext property of the Label.  But we can just set the data context for the whole page and then that data context will automatically get used for all controls on the page (if they don’t set their own data context).  This would be handy if we plan on adding other controls later that are also bound to Garfield.  We do this in our Loaded event:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    _garfield = new Cat();
    _garfield.Name = "Garfield Arbuckle";
    _garfield.Motto = "Carpe Catnip";

    // Set data context of main grid to be our Cat object
    LayoutRoot.DataContext = _garfield;
}

Now let’s try running our application.  When the Silverlight application starts up in a web browser, it looks like this:

Hey, that looks like success.  Our Label appears to have been bound to the NumLives property, because it’s showing that Garfield has 9 lives.

But what happens when we press the Kill button?  When I try it, nothing happens.  Inside the Cat object, the NumLives property should be decrementing.  And our Label should reflect the new value, since we set up the data binding.  But the label doesn’t appear to be changing.  Why not?

As it turns out, the NumLives property is changing internally whenever we kill Garfield.  But our client–the MainPage–is not being told that the property changed.  So the data binding isn’t fully functional and the label does not update.

We missed one small step when we set up data binding on our Cat object.  To properly bind to an object’s property, we need our Cat class to implement the INotifyPropertyChanged interface and to fire the PropertyChanged event whenever the NumLives property changes.  (For more info on INotifyPropertyChanged, see the MSDN documentation for INotifyPropertyChanged Interface).

To start with, we change our Cat class definition to indicate that we plan to implement the INotifyPropertyChanged interface.

public class Cat : INotifyPropertyChanged

If you try to build the project now, you’ll get an error telling you that you haven’t implemented the PropertyChanged event.  This is because when we inherit from INotifyPropertyChanged, we’re agreeing to a contract that says we’ll implement the interface’s methods.  In this case, it means that we’ll implement the PropertyChanged event.

The easiest way to implement the event is to right-click on INotifyPropertyChanged and select “Implement Interface”.  Then select “Implement Interface” again.

When you do that, you’ll get the following event declaration added to your code:

public event PropertyChangedEventHandler PropertyChanged;

Next, we need some code that will fire this event.  So we create a little method that we can use throughout our class.  I added the following code after the event declaration:

public void OnPropertyChanged(PropertyChangedEventArgs e)
{
    if (PropertyChanged != null)
        PropertyChanged(this, e);
}

Finally, we need to fire this event whenever the value of NumLives property changes.  We do this by invoking the OnPropertyChanged method that we just implemented.  We also have to pass the name of the property that is changing when we fire the event.  Here is the updated code for the NumLives property:

private uint _numLives;
public uint NumLives {
    get { return _numLives; }
    set
    {
        _numLives = value;
        OnPropertyChanged(new PropertyChangedEventArgs("NumLives"));
    }
}

That should be everything that we need to get the data binding to work.

For reference, here is the full source code listing for our Cat class:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace SilverlightClassLibrary1
{
    public class Cat : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }

        public string Name { get; set; }
        public string Motto { get; set; }

        private uint _numLives;
        public uint NumLives {
            get { return _numLives; }
            set
            {
                _numLives = value;
                OnPropertyChanged(new PropertyChangedEventArgs("NumLives"));
            }
        }

        public Cat() { NumLives = 9; }

        public void Die()
        {
            if (NumLives > 0)
                NumLives--;
            else
                throw new Exception("This cat is already dead");

            return;
        }
    }
}

Killing the Cat

Finally, let’s run our application.  Now when we start up the application and run it in browser, we see the # lives indicator decrement whenever we click the Kill button.  Success!

Deployment

Let’s look at one more thing.  When we create and use a Silverlight class library and then deploy and run our Silverlight application, what is really going on?  We saw earlier that we’re creating a DLL.  But what actually happens to that DLL when some client hits the web page that hosts our Silverlight Application?

In Windows Explorer, let’s find the project directory and drill down until we see the ClientBin directory under the SilverlightApplication1.Web project.

In ClientBin dir, we see just one file: SilverlightApplication1.xap.  This is the XAP file that represents our Silverlight application and which gets deployed by the web server whenever a client loads the hosting ASP.NET page.

Let’s take a look inside the .xap file.  (Just rename the extension to .zip and double-click to open the .zip archive).  Here’s what we see:

The important components to notice are SilverlightApplication1.dll and SilverlightClassLibrary1.dll.  SilverlightApplication1.dll is the main DLL that contains our Silverlight application (MainPage class, derived from Silverlight UserControl).  SilverlightClassLibrary1.dll is the output of our SilverlightClassLibrary1 project–a DLL that contains our Cat object.  So we see that when our Silverlight application is deployed, the referenced class library is also deployed to the client, since it is included in the .xap file.

Finally

Now we’ve seen the main purpose of the Silverlight Class Library.  You can create a separate DLL that contains one or more classes that your Silverlight application is going to make use of, when running on the client.  Since the Silverlight application makes use of the class library, the class library is deployed to the client along with the main Silverlight application.

Silverlight 4 Project Types part I – Silverlight Application

Ok, let’s take a look at the different types of Silverlight applications that you can create out-of-the-box with Visual Studio 2010.  Now that I’ve installed Visual Studio 2010 and Silverlight 4, I want to take a quick spin through each of the different project types that the New Project wizard makes available.

After firing up Visual Studio 2010, I click on the New Project link and then select the Silverlight project type under C#.  Here’s the default list that I see:

  • Silverlight Application
  • Silverlight Navigation Application
  • Silverlight Class Library
  • Silverlight Business Application
  • WCF RIA Services Class Library
  • Silverlight Unit Test Application

I’d like to take a quick look at each project type, looking at the pieces that make up the project and then thinking a little bit about when to use that particular project type.  As I walk through the various project types, I’d also like to think a little bit about the ecosystem in which the Silverlight application lives.  In other words, what other components might you typically create when designing a solution of that type?

I also want to think a little bit about the tooling.  What tools would you typically use to work on the project that you’re creating?  Would Visual Studio 2010 alone be sufficient?  Or would you spend a lot of time working in Blend?  What about SQL Server 2008?

The Silverlight Application

The first project type—the Silverlight Application—looks like it might be the same thing that I created with Visual Studio 2008 and Silverlight 2, back in the Hello Silverlight World, Part 1 post.

The New Application dialog that we see next is very similar to what I saw with Visual Studio 2008 and Silverlight 2.  As before, we have to host our Silverlight application somewhere.

Notice that this time we have one additional project type that we didn’t have before—an ASP.NET MVC Web Project.  So we can basically go with a “classic” ASP.NET web site or an MVC web site.

The default is to host Silverlight in a new ASP.NET web application project.  But if I uncheck the first checkbox, I get a simple Silverlight project with no containing web site:

If you go this route and then press F5 to “run” your Silverlight application, Visual Studio will just create a test .html page in which to host your Silverlight control.

If you take a look at this page, you’ll see a simple HTML page with a familiar <object> tag hosting the Silverlight control.  (See my post on the Lifecycle of a Silverlight Control for more details on how this is done).

If we instead go with the defaults on the New Silverlight Application dialog (host the Silverlight Application in a new ASP.NET Web Application project), we end up with a simple ASP.NET project that contains both .html and .aspx pages hosting the new Silverlight control.

In either case, .html or .aspx, your Silverlight application is embedded in the web page

<div id="silverlightControlHost">
 <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
 <param name="source" value="ClientBin/SLApp1.xap"/>
 <param name="onError" value="onSilverlightError" />
 <param name="background" value="white" />
 <param name="minRuntimeVersion" value="4.0.41108.0" />
 <param name="autoUpgrade" value="true" />
 <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.41108.0" style="text-decoration:none">
 <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
 </a>
 </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>

As I describedin The Lifecycle of a Silverlight Control, this <div> tag embeds your Silverlight application (control) into a web page using the application/x-silverlight-2 MIME type.  This MIME type now maps to the AgControl.AgControl.4.0 class, implemented in npctrl.dll, which can be found in C:\Program Files\Microsoft Silverlight\4.0.41108.0.

Visually, the pieces of the puzzle look like this (from MSDN article on Silverlight 4.0 Application Services):

So as before, a Silverlight application is managed code that runs in the context of a browser plugin.  Here’s how things work when your browser renders a page containing a Silverlight control:

  • Browser renders HTML  from .html page (or generated HTML from ASP.NET page)
  • Browser sees <object> tag for application/x-silverlight-2 MIME type and fires up the Silverlight plug-in
  • Silverlight plug-in loads the Silverlight core services
  • Silverlight plug-in loads the Silverlight CLR, which creates an AppDomain for your application
  • .xap file containing your Silverlight application is downloaded from the server
  • Your application manifest is loaded/read (from AppManifest.xaml, in .xap)
  • Your main Silverlight application DLL is loaded (from .xap)
  • Silverlight CLR instantiates your Application object and fires its Startup event
  • Your application’s Startup event creates a new instance of your main page (a Silverlight UserControl)
  • Your main page (e.g. MainPage in wizard-generated project) renders itself by reading/loading its .xaml file

Voila.  At the end of all this, you get a Silverlight Application rendered in an ASP.NET web page.  In our case, having generated everything using the Project Wizard, we can just press F5 to run the application–launching a browser window and loading your auto-generated ASP.NET page.  It looks like this (the Silverlight application has the green background):

The XAP Payload

One final topic to cover quickly is–what exactly does the downloaded .xap file contain?  In our wizard-generated test project, you’ll find a ClientBin directory, which contains the compiled Silverlight application in a .xap file.  In our case, it’s named SLApp1.xap.

If you just rename the .xap file as SLApp1.zip and double-click on it, you can see what it contains:

The main pieces here are the application manifest, which tells the Silverlight runtime what object to start up first, and the assembly in which that object lives.  The .xap file also contains the assembly (SLApp1.dll) that contains our actual code.

The .xap file also contains some dependent DLLs, which are sent down to the client as part of the .xap package.

Wrapping Up

That’s all there is to a basic Silverlight Application.  Next time, I’ll take a look at the Silverlight Navigation Application, which lets us create a complete Silverlight application with multiple pages, rather than a single user control.

Silverlight Gets Full-Fledged Designer Support in Visual Studio 2010

Trying to wrap my head around the current situation with Silverlight 2 and 3 support in Visual Studio 2008 and 2010, I’m confused enough that I feel like shouting out a line from my daughter’s favorite Dr. Suess book, Fox in Socks:  “Now wait a minute, Mr. Socks Fox”!!

It is a little confusing.  But I think I now understand who supports what and I’ll take a stab at jotting it down, for future reference.

Visual Studio 2008 SP1

Visual Studio 2010

  • Supports both Silverlight 2 and Silverlight 3
  • Can install both on the same development machine
  • Each Silverlight project targets one of the two Silverlight versions
  • Silverlight 2 — need to install the Silverlight 2 SDK manually
  • Silverlight 3 — install manually

Ok, as far as I can tell, that’s the current situation.

This basically boils down to two questions:

  • Do I want to develop in Silverlight 2 or Silverlight 3?
    • Silverlight 2 is more stable and is officially released
    • Silverlight 3 (beta) — new controls, navigation framework, out-of-browser support
  • Which version of Visual Studio do I want to use?
    • VS 2008 — easier install experience, stable/released
    • VS 2010 — improved tooling for Silverlight & WPF

The last point is what I want to talk about.  Notice that improved tooling for Silverlight is a feature of Visual Studio, not of Silverlight itself.  Visual Studio 2010 finally gives us full design-time drag-and-drop support for Silverlight.

Let’s see what this looks like.  But first, let’s go back and take a look at the Silverlight design-time experience in Visual Studio 2008.  (I’m using Silverlight 3 here).

The Bad Old Days – Visual Studio 2008 SP1

Until now, Silverlight developers haven’t had the most basic tooling enjoyed by even the lowliest VB6 developers.  Namely — the ability to drag and drop controls onto a design surface and set their properties right in the designer.

Specifically, here’s what you couldn’t do.  If you look at the split window for Silverlight controls in the designer, you’ll notice that the upper pane is labeled “Preview”.

Preview Pane

This was a “Preview” pane because all it could do was to render your XAML on the screen as a preview of how it would eventually look in your Silverlight application.  You couldn’t drag controls onto this surface.  You also couldn’t select any controls in order to reposition them or to set their properties.

In Visual Studio 2008, if you try dragging Silverlight controls onto this Preview window, you just get a big fat “don’t do this” icon.  Even sadder, you can’t select any controls.  If you look at the properties window in Visual Studio, you just see the following sad message:

No Property Editing

Thankfully, you could at least drag and drop controls down into your XAML.  This would at least insert the proper XAML tags for the control that you’d selected.  But you just got an empty tag.  (In the picture below, I’ve just dragged a Button into my XAML).

Drag Into XAML

And, although we weren’t able to set property values in the property editor, there was some consolation in that Intellisense worked in the XAML code.

Intellisense in XAML

So the Silverlight development environment was workable, but not ideal.  Also, you could always author/edit your UIs in Expression Blend.  But then there was a big learning curve to tackle.

Enter Visual Studio 2010

In Visual Studio 2010, we finally have full designer support for Silverlight applications.  In the picture below, I’ve just dragged a Button from the toolbox onto the design surface.

Silverlight Design Surface

It makes me want to weep.  (Who would have thought that a developer would be so happy with being able to drag a button onto a form)?

Not only did the designer let me drag the button onto a design surface, but now it actually gives me a little more than an empty/default Button tag in my XAML.  I actually get a sensibly configured button object, with a reasonable size and a preset label.  Also notice that the upper pane is now labeled “Design”, rather than “Preview”.

But don’t weep yet.  It gets better.  You can actually left-click to select the button in the designer.  When you do this, you’ll see that you can now actually set properties for the button in the property window.

Property Window

Now you may weep or cheer, depending on your particular emotional reaction.

You’ll also notice that you can now click on the little event icon and then double-click to generate event handlers in your code-behind.  (As opposed to using Intellisense in the XAML to discover relevant events).

Event Properties

This is great, although I still don’t understand why there is no dropdown in the properties window to select the individual controls.  Is there a good reason why neither WPF or Silverlight applications allow selecting individual controls from the property window?

Also note that all of the above is possible in both Silverlight 2 and Silverlight 3.

Where Are We?

So clearly, Silverlight is now a full-fledged citizen in Visual Studio, with full tooling.  This may not seem like much, but for anyone who works with Silverlight a lot, it will make a huge difference.  Not to mention a much shallower learning curve for developers coming up to speed with Silverlight.

Mr. Socks Fox wasn’t spouting blibber blubber after all.

Hello Silverlight World, part 3 – The Lifecycle of a Silverlight Control

Ok, continuing with building a simple Wizard-generated Silverlight application and then staring at it to see how it works..  Last time, I talked about the Application object in Silverlight vs. WPF.  This time I’ll continue looking at the pieces in the sample Silverlight application, looking at the Page class that was generated and what happens to this control at runtime on a client machine.

Pages vs. Windows

I pointed out a couple of posts back the interesting difference here, just in the terminology.  In Silverlight, your main design surface is a “page”, which sort of comes from the fact that you’re serving up a series of web “pages” with some content in each.  (Nevermind that a Silverlight control can never be an entire page by itself, but must be hosted in an .html or .aspx page).  In WPF, the main design surface is a “window”, which seems appropriate because it runs in a bordered window.

Silverlight’s UserControl Class

In Silverlight, you render all of your content in a class that derives from System.Windows.Controls.UserControl.  When you use the wizard to generate a Silverlight application, it creates a class named Page, e.g.:

    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }
    }

One other quick thing to look at, is what else we’re doing in our child class at runtime, beyond what we get in the UserControl base class.  If you build your Silverlight application and then look at the other half of the partial class, i.e. the generated code in Page.g.cs, you’ll see:

    public partial class Page : System.Windows.Controls.UserControl {

        internal System.Windows.Controls.Grid LayoutRoot;

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Windows.Application.LoadComponent(this, new System.Uri("/SilverlightApplication2;component/Page.xaml", System.UriKind.Relative));
            this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
        }
    }

So, like our App class that derived from System.Windows.Application, the Page class defines an InitializeComponent method that just calls the static Application.LoadComponent method, which just constitutes an object in question, based on its .xaml.  So for both our App and our Page class, the class is getting instantiated and then InitializeComponent causes it to finish initializing by reading the associated .xaml file and then setting properties and creating child objects based on what is in the .xaml.  This is the magic fairy dust that allows .xaml to work–at runtime, the .xaml is just interpreted and associated objects are created.

The second half of this process is happening at the point where we are setting the LayoutRoot property.  The wizard generated some .xaml for our page that has a Grid as the topmost element, with the name “LayoutRoot”.  Then, at code generation time, we get a Grid object declared and then point it to the object that we loaded from the .xaml.  (Using the FindName method).

Where Are We?

Ok, so we’ve seen that there really isn’t much to our Page class, other than the fact that it constitutes itself from the .xaml.  But what is really going on at runtime, on the client where this control will be hosted?

The Lifecycle of a Silverlight Control

To answer that, let’s just walk through the entire lifecycle of our Silverlight control, starting from how the code is downloaded from the server and continuing on to how the Silverlight runtime on the client’s machine loads and renders the control.

It All Starts With a Web Page

plugin-model

Here’s a diagram from the MSDN documentation that gives us the big picture.  Your Silverlight control runs in a managed environment (the Silverlight Common Language Runtime), which in turn runs in the context of a browser plug-in.  And that plug-in runs in the context of a web page that is downloaded from a web server to the client machine.

Remember that when we created our Silverlight application using the Visual Studio wizard, it also generated an ASP.NET web application in which to host our control.  (e.g. SilverlightApplication1.Web).  If you look at the web application, you’ll see that we’ve been given a couple examples of pages hosting our Silverlight control.  Specifically, you’ll see an .aspx and an .html page.  For now, let’s look at the more basic of the two–the .html page.

If you open this test page, e.g. SilverlightApplication1TestPage.html, and scroll to the bottom, you’ll see an <object> tag that mentions Silverlight:

    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"><param name="source" value="ClientBin/SilverlightApplication1.xap"/><param name="onerror" value="onSilverlightError" /><param name="background" value="white" /><param name="minRuntimeVersion" value="2.0.31005.0" /><param name="autoUpgrade" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
            <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
        </a>
    </object>

What we see here is a standard HTML <object> tag, which allows us to embed a 3rd party plug-in into the browser on the client’s machine.  When rendering the web page, the browser will set aside an area of the page and let the plug-in render directly to that area.  In this case, the 3rd party is Microsoft and the plug-in is Silverlight.

So here’s how things get rolling with our Silverlight control, on the client’s machine (whoever is pointing their browser at your .html page):

  • Client starts up their browser and points it at SilverlightApplication1TestPage.html (let’s assume that the test page is on a web server somewhere)
  • The .html page is downloaded from the web server to the client and the browser begins rendering the HTML content
  • The browser reaches the <object> tag, which indicates that a plugin should be loaded, started up, and allowed to render that part of the page
  • To figure out how to call the plugin, the browser uses the value of the type attribute on the object tag.
  • In our cases, this type is application/x-silverlight-2.  This is a MIME type, which maps to Silverlight 2
  • Using the MIME type, the browser loads the plugin
    • Under Windows, there is a registry entry that associates this MIME type with an ActiveX control named AgControl.AgControl, which in turn is implemented by a DLL npctrl.dll, located in C:\Program Files\Microsoft Silverlight\2.0.40115.0
    • So npctrl.dll is the actual plugin implementation–an unmanaged Windows DLL that implements the plugin API and, in turn, launches the Silverlight CLR–the execution environment in which your Silverlight control actually runs

Ok, if you were paying attention, you may have noticed something surprising in that last bullet point:  ActiveX??  Isn’t ActiveX dead and buried, now that we’re dealing with a managed environment?

Well, yes and no.  The code that we are authoring–our Silverlight control–does run in a managed environment on the client machine, in that it runs inside of the Silverlight CLR/runtime.  But the Silverlight plugin itself has to interact with the web browser and, as such, is unmanaged code that implements that standard browser plug-in API(s) that allow it to run within the browser.

So clearly, npctrl.dll is unmanaged code.  But ActiveX?  The MSDN documentation is not 100% clear on this point, but here’s what I think is going on.  npctrl.dll is both a classic Win32 DLL (non-COM), as well as an ActiveX control (COM server).  Which mode it runs in depends on the browser.   When running inside of Internet Explorer, the plug-in runs as an ActiveX control, implementing the IXcpControl COM interface.  However, when Silverlight is hosted in other browsers, like Mozilla, it implements the Netscape Plug-in API, running as a classic Win32 DLL.  (It implements functions like NP_Initialize and NP_GetEntryPoints).  [This paragraph is mostly conjecture].

Silverlight Presentation Core

silverlight-architecture

Within the Silverlight plug-in, the next layer to take control is the Silverlight Presentation Core.  You can see the Presentation Core as the bottom blue box in this diagram (also found in MSDN documentation).

The Presentation Core is responsible for rendering everything in the browser, handling user interaction, playing video, and parsing XAML.  It’s implemented in agcore.dll, which is a classic Win32 DLL.  (Not a COM server and not a .NET executable).

When your browser starts up (in Firefox, at least), both npctrl.dll (Plug-in) and agcore.dll (Presentation Core) are loaded.  The remaining Silverlight runtime libraries described below are only loaded when you actually load a page containing a Silverlight control.

Silverlight CoreCLR

After your browser has loaded the Silverlight plug-in, it does three basic things:

  • Starts up the Silverlight Common Language Runtime
  • Downloads the .xap file containing your Silverlight control and Application object from the server
  • Instantiates your Application object and loads it

The CoreCLR, or Silverlight Common Language Runtime, is the Silverlight version of the CLR that runs inside the Silverlight plug-in.  (Labeled CLR Execution Engine in the above diagram).  This is the managed environment that your Silverlight applications run inside, similar to the CLR that hosts thick-client .NET applications.

The CoreCLR is implemented in coreclr.dll, also in C:\Program Files\Microsoft Silverlight\2.0.xxxxx.0.  The CoreCLR is based on the same codebase as the desktop version of the CLR, but much smaller, and with features not required in a browser environment removed.  (In the desktop world, the equivalent DLLs are mscoree.dll and mscorwks.dll).

Note: coreclr.dll is also just a “plain old” unmanaged Win32 DLL.  It is the implementation of the .NET CLR, so it does not run in a managed environment itself.

The XAP File

Before Silverlight can run any of your code on the client machine, it has to download it from the server.  Your Silverlight application is packaged into a .xap file.  The .xap file is nothing more than a .zip file that has been renamed.  You can prove this to yourself by building your application and then renaming the resulting .xap file as a .zip file.

silverlight-application-structure

If you look at the files inside your .xap, for a typical wizard-generated Silverlight application, you’ll find two files:

  • AppManifest.xaml
  • SilverlightApplication1.dll

The AppManifest.xaml file is the application manifest, which tells the Silverlight runtime what DLLs are present in this package and which one contains the entry point, or startup object, for your Silverlight application.  For example, you might see something like the following:

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    EntryPointAssembly="SilverlightApplication1"
    EntryPointType="SilverlightApplication1.App"
    RuntimeVersion="2.0.31005.0">
  <Deployment.Parts>
    <AssemblyPart x:Name="SilverlightApplication1" Source="SilverlightApplication1.dll" />
  </Deployment.Parts>
</Deployment>

Note that the manifest tells Silverlight to load the assembly located in SilverlightApplication1.dll and that the startup object is SilverlightApplication1.App, which is the class that derives from System.Windows.Application.

Starting Up

Once the .xap file is downloaded, the CoreCLR can instantiate your object and get things started.  It does this by:

  • Instantiating an instance of your entry point type, e.g. SilverlightApplication1.App
  • Firing the Application.Startup event

Our wizard-generated Silverlight application included wizard-generated code to get everything up and running as follows:

  • During the App constructor
    • Wire a handler for the Application.Startup event
    • Call App.InitializeComponent
  • App.InitializeComponent, also wizard-generated :
  • The handler for the Application.Startup event
    • Instantiates a new Page object  (the actual Silverlight control to be displayed)
    • Sets the RootVisual property of the parent App object to point to the Page
  • During the Page constructor
    • Call Page.InitializeComponent
  • Page.InitializeComponent
    • Calls Application.LoadComponent, reconstituting the Page object from the associated XAML (BAML)

That’s really all there is to it.  At this point, through the magic of the browser plug-in architecture and the fact that the Silverlight CoreCLR is running on the client’s PC, you have a native .NET (Silverlight) application running on the client, hosted in the browser.

References

Debugging Silverlight Applications with windbg and sos.dll – 21 Aug 2008 – Tess Ferrandez
Debugging Tools and Symbols: Getting Started – Windows Hardware Developer Central
Dissecting Silverlight – 1 May 2007 – Ed Burnette
Setting a Silverlight 2 Startup Breakpoint Using WinDBG – 10 Jan 2009 – David Betz
Silverlight Application Services – MSDN
Silverlight Application Structure – MSDN
Silverlight Architecture – MSDN
Silverlight Plug-In Object Reference – MSDN

Hello Silverlight World, part 2 – The Application Object

In my last Silverlight post, Hello Silverlight part 1 – Generating the Project, I started creating a Silverlight-based Hello World application.  I described the various pieces that get created by the Project Wizard in Visual Studio 2008.  I also started comparing the Silverlight application to a wizard-generated WPF application.

Let me continue looking at the individual pieces that make up a bare-bones Silverlight application.  Maybe the convention should be to call it a “Silverlight control”, since that seems a bit more accurate.  For now, I’ll stick with Visual Studio’s terminology and call it a “Silverlight application”.

App.xaml

Like our WPF application, the main entry point of the Silverlight application is described by the App.xaml / App.xaml.cs files.  In both WPF and Silverlight, these files define a subclass of System.Windows.Application, which serves as the main object loaded at runtime.

In both WPF and Silverlight, we can look at the code in App.xaml.cs and App.g.cs (generated at build time) to get a sense of how the application gets loaded and run.  What we see is very different behavior, despite the fact that both App classes appear to derive from System.Windows.Application.

In the WPF application, here’s what happens:

  • There is an entry point named Main()
  • Main()
    • Creates an instance of the App class
    • Calls the InitializeComponent method of the App object
    • Calls the Run method of the App object
  • App.InitializeComponent
    • Sets App.StartupUri property to point to a Uri object pointing to Window1.xaml, our main window

In the Silverlight application, something very different is going on at startup:

  • There is no Main() method
  • The App constructor
    • Wires up the Application_Startup event handler to the App.Startup property
    • Wires up the Application_Exit event handler to the App.Exit property
    • Wires up the Application_UnhandledException event handler to the UnhandledException property
    • Invokes InitializeComponent
  • Application_Startup
    • Instantiates a new Page object (the class for our main page)
    • Sets App.RootVisual to point to this page object
  • InitializeComponent
    • Calls Application.LoadComponent, passing it a new Uri object pointing to App.xaml

Why is the startup behavior so radically different, between WPF and Silverlight, given that the main application appears to be inherited from System.Windows.Application in both cases?

The answer is that, while the class name and namespace are identical, the Application object in Silverlight is a very different animal than the one that is part of WPF.  Remember that the WPF application is running against an entirely different .NET Framework than the Silverlight application.  WPF is referencing/using the full .NET Framework 3.5 (with pieces from 2.0, 3.0 and 3.5), while the Silverlight application is referencing/using the Silverlight Framework, which is an entirely different set of libraries.  While much of the Silverlight framework is a subset of the WPF framework, the Application object is entirely different.

  • In WPF, the System.Windows.Application class lives in PresentationFramework.dll
  • In Silverlight, System.Windows.Application lives in System.Windows.dll

PresentationFramework.dll is part of the .NET Framework 3.0 and exists on a  client system when they install the full .NET Framework (3.0 or 3.5).  System.Windows.dll is part of the Silverlight framework and exists on a client system when they install Silverlight.

You can see this by reading the documentation (MSDN).  Or you can see how different these Application classes are by doing the following:

  • In the WPF application, open the App.xaml.cs file, right-click on Application and choose Go To Definition
    • You’ll see that the Application class has a Run method and a StartupUri property, but no RootVisual property
    • Now hover over the tab for this window in Visual Studio–you’ll see a temp filename that contains the name “PresentationFramework.dll”
  • In the Silverlight application, open the App.xaml.cs file, right-click on Application and choose Go To Definition
    • You’ll see a very different Application class, with a RootVisual property, but no Run method
    • Hover over the tab again–you’ll see a temp file name containing “System.Windows.dll”

Let’s Stop Here

That’s a good stopping point, for now.  We’ve looked just a little bit under the covers in the Silverlight application–enough to see that the main Application object loaded at runtime is very different from the object loaded in the WPF application.

Learning Out Loud

I’ve always sort of figured that this blog was a place to post things I was just learning, rather than a place to publish tutorials about technologies that I have more expertise in.

Because of the nature of our field, and the amount of new technologies that are always coming out, I’m far more interested in learning than I am in teaching.  There are already plenty of great teachers out there who are blogging, writing or lecturing.  I don’t really aspire to sell myself as a teacher of technologies—that would take far too much time and energy.

Instead, I see this blog as a forum for my attempts to learn new technologies—e.g. WPF and Silverlight.  I’m always looking for new ways to motivate myself to learn new technologies and having a blog is a good way to force myself to dive in and start learning something new.  When I realize that I haven’t posted anything for a few days, I feel the urge to start pulling together the next post.  Then, because I know I’m going to have to write about it, I find that I force myself to explore whatever the topic is in a much deeper manner than I would if I were just reading a book or attending a class.

This has been working out great so far.  I’m discouraged by how little time I have to study these new technologies.  I’d like to post far more frequently than I do.  But at least I’m gradually learning some new bits and pieces, about technologies like WPF and Silverlight.

Reminding myself of my goals also helps me to just relax and not worry so much about making mistakes.  I’m just capturing on “paper” what I’m learning, as I learn it.  Since I’m only beginning the journey of grokking whatever it is, I don’t need to worry about whether I get it right or not.

Remembering all of this led me to change the tagline of this blog.  Instead of offering up my thoughts on various topics, I now see this as “learning out loud”.  That perfectly describes what I think I’m doing—learning new stuff, stumbling through it, and capturing the current state of my knowledge so that I can come back and refer to it later.

So let the journey continue—there’s still so much to learn!