Example #1
0
        public void SetUp()
        {
            _record1 = CreateRecord("Teresa", 43);
            _record2 = CreateRecord("M�rcia", 26);
            _record3 = CreateRecord("Bamboo", 27);

            _result = new SearchResult();
            _result.Add(new SearchHit(_record1));
            _result.Add(new SearchHit(_record2));
            _result.Add(new SearchHit(_record3));
        }
Example #2
0
        public async Task LoadPage()
        {
            int takeCount = SearchResultIds.Count() - SearchResult.Count();

            if (takeCount > 0)
            {
                IsLoading = true;
                try
                {
                    if (takeCount > loadCount)
                    {
                        takeCount = loadCount;
                    }
                    var subSet = SearchResultIds.Skip(SearchResult.Count()).Take(takeCount);
                    var count  = subSet.Count();
                    foreach (var boardGame in await cache.BoardGamesFromIds(subSet))
                    {
                        SearchResult.Add(boardGame);
                    }
                }
                finally
                {
                    IsLoading = false;
                }
            }
        }
        private async void SearchAction()
        {
            if (SearchFieldVisibility != Visibility.Visible)
            {
                SearchFieldVisibility = Visibility.Visible;
                return;
            }

            SearchResult.Clear();

            if (string.IsNullOrWhiteSpace(SearchQuery))
            {
                return;
            }

            try
            {
                _songSearchService.Query = SearchQuery;
                foreach (var song in await _songSearchService.FetchAsync())
                {
                    SearchResult.Add(song);
                }
            }
            catch (Exception ex)
            {
                _logger.Log($"{Tag} FetchFetchSongs error {ex.Message}", Category.Exception, Priority.High);
                _dialogService.ShowError("Spotify search", ex.Message);
            }

            SearchFieldVisibility = Visibility.Hidden;
        }
Example #4
0
        private void Se_Find(object sender, Gallerie e)
        {
            SearchResult.Add(e);


            try
            {
                Preview_AddReverse(e);

                Panel_Search_Download.Label_Select_Page?.Invoke(new MethodInvoker(() =>
                {
                    if (Math.Ceiling((double)SearchResult.Count / Previews.Count) != int.Parse(Panel_Search_Download.Label_Select_Page.Text.Split(' ')[1]))
                    {
                        Panel_Search_Download.Label_Select_Page.Text = "~ " + Math.Ceiling((double)SearchResult.Count / Previews.Count).ToString();
                    }
                }));
                ///
                /// MessageBox.show Preview.Count가 0이라서 생기는 오류
                ///
                ///
            }
            catch (Exception)
            {
            }
        }
 void AddToResult(SearchResult result, Postings found)
 {
     foreach (Posting posting in found)
     {
         result.Add(new SearchHit(posting.Record));
     }
 }
Example #6
0
        public void TestIntersect()
        {
            SearchResult other = new SearchResult();

            other.Add(new SearchHit(_record3));
            other.Add(new SearchHit(_record1));

            AssertSearchHits(_result.Intersect(other), _record1, _record3);

            other = new SearchResult();
            other.Add(new SearchHit(_record2));

            AssertSearchHits(_result.Intersect(other), _record2);

            AssertEquals(0, _result.Intersect(new SearchResult()).Count);
            AssertSearchHits(_result.Intersect(_result), _record1, _record2, _record3);
        }
 public void Initialize()
 {
     SearchResult.Clear();
     foreach (ProductViewModel product in Products)
     {
         SearchResult.Add(product);
     }
 }
        private async void SingleSearchAction()
        {
            var v = _container.Resolve <YoutubeFindSingleView>();
            await DialogHost.Show(v, "RootDialog");

            var result = ((YoutubeFindSingleViewModel)((UserControl)v).DataContext).Result;

            SearchResult.Clear();
            SearchResult.Add(result);
        }
 private async void MoreAction()
 {
     if (_songSearchService != null && _songSearchService.Query != null)
     {
         foreach (var song in await _songSearchService.FetchAsync())
         {
             SearchResult.Add(song);
         }
     }
 }
Example #10
0
        private static void Search()
        {
            SearchResult.Clear();
            HitCount.Clear();

            if (searchText.Equals("?"))
            {
                for (int i = 0; i < GHelpDatabase.Instance.Entries.Count; ++i)
                {
                    SearchResult.Add(i);
                    HitCount.Add(1);
                    expandedFlags = new bool[SearchResult.Count];
                }
                return;
            }

            string text = searchText;

            if (text.Length < 3)
            {
                return;
            }

            string[] split = text.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
            if (split.Length == 0)
            {
                return;
            }
            for (int i = 0; i < split.Length; ++i)
            {
                split[i] = split[i].ToLower();
            }

            List <GHelpEntry> entries = GHelpDatabase.Instance.Entries;

            for (int i = 0; i < entries.Count; ++i)
            {
                float      count = 0;
                GHelpEntry e     = entries[i];
                for (int j = 0; j < split.Length; ++j)
                {
                    count += e.Question.ToLower().Contains(split[j]) ? 1 : 0;
                    count += e.Answer.ToLower().Contains(split[j]) ? 0.5f : 0;
                }

                SearchResult.Add(i);
                HitCount.Add(count);
            }

            SearchResult.Sort((i0, i1) => - HitCount[i0].CompareTo(HitCount[i1]));
            HitCount.Sort((i0, i1) => - i0.CompareTo(i1));

            expandedFlags = new bool[SearchResult.Count];
        }
Example #11
0
        private void Search(string query)
        {
            Expression <Func <ProductViewModel, bool> > filter = compiler.Compile(query);
            IEnumerable <ProductViewModel> result = Products.AsQueryable().Where(filter);

            SearchResult.Clear();
            foreach (ProductViewModel product in result)
            {
                SearchResult.Add(product);
            }
        }
Example #12
0
 private async void FetchMoreResultCommandAction()
 {
     try
     {
         foreach (var item in await _songSearchService.FetchAsync())
         {
             SearchResult.Add(item);
         }
     }
     catch (Exception)
     {
         //TODO:write can fetchhmore method....
     }
 }
        /// <summary>検索処理</summary>
        /// <param name="parameter"></param>
        private void ExecuteSearch(object parameter)
        {
            Logger.Info(CLASS_NAME, "ExecuteSearch", $"start. SearchWord:[{SearchWord}]");

            if (_model == null)
            {
                Logger.Fatal(CLASS_NAME, "ExecuteSearch", "_model is null");
                return;
            }

            if (string.IsNullOrEmpty(SearchWord))
            {
                Logger.Error(CLASS_NAME, "ExecuteSearch", "SearchWord is null or empty!");
                return;
            }

            // dicのintはindex部分なので本文キャレット移動、stringは結果表示リストに使用する
            Dictionary <int, string> indexWordPairs = _model.SearchAllWordsInText(SearchWord, TextDocument.Text);

            if (UpdateSearchResultVisiblity(indexWordPairs) == false)
            {
                Logger.Error(CLASS_NAME, "ExecuteSearch", "UpdateSearchResultVisibility return false!");
                return;
            }

            // 旧検索結果をクリアする
            SearchResult.Clear();

            // 念のため昇順にソートしておく
            indexWordPairs.OrderBy(pair => pair.Key);

            SearchResultEntity[] searchResults = new SearchResultEntity[indexWordPairs.Count];
            foreach (KeyValuePair <int, string> kvp in indexWordPairs)
            {
                SearchResult.Add(
                    new SearchResultEntity()
                {
                    Index       = kvp.Key,
                    DisplayWord = kvp.Value
                }
                    );
            }

            // 検索結果にハイライトをかける
            _model.ApplyHighlightToSearchResult(SearchWord);
        }
Example #14
0
        private void autoSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
            var resultList = AllCities.Where(x => $"{x.City}({x.Prov})".StartsWith(sender.Text)).ToList();

            SearchResult.Clear();
            if (resultList.Count == 1) //回车能够直接添加,而不需要再次点击listView
            {
                var resultCity = resultList[0];
                ParentPage.AddCity(resultCity);
            }
            else
            {
                foreach (var item in resultList)
                {
                    SearchResult.Add(item);
                }
            }
        }
Example #15
0
        public async ValueTask LoadTags()
        {
            try
            {
                if (Interlocked.Increment(ref _loading) != 1)
                {
                    return;
                }
                if (_loaded)
                {
                    return;
                }
                var tags = await Model.ListTags(_query.QueryString, _query.TypeId, _query.Offset, _query.Limit);

                if (tags != null && tags.Count > 0)
                {
                    _query.Offset += _query.Limit;
                    foreach (var tag in tags.Where(it => SelectedTags.All(tag => tag.ObjectId != it.ObjectId)))
                    {
                        var displayTag = new DisplayTag(tag);
                        displayTag.ClickCommand = new AsyncCommand(async() =>
                        {
                            if (SelectedTags.All(it => it.ObjectId != displayTag.ObjectId))
                            {
                                displayTag.ClickCommand = new AsyncCommand(async() =>
                                {
                                    SelectedTags.Remove(displayTag);
                                });
                                SelectedTags.Add(displayTag);
                            }
                        });
                        SearchResult.Add(displayTag);
                    }
                }
                else
                {
                    _loaded = true;
                }
            }
            finally
            {
                Interlocked.Decrement(ref _loading);
            }
        }
Example #16
0
 public void FillStep2Results()
 {
     foreach (InformationOrder order in Processor.ProcessorArgs.Orders)
     {
         Step2Entrys.Add(new ProcessorStep2(order, true));
     }
     foreach (InformationOrder order in Processor.ProcessorArgs.DiscardedOrders)
     {
         Step2Entrys.Add(new ProcessorStep2(order, false));
     }
     foreach (InformationCopy copy in Processor.ProcessorArgs.CopyOrders)
     {
         Step2Entrys.Add(new ProcessorStep2(copy, true));
     }
     //
     foreach (InformationOrder order in Processor.ProcessorArgs.SearchResults)
     {
         SearchResult.Add(new SearchEntry(order));
     }
     OnPropertyChanged("VisibilityStep2Entrys");
     OnPropertyChanged("VisibilitySearchResult");
 }
        public async void LoadMoreAsync()
        {
            _busyIndicatorManager.Start();

            List <SearchInBookResultItemDataModel> items;

            try
            {
                items = (await _bookSearch.SearchNext(LOAD_COUNT)).Select(result => _searchController.ToDataModel(result, _searchQuery, BookId)).ToList();
            }
            finally
            {
                _busyIndicatorManager.Stop();
            }

            foreach (var item in items)
            {
                SearchResult.Add(item);
            }

            CanLoadMore = items.Count >= LOAD_COUNT;
        }
Example #18
0
        internal async void Search(string queryText)
        {
            var req = new SearchRequest {
                Keyword = queryText.Trim()
            };

            SearchResult.Clear();
            foreach (var item in DataSourceManager.Instance.Sources)
            {
                if (!item.IsAvailable)
                {
                    continue;
                }
                try
                {
                    foreach (var book in (await item.ExecuteAsync(req).ConfigureAwait(false)).Books)
                    {
                        SearchResult.Add(book, item);
                    }
                }
                catch { }
            }
        }
Example #19
0
        /// <summary>
        /// Function for the parsing thread
        /// First it checks if a parse process could be started
        /// Then it starts the process
        /// - Loading the page source code
        /// - Parsing the page source code
        /// - Signal of process finish
        /// </summary>
        private void ThreadFunction()
        {
            while (true)
            {
                if (ThreadRunning)
                {
                    try
                    {
                        lock (thisLockThread)
                        {
                            // Set state
                            State            = WebParserState.Started;
                            LastErrorCode    = WebParserErrorCodes.Started;
                            LastExepction    = null;
                            LastRegexListKey = null;
                            Percent          = 0;
                            SetAndSendState(WebParserInfoState);

                            // Check if thread should be canceled
                            if (CancelThread)
                            {
                                LastErrorCode = WebParserErrorCodes.CancelThread;
                                LastExepction = null;
                                Percent       = 0;
                                SetAndSendState(WebParserInfoState);
                            }

                            if (ThreadRunning)
                            {
                                // Reset search result
                                if (SearchResult != null && SearchResult.Count > 0)
                                {
                                    SearchResult.Clear();
                                }

                                // Check if thread should be canceled
                                if (CancelThread)
                                {
                                    LastErrorCode = WebParserErrorCodes.CancelThread;
                                    LastExepction = null;
                                    Percent       = 0;
                                    SetAndSendState(WebParserInfoState);
                                }

                                if (ThreadRunning)
                                {
                                    // Set state to loading
                                    State         = WebParserState.Loading;
                                    LastErrorCode = WebParserErrorCodes.ContentLoadStarted;
                                    LastExepction = null;
                                    Percent       = 5;
                                    SetAndSendState(WebParserInfoState);

                                    // Create web client with the given or default user agent identifier.
                                    using (var client = new WebClient())
                                    {
                                        // Browser identifier (e.g. FireFox 36)
                                        client.Headers["User-Agent"] = UserAgentIdentifier;
                                        // Download content as raw data
#if _DEBUG_THREADFUNCTION
                                        Console.WriteLine(@"WebSide: {0}", _webSite);
#endif
                                        DownloadComplete = false;
                                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                        client.DownloadDataCompleted   += new DownloadDataCompletedEventHandler(client_DownloadDataWebSiteCompleted);
                                        client.DownloadDataAsync(new Uri(_webSite));
                                        while (!DownloadComplete)
                                        {
                                            // Check if thread should be canceled
                                            if (CancelThread)
                                            {
                                                LastErrorCode = WebParserErrorCodes.CancelThread;
                                                LastExepction = null;
                                                Percent       = 0;
                                                SetAndSendState(WebParserInfoState);
                                                DownloadComplete = false;
                                                client.CancelAsync();
                                                break;
                                            }
                                            Thread.Sleep(10);
                                        }
                                        client.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                        client.DownloadDataCompleted   -= new DownloadDataCompletedEventHandler(client_DownloadDataWebSiteCompleted);
                                    }

                                    // Check if the website content load was successful and call event
                                    if (WebSiteContent == @"")
                                    {
                                        LastErrorCode = WebParserErrorCodes.NoWebContentLoaded;
                                        LastExepction = null;
                                        Percent       = 0;
                                        SetAndSendState(WebParserInfoState);
                                    }
                                    else
                                    {
                                        LastErrorCode = WebParserErrorCodes.ContentLoadFinished;
                                        LastExepction = null;
                                        Percent       = 10;
                                        SetAndSendState(WebParserInfoState);
                                    }

                                    // Check if thread should be canceled
                                    if (CancelThread)
                                    {
                                        LastErrorCode = WebParserErrorCodes.CancelThread;
                                        LastExepction = null;
                                        Percent       = 0;
                                        SetAndSendState(WebParserInfoState);
                                    }

                                    if (ThreadRunning)
                                    {
                                        // Set state to parsing
                                        State         = WebParserState.Parsing;
                                        LastErrorCode = WebParserErrorCodes.SearchStarted;
                                        LastExepction = null;
                                        Percent       = 15;
                                        SetAndSendState(WebParserInfoState);

                                        int statusValueStep = (100 - 15) / RegexList.RegexListDictionary.Count;
                                        int statusValue     = 15;
#if _DEBUG_THREADFUNCTION
                                        Console.WriteLine("Parsing-Step: {0}", statusValueStep);
#endif

                                        // Loop through the dictionary and fill the result in the result list
                                        foreach (var regexExpression in RegexList.RegexListDictionary)
                                        {
                                            // Check if thread should be canceled
                                            if (CancelThread)
                                            {
                                                LastErrorCode = WebParserErrorCodes.CancelThread;
                                                LastExepction = null;
                                                Percent       = 0;
                                                SetAndSendState(WebParserInfoState);
                                                break;
                                            }

                                            // Set last regex key
                                            LastRegexListKey = regexExpression.Key;

#if _DEBUG_THREADFUNCTION
                                            Console.WriteLine("Key: {0}", regexExpression.Key);
#endif
                                            var regexElement = regexExpression.Value;

#if _DEBUG_THREADFUNCTION
                                            Console.WriteLine("RegexString: {0}", regexElement.RegexExpresion);
#endif
                                            // Build the reges options
                                            List <RegexOptions> tmpRegexOptionsList = regexElement.RegexOptions;
                                            RegexOptions        tmpRegexOptions     = RegexOptions.None;

                                            if (tmpRegexOptionsList != null && tmpRegexOptionsList.Count > 0)
                                            {
                                                foreach (var regexOption in tmpRegexOptionsList)
                                                {
                                                    tmpRegexOptions |= regexOption;
                                                }
                                            }

#if _DEBUG_THREADFUNCTION
                                            Console.WriteLine("RegexOptionSet: {0}", tmpRegexOptions);
#endif

                                            // Search for the value
                                            var             added           = false;
                                            MatchCollection matchCollection = Regex.Matches(WebSiteContent, regexExpression.Value.RegexExpresion, tmpRegexOptions);

                                            // Add the parsing result if a result has been found
                                            if (regexExpression.Value.RegexFoundPosition < matchCollection.Count)
                                            {
                                                if (SearchResult == null)
                                                {
                                                    SearchResult = new Dictionary <string, List <string> >();
                                                }
                                                List <string> listResults = new List <string>();

                                                // If a specific search result should be taken or all results (RegexFoundPosition == -1)
                                                if (regexExpression.Value.RegexFoundPosition >= 0)
                                                {
#if _DEBUG_THREADFUNCTION
                                                    Console.WriteLine(String.Format(@"Value: '{0}' = '{1}'", regexExpression.Key, matchCollection[regexExpression.Value.RegexFoundPosition].Groups[1].Value));
#endif
                                                    if (regexExpression.Value.DownloadResult)
                                                    {
                                                        // Create web client with the given or default user agent identifier.
                                                        using (var client = new WebClient())
                                                        {
                                                            // Browser identifier (e.g. FireFox 36)
                                                            client.Headers["User-Agent"] = UserAgentIdentifier;

                                                            // Download a string
#if _DEBUG_THREADFUNCTION
                                                            Console.WriteLine(@"DownLoad-WebSide: {0}", matchCollection[regexExpression.Value.RegexFoundPosition].Groups[1].Value);
#endif
                                                            DownloadComplete = false;
                                                            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                                            client.DownloadDataCompleted   += new DownloadDataCompletedEventHandler(client_DownloadDataContentCompleted);
                                                            client.DownloadDataAsync(new Uri(matchCollection[regexExpression.Value.RegexFoundPosition].Groups[1].Value));
                                                            while (!DownloadComplete)
                                                            {
                                                                // Check if thread should be canceled
                                                                if (CancelThread)
                                                                {
                                                                    LastErrorCode = WebParserErrorCodes.CancelThread;
                                                                    LastExepction = null;
                                                                    Percent       = 0;
                                                                    SetAndSendState(WebParserInfoState);
                                                                    DownloadComplete = false;
                                                                    client.CancelAsync();
                                                                }
                                                                Thread.Sleep(10);
                                                            }
                                                            client.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                                            client.DownloadDataCompleted   -= new DownloadDataCompletedEventHandler(client_DownloadDataContentCompleted);

                                                            listResults.Add(Convert.ToBase64String(DataContent));
                                                        }
                                                    }
                                                    else
                                                    {
                                                        for (int i = 1; i < matchCollection[regexExpression.Value.RegexFoundPosition].Groups.Count; i++)
                                                        {
                                                            // Check if thread should be canceled
                                                            if (CancelThread)
                                                            {
                                                                LastErrorCode = WebParserErrorCodes.CancelThread;
                                                                LastExepction = null;
                                                                Percent       = 0;
                                                                SetAndSendState(WebParserInfoState);
                                                            }

                                                            if (matchCollection[regexExpression.Value.RegexFoundPosition].Groups[i].Value != "")
                                                            {
                                                                listResults.Add(matchCollection[regexExpression.Value.RegexFoundPosition].Groups[i].Value);
                                                                i = matchCollection[regexExpression.Value.RegexFoundPosition].Groups.Count;
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    foreach (Match match in matchCollection)
                                                    {
                                                        // Check if thread should be canceled
                                                        if (CancelThread)
                                                        {
                                                            LastErrorCode = WebParserErrorCodes.CancelThread;
                                                            LastExepction = null;
                                                            Percent       = 0;
                                                            SetAndSendState(WebParserInfoState);
                                                        }
#if _DEBUG_THREADFUNCTION
                                                        Console.WriteLine(String.Format(@"Value: '{0}' = '{1}'", regexExpression.Key, match.Groups[1].Value));
#endif
                                                        if (regexExpression.Value.DownloadResult)
                                                        {
                                                            for (int i = 1; i < match.Groups.Count; i++)
                                                            {
                                                                // Check if thread should be canceled
                                                                if (CancelThread)
                                                                {
                                                                    LastErrorCode = WebParserErrorCodes.CancelThread;
                                                                    LastExepction = null;
                                                                    Percent       = 0;
                                                                    SetAndSendState(WebParserInfoState);
                                                                }

                                                                if (match.Groups[i].Value != "")
                                                                {
                                                                    // Create web client with the given or default user agent identifier.
                                                                    using (var client = new WebClient())
                                                                    {
                                                                        // Browser identifier (e.g. FireFox 36)
                                                                        client.Headers["User-Agent"] = UserAgentIdentifier;

                                                                        // Download a string
#if _DEBUG_THREADFUNCTION
                                                                        Console.WriteLine(@"DownLoad-WebSide: {0}", match.Groups[i].Value);
#endif
                                                                        DownloadComplete = false;
                                                                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                                                        client.DownloadDataCompleted   += new DownloadDataCompletedEventHandler(client_DownloadDataContentCompleted);
                                                                        client.DownloadDataAsync(new Uri(match.Groups[i].Value));
                                                                        while (!DownloadComplete)
                                                                        {
                                                                            // Check if thread should be canceled
                                                                            if (CancelThread)
                                                                            {
                                                                                LastErrorCode = WebParserErrorCodes.CancelThread;
                                                                                LastExepction = null;
                                                                                Percent       = 0;
                                                                                SetAndSendState(WebParserInfoState);
                                                                                DownloadComplete = false;
                                                                                client.CancelAsync();
                                                                            }
                                                                            Thread.Sleep(10);
                                                                        }
                                                                        client.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                                                        client.DownloadDataCompleted   -= new DownloadDataCompletedEventHandler(client_DownloadDataContentCompleted);
                                                                        listResults.Add(Convert.ToBase64String(DataContent));
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            for (int i = 1; i < match.Groups.Count; i++)
                                                            {
                                                                // Check if thread should be canceled
                                                                if (CancelThread)
                                                                {
                                                                    LastErrorCode = WebParserErrorCodes.CancelThread;
                                                                    LastExepction = null;
                                                                    Percent       = 0;
                                                                    SetAndSendState(WebParserInfoState);
                                                                }

                                                                if (match.Groups[i].Value != "")
                                                                {
                                                                    listResults.Add(match.Groups[i].Value);
//                                                                    i = match.Groups.Count;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                                SearchResult.Add(regexExpression.Key, listResults);
                                                added = true;
                                            }

                                            // Check if no result has been found or is not added and the result can not be empty
                                            if ((matchCollection.Count == 0 || added == false) && !regexElement.ResultEmpty)
                                            {
#if _DEBUG_THREADFUNCTION
                                                Console.WriteLine(String.Format(@"No MATCH found!"));
#endif
                                                LastErrorCode = WebParserErrorCodes.ParsingFailed;
                                                LastExepction = null;
                                                Percent       = 0;
                                                SetAndSendState(WebParserInfoState);
                                                break;
                                            }

                                            statusValue += statusValueStep;

                                            if (statusValue < 100)
                                            {
                                                LastErrorCode = WebParserErrorCodes.SearchRunning;
                                                LastExepction = null;
                                                Percent       = statusValue;
                                                SetAndSendState(WebParserInfoState);
                                            }
                                        }

                                        // Get time to press "Cancel"
                                        Thread.Sleep(100);

                                        if (ThreadRunning)
                                        {
                                            LastErrorCode = WebParserErrorCodes.SearchFinished;
                                            LastExepction = null;
                                            Percent       = 100;
                                            SetAndSendState(WebParserInfoState);
                                        }

                                        // Check if thread should be canceled
                                        if (CancelThread)
                                        {
                                            LastErrorCode = WebParserErrorCodes.CancelThread;
                                            LastExepction = null;
                                            Percent       = 0;
                                            SetAndSendState(WebParserInfoState);
                                        }

                                        // Get time to press "Cancel"
                                        Thread.Sleep(100);

                                        if (ThreadRunning)
                                        {
                                            // Signal that the thread has finished
                                            LastErrorCode = WebParserErrorCodes.Finished;
                                            LastExepction = null;
                                            Percent       = 100;
                                            SetAndSendState(WebParserInfoState);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (WebException webEx)
                    {
                        // Set state
                        State         = WebParserState.Idle;
                        LastErrorCode = WebParserErrorCodes.WebExceptionOccured;
                        LastExepction = webEx;
                        Percent       = 0;
                        SetAndSendState(WebParserInfoState);
                    }
                    catch (Exception ex)
                    {
                        // Set state
                        State         = WebParserState.Idle;
                        LastErrorCode = WebParserErrorCodes.ExceptionOccured;
                        LastExepction = ex;
                        Percent       = 0;
                        SetAndSendState(WebParserInfoState);
                    }
                }

                Thread.Sleep(10);
            }
        }
Example #20
0
        public SearchResult Search(string searchString)
        {
            var words = searchString.ToLower().Split(' ').ToList();

            foreach (string s in words)
                s.Trim();

            var result = new SearchResult(this);
            var resultSongs = result.GetSongs();

            // 4 first dictionaries contain title, artist, album and genre fields
            for (int i = 0; i < 4; i++)
            {
                var dictionary = sortDictionaries[i];

                var keysToAdd = AndSearch(dictionary, words);

                foreach (string keyToAdd in keysToAdd)
                {
                    List<Song> currentList = dictionary[keyToAdd];
                    foreach (Song s in currentList)
                        if (!resultSongs.Contains(s))
                            result.Add(s);
                }
            }

            return result;
        }
Example #21
0
        public void Search(object sender, RoutedEventArgs e)
        {
            try
            {
                CommonViewModel.RecentSearchWord = this.SearchWord;

                List <Memo> result = new List <Memo>();

                if (this.IsSearchConditionTaskName)
                {
                    result = MemoModel.SearchTaskName(SearchWord);
                    CommonViewModel.IsRecentSearchConditionTaskName    = true;
                    CommonViewModel.IsRecentSearchConditionMemoContent = false;
                }
                else
                {
                    result = MemoModel.SearchMemoContent(SearchWord);
                    CommonViewModel.IsRecentSearchConditionTaskName    = false;
                    CommonViewModel.IsRecentSearchConditionMemoContent = true;
                }

                SearchResult.Clear();

                result.ForEach(memo =>
                {
                    string targetContent = string.Empty;
                    string contentHtml   = string.Empty;
                    int index            = 0;

                    if (this.IsSearchConditionTaskName)
                    {
                        targetContent = memo.EachTask.Content.Replace("\r", "<br>");
                    }
                    else
                    {
                        targetContent = memo.Content.Replace("\r", "<br>");
                    }

                    while (true)
                    {
                        index = targetContent.IndexOf(this.SearchWord, StringComparison.OrdinalIgnoreCase);
                        if (index < 0)
                        {
                            contentHtml += targetContent;
                            break;
                        }
                        else if (index > 0)
                        {
                            contentHtml = targetContent.Substring(0, index);
                        }

                        contentHtml  += $"<strong>{targetContent.Substring(index, this.SearchWord.Length)}</strong>";
                        targetContent = targetContent.Substring(index + this.SearchWord.Length);
                    }
                    contentHtml = $"<span>{contentHtml}</span>";
                    EachSearchResult eachSearchResult = new EachSearchResult();

                    if (this.IsSearchConditionTaskName)
                    {
                        eachSearchResult.TaskName    = contentHtml;
                        eachSearchResult.Date        = $"[{memo.EachTask.PlanDate.Date.ToString().Substring(0, 10)}({memo.EachTask.PlanDate.DayOfWeek.ToString().Substring(0, 3)})]";
                        eachSearchResult.ContentHtml = memo.Content;
                    }
                    else
                    {
                        eachSearchResult.TaskName    = memo.EachTask.Content;
                        eachSearchResult.Date        = $"[{memo.EachTask.PlanDate.Date.ToString().Substring(0, 10)}({memo.EachTask.PlanDate.DayOfWeek.ToString().Substring(0, 3)})]";
                        eachSearchResult.ContentHtml = contentHtml;
                    }
                    SearchResult.Add(eachSearchResult);
                });

                CommonViewModel.RecentSearchResult = new ObservableCollection <EachSearchResult>(SearchResult);
            }
            catch
            {
                CommonViewModel.NotifySystemMessage(GetLangMessage.GetMessage("Exception"));
            }
        }
        protected override SearchResult DoExecute(SearchParams p)
        {
            p.skip = LucQuery.Skip;

            var maxtop = p.numDocs - p.skip;

            if (maxtop < 1)
            {
                return(SearchResult.Empty);
            }

            //TODO: check r and r1 for null below (see hints)
            SearchResult r = null;
            SearchResult r1;

            var howManyList = new List <int>(Configuration.Lucene29.DefaultTopAndGrowth);

            if (howManyList[howManyList.Count - 1] == 0)
            {
                howManyList[howManyList.Count - 1] = int.MaxValue;
            }

            if (p.top < int.MaxValue)
            {
                var howMany = p.top;
                if ((long)howMany > maxtop)
                {
                    howMany = maxtop - p.skip;
                }
                while (howManyList.Count > 0)
                {
                    if (howMany < howManyList[0])
                    {
                        break;
                    }
                    howManyList.RemoveAt(0);
                }
                howManyList.Insert(0, howMany);
            }

            var top0 = p.top;

            for (var i = 0; i < howManyList.Count; i++)
            {
                var defaultTop = howManyList[i];
                if (defaultTop == 0)
                {
                    defaultTop = p.numDocs;
                }

                p.howMany    = defaultTop;
                p.useHowMany = i < howManyList.Count - 1;
                var maxSize = i == 0 ? p.numDocs : r.totalCount;
                p.collectorSize = Math.Min(defaultTop, maxSize - p.skip) + p.skip;

                r1 = Search(p);

                if (i == 0)
                {
                    r = r1;
                }
                else
                {
                    r.Add(r1);
                }
                p.skip += r.nextIndex;
                p.top   = top0 - r.result.Count;

                if (r.result.Count == 0 || r.result.Count >= top0 || r.result.Count >= r.totalCount)
                {
                    break;
                }
            }
            return(r);
        }