07 December 2012

Using BeginDetect and other methods in FCClient

Our official Face Detection and Recognition API client for the .NET Framework follows Asynchronous Programming Model. This model enables non-blocking calls to potentially long-running operations such as web service calls. In the case of Silverlight it is the only available way to call a web service (synchronous GetRequestStream, GetResponse and other operations are missing from HttpWebRequest class). Our client is a portable library, i.e. it has to work not only on full .NET Framework but also on Silverlight and Windows Phone. And we, like Silverlight, want to encourage you to follow good practices and not to block the UI thread during web service calls.
That is why the methods in the FCClient class support only asynchronous operations.
However we understand that for rapid prototyping and research purposes following APM model could be an overkill. Also we understand from support request that many developers are not familiar with APM. Fortunately there is an easy way to perform an asynchronous operations synchronously. Just pass null for callback and state in the call to Begin* method and pass its result to the corresponding End* method like in the following example:

FCClient client = new FCClient(yourApiKey, yourApiSecret);
FCResult result = client.Account.EndAuthenticate(

    client.Account.BeginAuthenticate(null, null));

Similarly face detection operation can be performed like this:

Stream stream = System.IO.File.OpenRead(@"C:\image.jpg");
FCResult result = client.Faces.EndDetect(

    client.Faces.BeginDetect(null, new Stream[] { stream },
    Detector.Default, Attributes.Default, null, null));

The result.Photos[0].Tags collection will contain the detected faces.

In case you are using the async feature of C# 5 (or corresponding VB.NET version) the APM pattern can be easily converted to Task<FCResult> to be awaited on:

Task<FCResult> = Task.Factory.FromAsync<FCResult>(
    client.Faces.BeginDetect(null, new Stream[] { stream },
    Detector.Default, Attributes.Default, null, null),
    client.Faces.EndDetect);

UPD: We have updated the client library to include async methods for supported platforms (.NET Framework 4.5,  .NET for Windows Store Apps and Windows Phone 8) and they can be used as follows:

FCResult result = await client.Faces.DetectAsync(
    null, new Stream[] { stream },
    Detector.Default, Attributes.Default);