The blog of dlaa.me

Posts from November 2008

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... :)

My take on simple HTML display in Silverlight [HtmlTextBlock sample updated for Silverlight 2 RTW!]

A couple of readers have asked about an update to my long-running HtmlTextBlock sample for Silverlight 2 RTW. (Background reading: HtmlTextBlock Announcement for the Alpha, Improvements, Beta 1 Update, Data Binding Support, Beta 2 Update) One person went so far as to migrate it himself after emailing me! :) He said the process went well, and I spent a bit of time on the bus ride home doing the migration myself to understand what was involved.

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!

Notes:

  • The only change to the Beta 2 code was to handle the fact that the type of the object returned by HtmlDocument.GetElementsByTagName is now a base class of the HtmlElement instance the code was expecting. After a simple application of the as operator, the code compiles and works like before!

That's it!

Gee, I wish everything went this smoothly... :)

My new home page [A collection of great Silverlight Charting resources!]

It's been nearly two weeks since the Silverlight Toolkit's November release. I've been trying to keep up with what's been written about Charting and want to summarize some of the most helpful posts I've seen so far.

Overviews (100 level)

Scenarios (200 level)

Internals (300 level)

My own Charting posts (Ego level)

Many, many thanks to everyone who has spent time helping others learn how to use Silverlight Charting!

PS - If I've missed any good resources, please leave a comment and to them - I'm always happy to find good Charting content! :)

Improving ChartBuilder's cultural sensitivity [ChartBuilder app/source updated!]

Kind readers Eugenio and Thimp independently reported that the initial version of ChartBuilder did not work well on machines with certain culture settings. Specifically, ChartBuilder was inadvertently using the CurrentCulture for formatting numbers in XAML and that's a problem because the XAML is parsed according to the InvariantCulture. For example, on German machines ChartBuilder would write a double value to XAML as "1,23" according to the German culture settings - and the XAML parser would complain that wasn't a valid value. I'm usually able to catch problems like this by running code analysis and fixing all the Microsoft.Globalization warnings like CA1305, but in this case the code was calling objectInstance.ToString() which doesn't have any IFormatProvider-based overloads and therefore generates no warnings.

My sincerest apologies to anyone who was affected by this problem. I have switched one of my machines to the German locale and will leave it there for a couple of days as punishment. :)

I made the culture fix on my bus ride this morning and had a bit of extra time, so I also made the following improvements:

  • Added support for the Axis.Interval property. Now it's possible to customize the frequency of the labels, tickmarks, and gridlines on an axis.
  • Added the "datavis" xmlns prefix so it's already present for people who might need to reference it. [Like me when I posted a sample to the forums the other day. :) ]
  • Updated the version to 2008/11/06.

Again, sorry for any trouble. I hope the updated ChartBuilder works well for everyone - and that you enjoy the minor improvements!

 

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.]

Easily create an ISO from a CD/DVD [Releasing ExtractISO tool and source]

A few years back I found myself in need of a tool to create an ISO image from a CD I owned. I searched around a bit, but the only tools I could find to do that were part of much larger programs and cost money I didn't want to spend. The concept seemed simple enough that I figured it would be fairly easy to write my own tool to do this. So I did. :)

ExtractISO is a native, console-mode application that does what its name suggests: extracts the contents of a CD or DVD and saves it to a file. The tool and complete source code are attached to this post as ExtractISO.zip. Here's the documentation that comes with it:

====================================
==  ExtractISO                    ==
==  http://blogs.msdn.com/Delay/  ==
====================================


Summary
=======

ExtractISO - Creates an ISO image file from a CD/DVD

ExtractISO reads raw sectors from the specified CD/DVD volume and writes them
to the specified ISO image file.  The resulting file can be burned to a blank
CD/DVD disc, mounted in a virtual CD/DVD drive, or opened in an ISO viewer.

For a discussion of the limitations of this process, please refer to:
   http://www.cdrfaq.org/faq02.html#S2-28

Note that direct access to a CD/DVD volume requires administrative privileges.

ExtractISO attempts to read damaged media by retrying failed reads a few times
before giving up. In the event of a persistent read failure, the partial output
file is not deleted so that subsequent extraction attempts (possibly after
cleaning the media and/or using a different drive to read it) can be attempted
without the loss of any successfully extracted data.

Syntax: ExtractISO D: File.iso
   D: is the CD/DVD drive to extract from
   File.iso is the file to write to


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

Version 1.11, 2008-11-04
Improved formatting of "bytes extracted" display value
Initial public release

Version 1.10, 2006-03-12
Added support for damaged media recovery (see above)

Version 1.01, 2005-05-18
Fixed silly integer overflow problem with "bytes extracted" display
Note: Problem affected display only; no functional impact

Version 1.0, 2005-04-27
Initial release

ExtractISO has been available to anyone inside Microsoft since I wrote it. Last week, I got an unexpected request to make it public so certain customers could use it. I was happy to do so, but one thing had been bothering me for a while: the status display of the bytes extracted so far didn't group by thousands. Instead of "1,000,000", the counter displayed as "1000000" which I find more difficult to parse. This was such a small issue, I never got around to fixing it - but now seemed like the ideal time to do so!

Unfortunately, this formatting task which is so simple in .NET seems to be quite a bit more involved with the Win32 API. The first problem is that printf doesn't support outputting the thousands separator. I considered using something like the sample code the previous link suggests, but wanted something simpler and easier to understand. A bit of research turned up the GetNumberFormat API which seemed like the perfect solution. However, the GetNumberFormat API suffers from at least two notable shortcomings: it's not easy to customize the output and the input needs to be a string. I did a quick test and found that the output of GetNumberFormat for "1000000" is "1,000,000.00" (on my machine using the default United States settings). This is close to what I wanted, but displaying the integral byte count with two digits of decimal precision just seems silly to me. So I looked for an easy way to customize the output via NUMBERFMT, and ran into the same issues Michael talks about in the post I linked to. When further research turned up no better alternatives, I decided to use GetNumberFormat and then "fix" its output by calling GetLocaleInfo(LOCALE_SDECIMAL) and removing everything after the localized decimal character(s). I like this approach because it is almost all platform code (i.e., code I don't have to write/test) and should be correct for all cultures where numbers are written as "1,000,000.00", "1.000.000,00", etc..

Other than the formatting issue I've just discussed, I made no other changes to the ExtractISO implementation. The only things I did were to update some of the VERSIONINFO settings, tweak the Build.cmd script, and recompile with the latest Visual Studio 2008.

ExtractISO works reasonably quickly, but it's worth mentioning that performance was specifically not a goal when I wrote it. The code implements a simple read/write loop with a 1 MB buffer and makes no attempt to interleave the two operations. The large-ish buffer should help minimize the overhead of the read/write calls, but I suspect a different implementation that issues the reads and writes in parallel would be faster. However, achieving that parallelism comes at the price of complexity - and I didn't feel the time it would have taken to write and debug that code was justified here. Even at top speed, the extraction operation is going to take a minute or two - an extra minute on top of that seems a small price to pay for simpler, easier to maintain code. You are welcome to disagree, of course. :) If you develop a faster implementation, I'd love to hear about it!

ExtractISO is a simple tool with a simple purpose - and one that I've used quite happily for a number of years now. If you've got a hankering for ISOs and like free stuff, please have a look at ExtractISO!

PS - ExtractISO cannot be used to duplicate audio CDs or copy-protected DVDs: audio CDs use a different storage scheme than data CDs and copy-protected DVDs store their encryption key in an "inaccessible" location of the disk.

[ExtractISO.zip]

Smaller is still better! [A simple step continues to shrink the download size of Silverlight 2 applications]

A few months ago, I looked at the size of Silverlight 2 XAP files and blogged a simple way to reduce the size of typical XAP files by about 22%. Silverlight 2 was still under development at the time and a lot of work has gone on since then (including the official release of Silverlight 2!). I wanted to revisit this topic to see if my XapReZip script was still worth running, or if it had been rendered useless by better default compression behavior for the Silverlight Tools package. I just ran XapReZip against three of the same scenarios as last time - here's the new data for sizes of the resulting XAP files:

Scenario Starting Size After XapReZip Difference Reduction
New Silverlight Project 4,365 3,491 874 20%
... with DatePicker 88,047 68,760 19,287 22%
... and DataGrid 216,368 170,217 46,151 21%

The results are nearly identical to what they were back in July when I first blogged about XapReZip, so the issue of sub-optimal default compression still seems to be with us. :( But the good news is that my original XapReZip script works just as well today as it did before! :) And even better news is that other folks have taken things a step further and written tools to make this even easier. Here's a post by Rob Houweling where he shares his ReXapper tool (a compiled, self-contained version of the same process). And here's a post I've just found by Valeri Hristov that uses 7-Zip - and appears to pre-date my original XapReZip post!

Keeping download size small helps get content to your users as quickly as possible - and satisfying users is always important! Please consider adding a re-compression step to your Silverlight 2 project today; your users - and download costs - will thank you. :)