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

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

Output

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