Microsoft Cognitive Services - Bing Search

Microsoft cognitive services

In this article, I'll explain how we can use Microsoft Cognitive Services for Search API, step by step.

Step 1

To consume Cognitive Services, you should have an Azure account. If you don't have any, you can create free account.

Step 2

Click
here and login.

Step 3

Now, follow these steps which I have marked into below image as follow.


Step 4

Create Search API. You can put the name you want and provide more information as below.


Click on "Create" button.

Step 5

Now, click on "All Resources" in left panel and then find your service which you have recently created. Bing Search Panel will open and follow these steps which I have marked on the below screen.


Step 6

Copy any one key and use it in your project.


Step 7

Now, create a new application and write the below code.

JavaScript code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="BingSearch.aspx.cs" Inherits="BingSearch" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.   
  8.     <title>Microsoft Cognitive Services Bing Search API- by puru</title>  
  9.     <style>  
  10.         .ulSearch {text-align: left;font-family: Arial;}  
  11.         .ulSearch li {padding: 10px;list-style-type: none;float: left;}  
  12.         .ulSearch li a {text-decoration: none;}  
  13.         .ulSearch li img {float: left;padding-right: 5px;width: 100px;height: 100px;}  
  14.         .ulSearch li div {float: left;width: 80%;}  
  15.         .ulSearch li span {color: gray;}  
  16.     </style>  
  17.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>  
  18. </head>  
  19. <body>  
  20.   
  21.     <script type="text/javascript">  
  22.         function Search() {  
  23.             if ($("#InputSearch").val().length > 0) {  
  24.                 var params = {  
  25.                     // Request parameters  
  26.                     "q": $("#InputSearch").val(),  
  27.                     "count""10",  
  28.                     "offset""0",  
  29.                     "mkt""en-us",  
  30.                     "safesearch""Moderate",  
  31.                 };  
  32.                 $.ajax({  
  33.                     url: "https://api.cognitive.microsoft.com/bing/v5.0/search?" + $.param(params),  
  34.                     beforeSend: function (xhrObj) {  
  35.                         // Request headers  
  36.                         xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key""xxx863xxx3434xxx852xxxc562xxx68");//put you key here  
  37.                     },  
  38.                     type: "GET",  
  39.                     // Request body  
  40.                     data: "{body}",  
  41.                 })  
  42.                 .done(function (data) {  
  43.                     $("#UlSearchResult").html("");  
  44.                     if (data.images != undefined) {  
  45.                         jQuery.each(data.images.value, function (index, value) {  
  46.                             if (value.name != undefined) {  
  47.                                 $("#UlSearchResult").append("<li><img src=" + value.thumbnailUrl + "/><div>" + value.name + "<br/><span>" + value.webSearchUrl + "</span><br/>" + value.contentUrl + "</div></li>");  
  48.                             }  
  49.                         })  
  50.                     }  
  51.                     else if (data.webPages != undefined) {  
  52.                         jQuery.each(data.webPages.value, function (index, value) {  
  53.                             if (value.name != undefined) {  
  54.                                 $("#UlSearchResult").append("<li><div><a href=" + value.displayUrl + ">" + value.name + "</a></br>" + value.url + "<br/><span>" + value.snippet + " </span></div></li>")  
  55.                             }  
  56.                         })  
  57.                     }  
  58.                     else if (data.news != undefined) {  
  59.                         jQuery.each(data.news.value, function (index, value) {  
  60.                             if (value.name != undefined) {  
  61.                                 $("#UlSearchResult").append("<li><img src=" + value.images.thumbnail.contentUrl + "/><div><a href=" + value.url + ">" + value.name + "</a><br/><span>" + value.description + " </span><br/>" + value.datePublished + " </div></li>")  
  62.                             }  
  63.                         })  
  64.                     }  
  65.                 })  
  66.                 .fail(function () {  
  67.                     alert("No result found");  
  68.                 });  
  69.             } else {  
  70.                 alert("Please enter what you want to search.");  
  71.             }  
  72.         }  
  73.     </script>  
  74.     Search  
  75.     <input type="text" name="InputSearch" id="InputSearch" />  
  76.     <input type="button" id="SearchButton" name="Search" value="Search" onclick="Search(); return false;" />  
  77.     <ul class="ulSearch" id="UlSearchResult"></ul>  
  78. </body>  
  79. </html>  
C# code
  1. protected async void ButtonSearch_Click(object sender, EventArgs e)  
  2.   {  
  3.       if (!string.IsNullOrEmpty(TextboxSearch.Text))  
  4.       {  
  5.           var client = new HttpClient();  
  6.           var queryString = HttpUtility.ParseQueryString(string.Empty);  
  7.   
  8.           // Request headers  
  9.           client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key"ConfigurationManager.AppSettings["BingSearch-Key"]);// put your //key here
  10.   
  11.           // Request parameters  
  12.           queryString["q"] = TextboxSearch.Text;  
  13.           queryString["count"] = "10";  
  14.           queryString["offset"] = "0";  
  15.           queryString["mkt"] = "en-us";  
  16.           queryString["safesearch"] = "Moderate";  
  17.           var uri = "https://api.cognitive.microsoft.com/bing/v5.0/search?" + queryString;  
  18.   
  19.           using (var r = await client.GetAsync(new Uri(uri)))  
  20.           {  
  21.               string result = await r.Content.ReadAsStringAsync();  
  22.               Rootobject LegList = JsonConvert.DeserializeObject<Rootobject>(result);  
  23.   
  24.               StringBuilder sb = new StringBuilder();  
  25.   
  26.               foreach (var item in LegList.webPages.value)  
  27.               {  
  28.                   sb.Append("<li><a href=" + item.displayUrl + ">" + item.name + "</a><br/><span>" + item.snippet + " </span></li>");  
  29.               }  
  30.               ulSearchResult.InnerHtml = sb.ToString();  
  31.           }  
  32.       }  
  33.   }  

Note- To create JSON object, we need to create RootObject class. So, we can create RootObject class as follow. Right click on result and you will see JSON result. Copy JSON result and create a new class in your project.



After creating class, go to Edit menu and click on 'Paste Special'. Then, click on 'Paste json as classes' as follows.



SearchResultInfo.cs
  1. namespace BingSearch  
  2. {  
  3.     public class SearchResultInfo  
  4.     {  
  5.     }  
  6.     public class Rootobject  
  7.     {  
  8.         public string _type { getset; }  
  9.         public Webpages webPages { getset; }  
  10.         public Rankingresponse rankingResponse { getset; }  
  11.     }  
  12.   
  13.     public class Webpages  
  14.     {  
  15.         public string webSearchUrl { getset; }  
  16.         public int totalEstimatedMatches { getset; }  
  17.         public Value[] value { getset; }  
  18.     }  
  19.   
  20.     public class Value  
  21.     {  
  22.         public string id { getset; }  
  23.         public string name { getset; }  
  24.         public string url { getset; }  
  25.         public string displayUrl { getset; }  
  26.         public string snippet { getset; }  
  27.         public DateTime dateLastCrawled { getset; }  
  28.         public About[] about { getset; }  
  29.     }  
  30.   
  31.     public class About  
  32.     {  
  33.         public string name { getset; }  
  34.     }  
  35.   
  36.     public class Rankingresponse  
  37.     {  
  38.         public Mainline mainline { getset; }  
  39.     }  
  40.   
  41.     public class Mainline  
  42.     {  
  43.         public Item[] items { getset; }  
  44.     }  
  45.   
  46.     public class Item  
  47.     {  
  48.         public string answerType { getset; }  
  49.         public int resultIndex { getset; }  
  50.         public Value1 value { getset; }  
  51.     }  
  52.   
  53.     public class Value1  
  54.     {  
  55.         public string id { getset; }  
  56.     }  
  57. }  
HTML for C# code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="BIngSearchCSharp.aspx.cs" Inherits="BIngSearchCSharp" Async="true" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.   <title>Microsoft Cognitive Services Bing Search API- by puru</title>  
  8.     <style>  
  9.         .ulSearch {text-align: left;font-family: Arial;}  
  10.         .ulSearch li {padding: 10px;list-style-type: none;float: left;}  
  11.         .ulSearch li a {text-decoration: none;}  
  12.         .ulSearch li img {float: left;padding-right: 5px;width: 100px;height: 100px;}  
  13.         .ulSearch li div {float: left;width: 80%;}  
  14.         .ulSearch li span {color: gray;}  
  15.     </style>  
  16. </head>  
  17. <body>  
  18.     <form id="form1" runat="server">  
  19.         <div>  
  20.   
  21.             <asp:TextBox ID="TextboxSearch" runat="server" />  
  22.             <asp:Button ID="ButtonSearch" runat="server" Text="Search" OnClick="ButtonSearch_Click" />  
  23.             <ul id="ulSearchResult" class="ulSearch" runat="server"></ul>  
  24.         </div>  
  25.     </form>  
  26. </body>  
  27. </html>  

Output

Enter text which you want to search and click on "Search" button. You will find the following result.


Similar Articles