Top Banner
Integrate Search Function to Your App using Bing Search API Marvin Heng Twitter : @hmheng Blog : http://hmheng.pinsland.com Github: https://github.com/hmheng Microsoft Cognitive Service
25

AI: Integrate Search Function into Your App Using Bing Search API.

Jan 21, 2018

Download

Technology

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function to Your App using Bing Search API

Marvin HengTwitter : @hmhengBlog : http://hmheng.pinsland.comGithub: https://github.com/hmheng

Microsoft

Cognitive Service

Page 3: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App1. First, we need to obtain the API key for Bing Search APIs v7. To learn how to get one, click here.

Page 4: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App2. Secondly, we need to create a Xamarin Cross Platform Mobile App. Don’t have one yet? Click to learn how to create one!

Page 5: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App3. Thirdly, we need to add a NuGet Packages – Newtonsoft.Json, right click Solution in the Solution Explorer -> Manage NuGet Packages for Solution…

3b

3a

Page 6: AI: Integrate Search Function into Your App Using Bing Search API.

4b4a

4c

Integrate Search Function Into Mobile App4. Let’s search Newtonsoft.Json and install it to all the projects.

Page 7: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App5. Now, we need to add some Search Bar components to MainPage.xaml as specified below.

5

Page 8: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App6. Down below the Grid component, let’s add a list view to show the returned search result.

6

Page 9: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App7. Create a folder named Models. We will create few classes under this folder later.

7

Page 10: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App8. Right Click “Models” folder -> Add -> select Class from the list. Name the new class as SearchTagObj.cs.

8a

8b

Page 11: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App9. Create two variables for SearchTagsObj class as below.

public class SearchTagsObj

{

public string name { get; set; }

public string content { get; set; }

}

Page 12: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App10. Create another new class and name it as WebResultsList.cs.

10a

10b

Page 13: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App11. Create the following variables for WebResultsList class.

public class WebResultsList

{

public string name { get; set; }

public string webSearchUrl { get; set; }

public uint totalEstimatedMatches { get; set; }

public ObservableCollection<WebValueObject> value { get;

set; }

public bool someResultsRemoved { get; set; }

}

Page 14: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App12. Create another new class and name it as WebValueObject.cs.

12a

12b

Page 15: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App13. Create the following variables for WebValueObject class.

public class WebValueObject

{

public string id { get; set; }

public string name { get; set; }

public string url { get; set; }

public string displayUrl { get; set; }

public string snippet { get; set; }

public string dateLastCrawled { get; set; }

public List<SearchTagsObj> searchTags { get; set; }

}

Page 16: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App14. Create another class under .Core project, name it as AppConstants.cs and add three variables as shown below.

public class AppConstants

{

public const string OcpApimSubscriptionKey =

"Ocp-Apim-Subscription-Key";

public const string BingWebSearchApiUrl =

"https://api.cognitive.microsoft.com/bing/v7.0/search

public static string BingWebSearchApiKey =

“<YOUR API KEY>";

}

14

Page 17: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App15. Now, head to MainPage.xaml.cs, we need to declare few variables.

ObservableCollection<WebValueObject> values;

string queryTerm;

HttpClient searchApiClient;

Page 18: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App16. Next, in the MainPage constructor, add click event handler for btnSearch & HttpClient to call WebApi later. Also, create the event handling function.

public MainPage()

{

InitializeComponent();

btnSearch.Clicked += BtnSearch_Clicked;

searchApiClient = new HttpClient();

searchApiClient.DefaultRequestHeaders.Add(AppConstants.OcpApimSubscript

ionKey, AppConstants.BingWebSearchApiKey);

}

private async void BtnSearch_Clicked(object sender, EventArgs e)

{

this.queryTerm = txtKeyword.Text;

await LoadData();

}

Page 19: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App17. Then, create LoadData function with following codes.

protected async Task LoadData()

{

LoadingIndicator.IsVisible = true;

LoadingIndicator.IsRunning = true;

WebResultsList webResults = null;

Boolean error = false;

try{

webResults = await GetQueryResults();

} catch {

error = true;

}

LoadingIndicator.IsVisible = false;

LoadingIndicator.IsRunning = false;

DataTable.IsVisible = true;

if (error) {

await ErrorAndPop("Error", "Error

fetching results", "OK");

}else if

(webResults?.totalEstimatedMatches>0)

{

values = webResults.value;

DataTable.ItemsSource = values;

}else{

await ErrorAndPop("Error", "No

results found", "OK");

}

}

Page 20: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App18. After that, create ErrorAndPop function with following codes.

protected async Task ErrorAndPop(string title, string text, string button)

{

await DisplayAlert(title, text, button);

Console.WriteLine($"ERROR: {text}");

await Task.Delay(TimeSpan.FromSeconds(0.1d));

await Navigation.PopAsync(true);

}

Page 21: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App19. Followed by, create a function GetQueryResults() to call the Bing Search API and returned the search results.

async Task<WebResultsList> GetQueryResults(){

var queryString = System.Net.WebUtility.UrlEncode(queryTerm);

string uri = AppConstants.BingWebSearchApiUrl + $"count=20&mkt=en-

US&q={queryString}&responseFilter=Webpages&setLang=en";

WebResultsList webResults = null;

HttpResponseMessage httpResponseMessage = await

searchApiClient.GetAsync(uri); var responseContentString = await

httpResponseMessage.Content.ReadAsStringAsync();

JObject json = JObject.Parse(responseContentString);

JToken resultBlock = json.SelectToken("$.webPages");

if (resultBlock != null){

webResults =

JsonConvert.DeserializeObject<WebResultsList>(resultBlock.ToString());

}

return webResults;

}

Page 22: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App20. Last but not least, create an event handler - ItemSelectedEventHandler forshowing the selected web result when user clicked the result item.

async void ItemSelectedEventHandler(object sender,

SelectedItemChangedEventArgs e){

if (e.SelectedItem == null) { return; }

WebView webView = new WebView

{

Source = new UrlWebViewSource{Url = ((WebValueObject)e.SelectedItem).url },

VerticalOptions = LayoutOptions.FillAndExpand

};

// Display the WebView

await Navigation.PushAsync(new ContentPage{

Content = webView, Title = ((WebValueObject)e.SelectedItem).name

});

// Deselect Item

((ListView)sender).SelectedItem = null;

}

Page 23: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function Into Mobile App21. Let’s compile and run it on your mobile device. Try to see what would happen when enter some keywords to search!

Page 24: AI: Integrate Search Function into Your App Using Bing Search API.

It’s so easy!Integrating Search function to Your App is So Easy!

Page 25: AI: Integrate Search Function into Your App Using Bing Search API.

Integrate Search Function to Your App using Bing Search API

Marvin HengTwitter : @hmhengBlog : http://hmheng.pinsland.comGithub: https://github.com/hmheng

Microsoft

Cognitive Service