Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Silverlight Layout States with Reactive Extensions

I’ve been working on several applications where I needed to display several items in a ListBox (or an ItemsControl) at startup, but they had to appear on the screen one by one, with a short delay, not all at once. Using ListBoxItem’s layout states took care of handling how an individual item would appear in the list, but I still needed to handle a short pause between each item being added to the list. Usually I resorted to using a Timer, which sorted out that needed delay for me, but that really felt like hacking that had nothing to do with the real problem.

Reactive Extensions, however, offer a much elegant solution. The GenerateFromTime() construction operator is a close relative to the Generate() operator used in my previous blog entry, except GenerateFromTime() adds an important time dimension to generated sequence – the last parameter in this operator lets you specify a delay between each call to OnNext():

private readonly IObservable<string> numbers = Observable.GenerateWithTime(1, i => i <= 8, i => i + 1, i => i.ToString(), i => TimeSpan.FromSeconds(.3));

The above code snippet will produce an observable sequence of 8 strings, progressing through these strings with a 0.3 seconds delay.

The rest of the code:

private void OnLoaded(object sender, RoutedEventArgs e)
{
    numbers.ObserveOnDispatcher().Subscribe(AddImage);
}

private void AddImage(string image)
{
    list.Items.Add(image);
}

Note the ObserveOnDispatcher() operator again – GenerateWithTime uses a timer operating on a background thread so we need to ensure the AddImage() method is called on the UI thread.

Layout states for this sample are kept really basic:

<VisualStateGroup x:Name="LayoutStates">
    <VisualStateGroup.Transitions>
        <VisualTransition GeneratedDuration="0:0:1">
            <VisualTransition.GeneratedEasingFunction>
                <CubicEase EasingMode="EaseOut"/>
            </VisualTransition.GeneratedEasingFunction>
        </VisualTransition>
    </VisualStateGroup.Transitions>
    <VisualState x:Name="AfterLoaded"/>
    <VisualState x:Name="BeforeLoaded">
        <Storyboard>
            <DoubleAnimation Duration="0" To="-94" Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
            <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="grid" d:IsOptimized="True"/>
        </Storyboard>
    </VisualState>
    <VisualState x:Name="BeforeUnloaded"/>
</VisualStateGroup>

And the final result can be observed by following this link.image

This post has shown how to use Reactive Extensions in Silverlight to gradually fill a ListBox, with a bonus of a nice item entry animation, provided by the layout states.

Download source code from here.



Reactive Extensions – from pull to push: where’s the block?

I’ve discussed Reactive Extensions with a few people after my Rx talk last week and thought I’d clear up some confusion by clarifying on this blog…

One thing to know about Reactive Extensions is that simply going from pull model (enumerating) to push model (observing) doesn’t give you immediate background thread processing – everything is still happening on the same thread.

For example, let’s look at the following code and put a few debugger breakpoints in it:

image

Right at the top, there’s an array of image names I’m adding to the ListBox (AddImage() method). In this WPF app, the OnLoaded() method handles the Loaded event, where foreach loop iterates through the array and calls the AddImage() method.

Red balls indicate the places where I’d put the breakpoints, and the number in it tells the order in which they would be hit. Following the track, it is obvious that the OnLoaded() method is blocking until all images in the array is added into the ListBox.

To transform this code to use the observer/pull model, the following changes are made:

  1. The array (now an IObservable<string>) is generated with the Generate() Observable constructor.
  2. foreach loop is removed from the OnLoaded() method and replaced with the Observable subscription, providing the methods for OnNext and OnCompleted.

The Subscribe() method looks harmless sitting alone on now shortened OnLoaded() method, but guess what – it’s still blocking it! Take a look at the execution path: the code would enter the method, and upon subscription, starts calling the AddImage() method. After that, it calls OnCompleted() and then, only then, continues the execution in the OnLoaded() method and finally exits.

The thing to be careful about here is the fact that even if the images.Subscribe() method looks innocent and instant, it may be executing a long(er) time, if an observable sequence is very long. Which also means that the current thread will be blocked for that time also. And we don’t want the UI thread blocked.

image

What we can do to achieve the behavior we want and expected (not blocking the UI) is forcing subscription on a new – background – thread and expect the observable to call us back on the UI thread. Note that the AddImage() method has to be called on the UI thread because the code accesses the ListBox and if called from a non-UI thread, the call would fail. The code below exercises these changes and results in a whole different flow: upon subscription, the UI thread exits the OnLoaded() method immediately, while the subscription processing is done in a new thread. ObserveOnDispatcher() operator ensures that for each element in the observable sequence, AddImage() method is safely called on the UI thread.

image



Bleeding Edge 2010: Reactive Extensions Slides and Demo

These are slides and demo from my talk on Reactive Extensions from Thursday’s Bleeding Edge conference:

Slides | Demo code

Thanks to all for attending the talk.



What's Wrong with *my* WCF Service?

While I was watching the Silverlight TV episode on common WCF service issues with Silverlight (Silverlight TV 46: What's Wrong with my WCF Service?) I remembered one more issue that bit my neck a while back and thought it was worth pointing it out again... It was one of those “Service returned ‘Not found’” issues, except nothing I would do seemed to help solving it.

My simple WCF service was returning an IEnumerable<T> and I was using a Linq query for filtering the results before returning them to the client. Can you guess where I’m going to?

Let’s step back and take a look at the symptoms I was facing: the original problem was that service call returned with the infamous “NotFound” exception.

I would try using Client Http Stack to get more info about the exception – nothing. Reverted to Browser Http Stack and implemented service stack to return Faults – still nothing. I wrapped my service method call into a try…catch statement inside service method – no errors would’ve been caught on the server side and the NotFound error would persist… Furthermore, stepping through the service code didn’t throw any exceptions and the error only happened when service call returned one or more records. When there was zero, it returned fine… Hmmm… Something happening on the wire? Fiddler wasn’t much of a help either.

What helped at last was a careful examination of the service method call. Facepalm! I was failing in materializing the Linq query by not forcing its evaluation with the .ToList() extension method (or similar) and data never made it to the other side.

Lesson learned – when your services return IEnumerable and you’re using Linq to query/transform data double check that you’re returning something that client would actually have a chance enumerating.



Watch Silverlight TV videos, pinned to full screen

One of the “annoyances” with Silverlight (and similar browser plugins) is with watching a video in a multi-monitor set up – you would pop out your Silverlight video player to full screen on one monitor and continue working on your other monitor – which would cause your video player to return to its normal size, ruining your watching experience. Well, that was the case until Silverlight 4 came out. Silverlight 4 supports “full-screen pinning” in a way that you can choose the Silverlight 4 app to remain pinned to full screen on one monitor even if you focus your work on the other.

Unfortunately, (the regular) Channel 9 still doesn’t use Silverlight 4 which means you don’t get this option of full-screen pinning, but guess what – Channel 9 is in a process of refurbishing and a preview of the new site is available at the http://preview.channel9.msdn.com. This is good news for us because they’re using Silverlight 4 for their player, which basically means you can watch your Silverlight TV full-screen pinned simply by prefixing Silverlight TV show’s URL with the word preview. For example, show 40: You Are Already a Windows Phone Developer is available on http://preview.channel9.msdn.com/shows/SilverlightTV/Silverlight-TV-40-You-Are-Already-a-Windows-Phone-Developer/.

However, there seems to be a lag with publishing new content, resulting in shows not being available on the preview site at the same time as on the regular time. At the time of this writing, it appears that Show 40 is the last one available on the preview site, with shows 41 and 42 remaining on the regular site only. Anyway, it’s good to see Channel 9 going Silverlight 4 – hope to the new site up and running soon.



Microsoft Silverlight 4 Data and Service Cookbook [Review]

It’s been a while since Silverlight 4 was released by Microsoft and while we’re patiently waiting for a few other books to be released, I would definitely recommend the "Microsoft Silverlight 4 Data and Service Cookbook” by Gill Cleeren and Kevin Dockx. It’s not an advanced book on Silverlight, nor is it a reference book, it’s compilation of useful, hands-on recipes to get you started on data scenarios using Silverlight 4. If you’re new to Silverlight, you’ll definitely appreciate the way this book is written: a short description of a problem will guide you through the provided code example and explanation of what and why, usually followed by the “There’s more…” section - and that’s the part that will be appreciated even by more advanced Silverlight developers, as it would reveal some hidden tricks and not-so-known secrets of Silverlight framework’s workings. As scenarios go, those seem to cover basic to intermediate type of problems, with advanced problems left out, which is kind of understandable, but at certain points in the book I still wished the authors would write more about an alternative implementation(s) of a solution, or point me to some (online) resource for further reading.

The book covers Silverlight data scenarios, starting with the essentials like Data Binding, moving its way through explaining the data controls and finally settle on explaining the ways Silverlight could talk to the data server through various services. Special chapters are dedicated to WCF RIA Services and converting existing applications to use Silverlight, the latter explaining a few of Microsoft technologies and APIs that are not directly associated to Silverlight, but which Silverlight applications could benefit a lot from by using them.

If you’re new to Silverlight and want to develop Line-of-Business applications, this book is definitely for you as it will get you started immediately and give you enough information to build on the provided code examples for yourself. If you’re an advanced Silverlight user, I think there are some high points in this book that will gain you additional knowledge on the subject, but be prepared to read a lot of code/XAML listings which you probably already know how they work and the problems they solve.

All in all, the “Microsoft Silverlight 4 Data and Service Cookbook” is a great Silverlight book to have – it’s available in print or digital edition (plus all code examples are available for download).



My NTK10 slide decks

Another NTK has ended, and in my opinion, this year’s conference was one of the greatest and most enjoyable for the past few years. This is a list of sessions I had (alone or with co-speakers), along with the PowerPoint slide decks (all in Slovenian Language):

Silverlight and MEF

[The Photo Gallery application I was showing is available on the CodePlex and will be updated with the latest bits shortly]

ASP.NET, WebForms, Silverlight – What to choose?

Having @dusanzu as a co-host, this was a Birds of Feather (BoF) session. And although not listed as such, it turned out great anyway. There wasn’t much slides since this was a discussion – the slide-deck will be available from the NTK site.

Silverlight and WCF RIA Services

[I built a basic NTK schedule viewer app from the scratch, using Silverlight Business project template and showing off different features of RIA Services in the process. If somebody is interested in seeing the code that was produced on the talk, please contact me]

Tips & Tricks: Expression Blend for Developers

Again, we (@krofdrakula and I) wanted to show as much useful information and show designer-developer workflow, so we concentrated on showing off Visual Studio, Expression Blend (through Team Foundation Server running in a cloud), and the result was only a two-slide PowerPoint slide-deck (which will be available for download from the NTK site as well). As it turned out, even those two slides were way too much for what we wanted to share in a 45-minute time slot.

What’s new in Silverlight 4?

[The source code accompanying this slide-deck is way overdue for publishing – stay tuned for my future blog posts, where I’ll cover all the features I put together in my Silverlight 4 demo app]

A big thanks to all that attended my talks, I hope to hear from you in the near future. Another big thanks goes to local Microsoft office, for organizing another great event.

Oh, and another thing – this year’s NTK conference was covered through twitter as well (significantly better than last year, but still, plenty of room to improve for the next year). I’ll sign off with the snapshot of Twedge, a Silverlight 4 widget, finding its way to the CodePlex later this week. To see it in action, visit http:/www.ntk.si.

image

See you next year!



NT Konferenca 2010 – Where you’ll find me

This year’s NT Konferenca is starting next week! Organized by local Microsoft, it will be held (for the 15th year in a row!) in beautiful Portoroz (Slovenia), that’s now become a traditional venue for this event. Over 130 sessions, labs and seminars will be delivered by over 130 speakers in only four days – that’s a lot of content.

I’ll be speaking (and discusing things) on the following conference sessions:

Tuesday, 25th

10:15 – 11:30 Silverlight and MEF
11:45 – 12:30 ASP.NET, WebForms, Silverlight – What to choose? [BoF session, co-hosting with @dusanzu]

Wednesday, 26th

10:15 – 11:30 Silverlight and WCF RIA Services
11:45 – 12:30 Tips & Tricks: Expression Blend For Developers [Tips & Tricks session, co-presenting with @krofdrakula]
13:30 – 14:15 What’s new in Silverlight 4?
16:30 – 17:30 MVP Panel [A panel discussion with all Slovenian MVPs]

See any theme/pattern here? ;)

You can follow me and my whereabouts next week through twitter [@andrejt], with the official conference hashtag being #ntk10.

See you next week…



Named & optional parameters in Silverlight 4

Named & optional parameters are a new C# language feature coming up with .NET FX 4.0 and guess what… it’s in Silverlight 4 as well!

Optional parameters will come very useful when defining complex APIs where you would usually have to provide several overloads for the same method for it to make sense to wide variety of usages. Let’s take a look at this basic example:

public void PositionWindow(bool isTopMost, double left = 0, double top = 0, double width = 800, double height = 600)
{
    Window window = Application.Current.MainWindow;
    window.TopMost = isTopMost;
    window.Left = left;
    window.Top = top;
    window.Width = width;
    window.Height = height;
}

isTopMost is the only parameter that’s required, all other parameter specify their default value, which makes them optional. Needless to say, the default values will be used for those parameters which the calling function doesn’t provide. One thing to know is that optional parameter must always be declared after required parameters.

The following calls are all valid:

PositionWindow(true); // position and size set to defaults
PositionWindow(true, 100); // top position and size set to defaults
PositionWindow(true, 100, 200); // sizes set to defaults
PositionWindow(true, 100, 200, 600, 200); // all parameters provided

But what if you wanted to provide the size only and leave the position to be set to defaults? Enter named parameters. The same method above can be called also with:

PositionWindow(isTopMost:true, width: 600, height: 200); // named parameters
PositionWindow(true, width: 600, height: 200); // naming is optional when positioned right
PositionWindow(true, height: 200, width: 600); // order doesn't matter
PositionWindow(height: 200, width: 600, isTopMost: true); // ... even with the required parameters

Simple, eh? The need for named and optional parameters may have come from the need to simplify COM automation, but they may prove just as useful in many other cases. But before you go start creating methods with tens of optional parameters, note that this is not the ultimate solution, and one thing worth noting is although the calls above look like they are passing the specified parameters only, the compiler in fact generates them with all parameters in place. This is how the Reflector sees that last batch of calls:

bool CS$0$0000 = true;
double CS$0$0001 = 600.0;
double CS$0$0002 = 200.0;
this.PositionWindow(CS$0$0000, 0.0, 0.0, CS$0$0001, CS$0$0002);
CS$0$0001 = 600.0;
CS$0$0002 = 200.0;
this.PositionWindow(true, 0.0, 0.0, CS$0$0001, CS$0$0002);
CS$0$0001 = 200.0;
CS$0$0002 = 600.0;
this.PositionWindow(true, 0.0, 0.0, CS$0$0002, CS$0$0001);
CS$0$0001 = 200.0;
CS$0$0002 = 600.0;
CS$0$0000 = true;
this.PositionWindow(CS$0$0000, 0.0, 0.0, CS$0$0002, CS$0$0001);

Potential architectural issues aside, I’m quite happy to see this feature come to Silverlight as well. How about you?



Putting Silverlight tweets on the map

Twitter Maps application was updated last night to allow embedding custom Twitter maps on web sites. The process of creating a custom Twitter map is fairly easy, these are the steps for creating a Silverlight tweets map.

1. Go to the Bing Maps site, click on the MAP APPS button and select the Twitter Maps application:

image

The Twitter Maps application will open, showing you the location of the most recent tweets in your area. Of course, only geotagged tweets will be shown on the map.

2. Click on the plus sign on the left side to open the Search Filters panel:

image

3. Type “silverlight” into the keywords field and click Submit:

image

4. Click the Embed in your site button, found at the bottom of the left column:

image

… and the embedding dialog window will show up.

5. Select Anywhere for the Map Location and check that the Current Filters is set to “silverlight”:

image6. Copy the provided HTML code into your site.

And this is how this Silverlight tweets map looks like:

Using different filters and settings will get you a whole lot of alternatives for creating your own Twitter map. With geotagging getting more popular by the day, your maps will be getting richer along the ride.