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

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

Post on 21-Jan-2018

32 views

Category:

Technology

0 download

Embed Size (px)

TRANSCRIPT

  1. 1. 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
  2. 2. Pre-requisites Created a Xamarin mobile app Cognitive Service Account
  3. 3. Integrate Search Function Into Mobile App 1. First, we need to obtain the API key for Bing Search APIs v7. To learn how to get one, click here.
  4. 4. Integrate Search Function Into Mobile App 2. Secondly, we need to create a Xamarin Cross Platform Mobile App. Dont have one yet? Click to learn how to create one!
  5. 5. Integrate Search Function Into Mobile App 3. Thirdly, we need to add a NuGet Packages Newtonsoft.Json, right click Solution in the Solution Explorer -> Manage NuGet Packages for Solution 3b 3a
  6. 6. 4b4a 4c Integrate Search Function Into Mobile App 4. Lets search Newtonsoft.Json and install it to all the projects.
  7. 7. Integrate Search Function Into Mobile App 5. Now, we need to add some Search Bar components to MainPage.xaml as specified below. 5
  8. 8. Integrate Search Function Into Mobile App 6. Down below the Grid component, lets add a list view to show the returned search result. 6
  9. 9. Integrate Search Function Into Mobile App 7. Create a folder named Models. We will create few classes under this folder later. 7
  10. 10. Integrate Search Function Into Mobile App 8. Right Click Models folder -> Add -> select Class from the list. Name the new class as SearchTagObj.cs. 8a 8b
  11. 11. Integrate Search Function Into Mobile App 9. Create two variables for SearchTagsObj class as below. public class SearchTagsObj { public string name { get; set; } public string content { get; set; } }
  12. 12. Integrate Search Function Into Mobile App 10. Create another new class and name it as WebResultsList.cs. 10a 10b
  13. 13. Integrate Search Function Into Mobile App 11. 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 value { get; set; } public bool someResultsRemoved { get; set; } }
  14. 14. Integrate Search Function Into Mobile App 12. Create another new class and name it as WebValueObject.cs. 12a 12b
  15. 15. Integrate Search Function Into Mobile App 13. 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 searchTags { get; set; } }
  16. 16. Integrate Search Function Into Mobile App 14. 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 = "; } 14
  17. 17. Integrate Search Function Into Mobile App 15. Now, head to MainPage.xaml.cs, we need to declare few variables. ObservableCollection values; string queryTerm; HttpClient searchApiClient;
  18. 18. Integrate Search Function Into Mobile App 16. 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(); }
  19. 19. Integrate Search Function Into Mobile App 17. 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"); } }
  20. 20. Integrate Search Function Into Mobile App 18. 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); }
  21. 21. Integrate Search Function Into Mobile App 19. Followed by, create a function GetQueryResults() to call the Bing Search API and returned the search results. async Task 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(resultBlock.ToString()); } return webResults; }
  22. 22. Integrate Search Function Into Mobile App 20. Last but not least, create an event handler - ItemSelectedEventHandler for showing 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; }
  23. 23. Integrate Search Function Into Mobile App 21. Lets compile and run it on your mobile device. Try to see what would happen when enter some keywords to search!
  24. 24. Its so easy! Integrating Search function to Your App is So Easy!
  25. 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