Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

Using the API with Silverlight

Bing

Silverlight is a Microsoft framework that enables developers to build Rich Internet Applications (RIAs) using the same .NET framework and programming languages they are used to using in typical .NET applications. Because of its strong integration with browsers as well as with images and other media, it is a very interesting client for building applications using the Bing API .

Like JSON applications that live in the browser, Silverlight applications can’t typically invoke services (raw HTTP or SOAP) on domains other than the domain from which the Silverlight application is downloaded. But because Bing API publishes a crossdomain policy file at the root of its domain (http://api.search.live.net/crossdomain.xml) that allows RIAs like Silverlight to access its endpoints, it is possible to use the API from Silverlight.

Because Silverlight is really a .NET programming environment, the choices for API invocation are the same as the earlier .NET examples (although Silverlight also has a JSON-parsing object model). You can either use the raw HTTP XML interface or use the SOAP interface. The only difference is that, because Silverlight runs in the browser, the APIs we use are all asynchronous rather than synchronous. Example 10 shows code running inside of a Silverlight application that calls the HTTP XML interface.

Example 10: Using the HTTP XML Interface from Silverlight

WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
item.CurrentQuery = p;
item.Uri = 
new Uri(String.Format(_baseURI, AppId, "image", "sushi"));
wc.OpenReadAsync(item.Uri, item);

The difference between the .Net code show in Example 5 and the .Net code in Example 10 is that we are using the Silverlight WebClient type to simplify the HTTP programming model even further. To get the results, we need to set the WebClient.OpenReadCompleted delegate. When the request is finished, the WebClient will call our wc_OpenReadCompleted method. Example 11 shows this method.

Example 11: WebClient callback

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    Stream streamResult = e.Result;
    XDocument xd = XDocument.Load(XmlReader.Create(streamResult));
    //use the XDocument
}

In Example 11 we are again using XDocument, part of the XLINQ programming model, which is available in Silverlight. This allows us to build a collection of strongly-typed objects to data bind against a Silverlight control.

Show:
© 2014 Microsoft. All rights reserved.