Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Announcing a new user group

Dear Slovenian developers and UI enthusiasts, mark your calendars for 8th of November 2011 as that’s the day we’re launching a new user group targeting the UI/UX professionals.

SIUX LogoSIUX – Slovenian UX User Group – a sister user group (or a Siamese twin group as we fondly call it Smile) of now years-running SLODUG, Slovenian Developers User Group (SLODUG), where we’ll focus on technologies and areas like WPF, Silverlight, HTML5, Kinect, Windows Phone, Windows 8; talk through their visual and interaction design aspects; explore user interface examples, usability and related factors.

SLODUG and SIUX will share their members and meeting place. As mentioned, the first, inaugural meeting, will take place on Tuesday, 8th of November 2011, starting at 17h. Two talks are scheduled for the meeting: Developing for XBox Kinect by Sašo Zagoranski and Metro: the UI of the future?  by me. The meeting will take place in Microsoft Lecture room at Šmartinska 140.

Full agenda:

17:00: Intro & announcements
17:15 – 18:00: Developing for XBox Kinect, Sašo Zagoranski / Semantika d.o.o.
18:15 – 19:00: Metro: UI of the future?, Andrej Tozon / ANT Andrej Tozon s.p.
19:00: Discussion over pizza &  beer

We’re also looking for speakers – if you’re interested or  know anybody from the field, please contact me and we’re schedule your talk in one of our next meetings.

Hope to see you!

Until then, you can follow us on Twitter or join our Facebook group.



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



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.



My articles on SilverlightShow

A few of my Silverlight articles were published on the SilverlightShow site this past two months. The first one is an introduction to Silverlight/(WPF)/Blend behaviors, where I create a Silverlight Halloween Sound Player without writing a single line of code – the application is composed entirely in Expression Blend, using various behaviors.

Halloween Sound Player

I also used behaviors for another article, to showcase some of the new Silverlight 4 features: WebCam capture support, printing, drag/drop, clipboard, commanding, some databinding enhancements and implicit styling support. The result is a nice doodling application, which can be used to entertain your kids.Camdoodle

The third article was about creating a Europe Weather Map with Silverlight, showing current weather conditions for some of the larger cities in Europe. It was mostly about using the Bing Maps Silverlight Control SDK, but fun anyway.

Europe Weather map

You can expect more articles appearing on SilverlightShow in the next days/months. Leave a comment if you find them useful.



Developers, please mind the locale!

I’m observing this really irritating trend with new software lately…

I followed up on a couple of tweets today to try the new Silverlight application everyone was RT’ing of. Clicked on the link and the loading animation began. Seconds later, it… stopped.

Huh?

Then I noticed an icon in IE’s left bottom corner…

image

The following detailed message confirmed my assumptions about what caused the error:

image

“Input string was not in a correct format”!

I’m sure that if you live outside US/UK and follow Silverlight community, you have encountered this error before. For example, I’ve been to at least two online events in the past year, with live streaming content delivered over a Silverlight player, which displayed this very same error when launched.

Here is the list of some other apps that I’ve worked with recently, that have been showing the same symptoms. To name just a few:

Silverlight Bing Maps, specifically the Twitter app – can you find the difference between these two links?

http://www.bing.com/maps/explore/#5872/style=auto&lat=46.037671&lon=14.533958&z=11&
pid=5874/5003/0.40326=s&o=&a=0&n=0

and

http://www.bing.com/maps/explore/#5872/style=auto&lat=46,037671&lon=14,533958&z=11&
pid=5874/5003/0.40326=s&o=&a=0&n=0

The first link uses a dot as a decimal separator and will work for English locales, while the second one uses commas and will work for non-English locales (speaking generally). Note that URL will be converted to the default format when application is loaded, probably throwing you somewhere in an ocean, if the numbers weren’t in the expected format.

Live Labs Pivot (desktop app) will crash on startup when locale is not set to English.

Six-Degrees Search is the application I’ve tried to run today. A Silverlight app, based on the EntityCube entity search engine and being developed by Microsoft Research. Regional settings need to be set to English locale for application to load correctly.

Mentioned software might be labeled Beta or prototype, but that hardly justifies the fact that developers didn’t support non-English locales from the very start. Therefore I’m taking this blog post to appeal to all Silverlight developers, especially those working with regional settings set to English natively:

Please, make your applications respect local regional settings as early in the development as possible. Silverlight may be cross-platform and cross-browser, but developers, not taking local regional settings into the account, don’t even make it cross-locale.

Just in case anyone encounters a weird behaving application, showing symptoms described at the very top of this post, this is one of the things to try first: The most likely cause for the above error is a wrong date or number format. Changing your local regional settings will probably help:

image



MVVM with WPF, Silverlight, and… Windows Forms

In my post-NTK09 conference blog post I mentioned one of my MVVM demos was about sharing a ViewModel between WPF, Silverlight and even Windows Forms application. I got a lot of requests for posting sample code online since then, which I intended to do earlier, but because the sample application code was closely related to the conference, I wanted to create a whole new sample application first and share that. Of course time passed and other things kept me busy from actually doing it. With Silverlight 4 Beta coming out recently, things progressed even further in so I decided to keep things as they were, and post the original sample code. I’ll explain it in few lines (and pictures) here, and the source code can be found here.

What’s it all about?

The purpose of the sample (and my NTK09 talk in general) was about the MVVM pattern principle and how it can be used to totally separate the User Interface from the business logic and data. The application I built was a conference session schedule viewer / editor. Technically, there are three application flavors: WPF, Silverlight and WinForms. They share the same data access (WCF service) and ViewModel. The only thing different between the three is their UI implementation.

imageimageimage

Notice the small arrow overlay over the C# icon on Silverlight and WinForms PageViewModel.cs? That’s because both project are linking the original file from the WPF project, which I created first. That means that ViewModel is exactly the same across all three projects when they are compiled. And with all three project, this is the ViewModel that serves up the main page.

The WPF project

I created the WPF project to ‘just work’. I didn’t bother with styling and the looks, I intentionally left it ugly. I used Prism for commanding and WCF based web service for communicating the data.

image

The ‘Dan’ (Day) and ‘Kategorija’ (Category) serve as the filter for the session list on the left. Each combo box change results in a server request which returns new data for filling the session list. Other fields are editable session details fields. Three buttons on the top left correspond to New, Edit and Delete, in that order.

The Silverlight project

The Silverlight project differ from WPF in that that it’s in color :)

Silverlight

Prism is still used for commanding, but the UI is quite different. I even provided the View (above) and Edit (bottom) screens.

Silverlight Edit

As said, the difference between the WPF and Silverlight applications is just and only different XAML. And both have zero code-behind code. Moving on to…

The Windows Forms project

I  didn’t bother much with making Windows Forms project to work. I last coded anything in WinForms 2+ years ago so I suspect I won’t have to go there again… However, this is the UI I put together:

Windows Forms

It’s very similar to WPF, but data bindings perform much slower. Data bindings? There’s data bindings in WinForms too?

LOL. Sometimes I really do get questions like that. Anyway, let’s see the ‘code behind’. [There’s actually quite a few lines of code behind in Windows Forms because it’s used to instantiate and initialize all controls on the screen. That code is stored in the .designer file and I’m ignoring it as the code behind]

private void MainForm_Load(object sender, EventArgs e)
{
    PageViewModel viewModel = new PageViewModel();

    dayBox.DataBindings.Add("DataSource", viewModel, "Days");
    categoryBox.DataBindings.Add("DataSource", viewModel, "Categories");
    categoryBox.DisplayMember = "Name";
    speakerBox.DataBindings.Add("DataSource", viewModel, "Speakers");
    speakerBox.DisplayMember = "FullName";
    speakerBox.ValueMember = "Id";
    startTimeBox.DataBindings.Add("DataSource", viewModel, "TimeValues");
    endTimeBox.DataBindings.Add("DataSource", viewModel, "TimeValues");
    sessionList.DataBindings.Add("DataSource", viewModel, "Sessions");
    sessionList.DisplayMember = "Title";

    dayBox.DataBindings.Add("SelectedValue", 
        viewModel, "SelectedDay", true, DataSourceUpdateMode.OnPropertyChanged);
    categoryBox.DataBindings.Add("SelectedValue", 
        viewModel, "SelectedCategory", true, DataSourceUpdateMode.OnPropertyChanged);
    sessionList.DataBindings.Add("SelectedValue", 
        viewModel, "SelectedSession", true, DataSourceUpdateMode.OnPropertyChanged);
    speakerBox.DataBindings.Add("SelectedValue", 
        viewModel, "SelectedSession.SpeakerId", true, DataSourceUpdateMode.OnPropertyChanged);

    startTimeBox.DataBindings.Add("Text", 
        viewModel, "SelectedSession.StartTime", true, DataSourceUpdateMode.OnValidation);
    endTimeBox.DataBindings.Add("Text", 
        viewModel, "SelectedSession.EndTime", true, DataSourceUpdateMode.OnValidation);
    titleBox.DataBindings.Add("Text", 
        viewModel, "SelectedSession.Title", true, DataSourceUpdateMode.OnValidation);
    descriptionBox.DataBindings.Add("Text", 
        viewModel, "SelectedSession.Description", true, DataSourceUpdateMode.OnValidation);

    newButton.Click += (s, ev) => 
        { viewModel.NewSessionCommand.Execute(null); };
    editButton.Click += (s, ev) => 
        { viewModel.EditSessionCommand.Execute(viewModel.SelectedSession); };
    deleteButton.Click += (s, ev) => 
        { viewModel.DeleteSessionCommand.Execute(viewModel.SelectedSession); };
    saveButton.Click += (s, ev) => 
        { viewModel.EndEditSessionCommand.Execute(viewModel.SelectedSession); };
    cancelButton.Click += (s, ev) => 
        { viewModel.CancelEditSessionCommand.Execute(viewModel.SelectedSession); };
}

This is all the code for the main form. You’ll notice it’s all used for binding controls to various properties on the ViewModel. I could also get rid of some of the lines by setting the properties on the WinForms designer (thus moving them to the .designer file). The last section wires button clicks to execute commands in the ViewModel.

There is absolutely no business logic in this code which makes it very similar to declarative XAML in WPF and Silverlight projects. I was toying with the idea of making an Extender Provider to get rid of the above lines completely and do it all just with the Windows Forms designer – I made a working prototype, but wasn’t generic enough to include it in the sample.

Source code

Bellow is the full source for all three main and related projects. Also included is the Test project with a few Silverlight Unit Test Framework tests. Database is not included so you’ll not be able to actually run any of the applications. Sorry. I’ll post the Silverlight version online when time permits.



Windows 7 Launch talk: Building cool applications with MS Expression tools

Windows 7 launch day was fun. I gave a talk on Expression tools (and related) – here’s the PowerPoint slide deck for those who asked for it:

I used Expression Blend 3 to build a photo viewer application, which I’ll blog about later; key points here were designer-developer workflow + using sample data and behaviors.

I blogged about the Microsoft ICE last year and I used that exact sample I’ve used in that blog post, but with one difference: did you know that by installing ICE on your desktop will, you can stitch panoramic (or large composite) photos right from your Windows Live Photo Gallery? It’s as easy as selecting the photos and click on the Extras menu item:

Create Image Composite...

Yet another option for stitching a bunch of photos together will give you the Deep Zoom Composer(free and not listed as an Expression tool, but sure looks and feels like it), which has similar features and much more compositing power (different zoom levels, layers, etc.)

And for closing I briefly showcased Expression Encoder 3 and IIS Smooth Streaming.

Yup, fun.



Silverlight LOB: Validation (#1)

When taking about data validation in applications, I usually describe the validation as the five-stage process or, put differently, five lines of defense against invalid data. In this post, I’ll write about the first line of defense – preventing the user entering the wrong data.

1. Preventing invalid input

This one’s logical, really. A user enters the data through input fields on some kind of input form, so naturally this would be the best place to put our first line of defense.

The first line of defense is about preventing user to enter invalid data into input fields. This doesn’t mean that if done proper and thorough, we wouldn’t need other places to check the data; it’s just the best place to filter out majority of faulty input that can happen during manual data entry. The goal here is to catch as many invalid data as possible, as soon as possible. This wouldn’t result only in better application responsiveness (no unnecessary trips to the server), the immediate feedback of invalid entry will provide a better user experience, possibly even educate the user to learn from her mistakes.

So, what are we talking about here?

A simple TextBox might not be the best solution for entering only numeric data. Seeing the TextBox on the input form, the user might expect she can enter anything she likes into the box, even if the label, put close by the input box, is saying to her: “Enter your age”. A kind of a NumericUpDown control visually gives user a much better idea of what should go into that box, plus she gets an option of manipulating that value; in this case, it’s adjusting the value with the Up and Down keys. In Windows Forms, for example, I liked to use a TextBox with a calculator dropdown for entering decimal data. Masked input boxes also work well, when you want the user to enter the data in a specific format.

If you don’t want to provide any visual clues that only numeric data should be entered in the input field and go for the standard TextBox, it’s very much recommended to handle the input for yourself and only allow numeric keys through. This is usually done by hooking into KeyDown event – either in codebehind class, or even better – with a custom TextBox behavior.

Yet another good example of filtering the data input to the underlying data type, is the DatePicker control. You can usually set the range of valid dates that can be selected and control whether or not date entry is required. With Silverlight DatePicker, it appears that date entry is always optional, even if bound to a non-nullable DateTime data type. Tabbing out of the DatePicker will leave the input box empty, but the bound property will still contain the old value. Hooking into DateValidationError or BindingValidationError event wouldn’t help so I tried to handle this case by manipulating the Selected date in the SelectedDateChanged event. Instead of doing it in the codebehind class, I created the following behavior:

public class RequiredDatePickerBehavior : Behavior<DatePicker>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectedDateChanged += OnSelectedDateChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.SelectedDateChanged -= OnSelectedDateChanged;
    }

    private void OnSelectedDateChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count == 0 && e.RemovedItems.Count > 0)
        {
            AssociatedObject.SelectedDate = (DateTime)e.RemovedItems[0];
        }
    }
}

… which can be used as:

<controls:DatePicker SelectedDate="{Binding BirthDate, Mode=TwoWay}"
                     Grid.Row="1" Grid.Column="1">
    <i:Interaction.Behaviors>
        <local:RequiredDatePickerBehavior />
    </i:Interaction.Behaviors>
</controls:DatePicker>

Attaching this behavior to the DatePicker will revert the date to the last valid value in case of deleting the text from the input box and thus making the DatePicker non-nullable.

Behaviors in general are a great way to extend an existing type (or types) of control and can be used for a variety of things. In this post I’ve shown a way to enhance the Silverlight DatePicker control to prevent entering empty values in cases when date is required. Remember next time you’ll find yourself coding KeyDown or similar control event handler in page’s codebehind class: consider writing a behavior!

To be continued…

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