Advertisement
apieceoffruit

Search App

Apr 18th, 2023
1,101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1.   public class SearchByString<T> : StringSearchPresenter
  2.     {
  3.         #region plumbing
  4.  
  5.         readonly ISearchEngine<T> _search;
  6.         readonly IQueryFactory<T> _query;
  7.         readonly StringSearchView<T> _view;
  8.  
  9.         public SearchByString(ISearchEngine<T> search,IQueryFactory<T> query,StringSearchView<T> view)
  10.         {
  11.             _search = search;
  12.             _query = query;
  13.             _view = view;
  14.         }
  15.  
  16.         public bool AttemptEmptySearchAnyway { get; set; } = true;
  17.  
  18.         #endregion
  19.  
  20.         public View View => _view;
  21.  
  22.         public async void PerformSearch()
  23.         {
  24.             try
  25.             {
  26.                 var search = _view.Search;
  27.                 if (string.IsNullOrWhiteSpace(search))
  28.                 {
  29.                     Say(EMPTY_SEARCH_STRING);
  30.                    
  31.                     if (AttemptEmptySearchAnyway)
  32.                         await UpdateUiWithResults(string.Empty);
  33.                     else
  34.                         ClearSearchResults();
  35.                    
  36.                     return;
  37.                 }
  38.  
  39.            
  40.                 await UpdateUiWithResults(search);
  41.             }
  42.             catch (Exception ex)
  43.             {
  44.                Say(INTERNAL_ERROR,ex);
  45.             }
  46.         }
  47.  
  48.         public void UpdateAutoComplete()
  49.         {
  50.             var search = _view.Search;
  51.             if (_search.HasSpellcheckSuggestion(search, out var s))
  52.             {
  53.                 _view.DidYouMean = s;
  54.                 Say(PROBABLE_SPELLING_MISTAKE);
  55.             }
  56.             _view.AutoComplete = String.IsNullOrWhiteSpace(search) ? new List<string>() : _search.AutoComplete(search);
  57.         }
  58.  
  59.         void ClearSearchResults()
  60.         {
  61.             _view.Results = new List<T>();
  62.         }
  63.        
  64.         async Task UpdateUiWithResults(string query)
  65.         {
  66.             var results = (await _query.Search(query).Execute()).ToList();
  67.             if (results.Count <= 0)
  68.                Say(NO_RESULTS);
  69.             _view.Results = results;
  70.         }
  71.  
  72.         #region Utility
  73.  
  74.         void Say(string message, object context = null) => _view.SendMessage(Message.Say(message, context));
  75.        
  76.  
  77.         #endregion
  78.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement