ai: integrate search function into your app using bing search api

25
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

Upload: hiang-meng-heng-marvin

Post on 21-Jan-2018

41 views

Category:

Technology


0 download

TRANSCRIPT

Integrate Search Function to Your App using Bing Search API

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

Microsoft

Cognitive Service

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.

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!

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

4b4a

4c

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

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

5

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

6

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

7

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

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; }

}

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

10a

10b

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; }

}

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

12a

12b

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; }

}

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

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;

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();

}

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");

}

}

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);

}

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;

}

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;

}

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!

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

Integrate Search Function to Your App using Bing Search API

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

Microsoft

Cognitive Service