Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Slides and demo from Bleeding Edge’2009

On this year’s Bleeding Edge conference I had a talk on debugging with my fellow SQL Server MVP. While he covered some common pitfalls, awaiting developers on the SQL Server side, I focused on the Silverlight side of development and debugging:

  • possible issues with application deployment
  • options and strategies for returning WCF faults with Silverlight 3
  • using windbg with Silverlight application to track its execution
  • finding data binding failures and memory leaks

This was our sample application: Bleeding Edge Shoppe[opens in new window]

Bleeding Edge Shoppe

[The full source code will be available shortly.]

And the slide deck:



Adventures in Silverlight LOB: The beginning

This is the beginning of what’s going to be yet another series focusing on developing LOB applications with Silverlight. I’ve been wanting to write more on this topic since NTK, but there was always something else… In the series, I’ll build a sample application, similar to what I’ve been presenting on NTK. Each post will focus on a specific area, technique or a trick, and show the actual implementation in the sample LOB app, following different patterns I’ve been using in application development in past couple of years. Any comments are welcome.

In this first post, we’ll set up the initial environment for the sample app and write a few words about sharing entities between client and server. This has already been discussed a lot, so I won’t get into greater detail, I’ll just focus on the main points.

Creating a new project

When creating a new Silverlight project, Visual Studio will ask you about creating the accompanying web project as well. The web project will host our data services so it’s kind of important to leave it be.

Adding the entities projects

Create two projects that will host the shared entities. One project will be referenced from the web project (server side), while the other one will be referenced from the Silverlight project (client side). Entity sharing is done in two steps. First is the physical sharing of the files – the “main” entity project would contain the original entity files, while the “supporting” entity project would only host copies of the entity files. Choosing “Add as Link” option in Visual Studio’s Add Item dialog will create a “copy” of the original file, meaning that you’re going to have to change the contents of the file in one place only, while it will be compiled in two different projects.

A couple of notes:

  • I usually choose the server side entity project to include the original files, and the client side would include the linked files.
  • When adding new entities to the main entity project, add the linked files to the other project before regenerating the service proxy; creating the proxy before that will make a proxy copy of the entity class which may result in some confusion when working with that entity.
  • It’s a good thing to declare your entity classes as partial, because you can later extend them with specific functionality on either server or client side.
  • When I started on my LOB apps several months ago, I had the following rule regarding marking entities with WCF serialization attributes: when all properties are going to be serialized, don’t mark any; when at least one shouldn’t be serialized, mark those, which should be. Later in the project I found out that it’s much more future-proof and consistent to always mark properties with proper serialization attributes.
  • As I’m seeing this is not a general practice with Silverlight developers, I still always separate the WCF contract (interface) from the service implementation. We’ll se how/if we can benefit from such approach later in the series.

So far, the solution looks like this:

solution

We started with a single entity called Person and the DemoService will be used to access the “database”. To keep it simple, the Database class will pose as an in-memory database.

Creating the client

The sample app uses a typical MVVM approach – a ViewModel, instantiating a service proxy and handling the communication with the service, with a View, responsible for displaying the data. The user can browse through the list of persons by clicking their name in the ListBox, while full details are being displayed next to it. I’m not using any real commanding yet, ListBox’s SelectedItem is bound two-way to appropriate VM property, which is also the source for the detail UI. All-in-all, very basic and common setup, which will be the starting ground for all next articles in the series. In the next part, we’ll add a support for editing a Person entity.

Run the application

Shout it

Silverlight, Prism EventAggregator and “lost events”

I’ve just started discovering Prism, mainly as a tool to help me use the MVVM with my apps. That said, by now, Prism proved itself with:

  • Support for Commanding
  • EventAggregator
  • Unity integration
  • Targeting both WPF and Silverlight

EventAggregator is great for inter-VM communication, but only when subscribing VM(s) is/are alive (instantiated) when publishing VM publishes the event. I may be wrong here (please somebody correct me), but I haven’t found a way for a newly instantiated subscriber VM get to already broadcasted event, which was published before the instantiation. The example here would be a new dialog window, with its VM wanting the last value that parent’s VM published before dialog was created (a selected ListBox value, for example). Sure, the publisher could publish the same event again after the dialog is created, but this would confuse things up because there may be other listeners subscribed to it and perhaps wouldn’t know how to handle the exact same event.

To solve this issue, I created a new class, deriving from the CompositePresentationEvent<T> and called it CachingCompositePresentationEvent<T>. The implementation is simple:

public class CachingCompositePresentationEvent<T> : CompositePresentationEvent<T>
{
    public bool HasValue { get; private set; }

    private T lastPayload;
    public T LastPayload
    {
        get
        {
            if (!HasValue)
            {
                throw new InvalidOperationException();
            }
            return lastPayload; 
        }
        private set
        {
            lastPayload = value;
            HasValue = true;
        }   
    }

    public override void Publish(T payload)
    {
        LastPayload = payload;
        base.Publish(payload);
    }
}

The HasValue will return true when at least one event was published at the time, and LastPayload will return the payload, included in the last published event.

If the event is declared as:

public class MyCachingEvent : CachingCompositePresentationEvent<int> { }

… then getting to its value would be:

MyCachingEvent ev = aggregator.GetEvent<MyCachingEvent>();
if (ev.HasValue)
{
    int value = ev.LastPayload;
}

This is the basics, there's plenty of room for improvement - like adding a Clear() method to clear the last payload value or clear it automatically on the first LastPayload read - just to clear the memory, when payload types aren’t simple/small.

Shout it

Countdown to Silverlight 3 #15: UI Virtualization

Silverlight 3 includes a new type of a StackPanel, called VirtualizingStackPanel. VirtualizingStackPanel enables UI virtualization and is now the default items panel for the ListBox, with virtualization option enabled.

If you want to turn UI virtualization in ListBox to off, set its VirtualizingStackPanel.VirtualizationMode to Standard (the default is Recycling). The embedded VirtualizingStackPanel will in this case behave as a plain old StackPanel.

VirtualizingStackPanel can be used with any ItemsControl, but it can’t be used on its own (like putting in on a page and manually cram a couple thousand of items on it as you could do with ordinary StackPanel). But the interesting thing is it is derived from an abstract class called VirtualizingPanel, which means the ability to create new kinds of virtualizing panels (!)

The following example shows the difference between Virtualization modes. I intentionally created a heavier item template for the UI, so difference would be more obvious. Try scrolling both ListBoxes to see how UI virtualization impacts the scrolling performance.

UI Virtualization

Run the application online

Source code below:



Countdown to Silverlight 3 #14: Selector.IsSynchronizedWithCurrentItem

Silverlight 3 puts the ICollectionView interface to some serious use and brings us the CollectionViewSource class, which provides a view on top of the data collection, meaning you can sort, filter or group your items within your view, without actually changing the underlying data. One artifact, coming with the class, is the IsSynchronizedWithCurrentItem property, which enhances the collection with a notion of a currently selected item. When Selector’s IsSynchronizedWithCurrentItem property is set to true, all other controls, bound to the same collection, are kept in sync with the selected item. Silverlight’s implementation is a bit different than WPF’s. You can’t set IsSynchronizedWithCurrentItem property to true by yourself, the value is determined from your Items source. If it implements the ICollectionView interface, then it’s going to be synchronized, unless explicitly turned off (with setting the property to false).

For this example, I created three ListBoxes, all bound to the CollectionViewSource. Two of them are kept in sync, the third one is not because it’s IsSynchronizedWithCurrentItem property is set to false. I put up a few additional TextBlocks, bound to other item properties, to show the synchro-magic going on behind all this.

There’s more to ICollectionView interface, but that’s also another post…

Run the application online

Source code below:

Countdown to Silverlight 3 #13: Bitmap effects

Silverlight 3 shipped with 2 built-in bitmap effects that can be applied to any UIElement – those are DropShadow and Blur. But not to worry, we can create and use a lot more effects, because these are pixel shaders, compatible with the ones built for WPF. There are quite a few WPF (now even including SL support) effects libraries out there and I will be looking at those in one of the future posts. This time, it’s only this simple and very straightforward example, showing off the two built-in effects.

SL3 Bitmap effects

Run the application online

Source code below:

Countdown to Silverlight 3 #12: ClearType font rendering

Text readability is very important for any LOB application and since Silverlight 3 is aimed towards creating LOB apps, Microsoft decided to address the readability issue by supporting ClearType in the final SL3 release. The best thing is – it’s on by default, but you can turn it off when you’re about to perform some kind of animation with it. Turning the ClearType off will improve the text rendering performance when animating it, since antialiasing requires some additional calculations and performing that for several times per second might result in a jerky animation. To turn the rendering optimization off, set the TextOptions.TextHintingMode property to Animated. To turn it back on after you’re done with the animation, you can either clear the property or set it to Fixed.

SL3 ClearType

Run the application online

Source code below:

Countdown to Silverlight 3 #11: Writeable Bitmap

Want to create a new bitmap image in Silverlight? Want to capture a part of your application and use it as a brush? Silverlight has an answer for you – WriteableBitmap is a BitmapSource-derived class that you can manipulate in the runtime, either by rendering UI elements on it or by manipulating pixels manually. The example (below) will show how to capture a movie frame or an entry form, along with altering some pixels on the captured image – try moving your mouse over either of the captured images.

Run the application online

Source code below:

Countdown to Silverlight 3 #10: Animation easing

Doing non-linear animations with Silverlight 2 involved “playing” with key splines, and it took quite some time to get it right, even if using a tool like Expression Blend. Silverlight 3 puts some ease in this process by introducing the new, predefined, so-called easing functions, that can be applied to an animation to affect its state while progressing through time. It’s similar to what you could achieve with the splines, but without the fuss. The functions include some standard progressions (Circle, Cubic, Exponential, Quadratic, etc), with a couple of more interesting ones (Back, Elastic).

If the provided functions not enough for you, you can create your own function by creating a new class, deriving from the EasingFunctionBase class. I’ve created a “JerkyEase” animation, which is really a very simple linear animation, but with a random jerky-interrupty points to make it look… well, kind of underperformant. Totally useless, but it made it into the sample deck until I figure out something more usable.

Run the application online

Source code below:

Countdown to Silverlight 3 #9: Day 0 and updated sample deck

After a week of spending my holidays, enjoying the sun and playing on the beach with my kids, it’s time to continue the Silverlight 3 countdown series… In the meantime, Silverlight 3 was officially released (it’s probably best to only reference the “Cream” of the SL3 release posts here, in case you missed all the fun, like I did).

I updated my Countdown sample application to match the SL3 RTW bits, with all the necessary changes, most of them having to do with OOB API changes (read more about SL2/SL3B breaking changes here). Visual Studio is now also providing a nice new settings screen for describing your OOB application.

OOB

I’ll continue adding more examples of SL3 new features in the future.

Congrats and thanks to everybody having their part in getting the Silverlight 3 release ready and out so soon after the initial release.

Run the updated application online[SL3RTW required]

Source code below: