Tag Archives: async

Windows 8 Windows Phone 7/8

Async, portable libraries and Windows Phone 7 in Visual Studio 2012

Windows phone topic Portable classes in Visual Studio 2012 are simply awesome. They allow high code reuse for multiple platforms. Another great addition in Visual Studio 2012 is support for asynchronous programming in C# 5 which, sadly, was not initially available for Windows Phone 7 developers.

If you want to target Windows Phone 8 and Windows Store, you can use Async if you also target .NET 4.5. If you want to target Windows Phone 7.1 and Windows Store, you cannot use asynchronous features from C# 5. But with the prerelease version of Async for .NET Framework 4, Silverlight 4 and 5, and Windows Phone 7.5 and 8 you can finally use Async in your Windows Phone 7 applications. If you want to target largest market, you need to support Windows Phone 7 along with Windows Phone 8, it is too large to simply ignore.

So, can we use Async in portable libraries while still targeting both Windows Phone 7 and Windows Store? Luckily, the answer is yes. But, and there is always a but, with one caveat – you must target .NET 4.0 instead of .NET 4.5.

The procedure is simple: create a new Portable Class Library and select the targets as seen on the image below:

Targets for Portable Class Library project

Portable Class Library targets

To add Async support, run the following command in the Package Manager Console:

Install-Package Microsoft.Bcl.Async -Pre

Voila, you can now write asynchronous code in a portable class library which can then be linked in Windows Phone 7, Windows Phone 8 and Windows Store projects. If you build a Windows Phone 7 application and link to such portable class library, you will need to add the same NuGet package to that project also.

Development

Thoughts on commenting asynchronous functions in C#

While I was wrapping up my asynchronous extension methods library, I realized that to be useful, all methods should have proper documentation. Since the number of extension methods wasn’t really large, I’d decided to add it. After all, how hard can it be? It is practically already properly documented since all I did was wrapping EAP pattern (MethodAsync function with MethodCompleted event) and the original functions were documented. But extracting proper commenting style that is both complete and consistent was actually harder you would expect it to be.

I will go through several items that needed to be commented with explanation why particular commenting style was used. If you are using some other style, please don’t hesitate from leaving a comment. read more »

Thought crime

Why you should (almost) never write void asynchronous methods?

I came across this interesting post by Christian Jacobsen titled async/await in C# – a disaster waiting to happen? in which he describes that simple refactoring can introduce serious bugs in async code. While there is definitely something to be said about possible problems with the new Async feature, his example can teach us something.

I will borrow his code to illustrate the point:

async void AcquireFromCamera(object sender, RoutedEventArgs e)
{
    try
    {
        var imageStream = await _cameraCapture.Shoot();
        var dto = new Dto(){ImageStream = imageStream};
        _handler.ImageCaptured(dto);
        Frame.Navigate(typeof(EditDataPage), dto.Id);
    }
    catch (Exception ex)
    {
        new MessageDialog(ex.Message).ShowAsync();
    }
}

async void ImageCaptured(Dto dto)
{
    dto.Id = Guid.NewGuid().ToString();
    var file = await _fileHndlr.CreateFileAsync(dto.Id);
    dto.ImageFilePath = file.Path;
    _fileOperator.StoreStream(dto.ImageStream, file);
    SaveNewDataItem(dto);
    var dataItem = dataSource.GetItem(dto.Id);
    StoreData(dataItem);
}

Christiansen argues that this is a buggy piece of software since the AcquireFromCamera method calls ImageCaptured as if it was a synchronous method. And he is right since both methods are non-returning. This usage of asynchrony is called fire and forget.

To fix this one needs to change the return type from void to Task and the compiler will now warn you with the following warnings:

warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Void returning asynchronous methods are called fire and forget simply because you don’t need to know when they complete, you initiate them and that is it. The code above requires the ImageCaptured function to complete before continuing and for that you need to await it.

Change the return type for all asynchronous methods from void to Task or Task<T>. If the asynchronous method does not return any value, use Task. If it returns an instance of type T, use Task<T>.

So which methods can be both void and async? Only event handlers since the caller does not need to know when the method completes.

Windows Phone 7/8

Basic Facebook integration for your Windows Phone 7 application

Windows phone topic Facebook is unavoidable social engagement tool. If you are building a Windows Phone 7 application for a certain event, celebrity or anything that has a associated Facebook page, you should consider adding some sort of engagement with it in the app. One example is adding the most recent posts in some format to your client application. However, you cannot simply retrieve data from Facebook publicly, calls need to be authenticated first and for that we need to create a Facebook application first.

This post will show how to fetch the most recent posts from the page using only RestSharp. If you are building something more complicated with more integration, consider using this awesome library – Facebook C# SDK.

You can do that on the Facebook developers/Apps page and click Create New App and give your application a name. For the testing purposes, use some random app name. Creating new Facebook application read more »

Windows Phone 7/8

Async and RestSharp for Windows Phone 7

Windows phone topic I have mentioned RestSharp quite a lot of times, it is simply an essential library for building applications that communicate to the outside world. Ever since Async CTP shipped for Windows Phone 7, I wanted to make everything asynchronous. RestSharp comes with asynchronous methods already built in, but they are not compatible with Async since they don’t return Task.

But we can fix that easily with our good friend TaskCompletionSource<T> read more »

TFS/ALM

Creating and updating Work Items via OData for TFS

This entry is part of a series, OData Service for TFS»

In the last two posts we saw how to consume data via OData Service for TFS. Today we are going to create and update Work Items using the service. Create a new console application project, add a service reference to the OData service and create your context (like in the earlier posts).

Creating Work Items

Work Item is created via the TFSServiceReference.WorkItem.CreateWorkItem method. The method accepts four parameters:

  • ID – set to 0 since you are creating a new Work Item and you cannot specify an ID. If you use an existing ID on the server, you will get the following error:

    TF400276: You have tried to set a value for a field of a work item which is not opened or partial opened. You cannot set a value for a field of a work item which is not opened or partial opened.

    If you specify a non-existing ID, you will get an ArgumentNullException on the service side.

  • revision – set to 0 since newly created Work Item has revision 1. Value is unused.
  • createdDate – Value is unused.
  • changedDate – Value is unused.

read more »

Tips

VS11 style async wrapper for the OData async model

Using the previous post we can now write wrap all asynchronous functions written using the APM pattern into tasks. This is the preferred way to write the asynchronous code in C#5.

Here is the list of async extension wrappers for all asynchronous methods used with the OData for TFS series.

namespace DataServiceAsyncExtensions
{
    using System;
    using System.Collections.Generic;
    using System.Data.Services.Client;
    using System.Threading.Tasks;

    public static class DataServiceQueryExtensions
    {
        public static Task<IEnumerable<T>> ExecuteAsync<T>(this DataServiceQuery<T> query, object state)
        {
            return Task.Factory.FromAsync<IEnumerable<T>>(query.BeginExecute, query.EndExecute, state);
        }
    }

    public static class DataServiceContextExtensions
    {
        public static Task<IEnumerable<T>> ExecuteAsync<T>(this DataServiceContext context, DataServiceQueryContinuation<T> continuation, object state)
        {
            return Task.Factory.FromAsync<DataServiceQueryContinuation<T>, IEnumerable<T>>(context.BeginExecute<T>, context.EndExecute<T>, continuation, state);
        }

        public static Task<IEnumerable<T>> ExecuteAsync<T>(this DataServiceContext context, Uri requestUri, object state)
        {
            return Task.Factory.FromAsync<Uri, IEnumerable<T>>(context.BeginExecute<T>, context.EndExecute<T>, requestUri, state);
        }

        public static Task<DataServiceResponse> ExecuteBatchAsync(this DataServiceContext context, object state, params DataServiceRequest[] queries)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            return Task.Factory.FromAsync<DataServiceResponse>(context.BeginExecuteBatch(null, state, queries), context.EndExecuteBatch);
        }

        public static Task<DataServiceStreamResponse> GetReadStreamAsync(this DataServiceContext context, object entity, DataServiceRequestArgs args, object state)
        {
            return Task.Factory.FromAsync<object, DataServiceRequestArgs, DataServiceStreamResponse>(context.BeginGetReadStream, context.EndGetReadStream, entity, args, state);
        }

        public static Task<QueryOperationResponse> LoadPropertyAsync(this DataServiceContext context, object entity, string propertyName, object state)
        {
            return Task.Factory.FromAsync<object, string, QueryOperationResponse>(context.BeginLoadProperty, context.EndLoadProperty, entity, propertyName, state);
        }

        public static Task<QueryOperationResponse> LoadPropertyAsync(this DataServiceContext context, object entity, string propertyName, DataServiceQueryContinuation continuation, object state)
        {
            return Task.Factory.FromAsync<object, string, DataServiceQueryContinuation, QueryOperationResponse>(context.BeginLoadProperty, context.EndLoadProperty, entity, propertyName, continuation, state);
        }

        public static Task<QueryOperationResponse> LoadPropertyAsync(this DataServiceContext context, object entity, string propertyName, Uri nextLinkUri, object state)
        {
            return Task.Factory.FromAsync<object, string, Uri, QueryOperationResponse>(context.BeginLoadProperty, context.EndLoadProperty, entity, propertyName, nextLinkUri, state);
        }

        public static Task<DataServiceResponse> SaveChangesAsync(this DataServiceContext context, object state)
        {
            return Task.Factory.FromAsync<DataServiceResponse>(context.BeginSaveChanges, context.EndSaveChanges, state);
        }

        public static Task<DataServiceResponse> SaveChangesAsync(this DataServiceContext context, SaveChangesOptions options, object state)
        {
            return Task.Factory.FromAsync<SaveChangesOptions, DataServiceResponse>(context.BeginSaveChanges, context.EndSaveChanges, options, state);
        }
    }
}

The code is also available on github or you can download it from the link.

Tips

Wrapping Begin/End asynchronous API into C#5 tasks

Microsoft offered programmers several different ways of dealing with the asynchronous programming since .NET 1.0. The first model was Asynchronous programming model or APM for short. The pattern is implemented with two methods named BeginOperation and EndOperation. .NET 4 introduced new pattern – Task Asynchronous Pattern and with the introduction of .NET 4.5, Microsoft added language support for language integrated asynchronous coding style. You can check the MSDN for more samples and information. I will assume that you are familiar with it and have written code using it.

You can wrap existing APM pattern into TPL pattern using the Task.Factory.FromAsync methods. For example: read more »

TFS/ALM Windows Phone 7/8

Consuming OData for TFS using C# from Windows Phone 7 application

This entry is part of a series, OData Service for TFS»

*UPDATED 26.3.2012 ADDED CODE FOR ODATA SERVICE AUTHORIZATION AND FIXED ExecuteAsync wrapper*

In the earlier post we saw how to consume the OData service from console application. The same code applies for any desktop application, whether it is Windows Forms or WPF application. Since there is no support for developing WP7 applications in the Visual Studio 11 Beta, the code is written in the Visual Studio 2010 Express for Windows Phone.

Add the reference to the OData service using the instructions from the last post. read more »

TFS/ALM

Consuming OData for TFS using C#

This entry is part of a series, OData Service for TFS»

*UPDATED 26.3.2012 FIXED ExecuteAsync wrapper*

In the previous post we saw how to install and configure OData Service for TFS 11. Before we proceed with extending the service, let’s see how to consume it. For this example, we are going to build from scratch a simple console program using C#. Then we are going to fetch some data. We will be doing it in Visual Studio 11 in .NET 4.5.

Create a new Console Application project with in Visual C# templates and make sure that you target .NET Framework 4.5. Add new service reference and type in full path to OData Service, in my case the address is

http://localhost/ODataTFS.Web/DefaultCollection.

Note that the team project collection is included in the uri. Change default name for namespace to TFSData and click OK. Just before closing, the dialog should look similar to the image below. If you do not see IterationPaths in your dialog, do not worry, we will come to that part in our next posts. read more »