protected override void OnStartSearch() { var sourceItems = _searchTarget.SearchSourceData(); var resultItems = new List <IPowerShellCommand>(); uint resultCount = 0; ErrorCode = VSConstants.S_OK; try { string searchString = this.SearchQuery.SearchString; uint progress = 0; foreach (IPowerShellCommand item in sourceItems) { if (item.Name.ToLowerInvariant().Contains(searchString.ToLowerInvariant()) | item.ModuleName.ToLowerInvariant().Contains(searchString.ToLowerInvariant())) { resultItems.Add(item); resultCount++; } SearchCallback.ReportProgress(this, progress++, (uint)sourceItems.Count); } } catch { ErrorCode = VSConstants.E_FAIL; } finally { ThreadHelper.Generic.Invoke(() => { _searchTarget.SearchResultData(resultItems); }); SearchResults = resultCount; } base.OnStartSearch(); }
/// <summary> /// Override to start the search /// </summary> protected async override void OnStartSearch() { var sortQuery = "relevance"; int pageSize = 40; bool alwaysShowLink = false; var options = StackOverflowQuickLaunchPackage.Instance.OptionPage; if (options != null) { sortQuery = options.Sort.ToString().ToLowerInvariant(); pageSize = options.ShowResults; alwaysShowLink = options.AlwayShowLink; } //// Get the tokens count in the query //uint tokenCount = SearchQuery.GetTokens(0, null); //// Get the tokens //IVsSearchToken[] tokens = new IVsSearchToken[tokenCount]; //SearchQuery.GetTokens(tokenCount, tokens); var cancellationSource = new CancellationTokenSource(); var searchResult = (StackOverflowSearchResult)null; try { using (var client = new HttpClient( new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate } )) using (var response = await client.GetAsync("https://api.stackexchange.com/2.2/search/excerpts?order=desc&pagesize=" + pageSize + "&sort=" + sortQuery + "&site=stackoverflow&q=" + WebUtility.UrlEncode(SearchQuery.SearchString.Trim()), cancellationSource.Token)) using (var receiveStream = await response.Content.ReadAsStreamAsync()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(StackOverflowSearchResult)); searchResult = serializer.ReadObject(receiveStream) as StackOverflowSearchResult; } } catch (Exception ex) { this.ErrorCode = ex.HResult; this.SetTaskStatus(VSConstants.VsSearchTaskStatus.Error); this.SearchCallback.ReportComplete(this, 0); return; } // Check if the search was canceled if (this.TaskStatus == VSConstants.VsSearchTaskStatus.Stopped) { if (!cancellationSource.IsCancellationRequested) { cancellationSource.Cancel(); if (cancellationSource != null) { cancellationSource.Dispose(); } } // The completion was already notified by the base.OnStopSearch, there is nothing else to do return; } if (searchResult.ErrorId.HasValue) { this.SetTaskStatus(VSConstants.VsSearchTaskStatus.Error); this.SearchCallback.ReportComplete(this, this.SearchResults); return; } bool anyResults = false; if (searchResult != null && searchResult.Items.Length != 0) { anyResults = true; var results = searchResult.Items.Take(pageSize).ToArray(); // Since we know how many items we have, we can report progress for (int itemIndex = 0; itemIndex < results.Length; itemIndex++) { var itemResult = new StackOverflowSearchItemResult( (results[itemIndex].ItemType == ItemType.Question ? "Q: " : "A: ") + WebUtility.HtmlDecode(results[itemIndex].Title), FormatExcerpt(WebUtility.HtmlDecode(results[itemIndex].Excerpt)).Trim(), "https://stackoverflow.com/questions/" + results[itemIndex].QuestionId, new WinFormsIconUIObject(Resources.StackOverflow), searchProvider); // Create and report new result SearchCallback.ReportResult(this, itemResult); // Keep track of how many results we have found, and the base class will use this number when calling the callback to report completion SearchResults++; // Since we know how many items we have, we can report progress SearchCallback.ReportProgress(this, (uint)(itemIndex + 1), (uint)results.Length); } } if (!anyResults || alwaysShowLink) { // Create and report new result SearchCallback.ReportResult(this, new StackOverflowSearchItemResult($"Search Online on Stack Overflow for '{SearchQuery.SearchString}'", string.Empty, "https://stackoverflow.com/search?q=" + WebUtility.UrlEncode(SearchQuery.SearchString.Trim()), null, searchProvider)); // Only one result SearchCallback.ReportComplete(this, 1); } // Now call the base class - it will set the task status to complete and will callback to report search complete base.OnStartSearch(); }
//</Snippet13> //<Snippet14> protected override void OnStartSearch() { // Use the original content of the text box as the target of the search. var separator = new string[] { Environment.NewLine }; string[] contentArr = ((MyControl)m_toolWindow.Content).SearchContent.Split(separator, StringSplitOptions.None); // Get the search option. bool matchCase = false; //<Snippet11> matchCase = m_toolWindow.MatchCaseOption.Value; //</Snippet11> // Set variables that are used in the finally block. StringBuilder sb = new StringBuilder(""); uint resultCount = 0; this.ErrorCode = VSConstants.S_OK; try { string searchString = this.SearchQuery.SearchString; // If the search string contains the filter string, filter the content array. string filterString = "lines:\"even\""; if (this.SearchQuery.SearchString.Contains(filterString)) { // Retain only the even items in the array. contentArr = GetEvenItems(contentArr); // Remove 'lines:"even"' from the search string. searchString = RemoveFromString(searchString, filterString); } // Determine the results. uint progress = 0; foreach (string line in contentArr) { if (matchCase == true) { if (line.Contains(searchString)) { sb.AppendLine(line); resultCount++; } } else { if (line.ToLower().Contains(searchString.ToLower())) { sb.AppendLine(line); resultCount++; } } //<Snippet15> SearchCallback.ReportProgress(this, progress++, (uint)contentArr.GetLength(0)); //</Snippet15> // Uncomment the following line to demonstrate the progress bar. // System.Threading.Thread.Sleep(100); } } catch (Exception e) { this.ErrorCode = VSConstants.E_FAIL; } finally { ThreadHelper.Generic.Invoke(() => { ((TextBox)((MyControl)m_toolWindow.Content).SearchResultsTextBox).Text = sb.ToString(); }); this.SearchResults = resultCount; } // Call the implementation of this method in the base class. // This sets the task status to complete and reports task completion. base.OnStartSearch(); }