Using jQuery & Windows Azure Marketplace

I'm trying to create an Office365 webpart that displays a 5 day weather forecast. The sandbox restrictions mean that I can't call the data service from the server side code, so I need to make the call client side.

Marketplace data is accessible as JSON, so using jQuery and a cryptography library called crypto.js to handle the authentication I should be able to return some data.

Here is a simple htm page that demonstrates a working call to the Azure Marketplace, the username can be anything but the password should be your Primary Account Key from the data subscription.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Windows Azure Data Market</title>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script> 
    <script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.5.3-crypto-min.js"></script>   
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            var user = "{username}";
            var pwd = "{primary account key}";
            $.support.cors = true;
            $.ajax({
                type: "GET",
                beforeSend: function (xhr) {
                    var bytes = Crypto.charenc.Binary.stringToBytes(user + ":" + pwd);
                    var base64 = Crypto.util.bytesToBase64(bytes);
                    xhr.setRequestHeader("Authorization", "Basic " + base64);
                },
                url: "https://api.datamarket.azure.com/DataGovUK/MetOfficeWeatherOpenData/Site?$top=100&$format=json",
                dataType: "json",               
                success: function (data) {
                    alert('success!');
                },
                error: function (jqXHR, textStatus, errorThrown) {                    
                    alert(errorThrown.message);
                }
            });
        })
    </script>
</head>
<body>

</body>
</html>

3 comments:

Anonymous said...

Excellent post!. do you know if is the same way to work with storage account?

Thanks.

Ian Chivers said...

I think the storage account supports the oAuth standard, so I'd recommend you taking a look at that approach. The Marketplace data supports oAuth but accessing it via web/javascript requires user iteraction to get a code, which is no use at all!

Anonymous said...

You are simple...awesome!!!! :D

This worked effortlessly with Bing Related Search API.