The blog of dlaa.me

Trust, but verify [Free tool (and source code) for computing commonly used hash codes!]

Internet downloads (particularly large ones) are often published with an associated checksum that can be used to verify that the file was successfully downloaded. While transmission errors are relatively rare, the popularity of file sharing and malware introduce the possibility that what you get isn't always exactly what you wanted. The posting of checksums by the original content publisher attempts to solve this problem by giving the end user an easy way to validate the downloaded file. Checksums are typically computed by applying a cryptographic hash function to the original file; the hash function computes a small (10-30 character) textual "snapshot" of the file that satisfies the following properties (quoting from Wikipedia):

  • It is easy to compute the hash for any given data
  • It is extremely difficult to construct a [file] that has a given hash
  • It is extremely difficult to modify a given [file] without changing its hash
  • It is extremely unlikely that two different [files] will have the same hash

Because of these four properties, a user can be fairly confident a file has not been tampered with or garbled as long as the checksum computed on their own machine matches what the publisher posted. I say fairly confident because there's always the possibility of a hash collision - two different files with the same checksum. No matter how good the hash function is, the pigeonhole principle guarantees there will ALWAYS be the possibility of collisions. The point of a good hash function is to make this possibility so unlikely as to be impossible for all intents and purposes.

Popular hash functions in use today are MD5 and SHA-1, with CRC-32 rapidly losing favor. Speaking in very broad terms, one might say that the quality of CRC-32 is "not good", MD5 is "good", and SHA-1 is "very good". For now, that is; research is always under way that could render any of these algorithms useless tomorrow... (For more information about the weaknesses of each algorithm, refer to the links above.)

In order for published checksums to be useful, the user needs an easy way to calculate them. I looked around a bit and didn't a lot of free tools for computing these popular hash functions that I was comfortable with, so I wrote my own using .NET. Here it is:

ComputeFileHashes
   Computes CRC32, MD5, and SHA1 hashes for the specified file(s)
   Version 2009-01-12
   http://blogs.msdn.com/Delay/

Syntax: ComputeFileHashes FileOrPattern [FileOrPattern [...]]
   Each FileOrPattern can specify a single file or a set of files

Examples:
   ComputeFileHashes Image.iso
   ComputeFileHashes *.iso
   ComputeFileHashes *.iso *.vhd

[Click here to download ComputeFileHashes along with its complete source code.]

 

Here's the output of running ComputeFileHashes on the recently released Windows 7 Beta ISO images. Anyone can verify the checksums below on the MSDN Subscriber Downloads site. (Note: You need to be a subscriber to download files from there; everyone else can download from the official Windows 7 link.)

C:\T>ComputeFileHashes.exe "M:\Windows 7\*"

M:\Windows 7\en_windows_7_beta_dvd_x64_x15-29074.iso
CRC32: 8E2FAD39
MD5: 773FC9CC60338C612AF716A2A14F177D
SHA1: E09FDBC1CB3A92CF6CC872040FDAF65553AB62A5

M:\Windows 7\en_windows_7_beta_dvd_x86_x15-29073.iso
CRC32: AABA5A48
MD5: F9DCE6EBD0A63930B44D8AE802B63825
SHA1: 6071184282B2156FF61CDC5260545C078CCA31EE

One of the things that was important to me when writing ComputeFileHashes was performance. Nobody likes to wait, and I'm probably even less patient than the average bear. One of the things I wanted my program to do was take advantage of multi-processing and the multi-core CPUs that are so prevalent these days. So ComputeFileHashes runs the three hash functions in parallel with each other and with loading the next bytes of the file. Theoretically, this can take advantage of four different cores - though in practice my limited testing suggests there's just not enough work to saturate them all. :)

While I paid attention to performance at a macro level (i.e., algorithm design), I didn't worry about it at a micro level (i.e., focused optimization). And I used .NET of all things. (Cue the doubters: "ZOMG, EPIC FAIL!!") If it uses .NET, it must be slow, right? Well, let's do the numbers:

  • I took some informal measurements of the time to compute hashes for the Windows 7 Beta x64 ISO image. ComputeFileHashes took just under 60 seconds to compute the CRC-32, MD5, and SHA-1 hashes of the 3.15 GB file on my home machine. Not instantaneous by any means, but also pretty reasonable for that amount of data.
  • Next up was my favorite program ever, Altap Salamander. I use Salamander for all my file management and it comes with a handy plugin for calculating/verifying checksums. Salamander is fully native code, so it should have a distinct performance advantage. Salamander took about 40 seconds to compute the CRC-32 and MD5 checksums in a single pass. This performance is noticeably better than ComputeFileHashes's, but it also doesn't include SHA-1 which is probably the most computationally intensive algorithm. I doubt adding SHA-1 would double the time, but it would almost certainly take longer. It's hard to balance missing features against better performance, so maybe this one is too close to call. :)
  • Last up was an internal tool I had called gethash. gethash is also native code and supports MD5, SHA-1, and some other hash types - but not CRC-32. However, gethash computes only one checksum a time. So I ran it once for SHA-1 in a time of just over 35 seconds and again for MD5 for another time of just over 35 seconds. The total time for gethash was therefore about 70 seconds and just like before we're missing one of the checksum types. In this case, one could argue that ComputeFileHashes wins the race because it's 10 seconds faster and delivers more value. Of course, if you only need one type of checksum, then you don't care that ComputeFileHashes generated others and gethash can do a single checksum in close to half the time it takes ComputeFileHashes. Again, no clear winner for me.

So depending on how you want to look at things, ComputeFileHashes is either the best or the worst of the lot. :) But recall that we're pitching an unoptimized .NET application against two solid native-code implementations. ComputeFileHashes pretty clearly held its ground and I'd say the doubters don't have much to complain about here.

Implementation notes:

  • .NET includes the HashAlgorithm abstract class and a variety of concrete subclasses for calculating cryptographic hashes. MD5 and SHA-1 are implemented by the Framework along with a handful of other useful hash functions. (In fact, it's trivial to add support for another HashAlgorithm to ComputeFileHashes simply by editing a table in the source code.) CRC-32 is not part of the Framework (due, I suspect, to its weaknesses), so I wrote my own CRC-32 HashAlgorithm subclass. I'll post more about this tomorrow.
  • The most efficient multi-hashing implementation would probably update each algorithm together as bytes are read from the file. However, the overhead of doing that with the .NET HashAlgorithm implementation (which sensibly expects blocks of data) seemed prohibitively expensive - and impractical to parallelize. An alternative would be to let different threads hash the complete file on their own. This parallelizes easily, but because the algorithms operate at different speeds, they'd soon be reading different parts of the file - and the disk thrashing would probably ruin performance. So I went with a compromise: ComputeFileHashes loads a 1 MB chunk of the file into memory, lets each of the algorithms process that block to completion on separate threads, then loads the next 1 MB of data and repeats. There's going to be some wasted time after the fastest algorithm completes and the slowest is still working, and there's probably some memory cache thrashing (for similar reasons as the disk) - but as the numbers above indicate, the performance of this approach is really quite reasonable. Of course, it's entirely possible that a different buffer size that would be even faster - so if you do some testing and find something better, please let me know! :)
  • ComputeFileHashes creates dedicated Threads for each of the hash functions it uses. Those threads stay around for the life of the application and are synchronized by a general-purpose helper class I wrote, WaitingRoom. I'll blog more about this in a couple of days.

ComputeFileHashes is a simple tool intended to make verifying checksums easy for anyone. I've wanted a good, fast, free, all-in-one solution I could trust for some time now, and the recent release of Windows 7 finally prompted me to write my own. I hope others to put ComputeFileHashes to use for themselves - perhaps even for the Windows 7 Beta! :)

The source code IS the executable [Releasing CSI, a C# interpreter (with source and tests) for .NET]

A few years ago I found myself spending a lot of time writing batch files to perform a variety of relatively simple tasks. For those who aren't familiar, you can do some surprisingly powerful things with batch files - but it usually involves a lot of trickery and arcane knowledge. I wanted a simpler way of doing things, but I didn't want to create a bunch of compiled executables and lose the elegant, easy-to-modify transparency that batch files offer. These days, I'd probably look to PowerShell for the solution, but back then there was no such thing...

What I did have was the power of .NET and some inspiration from a coworker's tool that was able to take .NET 1.1 source code and execute it "on the fly" without the need for compilation. What I did not have was something similar for .NET 2.0 or access to the source code for that tool (because the author had left the company). So I wrote my own:

============================================
==  CSI: C# Interpreter                   ==
==  Delay (http://blogs.msdn.com/Delay/)  ==
============================================


Summary
=======
CSI: C# Interpreter
     Version 2009-01-06 for .NET 3.5
     http://blogs.msdn.com/Delay/

Enables the use of C# as a scripting language by executing source code files
directly. The source code IS the executable, so it is easy to make changes and
there is no need to maintain a separate EXE file.

CSI (CodeFile)+ (-d DEFINE)* (-r Reference)* (-R)? (-q)? (-c)? (-a Arguments)?
   (CodeFile)+      One or more C# source code files to execute (*.cs)
   (-d DEFINE)*     Zero or more symbols to #define
   (-r Reference)*  Zero or more assembly files to reference (*.dll)
   (-R)?            Optional 'references' switch to include common references
   (-q)?            Optional 'quiet' switch to suppress unnecessary output
   (-c)?            Optional 'colorless' switch to suppress output coloring
   (-a Arguments)?  Zero or more optional arguments for the executing program

The list of common references included by the -R switch is:
   System.dll
   System.Data.dll
   System.Drawing.dll
   System.Windows.Forms.dll
   System.Xml.dll
   PresentationCore.dll
   PresentationFramework.dll
   WindowsBase.dll
   System.Core.dll
   System.Data.DataSetExtensions.dll
   System.Xml.Linq.dll

CSI's return code is 2147483647 if it failed to execute the program or 0 (or
whatever value the executed program returned) if it executed successfully.

Examples:
   CSI Example.cs
   CSI Example.cs -r System.Xml.dll -a ArgA ArgB -Switch
   CSI ExampleA.cs ExampleB.cs -d DEBUG -d TESTING -R


Notes
=====
CSI was inspired by net2bat, an internal .NET 1.1 tool whose author had left
Microsoft. CSI initially added support for .NET 2.0 and has now been extended
to support .NET 3.0 and .NET 3.5. Separate executables are provided to
accommodate environments where the latest version of .NET is not available.


Version History
===============

Version 2009-01-06
Initial public release

Version 2005-12-15
Initial internal release

[Click here to download CSI for .NET 3.5, 3.0, 2.0, and 1.1 - along with the complete source code and test suite.]

 

Using CSI is quite simple. Here's an example from the release package:

C:\T\CSI>TYPE Samples\HelloWorld.cs
using System;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello world.");
    }
}

C:\T\CSI>CSI.exe Samples\HelloWorld.cs
Hello world.

And if you use the included batch files to register the .CSI file type (more on this in the notes below), it's even easier:

C:\T\CSI>TYPE Samples\Greetings.csi
using System;

public class Greetings
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello {0}", string.Join(" ", args));
    }
}

C:\T\CSI>Samples\Greetings.csi out there world.
Hello out there world.

 

Notes:

  • Surprisingly, it's fairly straightforward to do what CSI does thanks to the CSharpCodeProvider class that's part of .NET. (In fact, the majority of the code for CSI is related to processing arguments, managing the display, and handling errors!) Behind the scenes, there's no real magic: CSharpCodeProvider is just a wrapper for the C# compiler which generates a temporary assembly that CSI calls into. Everything should work exactly the same under CSI as it would if compiled normally - the only difference is the convenience. :)
  • I hinted at the benefits of avoiding compilation above, but wanted to explain a bit more. In the usual way of doing things, there is typically (at least) a .CS file and a .EXE file for each tool used by, say a build process. The build process runs the .EXE file, and people refer to the .CS file. If anything ever needs to be changed, someone updates the .CS file, recompiles to generate a new .EXE, and checks both files in together. Usually... But sometimes they forget and only check in the .EXE - or there's some other .EXE-only modification that throws the synchronization of the two files out of whack and then it's just a mess to understand what's going on because the source code no longer matches the executable. CSI avoids that problem by allowing the build process to "run" the .CS file directly. Because there's only one file to manage, there's no chance of it getting out of sync!
  • Two simple scripts are included that can be used to RegisterCSI.cmd or UnregisterCSI.cmd. When run with administrative privileges, these scripts set up (or remove) a file association for .CSI files (which are just renamed .CS files) that automatically invokes CSI for the specified file. So, as shown in the earlier example, it's possible to run C# code files by name in a command window or by double-clicking them in the Windows Explorer!
  • There's a separate version of CSI compiled for each major .NET version that's in use today: 1.1, 2.0, 3.0, and 3.5. Aside from some minor functional limitations with the 1.1 version (due to non-existent features in that version of .NET), they're all the same CSI with the same options, etc.. The most obvious difference is the list of default assemblies included by the -R option: each version matches what Visual Studio 2008 provides as the default set of assemblies for a new project targeting the corresponding version of the Framework. The other big difference is that the .NET 3.5 version of CSI uses the C# 3.0 compiler (which can be a little tricky to do until someone shows you how), so it also supports new language features like var and all the LINQy syntax goodness that's available in .NET 3.5.
  • Editing standalone .CS files can be a bit annoying because the lack of an associated .CSPROJ file means that Visual Studio's IntelliSense isn't available. So I'll usually begin by creating a project in Visual Studio, taking advantage of its rich editing and debugging facilities to get everything working the way I want - then I pull out the resulting .CS file and run it with CSI. If there are any subsequent modifications to the code, they're usually trivial enough that the lack of IntelliSense isn't an issue. Alternatively, you could create a new project and add a link to the existing file in order to enable IntelliSense. OR you could use something like Snippet Compiler which offers a surprisingly rich Visual Studio-like editing and execution environment (with IntelliSense!) and works well with standalone .CS files.
  • Given that I've already mentioned PowerShell, what's the point of CSI? Well, maybe there isn't one... :) But I think there's still value here - even in a PowerShell world. (In fact, what prompted me to release CSI was an internal request to add support for .NET 3.5, so it seems at least one other person agrees with me.) Aside from knowing a bit about PowerShell and how it works, I haven't used it, so I won't try to do a feature comparison here. Some of the things PowerShell does are very cool and quite useful - and I think it's considerably better than .CMD files for automating typical tasks. Also, I love that it's tightly integrated with the .NET Framework. That said, it's another "language" to learn and not everybody has the time for that. Additionally, I don't think the current development and debugging options are quite as rich as Visual Studio already is. And PowerShell isn't available everywhere, whereas CSI offers a no-touch, install-free solution anywhere the .NET Framework can be found. Lastly, CSI is small (really small!) and very simple.
  • Though its name bears passing resemblance to a popular TV series, that's unintentional: once you know the C# compiler is named CSC.exe, it's obvious the C# interpreter should be named CSI.exe.

 

CSI was a fun project in its day and I've done quite a bit with it that would have been fairly tedious otherwise. Today's world offers plenty of alternatives - but if you're comfortable with C# and prefer to stick to one language for all your programming needs, CSI is pretty handy to have around. Because you never know when the urge to code will strike! :)

Yummier pies! [A technique for more flexible gradient styling of Silverlight Toolkit pie charts]

One of the goals of Charting for the Silverlight Toolkit is to enable rich, flexible styling by designers. (Background and overviews for Charting are available here and here.) And there are already some great resources for chart design: Designer’s Guide to Styling Silverlight Toolkit Charting Controls, Styling the Charts in the Silverlight Toolkit.

However, pie charts differ from the other common chart types in some significant ways and that makes the task of styling them a bit challenging. In particular, because styling happens at the DataPoint level (in the case of PieSeries, that's PieDataPoint: the visual representation of one of the slices of the pie), it initially seemed difficult to create a unified style for an entire pie because the sizes and positions of the individual slices can vary so dramatically for different data...

Working on something unrelated one day, I came across the GradientBrush.MappingMode property and realized the BrushMappingMode.Absolute enumeration was ideal for the pie styling problem. I created a simple demonstration and shared it with some folks on the Silverlight Toolkit team. That demo got passed around a bit and eventually made its way to Pete Brown; my sample shows up in his post about pie styling as what he calls the "Rainbow Brite" example.

Using Absolute mode is obviously a big win, but there's still a significant limitation: the coordinates it uses are expressed in pixels and therefore are closely tied to the size of the pie. What looks good for a pie at one size looks silly for that same pie when it is made a little bigger or smaller. I called this limitation out with my initial demo and Pete mentions it in his post as well...

Knowing that Absolute mode works well to enable cohesive styling for fixed-size pies (just look at Pete's great second example!), it seemed to me that the sizing limitation could be overcome with some fairly simple code. So when I got a chance, I wrote that code and put together the following proof-of-concept demonstration using the existing examples from Pete's post (with only a few trivial tweaks to the XAML to adjust gradient offsets). What's great is that now both pies can both be resized dynamically and the styling looks good at any size!

PieDataPointMappingModeUpdater sample application

[The complete sample code/project is available in PieDataPointMappingModeUpdater.zip as an attachment to this post.]

 

The principle here is simple: just update the relevant pixel coordinates of each gradient based on the current size of the PieSeries. What's more, a wrapper function abstracts out most of the complexity, so all that's necessary for the user is to pass in a simple helper method that's tailored to whatever specific pie design has been used. The helper is given the rectangular bounds of the pie and performs whatever gradient adjustments are necessary. It's that easy!

Here's what it looks like in code; the following is from the sample application's Page.xaml.cs:

/// <summary>
/// Initializes an instance of the Page class.
/// </summary>
public Page()
{
    InitializeComponent();

    // Hook up to Example1's PieSeries
    var pieSeries1 = Example1.Series[0] as PieSeries;
    PieDataPointMappingModeUpdater.UpdatePieSeries(pieSeries1, PieSeries1Updater, true);

    // Hook up to Example2's PieSeries
    var pieSeries2 = Example2.Series[0] as PieSeries;
    PieDataPointMappingModeUpdater.UpdatePieSeries(pieSeries2, PieSeries2Updater, true);
}

/// <summary>
/// Updates the gradients for Example1's PieSeries.
/// </summary>
private void PieSeries1Updater(PieDataPoint pieDataPoint, Rect pieBounds)
{
    var brush = pieDataPoint.Background as LinearGradientBrush;
    if (null != brush)
    {
        brush.StartPoint = new Point(pieBounds.Left, pieBounds.Top);
        brush.EndPoint = new Point(pieBounds.Right, pieBounds.Bottom);
    }
}

/// <summary>
/// Updates the gradients for Example2's PieSeries.
/// </summary>
private void PieSeries2Updater(PieDataPoint pieDataPoint, Rect pieBounds)
{
    var brush = pieDataPoint.Background as RadialGradientBrush;
    if (null != brush)
    {
        var center = new Point(
            pieBounds.Left + ((pieBounds.Right - pieBounds.Left) / 2),
            pieBounds.Top + ((pieBounds.Bottom - pieBounds.Top) / 2));
        brush.Center = center;
        brush.GradientOrigin = center;
        var radius = (pieBounds.Right - pieBounds.Left) / 2;
        brush.RadiusX = radius;
        brush.RadiusY = radius;
    }
}

Note that the constructor simply hooks things up and that each helper method is specific to the pie design it will be updating. All each updater does is nudge the pixel coordinates of its gradient to match up with the pie's size. So it seems reasonable to assume that other - potentially more complex - pie designs can be updated just as easily.

Here's the proof-of-concept wrapper method that does the bulk of the work:

/// <summary>
/// Updates the PieDataPoints of a PieSeries by applying the specified action to each.
/// </summary>
/// <param name="pieSeries">PieSeries instance to update.</param>
/// <param name="updater">Action to run for each PieDataPoint.</param>
/// <param name="keepUpdated">true to attach to the SizeChanged event of the PieSeries's PlotArea.</param>
public static void UpdatePieSeries(PieSeries pieSeries, Action<PieDataPoint, Rect> updater, bool keepUpdated)
{
    // Apply template to ensure visual tree containing PlotArea is created
    pieSeries.ApplyTemplate();
    // Find PieSeries's PlotArea element
    var children = Traverse<FrameworkElement>(
        pieSeries,
        e => VisualTreeChildren(e).OfType<FrameworkElement>(),
        element => null == element as Chart);
    var plotArea = children.OfType<Panel>().Where(e => "PlotArea" == e.Name).FirstOrDefault();
    // If able to find the PlotArea...
    if (null != plotArea)
    {
        // Calculate the diameter of the pie (0.95 multiplier is from PieSeries implementation)
        var diameter = Math.Min(plotArea.ActualWidth, plotArea.ActualHeight) * 0.95;
        // Calculate the bounding rectangle of the pie
        var leftTop = new Point((plotArea.ActualWidth - diameter) / 2, (plotArea.ActualHeight - diameter) / 2);
        var rightBottom = new Point(leftTop.X + diameter, leftTop.Y + diameter);
        var pieBounds = new Rect(leftTop, rightBottom);
        // Call the provided updater action for each PieDataPoint
        foreach (var pieDataPoint in plotArea.Children.OfType<PieDataPoint>())
        {
            updater(pieDataPoint, pieBounds);
        }
        // If asked to keep the gradients updated, hook up to PlotArea.SizeChanged as well
        if (keepUpdated)
        {
            plotArea.SizeChanged += delegate
            {
                UpdatePieSeries(pieSeries, updater, false);
            };
        }
    }
}

Attentive readers may have noticed that I'm using the same Traverse<T> implementation that ImplicitStyleManager uses - though I've got a custom getChildNodes implementation that works with the visual tree:

/// <summary>
/// Implementation of getChildNodes parameter to Traverse based on the visual tree.
/// </summary>
/// <param name="reference">Object in the visual tree.</param>
/// <returns>Stream of visual children of the object.</returns>
private static IEnumerable<DependencyObject> VisualTreeChildren(DependencyObject reference)
{
    var childrenCount = VisualTreeHelper.GetChildrenCount(reference);
    for (var i = 0; i < childrenCount; i++)
    {
        yield return VisualTreeHelper.GetChild(reference, i);
    }
}

 

And that's all there is to it! Now, not only do you know how to create appealing, holistic designs for fixed-size pie charts, you've got an easy way to keep those designs looking sharp for dynamically-sized pie charts as well. So go forth with that knowledge - and make even tastier pies! :)

[PieDataPointMappingModeUpdater.zip]

Expanded access to Silverlight 2's generic.xaml resources [SilverlightDefaultStyleBrowser updated for better compatibility!]

Kind reader (and fellow Silverlight Charting blogger!) Pete Brown contacted me recently to report that my SilverlightDefaultStyleBrowser application (background reading available here, here, here, here, and here) didn't seem to be working for assemblies from the Silverlight Toolkit or Telerik's RadControls for Silverlight. Specifically, he found that SilverlightDefaultStyleBrowser would work successfully with the controls in the Silverlight runtime and in the Silverlight SDK - but when he used the "Add Assembly" button to add assemblies from the Toolkit or RadControls, no new controls appeared in the list. This was unexpected and I started investigating...

Silverlight Toolkit: This scenario was particularly troubling because I'm on the Toolkit team and I know it's not doing anything weird that should break SilverlightDefaultStyleBrowser. So I stepped through the code for parsing generic.xaml and discovered that the root ResourceDictionary wasn't getting loaded. A bit more debugging revealed that this was because the Silverlight Toolkit's generic.xaml uses a different XAML namespace than SilverlightDefaultStyleBrowser was looking for (and than nearly every other Silverlight assembly I've seen). But the Toolkit is not at fault here - it turns out that Silverlight supports two different XAML namespaces! So I added support for the second namespace to SilverlightDefaultStyleBrowser, and now it happily parses assemblies from the Silverlight Toolkit. :)

RadControls: I'd assumed the issue here was the same and expected the RadControls to "just work" now that I'd added support for the second XAML namespace - but I was wrong. :( So I stepped through SilverlightDefaultStyleBrowser's generic.xaml parsing code again (recall that generic.xaml is a public entry point for Silverlight assemblies) and discovered that SilverlightDefaultStyleBrowser was finding and parsing the RadControls generic.xaml just fine all along - except that there weren't any Style elements in it. So SilverlightDefaultStyleBrowser's behavior was "correct" in the first place! What's different here is that the Telerik assemblies expose a generic.xaml containing references to custom elements that work at run time (when generic.xaml is parsed and executed by Silverlight), but which do not work with the simple XML-level parsing that SilverlightDefaultStyleBrowser performs. I'm guessing it would be fairly straightforward to modify SilverlightDefaultStyleBrowser to successfully expose the Telerik Styles, but I'm not going to add that custom code until/unless I hear from someone at Telerik that this is something they're okay with. So (for now, at least), SilverlightDefaultStyleBrowser doesn't find any Styles in the RadControls assemblies; that behavior is correct and "by design".

Having investigated the problem report and fixed what I could, I updated the public SilverlightDefaultStyleBrowser application and the downloadable source code. And started writing this post! :)

 

The version number of SilverlightDefaultStyleBrowser appears in the window's title and the latest release number is 1.0.3268.34946. (Note: I haven't updated the screen shot below which shows the introductory version number.) If installed via ClickOnce, the application should automatically prompt you to upgrade when it detects the update (which typically happens after running the application once or twice). If you're using the standalone EXE, you'll need to update manually.

SilverlightDefaultStyleBrowser Application

Click here or on the image above to install SilverlightDefaultStyleBrowser via ClickOnce with automatic updating.

Click here to download the standalone SilverlightDefaultStyleBrowser executable and source code in a ZIP file.

 

SilverlightDefaultStyleBrowser was written to do one thing and to do it simply. As is often the case when trying to duplicate existing behavior, there tend to be a few surprises along the way where things turn out not to work quite as expected. This was one of those surprises and I'm glad for the opportunity to fix this and make SilverlightDefaultStyleBrowser just a little more useful for everyone!

Great Silverlight charts are still just a click away [ChartBuilder sample and source code updated for Charting's December 08 release]

In yesterday's announcement of the December 08 release of Charting for Silverlight, I outlined some of the new Charting features and mentioned a forthcoming update to my ChartBuilder tool to show off the new features. (Background reading for ChartBuilder: Introduction and "user's guide", Updates.)

The new ChartBuilder is now live on the web - and I've even updated my sample screenshot! :)

You can click this text or the image below to run the latest ChartBuilder in your browser.

ChartBuilder

[And click here to download the complete ChartBuilder source code.]

Release notes:

  • Added support for new series type BubbleSeries. To keep thing simple and avoid needing to specify another set of values, the bubble size is bound to the dependent value of the series.
  • Added support for the new Independent(Range|Category)Axis and Dependent(Range|Category)Axis properties of the Column/Bar/Line/Scatter/Bubble series types. Off by default, either axis can be enabled by checking the relevant box in the settings panel for a series - then customized as always.
  • Added a ToolTip for the "Axes" header label to display the current value of the Chart.ActualAxes property in pseudo-XAML. More of a diagnostic aid than anything, this information can help understand the interaction between axes and series - and what's really going on behind the scenes.
  • Increased the maximum number of stand-alone Axis instances from 2 to 4 now that multiple axes are supported.
  • Various other improvements.
  • Updated the version to 2008-12-07.

ChartBuilder continues to be tremendously useful to me as an interactive Charting test application. The plethora of knobs, dials, and switches that represent a user experience designer's worst nightmare [ :) ] enable a degree of scenario testing that has helped find and fix a wide variety of issues. Furthermore, the interactive nature of the tool - and the ease with which it enables mocking up samples for answers on the Silverlight Controls and Silverlight Toolkit forum - has really seemed to help people understand Charting more easily.

My hope is that ChartBuilder can be just as useful to you - so if you've got ideas after using it, please let me know!

Silverlight Charting gets a host of improvements [Silverlight Toolkit December 08 release now available!]

The December 08 release of the Silverlight Toolkit was published a short while ago. Just about every control in the Toolkit got some love and attention for this release and I encourage you to have a look, download it, and enjoy!

That said, readers of my blog know that I'm all about the Charting. :) So just like my original Charting announcement and overview post, here's an announcement of the December 08 Charting release and an overview of some of the high points. By now, I assume folks have had time to play around with Charting and are starting to get into some more advanced scenarios, so the samples are going to be a little more technical than before. If you want a refresher on basic Charting concepts, please have a look at my original overview - all of those concepts still apply.

Though the Charting team was down to just two of us for this release, Jafar and I have done our best to deliver some pretty compelling new features. It's important to note that there are a few breaking changes from the November 08 release, but I hope you'll agree that the new functionality is worth the minor inconvenience of updating existing Charting code. As it happens, if you don't explicitly use the Axis class, you probably won't need to change anything at all!

 

I wrote the following summary for the release notes, and it seems like a good way to begin:

Notable Changes

Support has been added for arbitrary numbers of Axes for a Chart. A key and significant consequence of this change is that it is now possible to mix previously incompatible Series in the same chart (example: Column and Bar). The former "automatically share axes when possible" behavior remains present and can be used to render two series with a shared independent axis and different dependent axes in order to display related-but-differently-scaled values (example: an engine's torque and RPM).

The Column/Bar/Line/Scatter Series classes expose two new (optional) properties which specify a particular Axis instance to be used by the Series (rather than letting the Series choose from the Chart's Axes collection as it does by default). These properties allow very specific customization of each Series' axes in situations where maximum control is desired.

A design-time assembly for Charting has been created which is automatically used by Blend and Visual Studio to enhance the design-time experience. Most class properties are now categorized into custom "Data Visualization" and "Data Visualization Styles" categories to make them easier to find - while particularly common properties are now found in the "Common" category. ToolTips identify the purpose of each control and property, and Toolbox icons are automatically associated with each class. (Note: Some of these features are only supported by one of the design tools.)

The design-time behavior of DataPoints has been enhanced: DataPoints are now visible by default when dropped onto the design surface in Blend, so styling them is easier. PieDataPoint now creates a default Geometry (that can be customized interactively with the ActualRatio and ActualOffsetRatio properties) which makes it possible to see and understand relevant styling changes. DataPoints in a Chart show up in Visual Studio without a refresh of the design surface.

The Chart class is now decorated with ContentPropertyAttribute("Series") which means that it is no longer necessary to explicitly wrap Series with <charting:Chart.Series> ... </charting:Chart.Series> in XAML. Additionally, this enables Blend to display a Chart's Series in the "Objects and Timeline" pane and makes accessing the properties of a Series considerably easier. Example of simplified XAML syntax:

    <charting:Chart>
        <charting:PieSeries ... />
    </charting:Chart>

The behavior of the Axis classes during animations that expand or shrink the range of displayed data has been changed so that the animation of the size change is smooth (vs. jumping between axis intervals). This significantly increases the ease with which dynamic data changes can be observed and understood by the viewer.

The DataPointSeries class (a subclass of Series) has been unsealed to make the task of writing a custom Series considerably easier. While this change doesn't expose the entire hierarchy on which the "in-box" Series are built, it is a significant benefit to developers because DataPointSeries implements many of the key Series notions: the ItemsSource property, DataPoint creation, dynamic data detection, change animation, show/hide transitions, DataPoint selection, and more.

A new Series type, BubbleSeries, has been added (along with its associated BubbleDataPoint class). BubbleSeries is similar in nature to ScatterSeries, but conveys additional information by using the size of the data points to display an additional dependent value for each of the data points.

In scenarios where multiple columns/bars (of ColumnSeries/BarSeries) share the same category, all such data points will now be automatically displayed overlapping so that smaller values will no longer be obscured from view by larger values.

Breaking Changes

The Axis.AxisType property has been replaced by a corresponding hierarchy of Axis classes. The concrete classes map directly to the AxisType values that were removed: LinearAxis, DateTimeAxis, CategoryAxis. In addition to improving overall API consistency, a consequence of this refactoring is that the LinearAxis.Minimum/Maximum properties are now strongly typed as double and the corresponding properties on DateTimeAxis are strongly typed as DateTime - both of which improve development-time and design-time usability.

The Axis.ShouldIncludeZero property has been removed; this property is has no meaning for some axis types and is typically not needed because the same thing can be accomplished by setting Minimum or Maximum accordingly. A consequence of this is that Column/Bar charts will usually not include the 0 value by default (and therefore the "beginnings" of the columns/bars can be truncated). This behavior is consistent with Excel (demonstrated by creating a column chart of the values 10, 11, and 12 in Excel), though truncation is more likely because Charting's heuristics are more aggressive with regard to excluding 0.

Other Changes

Various UI improvements and bug fixes.

Whew - there's a lot of good stuff in there! :)

 

So now that we have an idea what's new, let's start by looking at the support for multiple axes with a common scenario: charting two quantities that are related, but measured in different units and/or on different scales. For the purposes of this demonstration, let's chart the performance characteristics of an imaginary engine:

Chart with multiple axes

[Note: Complete source code for all of the sample charts here can be found in the ChartingIntroduction.zip file attached to this post.]

The XAML for this Chart is straightforward (and discussed below):

<charting:Chart Title="Engine Performance">
    <!-- Power curve -->
    <charting:LineSeries
        Title="Power"
        ItemsSource="{StaticResource EngineMeasurementCollection}"
        IndependentValueBinding="{Binding Speed}"
        DependentValueBinding="{Binding Power}"
        MarkerWidth="5"
        MarkerHeight="5">
        <!-- Vertical axis for power curve -->
        <charting:LineSeries.DependentRangeAxis>
            <charting:LinearAxis
                Orientation="Vertical"
                Title="Power (hp)"
                Minimum="0"
                Maximum="250"
                Interval="50"
                ShowGridLines="True"/>
        </charting:LineSeries.DependentRangeAxis>
    </charting:LineSeries>
    <!-- Torque curve -->
    <charting:LineSeries
        Title="Torque"
        ItemsSource="{StaticResource EngineMeasurementCollection}"
        IndependentValueBinding="{Binding Speed}"
        DependentValueBinding="{Binding Torque}"
        MarkerWidth="5"
        MarkerHeight="5">
        <!-- Vertical axis for torque curve -->
        <charting:LineSeries.DependentRangeAxis>
            <charting:LinearAxis
                Orientation="Vertical"
                Title="Torque (lb-ft)"
                Minimum="50"
                Maximum="300"
                Interval="50"/>
        </charting:LineSeries.DependentRangeAxis>
    </charting:LineSeries>
    <charting:Chart.Axes>
        <!-- Shared horizontal axis -->
        <charting:LinearAxis
            Orientation="Horizontal"
            Title="Speed (rpm)"
            Interval="1000"
            ShowGridLines="True"/>
    </charting:Chart.Axes>
</charting:Chart>

We start with the usual Chart object to contain the series - but now we can put the series directly inside the Chart tags instead of inside nested Chart.Series tags (though that syntax still works and is fully supported). There are two LineSeries here (one for torque and one for power) and each starts out as you'd expect by hooking up to the data and doing a bit of customization. But then there's something new: the LineSeries.DependentRangeAxis property is used to identify a specific LinearAxis. Every series type (other than PieSeries which doesn't have axes) now exposes a Dependent???Axis property and an Independent???Axis property (where "???" is "Range" or "Category" depending on which series it is).

Normally, a series will search the Chart.Axis collection to find an axis that it can use - but when these new properties are set, it always uses the specified axis. So in this example we're providing a specific LinearAxis for each LineSeries to use and we're customizing it slightly to get the chart looking just how we want. Having specified both LineSeries in this manner, a third LinearAxis is added to the Chart.Axis collection where it will be found - and used - by both LineSeries when they acquire an independent value axis.

 

Moving on, here's a chart using the new BubbleSeries in a financial scenario (for a fictional stock ticker symbol). It's the usual "stock price by date" chart we've all seen before - but this chart is also showing the trading volume each day by varying the size the data points:

Bubble chart

The XAML for that Chart is what you'd expect:

<charting:Chart Title="Stock Performance">
    <!-- Stock price and volume -->
    <charting:BubbleSeries
        Title="ABCD"
        ItemsSource="{StaticResource StockDataCollection}"
        IndependentValueBinding="{Binding Date}"
        DependentValueBinding="{Binding Price}"
        SizeValueBinding="{Binding Volume}"
        DataPointStyle="{StaticResource CustomBubbleDataPointStyle}"/>
    <charting:Chart.Axes>
        <!-- Axis for custom labels -->
        <charting:DateTimeAxis
            Orientation="Horizontal">
            <charting:DateTimeAxis.AxisLabelStyle>
                <Style TargetType="charting:DateTimeAxisLabel">
                    <Setter Property="StringFormat" Value="{}{0:MMM d}"/>
                </Style>
            </charting:DateTimeAxis.AxisLabelStyle>
        </charting:DateTimeAxis>
    </charting:Chart.Axes>
</charting:Chart>

BubbleSeries is used just like a ScatterSeries, but it exposes an additional property SizeValueBinding that works just like Independent/DependentValueBinding to identify the source of the size values. The DataPointStyle property specifies a custom style for BubbleDataPoint (not shown here) where we've added the day's volume to the ToolTip of each bubble. This custom style was created in the usual manner - by starting from the default style for BubbleDataPoint and making the desired changes. (I did so in Visual Studio's XAML editor, but it could just as easily be done in Blend.)

Tweaking things just a little more, the independent value axis is customized by setting its AxisLabelStyle property and providing a style for the new DateTimeAxisLabel class. DateTime/NumericAxis/AxisLabel are the classes used to display an axis's labels. In this case we've provided a custom StringFormat so that the dates are all displayed in the friendly Month+Day pattern seen above. DateTimeAxisLabel offers specific StringFormat properties for each supported IntervalType - but in this case we've simply used the StringFormat property which conveniently overrides the other, more specific types.

 

Next up is a fairly typical column chart showing made-up bowling scores for some of the people on the Toolkit team. But there's twist because there are two "Shawn"s on the team:

Chart with overlapping columns

By now, the XAML is probably kind of boring in its predictability:

<charting:Chart Title="Bowling Scores">
    <!-- Scores -->
    <charting:ColumnSeries
        Title="Score"
        ItemsSource="{StaticResource ScoreDataCollection}"
        IndependentValueBinding="{Binding Player}"
        DependentValueBinding="{Binding Score}">
        <charting:ColumnSeries.IndependentCategoryAxis>
            <!-- Axis for automatic sorting -->
            <charting:CategoryAxis
                Orientation="Horizontal"
                SortOrder="Ascending"/>
        </charting:ColumnSeries.IndependentCategoryAxis>
    </charting:ColumnSeries>
</charting:Chart>

This is a standard ColumnSeries, which is specifying a IndependentCategoryAxis so the new SortOrder property of CategoryAxis can be used to automatically sort the category names. This data set contains two items with the independent value "Shawn". Previously, both would have been displayed in the same category slot with the same width which means the column in front could have obscured the one in back and led viewers to believe that only four scores were being displayed. But now ColumnSeries and BarSeries automatically detect this situation and overlap columns/bars in the same category slot (after sorting them by size). This behavior makes it clear that five values are being shown and makes it easy to hover over either of the "Shawn"s to get a ToolTip with the associated score.

 

The previous chart is interesting for another reason, too: it's using the natural, simple way to display the data, but a purist might argue that it's also the "wrong" way to do so... [Jafar and I actually had this "argument" - I won't say who took which position. :) ] Categorizing by player name works well enough, but what if we also had an image for each player and we wanted to display that image instead of their name? Changing the ColumnSeries.IndependentValueBinding property might work, but it's become obvious that we're mixing display concerns and data concerns.

When maintaining developer/designer separation is critical, what's probably more appropriate is to categorize by the actual data object - and then display it however we want. Here's a chart that does just that:

Chart with unique categories

And here's the XAML - which is a bit more complicated than before, but still quite manageable:

<charting:Chart>
    <!-- Customized Title -->
    <charting:Chart.Title>
        <StackPanel>
            <TextBlock
                Text="Bowling Scores"
                HorizontalAlignment="Center"/>
            <TextBlock
                Text="(Alternate Approach)"
                FontSize="10"
                HorizontalAlignment="Center"/>
        </StackPanel>
    </charting:Chart.Title>
    <!-- Scores -->
    <charting:ColumnSeries
        Title="Score"
        ItemsSource="{StaticResource ScoreDataCollection}"
        IndependentValueBinding="{Binding}"
        DependentValueBinding="{Binding Score}">
        <charting:ColumnSeries.IndependentCategoryAxis>
            <!-- Axis for automatic sorting and custom labels -->
            <charting:CategoryAxis
                Orientation="Horizontal"
                SortOrder="Ascending">
                <charting:CategoryAxis.AxisLabelStyle>
                    <Style TargetType="charting:AxisLabel">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="charting:AxisLabel">
                                    <TextBlock Text="{Binding Player}"/>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </charting:CategoryAxis.AxisLabelStyle>
            </charting:CategoryAxis>
        </charting:ColumnSeries.IndependentCategoryAxis>
    </charting:ColumnSeries>
</charting:Chart>

Now that we've set IndependentValueBinding to the data objects themselves, there are automatically five categories (one for each of the five objects in the data set). (Aside: CategoryAxis will still sort them for us because the data objects implement the IComparable interface.) Once the data is set up "properly", all that's left to do is customize how the objects are displayed - and this is done by providing a custom template for the AxisLabel class (something that's already been discussed).

One other thing to note above is how the Chart.Title property is set to a tree of UI elements instead of the usual string. Chart.Title (and other such properties in Charting) follows the ContentControl model because it makes simple things simple while also allowing more advanced scenarios. In this case, all we've done is provide a "subtitle" - but we could also have gone much further and created something very customized.

 

The last thing I wanted to highlight was some of the design-time enhancements for Charting in this release. Data points were previously a little tricky to customize because their default state is not visible (which allows the reveal/show animation to fade them in without flicker). Data points now check if they're being used in design-time and will automatically play their reveal/show animation so that they're visible on the design surface by default. PieDataPoint used to be extra tricky because its Geometry property is only set when it's actually being used by PieSeries. But now it knows about design-time and its ActualRatio/ActualOffsetRatio properties can be changed to interactively evaluate different styling approaches. Here's a stand-alone PieDataPoint in Blend showing off both of these improvements (along with the new "Data Visualization" property category):

PieDataPoint in Blend

 

I hope you're excited by some of the new functionality we've just looked at from the December 08 release of Charting! And naturally, we've made a some other improvements, too! :) You can browse the live Charting sample page to find out more - then download the December 08 Toolkit release and start playing around with the new stuff! As always, if you have questions about Charting, you can ask them in the Silverlight Controls forum. If you think you've found a bug, please report it with the Issue Tracker in the Toolkit's CodePlex site.

 

PS - If you're looking for an update to my ChartBuilder application (Background reading: Introduction, Update) to show off the new Charting functionality, please stay tuned because it will be available very soon! :)

PPS - I'm on vacation in December, so responses to blog comments and emails may be delayed. But please don't let that stop you from contacting me: I'll follow up on everything I get - I just might be a little slower than usual. :)

[ChartingIntroduction.zip]

Having problems with layout? Switch to Plan B! [LayoutTransformControl scenarios for WPF]

When I first wrote about adding full LayoutTransform fidelity to Silverlight with my LayoutTransformControl project, I mentioned that I'd found two scenarios where LayoutTransformControl's behavior differed from WPF's LayoutTransform. (Background reading for LayoutTransformControl: Motivation and introduction for Beta 1, Significant enhancements and update for Beta 2, Update for RTW, Fixes for two edge case bugs) These two differences were intentional because it seemed to me that the corresponding WPF behavior was incorrect. Now you can judge for yourself. :)

The sample WPF application shown here (note: complete source code is attached to this post) demonstrates two variants of the problematic scenarios; one rendered by WPF's LayoutTransform and the other by LayoutTransformControl. The top four cells demonstrate the first scenario and the bottom four cells demonstrate the second. Cells on the left show a variant that both implementations agree on while cells on the right show a small modification that demonstrates conflicting behavior. I've shaded the problematic sections red to help identify them. Here's how it looks:

WPF LayoutTransform issue demonstration

The XAML for top scenario's red quadrant is this:

<Grid Background="Orange">
    <Grid.LayoutTransform>
        <SkewTransform AngleX="-20"/>
    </Grid.LayoutTransform>
    <Grid MinHeight="75" MinWidth="75"/>
</Grid>

It's a simple skew on a free-sized Grid with arbitrary content (for simplicity, the content is another Grid with MinWidth/MinHeight, but this could be a Button or any other typical content). The behavior for positive skew angles makes sense to me, but the behavior for negative angles seems inconsistent and causes undesirable clipping of the content (which is really obvious when applied to a Button). The corresponding XAML for LayoutTransformControl's "correct" rendering is:

<l:LayoutTransformControl>
    <l:LayoutTransformControl.Transform>
        <SkewTransform AngleX="-20"/>
    </l:LayoutTransformControl.Transform>
    <Grid Background="Orange">
        <Grid MinHeight="75" MinWidth="75"/>
    </Grid>
</l:LayoutTransformControl>

The XAML for bottom scenario's red quadrant is this:

<Grid Width="75">
    <Grid Background="Orange">
        <Grid.LayoutTransform>
            <RotateTransform Angle="90"/>
        </Grid.LayoutTransform>
        <Grid MinHeight="125" MinWidth="125"/>
    </Grid>
</Grid>

It's a width-constrained, free-sized Grid with arbitrary content. The behavior for Angle=0 (or 180) makes sense to me, but the behavior for Angle=90 (or 270) does not; at this angle the content should be vertically unbounded and should stretch to the full 125 pixels of the inner Grid. Changing the nature of the outer constraint from width to height exhibits the same "doesn't stretch" behavior at Angle=90 (or 270). The corresponding XAML for LayoutTransformControl's "correct" rendering is:

<Grid Width="75">
    <l:LayoutTransformControl>
        <l:LayoutTransformControl.Transform>
            <RotateTransform Angle="90"/>
        </l:LayoutTransformControl.Transform>
        <Grid Background="Orange">
            <Grid MinHeight="125" MinWidth="125"/>
        </Grid>
    </l:LayoutTransformControl>
</Grid>

I reported both of these issues to the WPF team when I found them, but unfortunately they weren't able to address them for the .NET 3.5 SP1 release. Although it might put LayoutTransformControl out of a job, I'm optimistic that both will be fixed in a future update of WPF. :) For the time being, though, I humbly suggest giving LayoutTransformControl a try if you encounter unexpected behavior like this. It's probably the quickest, easiest patch you'll find!

[WpfLayoutTransformIssues.zip]

An unexceptional layout improvement [Two LayoutTransformControl fixes for Silverlight 2!]

I'd almost finished patting myself on the back for managing to implement WPF's LayoutTransform on Silverlight using just the RenderTransform available on that platform. (Background reading for LayoutTransformControl: Motivation and introduction for Beta 1, Significant enhancements and update for Beta 2, Update for RTW) Yes, everything was peachy - until I was contacted by kind reader Matthew Serbinski with a report of an InvalidOperationException being thrown by Silverlight when using LayoutTransformControl with a ScaleTransform with ScaleY=0... :(

You've probably already recognized ScaleY=0 as something of an edge case for layout: a value which collapses everything into nothingness. I looked into how WPF's LayoutTransform code handled this situation and discovered that it specifically detected circumstances corresponding to a transformation matrix without an inverse - and skipped performing the usual layout computations. My LayoutTransformControl implementation didn't look for this special case, ended up violating one of the rules of the layout system, and triggered the reported exception.

So I added a little bit of code to handle such input the same way WPF does. And while I was at it, I checked to see if maybe there were other special cases that LayoutTransformControl wasn't handling properly... Sure enough, I found one other scenario: that of needing to layout within an container having no width or height. In this case, LayoutTransformControl's behavior wasn't wrong enough to cause an exception (or any visible problem I noticed), but I made a similar tweak for consistency with WPF.

Changes in place, I modified the LayoutTransformControl sample application, its Silverlight test framework, and its WPF test framework to allow setting both ScaleX and ScaleY to 0. (I'd formerly limited ScaleX/ScaleY to positive values which is why I didn't realize there was a problem myself.) Then I spent some time playing around with the test apps: trying all kinds of things and looking for any other anomalous behavior. Nothing turned up, so I updated the LayoutTransformControl source code download and started writing this post... :)

LayoutTransformControl Sample Application

Changes to code always involve a certain amount of risk that a regression will be introduced. Fortunately, the changes here are small, self-contained, and easy to test - so I'm optimistic they won't cause problems for those of you already using LayoutTransformControl in your projects. Of course, if there are any new problems - or existing ones I don't know about yet! - please let me know and I'll look into them as quickly as I can.

Thank you for your help - happy LayoutTransform-ing!

Shamelessly benefitting from the work of others [Links to Silverlight Airlines and Surface samples for RTW!]

I try to keep up with migrating my various samples to the latest Silverlight Beta/RTW releases, but I don't always have the chance to do so as quickly as I'd like. That's why it was great to find that someone had already done some of the work for me. Two someones, in fact! :)

 

Silverlight Airlines Demo

The original Silverlight Airlines demo my team did for MIX 07 is available on the Silverlight.net gallery:
[Runnable Sample]
[Source Code]

 

Silverlight Surface Demo

My popular Silverlight Surface demo has been updated by pureBlue consulting to include video support:
[Runnable Sample]
[Source Code]

 

To be clear, I wasn't involved with the porting efforts and I haven't reviewed the source code for either sample. However, I bet these are both still great learning resources for new Silverlight developers!

Thank you to everyone out there who's helping to make Silverlight fun and easy to learn.

A fix for simple HTML display in Silverlight [HtmlTextBlock bug fix for Silverlight 2 RTW!]

I updated my HtmlTextBlock sample for RTW last night and got an email from kind reader Ed Silverton this morning pointing out a problem setting FontSize on a standalone instance of the control. (Background reading: HtmlTextBlock Announcement for the Alpha, Improvements, Beta 1 Update, Data Binding Support, Beta 2 Update, RTW Update) Unfortunately, this problem does not demonstrate itself in the sample project, so I missed it. :( Sorry about that!

Ed's scenario was that of setting the FontSize or Foreground properties in the XAML for an instance of HtmlTextBlock; he observed that they did not take effect. What I think happened is that these Silverlight properties became inheritable between Silverlight Beta 2 and RTW, so the code in HtmlTextBlock to set up TemplateBindings to them was interfering with their normal operation. I simply removed the code in HtmlTextBlock that deals with the inheritable properties: FontFamily, FontSize, FontStretch, FontStyle, FontWeight, and Foreground. (Note that TextDecorations doesn't count because it's not present on the Control class HtmlTextBlock derives from.) After that, all was well.

Mostly, that is... Ed's scenario now worked fine and so did the sample page - except for when the font size was changed to a small value. After that, changes to the font or size had no effect. Specifically, this problem seems to occur once the size of the text is small enough that the TextBlock fits completely within the bounds of the HtmlTextBlock. Not completely surprisingly, any changes to the TextBlock.Text property cause it to update itself correctly. I don't have a great deal more time to investigate this at the moment, and it's seeming like it may be an issue with Silverlight's TextBlock (I'll follow up internally), so I worked around the problem in the sample page (note: not the HtmlTextBlock code which I think is correct) by resetting the Text property when the font or size is changed by the user.

HtmlTextBlock Demonstration

I've updated the HtmlTextBlock demonstration page and the source code download, so you can try things out in your browser and/or download the code to see how it works!

Sigh, I knew yesterday's painless migration of this sample went too smoothly to be true... :)