Delay's Blog

Silverlight, WPF, Windows Phone, Web Platform, .NET, and more...

Posts
  • Delay's Blog

    You voted lots, we fixed lots [AJAX Control Toolkit release!]

    • 16 Comments

    Last night we published the 10920 release of the AJAX Control Toolkit. This release continued our trend of focusing on the most popular bugs and work items identified by the user community in the support forum and online issue tracker. A number of popular issues got fixed in this release, addressing nearly 1000 user votes!

    The release notes from the sample web site detail the improvements:

    General fixes:

    • Controls with Embedded styles (Calendar, Tabs and Slider): Toolkit controls no longer need explicit style references when loaded asynchronously. For example, if a Calendar control is placed inside an UpdatePanel and made visible on an UpdatePanel postback, the embedded styles are now loaded properly.
    • PopupBehavior positioning (AutoComplete, Calendar, DropDown, HoverMenu, ListSearch, PopupControl and ValidatorCallout): PopupBehavior now respects the position of its parent element even when the browser window is very narrow or the parent element is close the window edge.
    • Focusing extended controls (Accordion, CollapsiblePanel, DropShadow, Tabs): Pages that use Toolkit controls which re-parent DOM elements can use a workaround to focus a specific element on page load. The new method Utility.SetFocusOnLoad ensures that the desired control receives focus.

    Control specific fixes:

    • Calendar: Property to specify the position of Calendar, a default date feature that allows the calendar to start out with a selected date, and a consistent show, hide and focus story that makes the Calendar user experience more intuitive.
    • ModalPopup: Ability to disable repositioning of the ModalPopup in response to window resize and scroll.
    • ConfirmButton: ModalPopup functionality now supported in addition to the regular windows alert dialog.
    • MaskedEdit: Extended Textbox no longer uses Invariant culture if no CultureName is specified and falls back to the Page Culture.
    • AutoComplete: Allow users to associate additional data with the AutoComplete suggestions.
    • Slider: Slider can be easily customized using its various CSS properties.

    As with the previous release, we have published "source" and "no-source" versions for .NET 2.0/Visual Studio 2005 as well as for .NET 3.5/Visual Studio 2008 (still in Beta). Unique to the 3.5/2008 versions are the following:

    Features:

    • JavaScript IntelliSense support: We have added reference tags to all Toolkit JavaScript files that enables you to take advantage of new features in Visual Studio 2008 Beta 2. With the multi-targeting support in this Visual Studio Beta, IntelliSense will be available for the ASP.NET AJAX 1.0 flavor of the Toolkit as well. This article discusses the reference tag feature in detail.
    • Extender designer support: Enhanced designer support for Toolkit controls using the new "Add Extender" user interface.

    One thing we'd hoped to include with this release didn't quite make it in: our new automated testing framework. This framework is based on a different approach than our current framework - one that makes it easy to add additional test cases and leverage existing ones across new scenarios. The new testing framework has already dramatically improved our test coverage, helped identify new issues, and made fixing existing issues less risky!

    But we've been iterating on the new framework for the past couple of weeks and faced the usual decision when it came time to finalize this release: slip or ship. We slipped our release date a little in the hopes that we'd be able to include the new framework with this release, but eventually decided not to delay all the great new Toolkit code any longer. We wanted our users to take advantage of the new bits ASAP - so stay tuned for more on the new testing framework in a future release!

    As always, it's easy to sample any of the controls (no install required). You can also browse the project web site, download the latest Toolkit, and start creating your own controls and/or contributing to the project!

    If you have any feedback, please share it with us on the support forum!

  • Delay's Blog

    My new home page, extended [Updated collection of great Silverlight and WPF Charting resources!]

    • 25 Comments

    It's been a while since the March 09 release of the Silverlight Toolkit - and even longer since I last posted a collection of Charting links. It's clearly time for an update, so I've added a bunch of new links to the collection below (FYI: previously published links are gray):

    Overviews (100 level)

    Scenarios (200 level)

    Internals (300 level)

    Jafar Husain's posts (Partner level)

    My posts (Ego level)

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

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

  • Delay's Blog

    No rest for the weary [Free tool and source code to temporarily prevent a computer from entering sleep mode - now available for .NET, 32-bit, and 64-bit!]

    • 41 Comments

    It was over a year ago that I wrote and shared the first version of my Insomnia utility. A few months later, I published a new version of Insomnia to satisfy the two most popular feature requests. Here's how I explained Insomnia's motivation at the time:

    The default power settings for Windows are set up so a computer will go to sleep after 15 to 30 minutes of inactivity (i.e., no mouse or keyboard input). This is great because a computer that's not being used doesn't need to be running at full power. By letting an idle machine enter sleep mode, the user benefits from a significant reduction in electricity use, heat generation, component wear, etc.. And because sleep mode preserves the state of everything in memory, it's quick to enter, quick to exit, and doesn't affect the user's work-flow. All the same applications continue running, windows stay open and where they were, etc.. So sleep mode is a Good Thing and I'm a fan.

    However, sometimes a computer is busy even though someone isn't actively using the mouse and keyboard; common examples include playing a movie, burning a DVD, streaming music, etc.. In these cases, you don't want the machine to go to sleep because you're using it - even though you're not actually using it! So most media players and disc burners tell Windows not to go to sleep while they're running. In fact, there's a dedicated API for exactly this purpose: the SetThreadExecutionState Win32 Function.

    But what about those times when the computer is busy doing something and the relevant program doesn't suppress the default sleep behavior? For example, it might be downloading a large file, re-encoding a music collection, backing up the hard drive, or hashing the entire contents of the disk. You don't want the machine to go to sleep for now, but are otherwise happy with the default sleep behavior. Unfortunately, the easiest way I know of to temporarily suppress sleeping is to go to Control Panel, open the Power Options page, change the power plan settings, commit them - and then remember to undo everything once the task is finished. It's not hard; but it's kind of annoying...

     

    I've gotten a bunch of positive feedback on Insomnia and heard from a lot of people who use it for exactly the kinds of things I expected. (Thanks, everyone!) But I've also heard from a number of people who use Insomnia for a slightly different purpose: as an override of their machine's current power settings. For one reason or another, these people don't have control over their power configuration (perhaps because their domain enforces the relevant group policy), but still want to prevent their computer from going to sleep. This is usually because they want to connect to their machine remotely (ex: via file sharing or Remote Desktop) and can't do that if the machine is forced to sleep...

    Insomnia application

    These people tend to put a shortcut to Insomnia in their Startup group (click Start Menu, All Programs, Startup) and set the "Minimize" flag to automatically run Insomnia as an icon in the notification area whenever they log in. Because they leave Insomnia running all the time, their computer stays awake and they're able to use it whenever they need to. I've always thought this is a cool scenario - and felt that maybe a lower-overhead version of Insomnia would be particularly compelling here.

     

    I wrote the original Insomnia using the .NET Framework - which meant it was super-easy to write and took practically no time or effort on my part. That's the way (uh-huh, uh-huh!) I like it, because the thing I have the least of is spare time and so anything that makes me more productive is full of win. And in my experience, .NET isn't just more productive, it's dramatically more productive.

    That said, everything has a cost, and one of the common downsides of .NET is longer startup time and higher memory use. All the stuff .NET does for you (comprehensive APIs, high-level abstractions, garbage collection, etc.) takes extra time to load and extra memory to keep around. That said, I'll confidently suggest these costs are negligible in the majority of cases and the benefits of .NET (developer productivity, rich feature set, security, etc.) are overwhelmingly in its favor. But Insomnia is a little different than most programs: the application exists only as a wrapper for a single API (SetThreadExecutionState), so the people who run it all the time aren't really benefitting from the power of .NET...

    Insomnia minimized to the notification area

    I thought it might be fun to re-implement Insomnia in native code (vs. managed code) since it was such a simple program. I've done exactly that - and the result is that Insomnia is now available in three versions: .NET, 32-bit native, and 64-bit native!

     

    [Click here to download all three flavors of Insomnia along with the complete source code for managed and native.]

     

    Of course, while it was neat to do some Windows API coding for a change, the experience served to reinforce my belief in the fundamental productivity benefits of .NET and the power of the WPF/Silverlight layout system. About half the code in native Insomnia exists for the purpose of layout - which the .NET version accomplishes much more succinctly with XAML. The other half of the code handles basic framework-y stuff like creating a window, configuring it, etc. - more things WPF handles for you or makes quite convenient. And the last half of the code [ ;) ] deals with a variety of little things that are quite simple in the managed world, but require non-trivial effort in native code (ex: copying strings, setting up a complicated function call, etc.).

    Please don't get me wrong; I completely agree that native code has its place in life (and there's a certain feeling of power one gets from using it). But I've had enough of that for now and will be happy to return to .NET for my next project. :)

     

    Notes:

    • The most common question I get about Insomnia is whether it also disables the screen saver - it does not. When Insomnia is running, the screen saver will continue to kick in and turn off the monitor on its usual schedule. The difference is that the computer itself will not be allowed to enter sleep mode. Once the Insomnia window is closed, the computer can sleep again and will do so on its usual schedule.

    • The second most common question I get is why the Insomnia window stays above other windows. As I explained in the introductory post, this is so Insomnia is always visible when running and people will be less likely to accidentally leave their computers sleep-less by forgetting they've started it. This seems like the right behavior for the original "temporarily prevent sleep mode" scenario; for the "always on" scenario, minimizing Insomnia to the notification area seems to work well for everyone I've talked to.

    • My goal for the native version of Insomnia was to duplicate the functionality of the .NET version as closely as possible - not because I think the .NET version is perfect, but because it works well and it's what people are already familiar with. So while I wasn't obsessive about matching the font face and size exactly, a side-by-side comparison of the two programs shows a very strong correlation. :)

    • The one thing I didn't port from the .NET version was the "/minimize" command-line switch. Originally intended to make it easy for users to start Insomnia minimized, commenter rbirkby reminded me that Windows shortcuts already made that easy enough. It didn't seem necessary to duplicate this somewhat unnecessary feature, so I've omitted it to keep the native version just a bit simpler.

    • To start Insomnia minimized, just create a shortcut to it (right-click+drag+drop its icon somewhere (like the Start Menu / All Programs / Startup folder) then edit the shortcut's settings (right-click it and choose Properties) and choose "Minimized":

      Shortcut to start Insomnia minimized

      Alternatively, the following syntax will do the same thing from a batch file:

      start /MIN Insomnia.exe
    • Because the whole point of this exercise was to reduce Insomnia's run-time footprint, it's interesting to see how things worked out. Here's a table of the Resource Monitor statistics for each flavor as measured by opening and minimizing them all on my 64-bit Windows 7 machine:

      Flavor Commit (KB) Private (KB)
      .NET 66,972 17,940
      64-bit 2,144 1,876
      32-bit 1,652 1,332

      (Note that the .NET version uses somewhat less memory on a 32-bit version of Windows 7.)

    • Not only do the native versions of Insomnia use less memory - they start faster, too! Because they have fewer dependencies, there's simply less stuff to load from disk - and because disk access is (relatively) slow, minimizing it can do a lot to improve startup speeds.

    • Something that made life a little more pleasant for the native version was the SysLink common control - specifically its LM_GETIDEALSIZE message. This message is used to "Retrieve[s] the preferred height of a link for the control's current width." and it enabled me to approximate something kind of like WPF's measure/arrange-based layout system without having to write a bunch of code myself. So while I'd originally thought to use SysLink only for the hyperlink (duh!), I ended up using it for the version text and message as well!

    • As you'd expect, the Visual Studio solution/project for the new, native version of Insomnia uses the Visual Studio 2010 format. However, the solution/project for the original, managed version is still in the 2008 format I originally released it in (of course, opening it in VS 2010 automatically "upgrades" it).

  • Delay's Blog

    Powerful log file analysis for everyone [Releasing TextAnalysisTool.NET!]

    • 36 Comments

    A number of years ago, the product team I was on spent a lot of team analyzing large log files. These log files contained thousands of lines of output tracing what the code was doing, what its current state was, and gobs of other diagnostic information. Typically, we were only interested in a handful of lines - but had no idea which ones at first. Often one would start by searching for a generic error message, get some information from that, search for some more specific information, obtain more context, and continue on in that manner until the problem was identified. It was usually the case that interesting lines were spread across the entire file and could only really be understood when viewed together - but gathering them all could be inconvenient. Different people had different tricks and tools to make different aspects of the search more efficient, but nothing really addressed the end-to-end scenario and I decided I'd try to come up with something better.

    TextAnalysisTool was first released to coworkers in July of 2000 as a native C++ application written from scratch. It went through a few revisions over the next year and a half and served myself and others well during that time. Later, as the .NET Framework became popular, I decided it would be a good learning exercise to rewrite TextAnalysisTool to run on .NET as a way to learn the Framework and make some architectural improvements to the application. TextAnalysisTool.NET was released in February of 2003 as a fully managed .NET 1.0 C# application with the same functionality of the C++ application it replaced. TextAnalysisTool.NET has gone through a few revisions since then and has slowly made its way across parts of the company. (It's always neat to get an email from someone in a group I had no idea was using TextAnalysisTool.NET!) TextAnalysisTool.NET is popular enough among its users that I started getting requests to make it available outside the company so that customers could use it to help with investigations.

    The effort of getting something posted to Microsoft.com seemed overwhelming at the time, so TextAnalysisTool.NET stayed internal until now. With the latest request, I realized my blog would be a great way to help internal groups and customers by making TextAnalysisTool.NET available to the public!

    TextAnalysisTool.NET Demonstration

    You can download the latest version of TextAnalysisTool.NET by clicking here (or on the image above).

    In the above demonstration of identifying the errors and warnings from sample build output, note how the use of regular expression text filters and selective hiding of surrounding content make it easy to zoom in on the interesting parts of the file - and then zoom out to get context.

    Additional information can be found in the TextAnalysisTool.NET.txt file that's included in the ZIP download (or from within the application via Help | Documentation). The first section of that file is a tutorial and the second section gives a more detailed overview of TextAnalysisTool.NET (excerpted below). The download also includes a ReadMe.txt with release notes and a few other things worth reading.

    The Problem: For those times when you have to analyze a large amount of textual data, picking out the relevant line(s) of interest can be quite difficult. Standard text editors usually provide a generic "find" function, but the limitations of that simple approach quickly become apparent (e.g., when it is necessary to compare two or more widely separated lines). Some more sophisticated editors do better by allowing you to "bookmark" lines of interest; this can be a big help, but is often not enough.

    The Solution: TextAnalysisTool.NET - a program designed from the start to excel at viewing, searching, and navigating large files quickly and efficiently. TextAnalysisTool.NET provides a view of the file that you can easily manipulate (through the use of various filters) to display exactly the information you need - as you need it.

    Filters: Before displaying the lines of a file, TextAnalysisTool.NET passes the lines of that file through a set of user-defined filters, dimming or hiding all lines that do not satisfy any of the filters. Filters can select only the lines that contain a sub-string, those that have been marked with a particular marker type, or those that match a regular expression. A color can be associated with each filter so lines matching a particular filter stand out and so lines matching different filters can be easily distinguished. In addition to the normal "including" filters that isolate lines of text you DO want to see, there are also "excluding" filters that can be used to suppress lines you do NOT want to see. Excluding filters are configured just like including filters but are processed afterward and remove all matching lines from the set. Excluding filters allow you to easily refine your search even further.

    Markers: Markers are another way that TextAnalysisTool.NET makes it easy to navigate a file; you can mark any line with one or more of eight different marker types. Once lines have been marked, you can quickly navigate between similarly marked lines - or add a "marked by" filter to view only those lines.

    Find: TextAnalysisTool.NET also provides a flexible "find" function that allows you to search for text anywhere within a file. This text can be a literal string or a regular expression, so it's easy to find a specific line. If you decide to turn a find string into a filter, the history feature of both dialogs makes it easy.

    Summary: TextAnalysisTool.NET was written with speed and ease of use in mind throughout. It saves you time by allowing you to save and load filter sets; it lets you import text by opening a file, dragging-and-dropping a file or text from another application, or by pasting text from the clipboard; and it allows you to share the results of your filters by copying lines to the clipboard or by saving the current lines to a file. TextAnalysisTool.NET supports files encoded with ANSI, UTF-8, Unicode, and big-endian Unicode and is designed to handle large files efficiently.

    I maintain a TODO list with a variety of user requests, but I thought I'd see what kind of feedback I got from releasing TextAnalysisTool.NET to the public before I decide where to go with the next release. I welcome suggestions - and problem reports - so please share them with me if you've got any!

    I hope you find TextAnalysisTool.NET useful as I have!

  • Delay's Blog

    Scrolling so smooth like the butter on a muffin [How to: Animate the Horizontal/VerticalOffset properties of a ScrollViewer]

    • 10 Comments

    Recently, I got email from two different people with the same question: How do I animate the HorizontalOffset/VerticalOffset properties of a Silverlight/WPF ScrollViewer control? Just in case you've never tried this yourself, I'll tell you that it's not quite as easy as you'd think; those two properties are both read-only and therefore can't be animated by a DoubleAnimation. The official way to accomplish this task is to call the ScrollToHorizontalOffset or ScrollToVerticalOffset method - but of course that can't be done by a DoubleAnimation either...

    Aside: Why are HorizontalOffset and VerticalOffset read-only in the first place? Good question; I don't know! I don't see why they couldn't be writable in today's world, but I bet there was a good reason - once upon a time. :)

    While I didn't have the time to implement a solution myself, I did have an idea for what to do. It was inspired by a rather quirky business plan and went like this:

    1. Create an attached DP for ScrollViewer of type double called SettableHorizontalOffset
    2. In its change handler, call scrollViewerInstance.ScrollToHorizontalOffset(newValue)
    3. Animate the attached DP on the ScrollViewer of your choice
    4. ???
    5. Profit

    I cautioned at the time that my idea might not work - and sure enough, when I tried it myself, it didn't! It turns out that neither Silverlight nor WPF much like the idea of pointing Storyboard.TargetProperty at an attached DependencyProperty. So much for my clever idea; I needed a different way to solve the problem... And before long I realized that I could use a Mediator just like I did for a similar situation with LayoutTransformer (see previous posts).

     

    So I created a simple class, ScrollViewerOffsetMediator, which exposes a ScrollViewer property that you point at a ScrollViewer instance (hint: use a Binding with ElementName to make this easy) and a VerticalOffset property which is conveniently writable. :) Any changes to the VerticalOffset property are automatically applied to the relevant ScrollViewer via a call to its ScrollToVerticalOffset method - so you can animate the mediator and it'll be just like you were animating the ScrollViewer itself!

    That solves the original problem and it's all well and good - but it doesn't quite address a pretty common scenario: wanting to animate a ScrollViewer from top to bottom. You see, VerticalOffset is expressed in pixels and it's not easy to pass the (unknown) height of an arbitrary ScrollViewer to an animation in static XAML. So I added another property called ScrollableHeightMultiplier which takes a value between 0.0 and 1.0, multiplies it by the ScrollViewer's current ScrollableHeight and sets the VerticalOffset to that value. In this manner, animations can be written in general, pixel-independent terms, and it's easy to get the animated scrolling effect everybody wants!

    Aside: I've implemented support for only the vertical direction - doing the same thing for the horizontal direction is left as an exercise to the reader.

     

    The sample application uses ScrollableHeightMultiplier and an EasingFunction (just to show off!) and looks like this:

    AnimatingScrollViewerOffsets sample

     

    [Click here to download the complete AnimatingScrollViewerOffsets sample.]

     

    The XAML for the sample is quite straightforward:

    <Grid Height="200" Width="150">
    
        <!-- Trigger to start the animation when loaded -->
        <Grid.Triggers>
            <EventTrigger RoutedEvent="Grid.Loaded">
                <BeginStoryboard>
                    <BeginStoryboard.Storyboard>
                        <!-- Animate back and forth forever -->
                        <Storyboard
                            AutoReverse="True"
                            RepeatBehavior="Forever">
                            <!-- Animate from top to bottom -->
                            <DoubleAnimation
                                Storyboard.TargetName="Mediator"
                                Storyboard.TargetProperty="ScrollableHeightMultiplier"
                                From="0"
                                To="1"
                                Duration="0:0:1">
                                <DoubleAnimation.EasingFunction>
                                    <!-- Ease in and out -->
                                    <ExponentialEase EasingMode="EaseInOut"/>
                                </DoubleAnimation.EasingFunction>
                            </DoubleAnimation>
                        </Storyboard>
                    </BeginStoryboard.Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Grid.Triggers>
    
        <!-- ScrollViewer that will be animated -->
        <ScrollViewer
            x:Name="Scroller">
            <!-- Arbitrary content... -->
            <StackPanel>
                <ItemsControl
                    ItemsSource="{Binding}"
                    FontSize="32"/>
            </StackPanel>
        </ScrollViewer>
    
        <!-- Mediator that forwards the property changes -->
        <local:ScrollViewerOffsetMediator
            x:Name="Mediator"
            ScrollViewer="{Binding ElementName=Scroller}"/>
    
    </Grid>
    

     

    Here's the complete implementation of ScrollViewerOffsetMediator which naturally works perfectly well on WPF:

    /// <summary>
    /// Mediator that forwards Offset property changes on to a ScrollViewer
    /// instance to enable the animation of Horizontal/VerticalOffset.
    /// </summary>
    public class ScrollViewerOffsetMediator : FrameworkElement
    {
        /// <summary>
        /// ScrollViewer instance to forward Offset changes on to.
        /// </summary>
        public ScrollViewer ScrollViewer
        {
            get { return (ScrollViewer)GetValue(ScrollViewerProperty); }
            set { SetValue(ScrollViewerProperty, value); }
        }
        public static readonly DependencyProperty ScrollViewerProperty =
            DependencyProperty.Register(
                "ScrollViewer",
                typeof(ScrollViewer),
                typeof(ScrollViewerOffsetMediator),
                new PropertyMetadata(OnScrollViewerChanged));
        private static void OnScrollViewerChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var mediator = (ScrollViewerOffsetMediator)o;
            var scrollViewer = (ScrollViewer)(e.NewValue);
            if (null != scrollViewer)
            {
                scrollViewer.ScrollToVerticalOffset(mediator.VerticalOffset);
            }
        }
    
        /// <summary>
        /// VerticalOffset property to forward to the ScrollViewer.
        /// </summary>
        public double VerticalOffset
        {
            get { return (double)GetValue(VerticalOffsetProperty); }
            set { SetValue(VerticalOffsetProperty, value); }
        }
        public static readonly DependencyProperty VerticalOffsetProperty =
            DependencyProperty.Register(
                "VerticalOffset",
                typeof(double),
                typeof(ScrollViewerOffsetMediator),
                new PropertyMetadata(OnVerticalOffsetChanged));
        public static void OnVerticalOffsetChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var mediator = (ScrollViewerOffsetMediator)o;
            if (null != mediator.ScrollViewer)
            {
                mediator.ScrollViewer.ScrollToVerticalOffset((double)(e.NewValue));
            }
        }
    
        /// <summary>
        /// Multiplier for ScrollableHeight property to forward to the ScrollViewer.
        /// </summary>
        /// <remarks>
        /// 0.0 means "scrolled to top"; 1.0 means "scrolled to bottom".
        /// </remarks>
        public double ScrollableHeightMultiplier
        {
            get { return (double)GetValue(ScrollableHeightMultiplierProperty); }
            set { SetValue(ScrollableHeightMultiplierProperty, value); }
        }
        public static readonly DependencyProperty ScrollableHeightMultiplierProperty =
            DependencyProperty.Register(
                "ScrollableHeightMultiplier",
                typeof(double),
                typeof(ScrollViewerOffsetMediator),
                new PropertyMetadata(OnScrollableHeightMultiplierChanged));
        public static void OnScrollableHeightMultiplierChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var mediator = (ScrollViewerOffsetMediator)o;
            var scrollViewer = mediator.ScrollViewer;
            if (null != scrollViewer)
            {
                scrollViewer.ScrollToVerticalOffset((double)(e.NewValue) * scrollViewer.ScrollableHeight);
            }
        }
    }
    

     

    PS - Thanks to Homestar Runner's Strong Bad for inspiring the title of this post.

  • Delay's Blog

    Never do today what you can put off till tomorrow [DeferredLoadListBox (and StackPanel) help Windows Phone 7 lists scroll smoothly and consistently]

    • 35 Comments

    In my previous post about how LowProfileImageLoader helps the Windows Phone 7 UI thread stay responsive by loading images in the background, I began with the following introduction:

    When writing applications for small, resource-constrained scenarios, it's not always easy to balance the demands of an attractive UI with the requirements of fast, functional design. Ideally, coding things the natural way will "just work" (the so-called pit of success) - and it usually does. But for those times when things need some extra "oomph", it's nice to have options. That's what my latest project, PhonePerformance is all about: giving developers performance-focused alternatives for common Windows Phone 7 scenarios.

     

    In this second post, I'll be demonstrating the use of my DeferredLoadListBox class in conjunction with the Silverlight StackPanel in order to get good performance from a scenario that's pretty common for social media applications: a scrolling list of entries with a picture and a brief bit of text. (Ex: Twitter posts, Facebook updates, blog comments, and the like.) As usual, I've written a sample application to show what I'm talking about - it displays a simple list of about 200 image+name pairs from the web (the followers of my Twitter account [you know who you are! :) ]). You can see a screen shot of the "List Scrolling" sample below:

    PhonePerformance List Scrolling sample
    Note: Everything in this post pertains to the latest (internal) Windows Phone 7 builds, not the public Beta bits. Although I'd expect things to work the same on the Beta build, I haven't verified that because the final bits will be released to the public on September 16th.
    Additional note: My discussion assumes all testing is done on actual phone hardware. Although running the emulator on a PC is a fantastic development experience, performance of applications in the emulator can vary significantly. The emulator is great for writing new code and fixing bugs, but performance work should be done on a real phone if at all possible.

     

    Okay, go ahead and run the sample and wait a moment for it to load the user list from the web (and enable those two buttons). Then choose the "default" (left) or "performance" (right) scenario and watch the behavior of the little blue dots moving across the screen as the list content populates. (I discussed the motivation behind the blue dots in the previous post - for now just remember that when the dots are flowing smoothly, life is good - and when the dots get jumpy or stop animating completely, the application is unresponsive.)

    Right now, we're interested in the different load times of the two scenarios. The "performance" side uses a StackPanel to get good scroll performance, but making that switch without doing anything else is likely to increase load times versus the default VirtualizingStackPanel used by the Windows Phone ListBox (because of the loss of virtualization; more on this later). That's why the sample also uses DeferredLoadListBox - to offset the performance loss by re-introducing enough pseudo-virtualization to bring performance back up to where it was. And as the sample application shows, the load times of the two lists are very similar. (Granted, neither is instantaneous - but it's also not the case that one is consistently faster than the other.)

    Now that both lists are populated, the real experiment begins: go ahead and scroll the "default" (left) list up and down and watch the item content as you do so. When scrolling at slow or moderate speeds, the movement will be smooth and the experience will be great. But once you start scrolling quickly, things begin to break down - you may start to see brief glimpses of missing items, flickering, or even black-outs...

    So with that baseline experience in mind, it's time to scroll the "performance" (right) list to see how it compares. The first thing you'll probably notice is that it's slower to load the images - that's due to the use of LowProfileImageLoader and was the topic of my previous post. The next thing you'll probably notice is that the scrolling is smooth for just about any speed - and especially for content that's already been on the screen at least once! I won't claim scrolling is perfect with StackPanel and DeferredLoadListBox, but it has been my experience (and that of others) that it can be notably better than the default behavior.

     

    To understand why the DeferredLoadListBox+StackPanel combination is effective, it's necessary to understand a little about how VirtualizingStackPanel works - and why that ends up being a problem in this scenario...

    Pretty much every Panel implementation for Silverlight and WPF works by measuring and arranging all its elements according to various layout guidelines (ex: stack, grid, etc.). This makes it straightforward to implement a custom Panel, but it also means that all the Children must be created and live in the visual tree from the beginning. Because in the vast majority of cases there are only a handful of children (and they're all on screen anyway), this isn't a problem. However, in the "really long list" scenario, there are often only 5-10 items on the screen at a time - and a few hundred other items that aren't. VirtualizingStackPanel works in conjunction with ItemsControl and ItemContainerGenerator to create only those elements that are actually on the screen. As the user scrolls the list, VirtualizingStackPanel automatically creates containers for any items about to come into view and recycles the containers for items that just scrolled out of view. (In reality, there's usually a screen's worth of buffer on either side.) Consequently, there are two big wins with VirtualizingStackPanel: load time (by virtue of creating only a fraction of the total elements) and memory consumption (by virtue of keeping only a fraction of the total elements around at any time).

    But (as sometimes happens in life) VirtualizingStackPanel's strength is also its weakness. All that container recycling and item juggling takes time to execute - and that's precious time on the UI thread that can't be spent doing other things (like updating the UI). So what seems to happen when a list is scrolling quickly enough is that the VirtualizingStackPanel falls behind more and more - until some of those containers that are scrolling into view are blank because they haven't been created or populated yet! And that's when the user sees visual glitches and rendering issues...

    Therefore, the fundamental approach I've taken to avoiding problems in scenarios like this is to replace the ListBox's VirtualizingStackPanel ItemsPanel with a StackPanel. This is quite easy to do - and the StackPanel's non-virtualizing nature means that scrolling long lists will be smooth as silk. However, there are two downsides to making this switch: load time is considerably longer and memory use will be significantly higher. The increased memory consumption probably won't be an issue with small- or medium-sized lists, but it could start to be a problem for large lists containing thousands of items. But while there are options for mitigating this, that's not my objective and I won't be going into them here. (Besides, I'm not sure how practical it is for people to scroll super-long lists, anyway!)

    The way I avoid longer load times is by using the DeferredLoadListBox class I wrote for just this purpose - what it does is hold off on populating off-screen containers until they're about to show up on the screen. In this manner, it restores some of the benefits of VirtualizingStackPanel by making the relevant portion of the load time (roughly) independent of the total number of items in the list. But it's important to note that DeferredLoadListBox works in one direction only! Although there's no reason it couldn't "re-virtualize" items as they scroll out of view, it specifically doesn't do so because doing (and undoing) that would consume precious CPU cycles. DeferredLoadListBox is really only about softening the blow of switching from VirtualizingStackPanel to StackPanel - it's not about trying to re-implement VirtualizingStackPanel's fundamental behavior.

    So with scrolling glitches avoided and load time back to where it started, there's just one other thing slowing things down and detracting from the user experience: the jumpiness that takes place during the first full scroll of the list. What's going on there is that the first full scroll causes all those "pseudo-virtualized" containers to be created - which causes the corresponding images to be downloaded from the web. We've established that downloading images on the UI thread is bad for performance, and this is exactly the scenario I created LowProfileImageLoader for! So by throwing LowProfileImageLoader into the mix, the first full scroll stays responsive, too.

    And at this point, we've arrived at the smooth, pleasing, consistent scrolling experience you get from the "List Scrolling" sample's "performance" column! Yay us! :)

     

    Of course, every application - and every scenario - is different, so there's no guarantee StackPanel, DeferredLoadListBox, or LowProfileImageLoader will help all the time (or even most of the time!). But what's nice is that it's extremely easy to try them out (alone or together), so there's nothing to lose by trying them out if your scenario seems likely to benefit!

     

    [Click here to download the compiled PhonePerformance assembly, sample applications, and full source code for everything.]

     

    To show what I mean, here's what the default scenario looks like:

    <ListBox ItemsSource="{Binding Followers}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Height="50">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="50"/>
                        <ColumnDefinition Width="10"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Rectangle
                        Grid.Column="0"
                        Fill="{StaticResource PhoneChromeBrush}"/
                    <Image
                        Grid.Column="0"
                        Source="{Binding ProfileImageUrl}"
                        Width="48"
                        Height="48"/>
                    <TextBlock
                        Grid.Column="2"
                        Text="{Binding ScreenName}"
                        VerticalAlignment="Center"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="Height" Value="50"/>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

    And here's all it takes to convert it to use StackPanel, DeferredLoadListBox, and LowProfileImageLoader:

    <delay:DeferredLoadListBox ItemsSource="{Binding Followers}">
        <delay:DeferredLoadListBox.ItemTemplate>
            <DataTemplate>
                <Grid Height="50">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="50"/>
                        <ColumnDefinition Width="10"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Rectangle
                        Grid.Column="0"
                        Fill="{StaticResource PhoneChromeBrush}"/>
                    <Image
                        Grid.Column="0"
                        delay:LowProfileImageLoader.UriSource="{Binding ProfileImageUrl}"
                        Width="48"
                        Height="48"/>
                    <TextBlock
                        Grid.Column="2"
                        Text="{Binding ScreenName}"
                        VerticalAlignment="Center"/>
                </Grid>
            </DataTemplate>
        </delay:DeferredLoadListBox.ItemTemplate>
        <delay:DeferredLoadListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="Height" Value="50"/>
            </Style>
        </delay:DeferredLoadListBox.ItemContainerStyle>
        <delay:DeferredLoadListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel/>
            </ItemsPanelTemplate>
        </delay:DeferredLoadListBox.ItemsPanel>
    </delay:DeferredLoadListBox>

    (Don't forget to add the appropriate XMLNS to the top of the XAML file:)

    xmlns:delay="clr-namespace:Delay;assembly=PhonePerformance"

     

    The only thing I haven't talked about yet is the requirement that each ListBoxItem container needs to have a fixed height (via the ItemContainerStyle property; see above). This is currently necessary because it enables some optimizations in DeferredLoadListBox - however, it's important to note there's no need for all the containers to have the same fixed height - just that they all need to have a fixed height.

     

    Aside: As it exists today, DeferredLoadListBox only works with vertical scrolling lists. Of course, the same concepts can be applied to horizontally scrolling lists, too, but because that's not consistent with the UI conventions of Windows Phone 7, I haven't tried to generalize the code to support both orientations. I optimized for the performance of the common scenario - but if you'd like to tweak things to support horizontal scrolling instead - or as well! - it should be fairly straightforward to do. :)
  • Delay's Blog

    Make it your own [WebMatrix's new extensibility support enables developers and applications to customize the web development experience to their liking!]

    • 5 Comments

    In conjunction with Microsoft's ongoing BUILD Windows conference, we have just released betas of the next version of the Microsoft Web Platform. Today's releases include a lot of new functionality and I encourage interested parties to have a look at what's new in ASP.NET and WebMatrix.

    In this post, I'm going to focus on one aspect of the WebMatrix 2 Beta: extensibility. By exposing a public API and opening up the application to others, WebMatrix enables individuals and community members to customize the experience to best fit their own unique processes and workflow. Many aspects of the development experience are configurable, so users can become more productive by streamlining common tasks, automating monotonous ones, and simplifying difficult ones!

     

    Task-based extensibility

    Extensibility for the WebMatrix 2 Beta takes three forms: task-based extensibility, help extensibility, and extensions.

    1. Task-based extensibility refers to the ability of a web application like Umbraco or WordPress to embed a file within the install package to customize the WebMatrix user interface for that particular application. By providing some simple XML, applications in the Web App Gallery can add custom links to the Ribbon or dashboard, protect core application files, provide enhanced Intellisense for PHP, and more.

    2. Help extensibility makes it possible to integrate custom content with WebMatrix's new, context-sensitive help pane. The new help system shows links to relevant content and videos based on where the user is in the application and what he or she is doing. Help content is drawn from a variety of sources; content providers can create custom feeds to cover new topics or provide more context on existing ones. This article explains how to create custom help content.

    3. For developers, the real power lies in the ability to write extensions that run inside WebMatrix because they're capable of far richer customization. WebMatrix extensions can be written in any .NET language, are loaded by MEF, the Managed Extensibility Framework, and installed/uninstalled (behind the scenes) as NuGet packages (with a slight twist I'll explain in a different post). Similar to Visual Studio, WebMatrix has an extension gallery that allows users to browse and install extensions from a central feed - or create and share custom feeds!

     

    ColorThemeManager

    Opening WebMatrix's extension gallery (by clicking the "Extensions/Gallery" Ribbon button from the Site workspace) shows some of the extensions that have been created to help give an idea what's possible. I'll call out three of them:

    • ColorThemeManager - This extension by Yishai Galatzer allows you to customize the colors used by the file editor in WebMatrix, export your settings, and import settings from other sources. So if you're one of those people who enjoys looking at green on black text, then you're in luck. :)

    • ImageOptimizer - This extension by Mads Kristensen makes it easy to "optimize" the PNG and JPEG images of a web site by removing unnecessary metadata and recompressing content to minimize file sizes - thereby keeping bandwidth down and site responsiveness up.

    • Snippets - This extension by me makes it easy to insert snippets of text into an open document in the Files workspace. It was written to make WebMatrix demos a little easier (watch for it in the WebMatrix: uber geek in designer clothes presentation today at BUILD!), but its simplicity makes it a good learning tool, too. I'll be blogging the complete source code for Snippets in a few days.

     

    WebMatrix Extension project template

    In addition to providing an overview of the Snippets sample, I plan to discuss other aspects of WebMatrix extensibility over the next few weeks. In the meantime, you can start exploring WebMatrix extensibility today:

    1. Download the Microsoft.WebMatrix.Extensibility CHM file, unblock it (important: click here for directions on "unblocking" a file), open it, and browse the contents. (If you see the message "Navigation to the webpage was canceled", then the file is still blocked.)

    2. Download the "WebMatrix Extension" Visual Studio project template, save the ZIP file in your "%USERPROFILE%\Documents\Visual Studio 2010\Templates\ProjectTemplates" directory, choose File, New, Project in Visual Studio 2010, select the "Visual C#" node, click the "WebMatrix Extension" item, type a project name (ex: "MyExtension" (no spaces, please)), and click OK.

    The project template sets up the right infrastructure, all the necessary references, includes pre- and post-build rules to make development a little easier, and helps get you started with a simple Ribbon-based extension that demonstrates some of the basic extensibility points. The template's ReadMe.txt explains how to configure Visual Studio so that pressing F5 will automatically load the extension inside WebMatrix for a simple, seamless debugging experience with complete breakpoint support, etc.. FYI that I'd like to improve this template by adding support for NuGet package generation (so it will be easier to deploy extensions to a gallery) and maybe also create a VISX wrapper for it (to enable more seamless install of the template itself).

    Aside: While the project template "helpfully" copies your extension to the right place for WebMatrix to load it on startup, the extension is not properly installed and so WebMatrix doesn't know how to uninstall it. For now, the easiest way to get rid of a custom extension is to close WebMatrix and delete the contents of the "%USERPROFILE%\AppData\Local\Microsoft\WebMatrix\Components" directory.

     

    The new extensibility APIs in the WebMatrix 2 Beta allow developers to get started with extensions today. And while there aren't yet extension points for everything, there are enough to enable some pretty interesting scenarios. Available extension points include:

    Microsoft.WebMatrix.Extensibility help file
    • Ribbon content
      • Buttons, groups, tabs, etc.
    • Application information
      • Name, local path, remote URI
    • Integrated dialog and notification UI
    • Context menu items for application files/directories
    • Editor manipulation
      • Text buffer, settings, theming, custom types
    • Dashboard content
    • Simple commanding
    • Active workspace
    • More...

    That said, people are going to have a lot of great extension ideas that are either difficult or impossible to achieve with the Beta APIs. Not being able to put good ideas into practice is certainly disappointing, but it's also a great opportunity to let us know what features are missing from the API and how we can improve it! To make that easy, there's a WebMatrix forum where you can ask questions and exchange ideas. Once you've tried things out, please go there and share your thoughts!

     

    Aside: It probably goes without saying (but I'll say it anyway!) that the APIs available in the WebMatrix 2 Beta are subject to change and it's likely that extensions written for Beta will need to be modified in order to run on later releases. That's not to discourage people from writing extensions, but rather an attempt to set expectations appropriately. :)
    Further aside: It's natural to wonder if existing plugins for Visual Studio will "just work" in WebMatrix. The answer is that they will not - but in most cases it turns out that trying to load a Visual Studio extension inside WebMatrix wouldn't be all that meaningful anyway... At this point, the functionality of these two products and the target audience (both users and developers) are different enough that things don't align in a way that makes this scenario work.
  • Delay's Blog

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

    • 17 Comments

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

  • Delay's Blog

    My new home page, rejuvenated [Updated collection of great Silverlight/WPF/Windows Phone Data Visualization resources!]

    • 23 Comments

    It's been a few months since I posted my previous collection of Silverlight/WPF Charting links. In the meantime, the April 2010 release of the Silverlight Toolkit was published with support for stacked series and significant performance improvements! And Windows Phone 7 has been steadily building momentum - it's handy that the Data Visualization assembly also works on Windows Phone!

    So there's lots of good stuff - here are all the links (FYI: previously published links are gray):

    Overviews (100 level)

    Scenarios (200 level)

    Internals (300 level)

    Team Member posts (Partner level)

    My posts (Ego level)

    Many thanks go out to everyone who has spent time helping people learn how to use Silverlight/WPF/Windows Phone Data Visualization!

    PS - If I've missed something useful, please send me a link - I'm always happy to find more great content! :)

    PPS - The most recent version of this collection will always be pointed to by http://cesso.org/r/DVLinks. If you're going to create a favorite or link to this post, please use that URL so your link will always be current.

  • Delay's Blog

    Controls are like diapers: you don't want a leaky one [Implementing the WeakEvent pattern on Silverlight with the WeakEventListener class]

    • 25 Comments

    One of the nice things about developing on a platform that uses a garbage collecting memory manager (like Silverlight and WPF) is that the traditional concerns about memory leaks pretty much go away; most common types of memory leaks are impossible in a garbage collected environment. I say "most" and not "all" because there are still a few ways to leak memory - typically by creating a reference to an object and then "forgetting" about that reference. Sometimes this forgetfulness is simply an oversight on the part of the developer, but sometimes it is due to the reference being created in such a way that it's not obvious it even exists...

    One of the easiest ways to create a "hidden" reference is by creating an event handler. Greg Schechter blogged in detail about the event handler situation back in 2004, and interested readers would do well to refer to his post for more details and some pretty diagrams. To summarize the issue briefly: when component A attaches an event handler to an event on component B, what happens behind the scenes is that component B creates a reference to component A - which it needs in order to provide a notification to A when the event is fired. This "backwards" reference is a bit subtle, but if you know what you're looking for, it's usually not too hard to spot.

    What's more challenging is when a component you're using creates one of these backwards references in response to an action that's (superficially) completely unrelated to the event handling. As an exercise, see if you can spot the event handler here:

    control.ItemsSource = collection;

    Not so obvious, huh? :) The context needed to understand what's going on here is that an the control variable is some type that derives from ItemsControl (such as ListBox) and the collection variable is some type that derives from ObservableCollection<T>. It so happens that when an ItemsControl sees an assignment to its ItemsSource property of an object that implements INotifyCollectionChanged, it automatically adds a handler for that object's CollectionChanged event. And there's the potentially troublesome backward reference...

    All it takes to start leaking memory at this point is an application with a long-lived reference to an ObservableCollection that gets passed to a short-lived ItemsControl that gets discarded. What can end up happening is that all of the references to the ItemsControl go away when it is discarded except for the one the ItemsControl itself created to listen to CollectionChanged events. Unless something is done to avoid this problem, the long-lived reference to the ObservableCollection will inadvertently keep the ItemsControl and all of its references alive considerably longer than the application developer expects. Furthermore, if the application is creating and discarding these ItemsControls on a fairly regular basis, it will quickly build up a sizable memory leak due to the accumulation of all the "discarded" ItemsControls.

    As luck would have it, this situation was well understood and by the WPF team and that platform exposes APIs to implement what they call the WeakEvent pattern. WPF makes use of the WeakEvent pattern for its own ItemsControl, so the scenario described above isn't a problem in practice.

    However, the WeakEvent pattern APIs don't exist in Silverlight 2 and the scenario above actually is a problem for ItemsControl and its subclasses as well as the DataGrid, and Charting's Series classes (each of which has a non-ItemsControl-based ItemsSource property). The good news is that Silverlight intends to fix this problem for ItemsControl-derived classes as part of a future release. Unfortunately, that doesn't help Charting - and besides I'd like to help customers avoid this problem on the current release...

    So I got in touch with Silverlight developer Ivan Naranjo to see if his team had anything we could make use of and he kindly responded with something very much like the WeakEventListener class you see below. (For my part, I just tweaked things to address a few code- and source-analysis warnings and made a small change to avoid a possible area of confusion Ivan and I independently agreed on.) If you read Greg Schechter's post, the technique and implementation should look pretty familiar - WeakEventListener is a small, intermediary class that can be attached to an event so the resulting backwards reference affects only the extremely lightweight WeakEventListener and not the heavyweight class that created it. This avoids the costly "hidden" reference and allows the owning class to be garbage collected as soon as it is no longer in use. It was easy to add a WeakEventListener in Charting's Series.ItemsSource handler - and now our users don't have to worry about inadvertently leaking Chart instances!

    To show just how easy it is to use WeakEventListener, I created a sample project that you can download and experiment with as you read the rest of this post. Here's what it looks like:

    WeakEventListener Sample Application

    The sample application includes two custom controls: LeakyControl (which has a typical ItemsSource implementation) and FixedControl (which uses WeakEventListener). To see the problem and solution in action, start the application, click the "Check Status" button to verify both controls are present, then click "Remove From UI" to discard both controls. If you click "Check Status" again at this point, you'll see that both controls are still present - and that's expected because the garbage collector hasn't needed to run and so nothing has been done to clean up. Now click "Garbage Collect" and then "Check Status" again. You'll see that LeakyControl is still present, but FixedControl is gone. Yay, WeakEventListener works! :)

    Now, take things just a bit further and click "Clear ItemsSource", then "Garbage Collect", then "Check Status". We see that LeakyControl is gone as well! Why? Because by setting ItemsSource property of LeakyControl to null, we've explicitly told it we were done with the old collection and it knew enough to remove its event handler from that collection - thereby breaking the backwards reference and making itself eligible for clean-up during the next garbage collection. And, in fact, this is the workaround for controls that don't implement some form of the WeakEvent pattern and suffer from leaky behavior because of it: null-out the relevant property and hope they're kind enough to detach their event handlers in response. Depending on your application scenario, implementing this work around may be quite simple - or it may be almost impossible if your application has no way of knowing when some subcomponent has gotten into this situation - or no explicit knowledge of when affected controls are removed from the user interface. That's why it's nice when controls behave properly on their own - they work no matter what you do! :)

    For an idea of how an easy it is to make use of WeakEventListener in a control, here is the relevant (leaky) code from LeakyControl:

    // Change handler for the ItemsControl.ItemsSource-like DependencyProperty
    private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
    {
        // See if the old value implements INotifyCollectionChanged
        var oldNotifyCollectionChanged = oldValue as INotifyCollectionChanged;
        if (null != oldNotifyCollectionChanged)
        {
            // It does; detach from the CollectionChanged event
            oldNotifyCollectionChanged.CollectionChanged -= OnCollectionChanged;
        }
        // See if the new value implements INotifyCollectionChanged
        var newNotifyCollectionChanged = newValue as INotifyCollectionChanged;
        if (null != newNotifyCollectionChanged)
        {
            // It does; attach to the CollectionChanged event
            newNotifyCollectionChanged.CollectionChanged += OnCollectionChanged;
        }
    }
    

    And here's what that same code looks like in FixedControl where WeakEventListener is used to avoid the backward reference problem:

    // Change handler for the ItemsControl.ItemsSource-like DependencyProperty
    private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
    {
        // See if the old value implements INotifyCollectionChanged
        var oldNotifyCollectionChanged = oldValue as INotifyCollectionChanged;
        if (null != oldNotifyCollectionChanged)
        {
            // It does; detach our WeakEventListener and clear our reference
            _weakEventListener.Detach();
            _weakEventListener = null;
        }
        // See if the new value implements INotifyCollectionChanged
        var newNotifyCollectionChanged = newValue as INotifyCollectionChanged;
        if (null != newNotifyCollectionChanged)
        {
            // It does; create a WeakEventListener, attach us to it, and add it to the event
            _weakEventListener = new WeakEventListener<FixedControl, object, NotifyCollectionChangedEventArgs>(this);
            _weakEventListener.OnEventAction = (instance, source, eventArgs) =>
                instance.OnCollectionChanged(source, eventArgs);
            _weakEventListener.OnDetachAction = (weakEventListener) =>
                newNotifyCollectionChanged.CollectionChanged -= weakEventListener.OnEvent;
            newNotifyCollectionChanged.CollectionChanged += _weakEventListener.OnEvent;
        }
    }
    

    Note that the basic structure of the code is unchanged - there's just a bit more bookkeeping involved in creating and hooking up the WeakEventListener. The first thing to look at is the bottom half of the method where a new collection is handled - a WeakEventListener instance is created and a couple of properties are set. The OnEventAction property specifies a strongly-typed (thanks to WeakEventListener being generic!) function that gets called when the event is fired - this maps to whatever method would otherwise be used to handle the event. The OnDetachAction property specifies a strongly-typed function that gets called when the WeakEventListener is detached from the event it's listening to - it simply removes the WeakEventListener's handler for the event. (Note that this function takes a WeakEventListener parameter which should be used to unhook the event so as to prevent creating a closure that itself contains a hidden reference that could cause a leak. And if that last sentence makes no sense, don't worry about it - just follow the pattern shown here and you'll be fine.) Now that everything's in place, the WeakEventListener is attached to event of interest. Going back to the top half of the function, all that needs to be done is to manually detach the WeakEventListener from the event. The example also sets the WeakEventListener reference to null - but this is done for clarity and debugging convenience and not because it's necessary.

    That's all there is to it - WeakEventListener adds only a couple of lines of code and saves gobs of aggravation!

    Aside: People who prefer not to use anonymous methods like I've done here are welcome to write explicit methods to do the same thing. It's a few more lines of code and a tiny bit more work, but if you go that route, you can create static methods which almost guarantee you won't inadvertently create a leaky closure. Either way you do it, WeakEventListener works the same.

    Finally, here's the complete implementation of WeakEventListener for anyone who's curious how it works:

    /// <summary>
    /// Implements a weak event listener that allows the owner to be garbage
    /// collected if its only remaining link is an event handler.
    /// </summary>
    /// <typeparam name="TInstance">Type of instance listening for the event.</typeparam>
    /// <typeparam name="TSource">Type of source for the event.</typeparam>
    /// <typeparam name="TEventArgs">Type of event arguments for the event.</typeparam>
    internal class WeakEventListener<TInstance, TSource, TEventArgs> where TInstance : class
    {
        /// <summary>
        /// WeakReference to the instance listening for the event.
        /// </summary>
        private WeakReference _weakInstance;
    
        /// <summary>
        /// Gets or sets the method to call when the event fires.
        /// </summary>
        public Action<TInstance, TSource, TEventArgs> OnEventAction { get; set; }
    
        /// <summary>
        /// Gets or sets the method to call when detaching from the event.
        /// </summary>
        public Action<WeakEventListener<TInstance, TSource, TEventArgs>> OnDetachAction { get; set; }
    
        /// <summary>
        /// Initializes a new instances of the WeakEventListener class.
        /// </summary>
        /// <param name="instance">Instance subscribing to the event.</param>
        public WeakEventListener(TInstance instance)
        {
            if (null == instance)
            {
                throw new ArgumentNullException("instance");
            }
            _weakInstance = new WeakReference(instance);
        }
    
        /// <summary>
        /// Handler for the subscribed event calls OnEventAction to handle it.
        /// </summary>
        /// <param name="source">Event source.</param>
        /// <param name="eventArgs">Event arguments.</param>
        public void OnEvent(TSource source, TEventArgs eventArgs)
        {
            TInstance target = (TInstance)_weakInstance.Target;
            if (null != target)
            {
                // Call registered action
                if (null != OnEventAction)
                {
                    OnEventAction(target, source, eventArgs);
                }
            }
            else
            {
                // Detach from event
                Detach();
            }
        }
    
        /// <summary>
        /// Detaches from the subscribed event.
        /// </summary>
        public void Detach()
        {
            if (null != OnDetachAction)
            {
                OnDetachAction(this);
                OnDetachAction = null;
            }
        }
    }
    
Page 3 of 28 (277 items) 12345»