Home > asynch, JSON, RIA, silverlight > A Silverlight Bing API Web Application: Working with JSON (Part 1)

A Silverlight Bing API Web Application: Working with JSON (Part 1)

silverlight logo
Today I have been developing a Silverlight Rich Internet application which utilizes the Microsoft Bing API. To be honest I have never used Silverlight to develop an application before (typically web applications: ASP.net and desktop client applications: Win-Forms). After viewing some of the Silverlight video tutorials I decided to dive straight into development. After viewing some of Microsoft Bing if you haven’t heard of it is Microsoft’s search engine site, in many ways similar to Google.

This is part 1 of a 2 part post about developing a Silverlight application using the Bing API.

Please see this post to see screen-shots and server side code needed to implement this small application.

More info after the jump, including JSON and API usage.

User requirements:

- Allow user to search for any given term
- Provide search function for search categories: Images/Videos/Web
- Provide interactive search experience

The Microsoft Bing API

Taken from MSDN:

The Bing Application Programming Interface (API), Version 2, enables developers to programmatically submit queries to and retrieve results from the Bing Engine.

Therefore, a developer could create their own search engine using the Bing API and even incorporate it into a desktop Win-forms application.

The Bing API uses a REST style architecture. Since REST uses HTTP the Bing API is able to support the following protocols:

JavaScript Object Notation (JSON)

XML

SOAP

JavaScript Object Notation

I decided to use JavaScript Object Notation (JSON) since I had never used it before and tended to always stick with XML or SOAP. My first area of research took me to the official JSON website, here I found a detailed specification about the protocol:

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON Object

- An unordered set of name/value pairs.

- Begins with { (left brace) and ends with } (right brace)

- Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

E.g.

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": {
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}

In the above example the Object is called 'widget'.

Array

- ordered collection of values

- begins with [ (left bracket) and ends with ] (right bracket)

- Values are separated by , (comma)

E.g.

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

In the above example the array is called 'menuitem', as indicated via the square [] brackets, which contains the associated values.

Value

- Primitive types such as string ("the string") or number (11) or boolean (true) or object or array.

Example of Microsoft Bing API result:

JSON Class

I found out on MSDN that there is a .NET JSON class available, this helped me greatly with parsing the API results in the JSON format.

Class Definition
JsonArray Ordered sequence of zero or more JsonValue objects
JsonObject Unordered collection of zero or more key/value pairs
JsonPrimitive Represents a JSON primitive type
JsonValue Abstract base class for JSON

General Microsoft Bing API usage

Before we are able to interact with the Bing API an application id is needed. This application id is a way in which a user/developer using the API can be uniqually identified and also authenticated. Application id's are free to obtain but you need a Live/Hotmail account and are available here.

In the next couple of examples I'll be using a fictional app id.

As mentioned earlier the API uses a REST style architecture, and so to use simply create a HTTP request with the search parameters inside the HTTP request URL.

e.g.

http://api.bing.net/json.aspx?AppId=jfjsk2fjfklfka&Query=apple&
Sources=web&Sources=image&Sources=video&Web.Offset=50&
Image.Offset=50&Video.Offset=50&Image.Count=50&Web.Count=50&Video.Count=50

So lets break down the above HTTP request:

Where the API is found:

http://api.bing.net/

Which format the results will be in returned in:

json.aspx

For JSON:

http://api.bing.net/json.aspx

For XML:

http://api.bing.net/xml.aspx

Insert the Application id:

AppId=jfjsk2fjfklfka

So now the HTTP request URL is shaping up:

http://api.bing.net/json.aspx?AppId=jfjsk2fjfklfka

Next insert the query parameters

Query=apple

Here I am using the API to search for the term apple

Next you need to tell the API which sources it needs to search from:

Sources=web&Sources=image&Sources=video

Here I am requesting that the API search for web, images, and video items.

Again the HTTP request URL is shaping up:

http://api.bing.net/json.aspx?AppId=jfjsk2fjfklfka&Query=apple&
Sources=web&Sources=image&Sources=video&

How to restrict the number of results sent back by the API (Opional):

Web.Offset=50&
Image.Offset=50&Video.Offset=50&Image.Count=50&Web.Count=50&Video.Count=50

The above example shows that I want 50 results of images, videos and web items. The default is

around 10 items for each category images/web and so on.

So the entire HTTP request URL looks something like this:

http://api.bing.net/json.aspx?AppId=jfjsk2fjfklfka&Query=apple&
Sources=web&Sources=image&Sources=video&Web.Offset=50&
Image.Offset=50&Video.Offset=50&Image.Count=50&Web.Count=50&Video.Count=50

What the web-server returns back

So once the client has sent this HTTP request to the web-server what does the server return.

Well because we requested the results to be in a JSON format earlier we should get back the

results in JSON.

Below is the actual response from the server when I searched for the term 'apple' with HTTP request URL in FireFox:

http://api.bing.net/json.aspx?AppId=jfjsk2fjfklfka&Query=apple&Sources=web

using the API:

When I first tried this in Firefox it told me to save the file to my hard-drive and open it from there, inside the saved file this is what was inside:

{"SearchResponse":{"Version":"2.2","Query":
{"SearchTerms":"apple"},"Web":
{"Total":150000000,"Offset":0,"Results":
[{"Title":"Apple (United Kingdom)","Description":"Official site for Macintosh
products in the UK. Products, store, support and dealer list.",
"Url":"http:\/\/www.apple.com\/uk\/",
"CacheUrl":"http:\/\/cc.bingj.com\/cache.aspx?q=apple&d=76651518509612&w=
590d19f6,37350c43",
"DisplayUrl":"www.apple.com\/uk","DateTime":"2009-09-01T13:56:27Z",
"DeepLinks":[{"Title":"iPhone",
"Url":"http:\/\/www.apple.com\/uk\/iphone\/"},
{"Title":"Mac","Url":"http:\/\/www.apple.com\/uk\/mac\/"},
{"Title":"Apple Retail Store","Url":"http:\/\/www.apple.com\/uk\/retail\/"},
{"Title":"iPod iTunes","Url":"http:\/\/www.apple.com\/uk\/itunes\/"},
{"Title":"Store","Url":"http:\/\/store.apple.com\/uk"},
{"Title":"Downloads","Url":"http:\/\/www.apple.com\/uk\/downloads\/"},
{"Title":"Support","Url":"http:\/\/www.apple.com\/uk\/support\/"},
{"Title":"iPod shuffle","Url":"http:\/\/www.apple.com\/uk\/ipodshuffle\/"},
{"Title":"MacBook Pro","Url":"http:\/\/www.apple.com\/uk\/macbookpro\/"},
{"Title":"Contact Us","Url":"http:\/\/www.apple.com\/uk\/contact\/"},
{"Title":"What’s new in iTunes","Url":
"http:\/\/www.apple.com\/uk\/itunes\/whatsnew\/"},
{"Title":"Mac mini","Url":"http:\/\/www.apple.com\/uk\/macmini\/"},
{"Title":"MacBook","Url":"http:\/\/www.apple.com\/uk\/macbook\/"}]}]}}}

As you can see Firefox does not know how to render JSON properly and simply displayed it in plain text, to display the JSON properly I installed a Firefox addon called JSONView.

Install JSONView to view JSON in Firefox

After installing JSONView the following was displayed:

{

    *
      -
      SearchResponse: {
          o Version: "2.2"
          o
            -
            Query: {
                + SearchTerms: "apple"
            }
          o
            -
            Web: {
                + Total: 150000000
                + Offset: 0
                +
                  -
                  Results: [
                    #
                      -
                      {
                         * Title: "Apple (United Kingdom)"
                         * Description: "Official site for Macintosh products in the UK.
                           Products, store, support and dealer list."
                         * Url: http://www.apple.com/uk/
                         * CacheUrl: http://cc.bingj.com/cache.aspx?
                                     q=apple&d=76651518509612&w=590d19f6,
                                     37350c43
                         * DisplayUrl: "www.apple.com/uk"
                         * DateTime: "2009-09-01T13:56:27Z"
                         *
                       -
                          DeepLinks: [
                          o
                          -
                          {
                            + Title: "iPhone"
                            + Url: http://www.apple.com/uk/iphone/
                          }
                          o
                          -
                          {
                            + Title: "Mac"
                            + Url: http://www.apple.com/uk/mac/
                          }
                          o
                          -
                          {
                            + Title: "Apple Retail Store"
                            + Url: http://www.apple.com/uk/retail/
                          }
                          o
                          -
                          {
                            + Title: "iPod iTunes"
                            + Url: http://www.apple.com/uk/itunes/
                          }
                          o
                          -
                          {
                            + Title: "Store"
                            + Url: http://store.apple.com/uk
                          }
                          o
                          -
                          {
                            + Title: "Downloads"
                            + Url: http://www.apple.com/uk/downloads/
                          }
                          o
                          -
                          {
                            + Title: "Support"
                            + Url: http://www.apple.com/uk/support/
                          }
                          o
                          -
                          {
                            + Title: "iPod shuffle"
                            + Url: http://www.apple.com/uk/ipodshuffle/
                          }
                          o
                          -
                          {
                            + Title: "MacBook Pro"
                            + Url: http://www.apple.com/uk/macbookpro/
                          }
                          o
                          -
                          {
                            + Title: "Contact Us"
                            + Url: http://www.apple.com/uk/contact/
                          }
                          o
                          -
                          {
                            + Title: "What’s new in iTunes"
                            + Url: http://www.apple.com/uk/itunes/whatsnew/
                          }
                          o
                          -
                          {
                            + Title: "Mac mini"
                            + Url: http://www.apple.com/uk/macmini/
                          }
                          o
                          -
                          {
                            + Title: "MacBook"
                            + Url: http://www.apple.com/uk/macbook/
                          }
                        ]
                      }
                  ]
            }
      }
}

To continue reading please see this post to see server side code and screen-shots of the application.

Categories: asynch, JSON, RIA, silverlight
  1. October 12, 2009 at 7:41 am | #1

    I need a link for Silverli8 tutorials…… Please provide information over it. Provide links to related topics if possible.

  2. October 16, 2009 at 1:39 pm | #2

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

    • software_jedi
      January 7, 2010 at 10:56 am | #3

      sure why not, just let me know what your quoting.

  1. September 11, 2009 at 5:57 pm | #1
  2. October 8, 2009 at 1:53 pm | #2
  3. January 7, 2010 at 11:01 am | #3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.