Paulo Morgado

.NET Development & Architecture

Recent Articles

view all

Events

Projects

Recent Readers

Visitor Locations

Visitor Locations

Disclaimer

The opinions and viewpoints expressed in this site are mine and do not necessarily reflect those of Microsoft, my employer or any community that I belong to. Any code or opinions are offered as is. Products or services mentioned are purchased by me, made available to me by my employer or the manufacturer/vendor which doesn't influence my opinion in any way.

Building a Release Pipeline with Team Foundation Server + Hands On Lab

The Practices & Patterns team has released another guidance.

This time it’s the Building a Release Pipeline with Team Foundation Server 2012.

Prism For Windows Runtime Is Out

Prism for the Windows Runtime and the associated AdventureWorks Shopper reference implementation is now available on the Windows Dev Center.

You can read all about it on Blaine Wastell’s blog.

Brian Noyes has also released a Pluralsight course: http://tinyurl.com/prismrtcoursesummary

Red Gate Is Looking For Feedback On Its ASP.NET MVC Web Development Education Website

Red Gate is looking for feedback on its ASP.NET Web Development Education website.

Visit their website and answer the survey.

Developing an End-to-End Windows Store app using C++ and XAML: Hilo

Patterns & Practices has released Hilo guidance: Developing a Windows Store app using C++ and XAML which is part of the Windows SDK.

Using The GeoCoordinateReactiveService

Having created an Rx wrapper over the GeoCoordinateWatcher on a previous post, in this post I’ll demonstrate how it can be used in a simple application.

The application will display the status of the service, the position and the distance traveled.

For this simple application the service will be exposed as a singleton property of the App class:

public partial class App : Application
{
    // ...

    public static IGeoCoordinateReactiveService GeoCoordinateService { get; private set; }

    public App()
    {
        // ...

        InitializePhoneApplication();

        // ...
    }

    // ...

    private void InitializePhoneApplication()
    {
        // ...

        GeoCoordinateService = new GeoCoordinateReactiveService();

        // ...

    }

    // ...

}

Getting the status of the service is very simple. It just requires subscribing to the StatusObservable. Since we want to display the status, we need to observe it on the dispatcher before:

App.GeoCoordinateService.StatusObservable
    .ObserveOnDispatcher()
    .Subscribe(this.OnStatusChanged);

For the position we do the same with the PositionObservable:

App.GeoCoordinateService.PositionObservable
    .ObserveOnDispatcher()
    .Subscribe(this.OnPositionChanged);

The distance traveled would seem a bit more complicated because we need to keep track of the last position and calculate the distance traveled on every position change. But this is where the Rx excels with its query operators. If we combine the position observable with the position observable having skipped one position with the zip operator we end up with an observable with the current and previous position. And if we apply a selector, we get the traveled distance:

App.GeoCoordinateService.PositionObservable
    .Zip(
        App.GeoCoordinateService.PositionObservable.Skip(1),
        (p1, p2) => p1.Location.GetDistanceTo(p2.Location))
    .ObserveOnDispatcher()
    .Subscribe(this.OnDistanceChanged);

You can find the complete implementation of the service and application here.


Resources:

Would you like to have roaming settings in Visual Studio?

The C++ Team (blog) has been researching roaming Visual Studio settings and they have a few questions that will help gain insights into what the best experience would be. They have created a survey (http://aka.ms/vsroaming) aimed at understanding Visual Studio settings usage patterns and gathering feedback. The survey should take less than 10 minutes, maybe more if you want to provide a ton of details.

Your voice is important. Make sure it is heard!

Implementing The GeoCoordinateWatcher As A Reactive Service

With Rx, events are first class citizens that can be passed around and composed as needed in a very simple way.

The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, and parameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers.” – from the MSDN page.

The library also provides a considerable amount of helpers that make it easy to warp events into observables.

Wrapping the GeoCoordinateWatcher as a reactive service is quite simple. All it takes is creating observables and exposing the events as observables:

public class GeoCoordinateReactiveService : IGeoCoordinateReactiveService, IDisposable
{
    private readonly GeoCoordinateWatcher geoCoordinateWatcher = new GeoCoordinateWatcher();

    public GeoCoordinateReactiveService()
    {
        this.StatusObservable = Observable
            .FromEventPattern<GeoPositionStatusChangedEventArgs>(
                handler => geoCoordinateWatcher.StatusChanged += handler,
                handler => geoCoordinateWatcher.StatusChanged -= handler);

        this.PositionObservable = Observable
            .FromEventPattern<GeoPositionChangedEventArgs<GeoCoordinate>>(
                handler => geoCoordinateWatcher.PositionChanged += handler,
                handler => geoCoordinateWatcher.PositionChanged -= handler);
    }

    public IObservable<EventPattern<GeoPositionStatus> StatusObservable { get; private set; }

    public IObservable<EventPattern<GeoPosition<GeoCoordinate>> PositionObservable { get; private set; }
}

And now, instead of the StatusChanged and PositionChanged events we have respectively the StatusObservable and PositionObservable as a stream of EventPattern<TEventArgs> instances.

But the EventPattern<TEventArgs> class includes the source of the event and an the event arguments in properties which is far more than we need in this case. With normal LINQ operators we can convert thes streams of EventPattern<TEventArgs> instances in streams of the desired values.

public class GeoCoordinateReactiveService : IGeoCoordinateReactiveService, IDisposable
{
    private readonly GeoCoordinateWatcher geoCoordinateWatcher = new GeoCoordinateWatcher();

    public GeoCoordinateReactiveService()
    {
        this.StatusObservable = Observable
            .FromEventPattern<GeoPositionStatusChangedEventArgs>(
                handler => geoCoordinateWatcher.StatusChanged += handler,
                handler => geoCoordinateWatcher.StatusChanged -= handler)
            .Select(ep => ep.EventArgs.Status);

        this.PositionObservable = Observable
            .FromEventPattern<GeoPositionChangedEventArgs<GeoCoordinate>>(
                handler => geoCoordinateWatcher.PositionChanged += handler,
                handler => geoCoordinateWatcher.PositionChanged -= handler)
            .Select(ep => ep.EventArgs.Position);
    }

    public IObservable<GeoPositionStatus> StatusObservable { get; private set; }

    public IObservable<GeoPosition<GeoCoordinate>> PositionObservable { get; private set; }
}

And to use these observables all it is needed is to subscribe to them:

geoCoordinateWatcherService.StatusObservable
    .Subscribe(this.OnStatusChanged);

geoCoordinateWatcherService.PositionObservable
    .Subscribe(this.OnPositionChanged);

But, usually, we want to use these values in view model to bind to the UI and, consequently, we want this to happen in the UI thread:

geoCoordinateWatcherService.StatusObservable
    .ObserveOnDispatcher()
    .Subscribe(this.OnStatusChanged);

geoCoordinateWatcherService.PositionObservable
    .ObserveOnDispatcher()
    .Subscribe(this.OnPositionChanged);

It’s as simple as that!


Resources:

Developing Multi-tenant Applications for the Cloud, 3rd Edition

Microsoft Patterns & Practices has recently released Developing Multi-tenant Applications for the Cloud, 3rd Edition.

A Synchronization Context Based On The TPL Dataflow Library

The purpose of the synchronization model implemented by the SynchronizationContext class is to allow the asynchronous/synchronization operations of the common language runtime to behave properly with different synchronization models. This model also simplifies some of the requirements that managed applications have to follow in order to work correctly under different synchronization environments. Examples of such synchronization environments are user interface infrastructures like Windows Forms, Windows Presentation Foundation and ASP.NET.

Providers of synchronization models extend this class to provide their own implementations. Because these user interface infrastructures usually run on their own threads, dispatching execution to their execution contexts usually means leaving the current thread.

The Task Parallel Library (TPL) provides dataflow components to help increase the robustness of concurrency-enabled applications. These dataflow components are collectively referred to as the TPL Dataflow Library. This dataflow model promotes actor-based programming by providing in-process message passing for coarse-grained dataflow and pipelining tasks. The dataflow components build on the types and scheduling infrastructure of the TPL and integrate with the C#, Visual Basic, and F# language support for asynchronous programming. These dataflow components are useful when you have multiple operations that must communicate with one another asynchronously or when you want to process data as it becomes available.

The TPL Dataflow Library (System.Threading.Tasks.Dataflow namespace) is not distributed with the .NET Framework 4.5. To install the System.Threading.Tasks.Dataflow namespace, open your project in Visual Studio 2012, choose Manage NuGet Packages from the Project menu, and search online for the Microsoft.Tpl.Dataflow package.

Sometimes, for demo or testing purposes, I need a synchronization context that behaves like the user interface ones but doesn’t force me to build applications with a user interface and the TPL Dataflow Library seemed like a good option to implement such synchronization context.

It was as easy as this:

public class TplDataflowSynchronizationContext : SynchronizationContext
{
    private ActionBlock<ActionItem> ab
        = new ActionBlock<ActionItem>(
            item =>
            {
                Trace.WriteLine(
                    string.Format("{0}: {1}", Environment.CurrentManagedThreadId, item.operation));

                try
                {
                    item.d(item.state);
                }
                finally
                {
                    item.SetResult(true);
                }
            });

    public override SynchronizationContext CreateCopy()
    {
        return new TplDataflowSynchronizationContext();
    }

    public override void Post(SendOrPostCallback d, object state)
    {
        Trace.WriteLine(
            string.Format("{0}: Posting...", Environment.CurrentManagedThreadId));

        this.ab.Post(new ActionItem { d = d, state = state, operation = "Post" });

        Trace.WriteLine(
            string.Format("{0}: Posted.", Environment.CurrentManagedThreadId));
    }

    public override void Send(SendOrPostCallback d, object state)
    {
        Trace.WriteLine(
            string.Format("{0}: Sending...", Environment.CurrentManagedThreadId));

        ActionItem item = new ActionItem { d = d, state = state, operation = "Send" };
        this.ab.SendAsync(item);
        item.Task.Wait();

        Trace.WriteLine(
            string.Format("{0}: Sent.", Environment.CurrentManagedThreadId));
    }

    public class ActionItem : TaskCompletionSource<bool>
    {
        public SendOrPostCallback d;
        public object state;
        public string operation;
    }
}

UPDATE:

Fixed implementation because the SynchronizationContext.Send method returned without having completely executed the operation. Thanks to Svick for pointing that out and Stephen Toub for the help fixing it.

What’s New In C# 5.0 Session Materials From Rumos InsideOut Event

Here are the materials from my What’s New In C# 5.0 session at the Rumos InsideOut Event.

Slide deck:

What's New In C# 5.0 from Paulo Morgado

Sample code:

C# 5.0 Async/Await Demo Code

More Posts Next page »