Migrating Bing Search API 2.0 to Windows Azure based new Bing Search API

The C# code sample below demonstrates how to migrate from old bing search API 2.0 to new Windows Azure based bing search API

Microsoft came up with the Bing Search few years back to compete with the Google search with an edge for the developers to create their own solutions based on it. Microsoft exposed its public search API to be easily used by the developer community around the globe.
The Bing Search API enables developers to embed and customize search results in applications or websites using XML or JSON. Add search functionality to a website, create unique consumer or enterprise apps, or develop new mash-ups. The Bing Search API gives you access to web, image, news, and video results, as well as related search and spelling suggestions. Microsoft came up with Bing Search API 2.0 earlier.

With introduction of Windows Azure, the Bing Search API 2.0 is transitioned to new cloud-based data service that is available via subscription based on usage requirements. The new cloud-based Bing Search API enables developer community to create their own applications using it to search, get and use the available data store provided by Bing. They can also analyze the data online using the new Service Explorer tool.

The new version of the Bing Search API includes:

• Metered subscription of query limits.
• HTTPS query URLs (sometimes called "endpoints") that provide results in either XML or JSON media formats.
• Open Data Protocol (OData) support for easy consumption across multiple development systems.
• Improved support for data types.
• The ability to monetize applications in the Windows Azure Marketplace.
• Access to fresher results and improved relevance.

For users of old Bing Search API 2.0, the migration documents are provided at Windows Azure Marketplace to move to new and fresh cloud based Bing Search API.
There are two issues you will face while moving you codebase to new API. First, if the code was written in .Net 2.0, so the new <BingSearchContainer.cs> provided at Windows Azure Marketplace will not work as such as this file requires version 4.0. Second, you need get new Bing account key.
Following is the list of changes to be made to migrate to new Bing search API.
1. Change your API service root URL to https://api.datamarket.azure.com/Bing/Search/
2. Get the BING ACCOUNT KEY


Using new BingsearchContainer.cs as provided at Windows Azure marketplace:

internal class SearchBing : SearchWeb, IDisposable
{
                Dictionary<SettingFields, string> _optionalParameters;
               List<Dictionary<SearchResultFields, string>> _newPage;
                const string SEARCHAPISERVICEURI = "https://api.datamarket.azure.com/Bing/Search/";
                const string BINGACCOUNTKEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Set your account key here in place
      
                 internal Dictionary<SettingFields, string> OptionalParameters
                {
                                set
                                {
                                                _optionalParameters = value;
                                  }
                 }


                 internal List<Dictionary<SearchResultFields, string>> NewPage
                 {
                 get
                 {
                                   return _newPage;
                }
                 }                            

                 internal void Search(string _searchQuery, uint _offset)
                {

                                var _bingSearchAzure  =  new BingSearchContainer(new Uri(SEARCHAPISERVICEURI));
                               _bingSearchAzure.Credentials = new System.Net.NetworkCredential(BINGACCOUNTKEY, BINGACCOUNTKEY);
                                string options = String.Empty;


             if (_optionalParameters != null)
                options = SetOptionalParameters();
            
            var _searchResponse = _bingSearchAzure.Image(_searchQuery, null, null, "strict", null, null, options);
            _searchResponse = _searchResponse.AddQueryOption("$top", this._resultsPerPage);
            _searchResponse = _searchResponse.AddQueryOption("$skip", _offset);
            
            
            var result = _searchResponse.Execute();
             this.TotalResults = 1000;
            _newPage = new List<Dictionary<SearchResultFields, string>>();
            foreach(ImageResult _result in result)
            {
                     Dictionary<SearchResultFields, string> _newResult = new Dictionary<SearchResultFields, string>();
                                   _newResult.Add(SearchResultFields.ThumbnailURL, _result.Thumbnail.MediaUrl);
                                   _newResult.Add(SearchResultFields.ThumbnailHeight, _result.Thumbnail.Height.ToString());
                                  _newResult.Add(SearchResultFields.ThumbnailWidth, _result.Thumbnail.Width.ToString());
                                   _newResult.Add(SearchResultFields.MainImageURL, _result.MediaUrl);
                                   _newResult.Add(SearchResultFields.Source, _result.SourceUrl);
                                   _newResult.Add(SearchResultFields.Title, _result.Title);
                                 _newResult.Add(SearchResultFields.Height, _result.Height.ToString());
                                   _newResult.Add(SearchResultFields.Width, _result.Width.ToString());
                                   _newResult.Add(SearchResultFields.Size, _result.FileSize.ToString());
                                   _newPage.Add(_newResult);
                
            }
            
      }
                 

                  private string [] SetOptionalParameters()
             {
            
           _parametersArray = new string[_optionalParameters.Count];
             int _index = 0;
             foreach (KeyValuePair<SettingFields, string> _parameters in _optionalParameters)
           {
                                _parametersArray[_index] = _parameters.Key.ToString() + ":" + _parameters.Value;
                 _index = _index + 1;
           }
           return _parametersArray ;

                 }
}



Using the new Bing Search API using webrequest (Workable solution for any framework):


internal class SearchBing : SearchWeb, IDisposable
{

                Dictionary<SettingFields, string> _optionalParameters;
               List<Dictionary<SearchResultFields, string>> _newPage;
                const string SEARCHAPISERVICEURI = "https://api.datamarket.azure.com/Bing/Search/";
                const string BINGACCOUNTKEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Set your       account key here in place
      
                 internal Dictionary<SettingFields, string> OptionalParameters
               {
                 set
                 {
                     _optionalParameters = value;
                 }
               }

        internal List<Dictionary<SearchResultFields, string>> NewPage
        {
             get
           {
                  return _newPage;
             }
        }                      

       internal void Search(string _searchQuery, uint _offset)
        {

           string imageSearchQueryUrl = SEARCHAPISERVICEURI + "Image?Query=%27" + _searchQuery + "%27&$top=" + this._resultsPerPage + "&$skip=" + _offset + "&$Options=%27" + System.Web.HttpUtility.UrlEncode(SetOptionalParameters ()) + "%27" ;
      
           XmlDocument xmlParseDom = new XmlDocument();
           System.Net.NetworkCredential accountCredential = new System.Net.NetworkCredential(BINGACCOUNTKEY, BINGACCOUNTKEY);

           XmlUrlResolver resolver = new XmlUrlResolver();
           resolver.Credentials = accountCredential;

           xmlParseDom.XmlResolver = resolver;
           xmlParseDom.Load(imageSearchQueryUrl);
    
           XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(xmlParseDom.NameTable);
           namespaceMgr.AddNamespace("atom","http://www.w3.org/2005/Atom");
           namespaceMgr.AddNamespace("m","http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
           namespaceMgr.AddNamespace("d","http://schemas.microsoft.com/ado/2007/08/dataservices");
            
           string nextResultSet = xmlParseDom.SelectSingleNode("/atom:feed/atom:link[@rel='next']/@href", namespaceMgr).Value;

            XmlNodeList imageresults =     xmlParseDom.SelectNode("/atom:feed/atom:entry/atom:content/m:properties",namespaceMgr);

            this.TotalResults = 1000;
            _newPage = new List<Dictionary<SearchResultFields, string>>();

           foreach(XmlNode _result in imageresults)
             {
                     Dictionary<SearchResultFields, string> _newResult = new Dictionary<SearchResultFields, string>();

                     XmlNodeList thumbnailNodelst = _result.LastChild.ChildNodes;
                     foreach (XmlNode xmlthumbnailNode in thumbnailNodelst)
                     {
                         if (xmlthumbnailNode.Name == "d:MediaUrl")
                              _newResult.Add(SearchResultFields.ThumbnailURL, xmlthumbnailNode.ChildNodes[0].InnerText);
                         if (xmlthumbnailNode.Name == "d:Width")
                              _newResult.Add(SearchResultFields.ThumbnailWidth, xmlthumbnailNode.ChildNodes[0].InnerText);
                         if (xmlthumbnailNode.Name == "d:Height")
                              _newResult.Add(SearchResultFields.ThumbnailHeight, xmlthumbnailNode.ChildNodes[0].InnerText);
                     }

                     _newResult.Add(SearchResultFields.MainImageURL, _result.SelectSingleNode(".//d:MediaUrl", namespaceMgr).InnerText);
                     _newResult.Add(SearchResultFields.Source, _result.SelectSingleNode(".//d:SourceUrl", namespaceMgr).InnerText);
                    _newResult.Add(SearchResultFields.Title, _result.SelectSingleNode(".//d:Title", namespaceMgr).InnerText);
                     _newResult.Add(SearchResultFields.Height, _result.SelectSingleNode(".//d:Height", namespaceMgr).InnerText);
                     _newResult.Add(SearchResultFields.Width, _result.SelectSingleNode(".//d:Width", namespaceMgr).InnerText);
                     _newResult.Add(SearchResultFields.Size, _result.SelectSingleNode(".//d:FileSize", namespaceMgr).InnerText);

                    _newPage.Add(_newResult);
                 }
            
}
                 

private string SetOptionalParameters()
{
            string  _parametersString = String.Empty;
            int _index = 0;
            foreach (KeyValuePair<SettingFields, string> _parameters in _optionalParameters)
             {
                 if (_index > 0)
                    _parametersString = _parametersString + "+";
                    _parametersString = _parametersString + _parameters.Key.ToString() + ":" + _parameters.Value;
                    _index = _index + 1;
             }
             return _parametersString;

   }
}

By Sushil Kumar   Popularity  (2071 Views)