Example #1
0
        public List <List <DataCollection> > Read(List <string> fields, SearchCollection searching)
        {
            List <SearchCollection> search = new List <SearchCollection>();

            search.Add(searching);

            List <List <DataCollection> > res = base.Read(fields, search);

            if (res.Count == 0)
            {
                this.ERROR = BD.ERROR;
                List <List <DataCollection> > err = new List <List <DataCollection> >();
                return(err);
            }

            foreach (List <DataCollection> lista in res)
            {
                Console.WriteLine("-----------------");
                foreach (DataCollection objeto in lista)
                {
                    Console.WriteLine(objeto.ToString());
                    Console.WriteLine("*****************");
                }
            }
            return(res);
        }
Example #2
0
 /// <summary>
 /// Convert a <see cref="SearchCollection"/> into a <see cref="Collection"/>.
 /// </summary>
 /// <param name="collection">The collection to convert.</param>
 /// <param name="provider">The provider representing TheMovieDb.</param>
 /// <returns>The converted collection as a <see cref="Collection"/>.</returns>
 public static Collection ToCollection(this SearchCollection collection, Provider provider)
 {
     return(new Collection
     {
         Slug = Utility.ToSlug(collection.Name),
         Name = collection.Name,
         Images = new Dictionary <int, string>
         {
             [Images.Poster] = collection.PosterPath != null
                                         ? $"https://image.tmdb.org/t/p/original{collection.PosterPath}"
                                         : null,
             [Images.Thumbnail] = collection.BackdropPath != null
                                         ? $"https://image.tmdb.org/t/p/original{collection.BackdropPath}"
                                         : null
         },
         ExternalIDs = new[]
         {
             new MetadataID
             {
                 Provider = provider,
                 Link = $"https://www.themoviedb.org/collection/{collection.Id}",
                 DataID = collection.Id.ToString()
             }
         }
     });
 }
Example #3
0
        private void AppendingResults(List <NpgsqlCommand> searchs)
        {
            var list = new List <Movie>();

            foreach (var e in searchs)
            {
                var reader = e.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        var m = new Movie(reader.GetValue(0).ToString(), Convert.ToInt32(reader.GetValue(1)));
                        if (list.FirstOrDefault(x => x.Name == m.Name && x.Year == m.Year) == null)
                        {
                            list.Add(m);
                        }
                    }
                }
                reader.Close();
            }
            if (list.Count() > 0)
            {
                list.ForEach(x => { if (SearchCollection.Count == 10)
                                    {
                                        return;
                                    }
                                    SearchCollection.Add(x); });
            }
            else
            {
                MessageBox.Show("There wasn't any strings");
            }
        }
Example #4
0
        async Task Search(string text)
        {
            SearchTerm = text;
            Skip       = 0;
            try
            {
                SearchCollection.Clear();
                // update current search options
                SearchStartDate = StartDate;
                SearchEndDate   = EndDate;
                SearchCategory  = SelectedCategory;
                // execute searchTask with the specified search keywords for the first time
                Debug.WriteLine(SearchTerm);
                IQueryResultEnumerable <News> items = await NewsManager.DefaultManager.GetNewsAsync((news) => news.Title.ToLower().Contains(SearchTerm.ToLower()) && news.NewsDate >= SearchStartDate && news.NewsDate <= SearchEndDate && (news.Type == SearchCategory || SearchCategory == "Tất cả"), Skip, 5);

                if (items != null && items.TotalCount > 0)
                {
                    HeaderString = "- " + items.TotalCount + " kết quả -";
                    foreach (var item in items)
                    {
                        SearchCollection.Add(item);
                    }
                    Skip += 5;
                }
                else
                {
                    HeaderString = "- Không có kết quả -";
                }
            } catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
Example #5
0
        public async Task CreateMovieCollectionView(SearchCollection collection)
        {
            if (collection == null)
            {
                return;
            }

            string documentType = "MovieCollectionView";
            string documentId   = String.Format("{0}:{1}", documentType, collection.Id);

            if (ShowDocument(String.Empty, documentId))
            {
                return;
            }

            CancellationTokenSource tokenSource = this.GetAsyncCommand(x => x.CreateMovieCollectionView(collection)).CancellationTokenSource;
            List <MovieContainer>   movies      = await RunAsync(() => App.Repository.GetCollectionAsync(collection.Id, Settings.Default.Language, tokenSource.Token));

            DocumentViewModel viewModel = ViewModelSource.Create <DocumentViewModel>();

            viewModel.Header                = () => collection.Name;
            viewModel.DocumentId            = documentId;
            viewModel.DocumentType          = documentType;
            viewModel.Parameter             = movies;
            viewModel.Parameters.Collection = collection;

            AddToDocuments(viewModel);
        }
        public SearchCollection SelectByCustomer(string customer)
        {
            SearchCollection searchCollection = new SearchCollection();
            IDataReader      Reader           = DataAccess.SelectByCustomer(customer);

            while (Reader.Read())
            {
                SearchInfo searchInfo = new SearchInfo();

                searchInfo.BookingID       = Convert.ToString(Reader["BookingID"]);
                searchInfo.BookingNo       = Convert.ToString(Reader["BookingNo"]);
                searchInfo.BookingDetailID = Convert.ToString(Reader["BookingDetailID"]);
                searchInfo.BookingDate     = Convert.ToDateTime(Reader["BookingDate"]);
                searchInfo.Quantity        = Convert.ToInt32(Reader["Quantity"]);
                searchInfo.CustomerID      = Convert.ToString(Reader["CustomerID"]);
                searchInfo.Gender          = Convert.ToString(Reader["Gender"]);
                searchInfo.CustomerName    = Convert.ToString(Reader["CustomerName"]);
                searchInfo.NRCNo           = Convert.ToString(Reader["NRCNo"]);
                searchInfo.PhoneNo         = Convert.ToString(Reader["PhoneNo"]);
                searchInfo.TripID          = Convert.ToString(Reader["TripID"]);
                searchInfo.SeatNo          = Convert.ToString(Reader["SeatNo"]);
                searchInfo.RouteID         = Convert.ToString(Reader["RouteID"]);
                searchInfo.RouteName       = Convert.ToString(Reader["RouteName"]);
                searchInfo.Date            = Convert.ToDateTime(Reader["Date"]);
                searchInfo.TimeID          = Convert.ToString(Reader["TimeID"]);
                searchInfo.Time            = Convert.ToString(Reader["Time"]);
                searchInfo.BusID           = Convert.ToString(Reader["BusID"]);
                searchInfo.BusNo           = Convert.ToString(Reader["BusNo"]);
                searchInfo.Price           = Convert.ToDecimal(Reader["Price"]);

                searchCollection.Add(searchInfo);
            }
            Reader.Close();
            return(searchCollection);
        }
        public SupergroupMembersViewModelBase(IProtoService protoService, ICacheService cacheService, ISettingsService settingsService, IEventAggregator aggregator, SupergroupMembersFilter filter, Func <string, SupergroupMembersFilter> search)
            : base(protoService, cacheService, settingsService, aggregator)
        {
            _filter = filter;
            _find   = search;

            Members = new SearchCollection <ChatMember, ChatMemberCollection>(SetItems, new ChatMemberHandler());
        }
Example #8
0
        public async Task TestSearchCollectionAsync()
        {
            await TestHelpers.SearchPagesAsync(i => TMDbClient.SearchCollectionAsync("007", i));

            SearchContainer <SearchCollection> result = await TMDbClient.SearchCollectionAsync("James Bond");

            SearchCollection item = result.Results.Single(s => s.Id == 645);

            await Verify(item);

            TestImagesHelpers.TestImagePaths(new[] { item.BackdropPath, item.PosterPath });
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            SearchCollection searchList = new SearchCollection();
            foreach (var s in controllerContext.HttpContext.Request.QueryString.AllKeys)
            {
                if (s.StartsWith("search_"))
                {
                    searchList.Add(s.Substring(7), controllerContext.HttpContext.Request.QueryString[s]);
                }
            }

            return searchList;
        }
Example #10
0
        public void TestSearchCollection()
        {
            TestHelpers.SearchPages(i => Config.Client.SearchCollectionAsync("007", i).Result);

            SearchContainer <SearchCollection> result = Config.Client.SearchCollectionAsync("James Bond").Result;

            Assert.True(result.Results.Any());
            SearchCollection item = result.Results.SingleOrDefault(s => s.Id == 645);

            Assert.NotNull(item);
            Assert.Equal(645, item.Id);
            Assert.Equal("James Bond Collection", item.Name);
            Assert.True(TestImagesHelpers.TestImagePath(item.BackdropPath), "item.BackdropPath was not a valid image path, was: " + item.BackdropPath);
            Assert.True(TestImagesHelpers.TestImagePath(item.PosterPath), "item.PosterPath was not a valid image path, was: " + item.PosterPath);
        }
Example #11
0
        public DownloadsViewModel(IProtoService protoService, ICacheService cacheService, ISettingsService settingsService, IStorageService storageService, IEventAggregator aggregator)
            : base(protoService, cacheService, settingsService, aggregator)
        {
            _storageService = storageService;

            //Items = new ItemCollection(this, string.Empty);
            Items = new SearchCollection <FileDownloadViewModel, ItemCollection>(SetSearch, new FileDownloadDiffHandler());
            Items.SetQuery(string.Empty);

            RemoveAllCommand       = new RelayCommand(RemoveAll);
            ToggleAllPausedCommand = new RelayCommand(ToggleAllPaused);
            SettingsCommand        = new RelayCommand(Settings);

            RemoveFileDownloadCommand = new RelayCommand <FileDownloadViewModel>(RemoveFileDownload);
            ViewFileDownloadCommand   = new RelayCommand <FileDownloadViewModel>(ViewFileDownload);
            ShowFileDownloadCommand   = new RelayCommand <FileDownloadViewModel>(ShowFileDownload);
        }
Example #12
0
        public async void LoadMore()
        {
            Skip += 5;
            IQueryResultEnumerable <News> items = await NewsManager.DefaultManager.GetNewsAsync((news) => news.Title.ToLower().Contains(SearchTerm.ToLower()) && news.NewsDate >= SearchStartDate && news.NewsDate <= SearchEndDate && (news.Type == SearchCategory || SearchCategory == "Tất cả"), Skip, 5);

            if (items != null)
            {
                foreach (var item in items)
                {
                    if (User.CurrentUser.Bookmarks.Contains(item))
                    {
                        item.IsBookmarkedByUser = true;
                    }
                    SearchCollection.Add(item);
                }
            }
        }
        private string CreateFilter(SearchCollection searchFields)
        {
            if (searchFields.Count == 0)
            {
                return string.Empty;
            }

            var filter = new StringBuilder();
            foreach (var fieldName in searchFields.AllKeys)
            {
                if (string.IsNullOrEmpty(searchFields[fieldName]))
                {
                    continue;
                }

                var fieldProp = typeof(Movie).GetProperty(fieldName);
                if (fieldProp != null)
                {
                    string fmt = null;
                    var attrs = fieldProp.GetCustomAttributes(typeof(SearchableAttribute), false);
                    if (attrs.Length == 1)
                    {
                        fmt = ((SearchableAttribute)attrs[0]).FilterFormat;
                    }
                    if (fmt == null)
                    {
                        if (fieldProp.PropertyType == typeof(string))
                        {
                            fmt = string.Format("{0} == \"{{0}}\"", fieldName);
                        }
                        else
                        {
                            fmt = string.Format("{0} == {{0}}", fieldName);
                        }
                    }

                    if (filter.Length > 0)
                    {
                        filter.Append(" and ");
                    }
                    filter.AppendFormat(fmt, searchFields[fieldName]);
                }
            }
            return filter.ToString();
        }
        public void SearchByCustomer(string customer)
        {
            SearchController searchController = new SearchController();
            SearchCollection searchCollection = searchController.SelectByCustomer(customer);

            if (searchCollection.Count != 0)
            {
                dgvBookingSearch.DataSource = searchCollection;
            }
            else
            {
                MessageBox.Show("Record not found in database", "Not Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
                searchCollection.Clear();
                this.dgvBookingSearch.DataSource = searchCollection;
                this.txtCustomer.Clear();
                this.txtCustomer.Focus();
            }
        }
 //
 // GET: /Movies/
 public ActionResult Index(SortingModel sorting, bool? search_user, SearchCollection search_fields)
 {
     string search_title = "";
     string filter = string.IsNullOrWhiteSpace(search_title) ? string.Empty : string.Format("Title.Contains(\"{0}\")", search_title);
     if (search_user.HasValue && search_user.Value && Request.IsAuthenticated)
     {
         if (!string.IsNullOrEmpty(filter))
         {
             filter += " and ";
         }
         filter += "CreatedBy == \"" + Membership.GetUser().UserName + "\"";
     }
     return View(_moviesService.GetAllMovies(
         search_fields,
         sorting.PageNumber,
         3, // TODO create constants class
         (string.IsNullOrEmpty(sorting.SortingCriteria) || sorting.SortingCriteria.Equals("none")) ? "ID" : sorting.SortingCriteria
         ));
 }
Example #16
0
        public void SearchResults()
        {
            if (string.IsNullOrEmpty(InputText))
            {
                MessageBox.Show("Text was null or empty. Check input string.");
                return;
            }
            SearchCollection.Clear();
            var words       = InputText.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var sqlCommands = new List <NpgsqlCommand>();

            while (words.Count > 0)
            {
                sqlCommands.Add(new NpgsqlCommand(SqlGeneration(words), connection));
                if (words.Count > 0)
                {
                    words.RemoveRange(words.Count - 1, 1);
                }
            }
            //sqlCommands.Add(new NpgsqlCommand(TitleGenerationSql(InputText),connection));
            sqlCommands.Add(new NpgsqlCommand(PartialGenerateSql(InputText), connection));
            AppendingResults(sqlCommands);
        }
Example #17
0
        public bool UserLogin(string email, string pw)
        {
            List <SearchCollection> temp = new List <SearchCollection>();
            SearchCollection        UsPw = new SearchCollection("email", CriteriaOperator.EQUALS, (object)email, true, LogicOperator.AND);

            temp.Add(UsPw);
            UsPw = new SearchCollection("password", CriteriaOperator.EQUALS, (object)pw, true, LogicOperator.NOTHING);
            temp.Add(UsPw);

            List <List <DataCollection> > res = base.Read(new List <string>()
            {
                "email"
            }, temp);

            if (res.Count == 0 || res.Count > 1)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
        public ChatSharedMediaViewModel(IProtoService protoService, ICacheService cacheService, ISettingsService settingsService, IStorageService storageService, IEventAggregator aggregator, IPlaybackService playbackService)
            : base(protoService, cacheService, settingsService, aggregator)
        {
            _playbackService = playbackService;
            _storageService  = storageService;

            Items = new ObservableCollection <ProfileItem>();

            Media      = new SearchCollection <MessageWithOwner, MediaCollection>(SetSearch, new SearchMessagesFilterPhotoAndVideo(), new MessageDiffHandler());
            Files      = new SearchCollection <MessageWithOwner, MediaCollection>(SetSearch, new SearchMessagesFilterDocument(), new MessageDiffHandler());
            Links      = new SearchCollection <MessageWithOwner, MediaCollection>(SetSearch, new SearchMessagesFilterUrl(), new MessageDiffHandler());
            Music      = new SearchCollection <MessageWithOwner, MediaCollection>(SetSearch, new SearchMessagesFilterAudio(), new MessageDiffHandler());
            Voice      = new SearchCollection <MessageWithOwner, MediaCollection>(SetSearch, new SearchMessagesFilterVoiceNote(), new MessageDiffHandler());
            Animations = new SearchCollection <MessageWithOwner, MediaCollection>(SetSearch, new SearchMessagesFilterAnimation(), new MessageDiffHandler());

            MessagesForwardCommand  = new RelayCommand(MessagesForwardExecute, MessagesForwardCanExecute);
            MessagesDeleteCommand   = new RelayCommand(MessagesDeleteExecute, MessagesDeleteCanExecute);
            MessagesUnselectCommand = new RelayCommand(MessagesUnselectExecute);
            MessageViewCommand      = new RelayCommand <MessageWithOwner>(MessageViewExecute);
            MessageSaveCommand      = new RelayCommand <MessageWithOwner>(MessageSaveExecute);
            MessageDeleteCommand    = new RelayCommand <MessageWithOwner>(MessageDeleteExecute);
            MessageForwardCommand   = new RelayCommand <MessageWithOwner>(MessageForwardExecute);
            MessageSelectCommand    = new RelayCommand <MessageWithOwner>(MessageSelectExecute);
        }
Example #19
0
        private void StartFuzzySearch(string searchStr, int manualIterator)
        {
            // start iterator
            if (manualIterator > 0)
            {
            }
            else
            {
                LocalIterationCount++;
                manualIterator = LocalIterationCount;
            }

            // setup fuzzystring options based on iteration
            List <FuzzyStringComparisonOptions> fuzzOptions = new List <FuzzyStringComparisonOptions>();
            FuzzyStringComparisonTolerance      tolerance;

            switch (manualIterator)
            {
            /* Iterations to widen the selection */
            // first auto iteration - strong matching using substring, subsequence and overlap coefficient
            case 1:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Strong;
                break;

            // second iteration - same as the first but with normal matching
            case 2:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Normal;
                break;

            // 3rd auto iteration - same as the first but with weak matching
            case 3:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Weak;
                break;

            /* Iterations to narrow down selection */
            // first manual iteration
            case 100:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Strong;
                break;

            default:
                // end and return
                return;
            }

            // Check whether the actual game name matches the search - if so return
            GDBPlatformGame gp = SystemCollection.Where(a => StripSymbols(a.GameTitle.ToLower()).Contains(searchStr)).FirstOrDefault();

            if (gp == null)
            {
            }
            else
            {
                SearchCollection = new List <GDBPlatformGame>();
                SearchCollection.Add(gp);
                WorkingSearchCollection = new List <GDBPlatformGame>();
                WorkingSearchCollection.Add(gp);
                return;
            }

            // iterate through each gamesdb game in the list
            foreach (GDBPlatformGame g in SystemCollection)
            {
                bool result = searchStr.ApproximatelyEquals(g.GameTitle, tolerance, fuzzOptions.ToArray());
                if (result == true)
                {
                    // match found - add to searchcollection
                    SearchCollection.Add(g);
                }
                else
                {
                    // match not found
                }
            }

            // check how many matches we have
            if (SearchCollection.Count == 1)
            {
                WorkingSearchCollection = new List <GDBPlatformGame>();
                WorkingSearchCollection.Add(SearchCollection.Single());
                return;
            }

            if (SearchCollection.Count > 1)
            {
                // add to working search collection
                WorkingSearchCollection.AddRange(SearchCollection.ToList());
                // clear SearchCollection
                //SearchCollection = new List<GDBPlatformGame>();

                // try the first word
                string[] arr     = BuildArray(searchStr);
                int      i       = 0;
                string   builder = "";
                while (i < arr.Length)
                {
                    if (i == 0)
                    {
                        builder += arr[i];
                    }
                    else
                    {
                        builder += " " + arr[i];
                    }
                    string b = StripSymbols(builder).ToLower();


                    var s = SystemCollection.Where(a => a.GameTitle.ToLower().Contains(b)).ToList();
                    if (s.Count == 1)
                    {
                        // one entry returned - this is the one to keep
                        WorkingSearchCollection = new List <GDBPlatformGame>();
                        //SearchCollection = new List<GDBPlatformGame>();
                        WorkingSearchCollection.Add(s.Single());
                        return;
                    }
                    if (s.Count > 1)
                    {
                        // still multiple entries returned - single match not found - continue
                        WorkingSearchCollection = new List <GDBPlatformGame>();
                        WorkingSearchCollection.AddRange(s);
                    }
                    if (s.Count == 0)
                    {
                        // no matches returned - this should never happen
                    }
                    i++;
                }

                // multiple matches found - run search again from the beginning but remove FIRST substring
                //StartFuzzySearch(searchStr, 100);
                return;

                /*
                 * string[] arr = BuildArray(searchStr);
                 * StartFuzzySearch(BuildSearchString(arr.Take(0).ToArray()), 1);
                 * // multiple matches found - run search again from the beginning but remove last substring
                 * StartFuzzySearch(BuildSearchString(arr.Take(arr.Count() - 1).ToArray()), 1);
                 */
            }
            if (SearchCollection.Count == 0)
            {
                // no matches found - run this method again with the next iterator (slightly weaker tolerance)
                StartFuzzySearch(searchStr, 0);
            }
        }
Example #20
0
        public TailViewModel([NotNull] ILogger logger,
                             [NotNull] ISchedulerProvider schedulerProvider,
                             [NotNull] IFileWatcher fileWatcher,
                             [NotNull] ISelectionMonitor selectionMonitor,
                             [NotNull] IClipboardHandler clipboardHandler,
                             [NotNull] ISearchInfoCollection searchInfoCollection,
                             [NotNull] IInlineViewerFactory inlineViewerFactory,
                             [NotNull] ISetting <GeneralOptions> generalOptions,
                             [NotNull] ISearchMetadataCollection searchMetadataCollection,
                             [NotNull] IStateBucketService stateBucketService,
                             [NotNull] SearchOptionsViewModel searchOptionsViewModel,
                             [NotNull] ITailViewStateRestorer restorer,
                             [NotNull] SearchHints searchHints,
                             [NotNull] ITailViewStateControllerFactory tailViewStateControllerFactory)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (schedulerProvider == null)
            {
                throw new ArgumentNullException(nameof(schedulerProvider));
            }
            if (fileWatcher == null)
            {
                throw new ArgumentNullException(nameof(fileWatcher));
            }
            if (selectionMonitor == null)
            {
                throw new ArgumentNullException(nameof(selectionMonitor));
            }
            if (clipboardHandler == null)
            {
                throw new ArgumentNullException(nameof(clipboardHandler));
            }
            if (searchInfoCollection == null)
            {
                throw new ArgumentNullException(nameof(searchInfoCollection));
            }
            if (inlineViewerFactory == null)
            {
                throw new ArgumentNullException(nameof(inlineViewerFactory));
            }
            if (generalOptions == null)
            {
                throw new ArgumentNullException(nameof(generalOptions));
            }
            if (searchMetadataCollection == null)
            {
                throw new ArgumentNullException(nameof(searchMetadataCollection));
            }
            if (stateBucketService == null)
            {
                throw new ArgumentNullException(nameof(stateBucketService));
            }
            if (searchOptionsViewModel == null)
            {
                throw new ArgumentNullException(nameof(searchOptionsViewModel));
            }
            if (searchHints == null)
            {
                throw new ArgumentNullException(nameof(searchHints));
            }

            Name                     = fileWatcher.FullName;
            SelectionMonitor         = selectionMonitor;
            SearchOptions            = searchOptionsViewModel;
            SearchHints              = searchHints;
            SearchCollection         = new SearchCollection(searchInfoCollection, schedulerProvider);
            CopyToClipboardCommand   = new Command(() => clipboardHandler.WriteToClipboard(selectionMonitor.GetSelectedText()));
            OpenFileCommand          = new Command(() => Process.Start(fileWatcher.FullName));
            OpenFolderCommand        = new Command(() => Process.Start(fileWatcher.Folder));
            SearchMetadataCollection = searchMetadataCollection;

            var horizonalScrollArgs = new ReplaySubject <TextScrollInfo>(1);

            HorizonalScrollChanged = args =>
            {
                horizonalScrollArgs.OnNext(args);
            };

            _tailViewStateControllerFactory = tailViewStateControllerFactory;

            //Move these 2 highlight fields to a service as all views require them
            UsingDarkTheme = generalOptions.Value
                             .ObserveOn(schedulerProvider.MainThread)
                             .Select(options => options.Theme == Theme.Dark)
                             .ForBinding();

            HighlightTail = generalOptions.Value
                            .ObserveOn(schedulerProvider.MainThread)
                            .Select(options => options.HighlightTail)
                            .ForBinding();

            //this deals with state when loading the system at start up and at shut-down
            _persister = new TailViewPersister(this, restorer);

            //An observable which acts as a scroll command
            var autoChanged = this.WhenValueChanged(vm => vm.AutoTail);
            var scroller    = _userScrollRequested.CombineLatest(autoChanged, (user, auto) =>
            {
                var mode = AutoTail ? ScrollReason.Tail : ScrollReason.User;
                return(new ScrollRequest(mode, user.PageSize, user.FirstIndex));
            })
                              .Do(x => logger.Info("Scrolling to {0}/{1}", x.FirstIndex, x.PageSize))
                              .DistinctUntilChanged();

            FileStatus = fileWatcher.Status.ForBinding();

            //command to add the current search to the tail collection
            var searchInvoker = SearchHints.SearchRequested.Subscribe(request =>
            {
                searchInfoCollection.Add(request.Text, request.UseRegEx);
            });

            //User feedback to show file size
            FileSizeText = fileWatcher.Latest.Select(fn => fn.Size)
                           .Select(size => size.FormatWithAbbreviation())
                           .DistinctUntilChanged()
                           .ForBinding();

            //tailer is the main object used to tail, scroll and filter in a file
            var lineScroller = new LineScroller(SearchCollection.Latest.ObserveOn(schedulerProvider.Background), scroller);

            MaximumChars = lineScroller.MaximumLines()
                           .ObserveOn(schedulerProvider.MainThread)
                           .ForBinding();

            //load lines into observable collection
            var lineProxyFactory = new LineProxyFactory(new TextFormatter(searchMetadataCollection), new LineMatches(searchMetadataCollection), horizonalScrollArgs.DistinctUntilChanged());

            var loader = lineScroller.Lines.Connect()
                         .LogChanges(logger, "Received")
                         .Transform(lineProxyFactory.Create, new ParallelisationOptions(ParallelType.Ordered, 3))
                         .LogChanges(logger, "Sorting")
                         .Sort(SortExpressionComparer <LineProxy> .Ascending(proxy => proxy))
                         .ObserveOn(schedulerProvider.MainThread)
                         .Bind(out _data, 100)
                         .LogChanges(logger, "Bound")
                         .DisposeMany()
                         .LogErrors(logger)
                         .Subscribe();

            //monitor matching lines and start index,
            Count       = searchInfoCollection.All.Select(latest => latest.Count).ForBinding();
            CountText   = searchInfoCollection.All.Select(latest => $"{latest.Count.ToString("##,###")} lines").ForBinding();
            LatestCount = SearchCollection.Latest.Select(latest => latest.Count).ForBinding();

            ////track first visible index
            var firstIndexMonitor = lineScroller.Lines.Connect()
                                    .Buffer(TimeSpan.FromMilliseconds(25)).FlattenBufferResult()
                                    .ToCollection()
                                    .Select(lines => lines.Count == 0 ? 0 : lines.Select(l => l.Index).Max() - lines.Count + 1)
                                    .ObserveOn(schedulerProvider.MainThread)
                                    .Subscribe(first =>
            {
                FirstIndex = first;
            });


            //Create objects required for inline viewing
            var isUserDefinedChanged = SearchCollection.WhenValueChanged(sc => sc.Selected)
                                       .Where(selected => selected != null)
                                       .Select(selected => selected.IsUserDefined)
                                       .DistinctUntilChanged()
                                       .Replay(1)
                                       .RefCount();

            var inlineViewerVisible = isUserDefinedChanged.CombineLatest(this.WhenValueChanged(vm => vm.ShowInline),
                                                                         (userDefined, showInline) => userDefined && showInline);

            CanViewInline       = isUserDefinedChanged.ForBinding();
            InlineViewerVisible = inlineViewerVisible.ForBinding();

            //return an empty line provider unless user is viewing inline - this saves needless trips to the file
            var inline = searchInfoCollection.All.CombineLatest(inlineViewerVisible, (index, ud) => ud ? index : new EmptyLineProvider());

            InlineViewer = inlineViewerFactory.Create(inline, this.WhenValueChanged(vm => vm.SelectedItem), searchMetadataCollection);

            _cleanUp = new CompositeDisposable(lineScroller,
                                               loader,
                                               firstIndexMonitor,
                                               FileStatus,
                                               Count,
                                               LatestCount,
                                               FileSizeText,
                                               CanViewInline,
                                               InlineViewer,
                                               InlineViewerVisible,
                                               SearchCollection,
                                               searchInfoCollection,
                                               HighlightTail,
                                               UsingDarkTheme,
                                               searchHints,
                                               searchMetadataCollection,
                                               SelectionMonitor,
                                               SearchOptions,
                                               searchInvoker,
                                               MaximumChars,
                                               _stateMonitor,
                                               horizonalScrollArgs.SetAsComplete(),
                                               _userScrollRequested.SetAsComplete());
        }
Example #21
0
 public MainWindowViewModel()
 {
     connection.Open();
     Find  = new Command(arg => SearchResults());
     Clear = new Command(arg => SearchCollection.Clear());
 }
 public IPagedList<Movie> GetAllMovies(SearchCollection filter, int pageIndex, int pageSize, string sortingCriteria)
 {
     return _moviesRepository.GetAll(CreateFilter(filter), pageIndex, pageSize, sortingCriteria);
 }
Example #23
0
        public SearchCollection <TItem> QueryItems <TItem, TSearchType>(IEnumerable <Guid> parentFolderIds, IEnumerable <ID> templateIds, IEnumerable <ID> baseTemplateIds, IEnumerable <Expression <Func <TSearchType, bool> > > filters, int?currentPage, int?pageSize)
            where TItem : ISitecoreItem
            where TSearchType : BaseSearchResultItem
        {
            Models.SearchCollection <TItem> results;

            using (IProviderSearchContext searchContext = ContentSearchManager.GetIndex(IndexName).CreateSearchContext(SearchSecurityOptions.EnableSecurityCheck))
            {
                // Reference: https://www.geekhive.com/buzz/post/2017/08/predicate-builder-advanced-search-queries/
                IQueryable <TSearchType> baseQuery = searchContext.GetQueryable <TSearchType>();
                Expression <Func <TSearchType, bool> > parentFolderPredicate = null;
                Expression <Func <TSearchType, bool> > templatePredicate     = null;
                Expression <Func <TSearchType, bool> > baseTemplatePredicate = null;

                parentFolderPredicate = ConvertParentFolderIdListToPredicate <TSearchType>(parentFolderIds);
                templatePredicate     = ConvertTemplateIdListToPredicate <TSearchType>(templateIds);
                baseTemplatePredicate = ConvertBaseTemplateIdListToPredicate <TSearchType>(baseTemplateIds);

                baseQuery = baseQuery.Where(i => i.Language == Context.Language.Name);

                if (parentFolderPredicate != null)
                {
                    baseQuery = baseQuery.Filter(parentFolderPredicate);
                }

                if (templatePredicate != null)
                {
                    baseQuery = baseQuery.Filter(templatePredicate);
                }

                if (baseTemplatePredicate != null)
                {
                    baseQuery = baseQuery.Filter(baseTemplatePredicate);
                }

                if (filters != null && filters.Any())
                {
                    foreach (Expression <Func <TSearchType, bool> > filter in filters)
                    {
                        baseQuery = baseQuery.Where(filter);
                    }
                }

                if (currentPage != null && pageSize != null)
                {
                    baseQuery = baseQuery.Page(currentPage.Value - 1, pageSize.Value);
                }

                SearchResults <TSearchType> searchResults = baseQuery.GetResults <TSearchType>();
                if (searchResults != null)
                {
                    results = new SearchCollection <TItem>
                    {
                        TotalRows = searchResults.TotalSearchResults
                    };

                    var scoreValue = searchResults.Select(i => i.Score);

                    results.AddRange(searchResults
                                     .Where(x => x.Document.GetItem() != null)
                                     .Select(x => SitecoreContext.CreateType <TItem>(x.Document.GetItem(), false, true, null)));

                    return(results);
                }

                return(null);
            }
        }
Example #24
0
        /// <summary>
        /// Fuzzy string matching (not currently used)
        /// </summary>
        /// <param name="searchStr"></param>
        /// <param name="manualIterator"></param>
        private void StartFuzzySearch(string searchStr, int manualIterator)
        {
            // start iterator
            if (manualIterator > 0)
            {
            }
            else
            {
                LocalIterationCount++;
                manualIterator = LocalIterationCount;
            }

            // setup fuzzystring options based on iteration
            List <FuzzyStringComparisonOptions> fuzzOptions = new List <FuzzyStringComparisonOptions>();
            FuzzyStringComparisonTolerance      tolerance;

            switch (manualIterator)
            {
            /* Iterations to widen the selection */
            // first auto iteration - strong matching using substring, subsequence and overlap coefficient
            case 1:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Normal;
                break;

            // second iteration - same as the first but with normal matching
            case 2:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Normal;
                break;

            // 3rd auto iteration - same as the first but with weak matching
            case 3:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Weak;
                break;

            /* Iterations to narrow down selection */
            // first manual iteration
            case 100:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Strong;
                break;

            default:
                // end and return
                return;
            }

            // iterate through each gamesdb game in the list
            foreach (ScraperMaster g in SystemCollection)
            {
                bool result = searchStr.ApproximatelyEquals(g.GDBTitle, tolerance, fuzzOptions.ToArray());
                if (result == true)
                {
                    // match found - add to searchcollection
                    SearchCollection.Add(g);
                }
                else
                {
                    // match not found
                }
            }

            if (SearchCollection.Count == 1)
            {
                WorkingSearchCollection = SearchCollection;
                return;
            }

            // Check whether the actual game name contains the actual search
            //GDBPlatformGame gp = SystemCollection.Where(a => StripSymbols(a.GameTitle.ToLower()).Contains(searchStr)).FirstOrDefault();
            List <ScraperMaster> gp = SystemCollection.Where(a => AddTrailingWhitespace(a.GDBTitle.ToLower()).Contains(AddTrailingWhitespace(SearchString))).ToList();

            if (gp == null)
            {
                // nothing found - proceed to other searches
            }
            else
            {
                if (gp.Count > 1)
                {
                    // multiples found - wipe out search collection and create a new one
                    SearchCollection = new List <ScraperMaster>();
                    SearchCollection.AddRange(gp);
                }
                else
                {
                    // only 1 entry found - return
                    SearchCollection = new List <ScraperMaster>();
                    SearchCollection.AddRange(gp);
                    WorkingSearchCollection = new List <ScraperMaster>();
                    WorkingSearchCollection.AddRange(gp);
                    return;
                }
            }


            // we should now have a pretty wide SearchCollection - count how many matched words
            Dictionary <ScraperMaster, int> totals = new Dictionary <ScraperMaster, int>();

            foreach (ScraperMaster g in SearchCollection)
            {
                int matchingWords = 0;
                // get total substrings in search string
                string[] arr          = BuildArray(searchStr);
                int      searchLength = arr.Length;

                // get total substrings in result string
                string[] rArr         = BuildArray(g.GDBTitle);
                int      resultLength = rArr.Length;

                // find matching words
                foreach (string s in arr)
                {
                    int i = 0;
                    while (i < resultLength)
                    {
                        if (StripSymbols(s) == StripSymbols(rArr[i]))
                        {
                            matchingWords++;
                            break;
                        }
                        i++;
                    }
                }
                // add to dictionary with count
                totals.Add(g, matchingWords);
            }

            // order dictionary
            totals.OrderByDescending(a => a.Value);
            // get max value
            var maxValueRecord = totals.OrderByDescending(v => v.Value).FirstOrDefault();
            int maxValue       = maxValueRecord.Value;
            // select all records that have the max value
            List <ScraperMaster> matches = (from a in totals
                                            where a.Value == maxValue
                                            select a.Key).ToList();

            if (matches.Count == 1)
            {
                // single match found
                WorkingSearchCollection = new List <ScraperMaster>();
                WorkingSearchCollection.AddRange(matches);
                return;
            }

            // run levenshetein fuzzy search on SearchCollection - 10 iterations
            int levCount = 0;

            while (levCount <= 10)
            {
                levCount++;
                double it = Convert.ToDouble(levCount) / 10;
                List <ScraperMaster> found = FuzzySearch.FSearch(searchStr, SearchCollection, it);
                //WorkingSearchCollection = new List<GDBPlatformGame>();

                if (found.Count == 1)
                {
                    // one entry returned
                    WorkingSearchCollection = new List <ScraperMaster>();
                    WorkingSearchCollection.AddRange(found);
                    return;
                }
                if (found.Count > 1)
                {
                    // multiple entries returned
                }

                if (found.Count == 0)
                {
                }

                //WorkingSearchCollection.AddRange(found);
                //return;
            }

            //return;

            // check how many matches we have
            if (SearchCollection.Count == 1)
            {
                WorkingSearchCollection = new List <ScraperMaster>();
                WorkingSearchCollection.Add(SearchCollection.Single());
                return;
            }

            if (SearchCollection.Count > 1)
            {
                // add to working search collection
                WorkingSearchCollection.AddRange(SearchCollection.ToList());
                // clear SearchCollection
                //SearchCollection = new List<GDBPlatformGame>();

                // try the first word
                string[] arr     = BuildArray(searchStr);
                int      i       = 0;
                string   builder = "";
                while (i < arr.Length)
                {
                    if (i == 0)
                    {
                        builder += arr[i];
                    }
                    else
                    {
                        builder += " " + arr[i];
                    }
                    string b = StripSymbols(builder).ToLower();


                    var s = SystemCollection.Where(a => a.GDBTitle.ToLower().Contains(b)).ToList();
                    if (s.Count == 1)
                    {
                        // one entry returned - this is the one to keep
                        WorkingSearchCollection = new List <ScraperMaster>();
                        //SearchCollection = new List<GDBPlatformGame>();
                        WorkingSearchCollection.Add(s.Single());
                        return;
                    }
                    if (s.Count > 1)
                    {
                        // still multiple entries returned - single match not found - continue
                        WorkingSearchCollection = new List <ScraperMaster>();
                        WorkingSearchCollection.AddRange(s);
                        //SearchCollection = new List<GDBPlatformGame>();
                    }
                    if (s.Count == 0)
                    {
                        // no matches returned - this should never happen
                    }
                    i++;
                }

                // multiple matches found - run search again from the beginning but remove FIRST substring
                //StartFuzzySearch(searchStr, 100);
                return;

                /*
                 * string[] arr = BuildArray(searchStr);
                 * StartFuzzySearch(BuildSearchString(arr.Take(0).ToArray()), 1);
                 * // multiple matches found - run search again from the beginning but remove last substring
                 * StartFuzzySearch(BuildSearchString(arr.Take(arr.Count() - 1).ToArray()), 1);
                 */
            }
            if (SearchCollection.Count == 0)
            {
                // no matches found - run this method again with the next iterator (slightly weaker tolerance)
                StartFuzzySearch(searchStr, 0);
            }
        }
Example #25
0
        public TailViewModel([NotNull] ILogger logger,
                             [NotNull] ISchedulerProvider schedulerProvider,
                             [NotNull] IFileWatcher fileWatcher,
                             [NotNull] ISelectionMonitor selectionMonitor,
                             [NotNull] IClipboardHandler clipboardHandler,
                             [NotNull] ISearchInfoCollection searchInfoCollection,
                             [NotNull] IInlineViewerFactory inlineViewerFactory,
                             [NotNull] GeneralOptionBindings generalOptionBindings,
                             [NotNull] ICombinedSearchMetadataCollection combinedSearchMetadataCollection,
                             [NotNull] IStateBucketService stateBucketService,
                             [NotNull] ITailViewStateRestorer restorer,
                             [NotNull] SearchHints searchHints,
                             [NotNull] ITailViewStateControllerFactory tailViewStateControllerFactory,
                             [NotNull] IThemeProvider themeProvider,
                             [NotNull] SearchCollection searchCollection,
                             [NotNull] ITextFormatter textFormatter,
                             [NotNull] ILineMatches lineMatches,
                             [NotNull] IObjectProvider objectProvider,
                             [NotNull] IDialogCoordinator dialogCoordinator)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (schedulerProvider == null)
            {
                throw new ArgumentNullException(nameof(schedulerProvider));
            }
            if (fileWatcher == null)
            {
                throw new ArgumentNullException(nameof(fileWatcher));
            }
            if (clipboardHandler == null)
            {
                throw new ArgumentNullException(nameof(clipboardHandler));
            }
            if (searchInfoCollection == null)
            {
                throw new ArgumentNullException(nameof(searchInfoCollection));
            }
            if (inlineViewerFactory == null)
            {
                throw new ArgumentNullException(nameof(inlineViewerFactory));
            }
            if (stateBucketService == null)
            {
                throw new ArgumentNullException(nameof(stateBucketService));
            }
            if (themeProvider == null)
            {
                throw new ArgumentNullException(nameof(themeProvider));
            }
            if (textFormatter == null)
            {
                throw new ArgumentNullException(nameof(textFormatter));
            }
            if (lineMatches == null)
            {
                throw new ArgumentNullException(nameof(lineMatches));
            }
            if (objectProvider == null)
            {
                throw new ArgumentNullException(nameof(objectProvider));
            }
            if (dialogCoordinator == null)
            {
                throw new ArgumentNullException(nameof(dialogCoordinator));
            }
            if (combinedSearchMetadataCollection == null)
            {
                throw new ArgumentNullException(nameof(combinedSearchMetadataCollection));
            }

            Name                  = fileWatcher.FullName;
            SelectionMonitor      = selectionMonitor ?? throw new ArgumentNullException(nameof(selectionMonitor));
            GeneralOptionBindings = generalOptionBindings;
            SearchHints           = searchHints ?? throw new ArgumentNullException(nameof(searchHints));

            CopyToClipboardCommand     = new Command(() => clipboardHandler.WriteToClipboard(selectionMonitor.GetSelectedText()));
            OpenFileCommand            = new Command(() => Process.Start(fileWatcher.FullName));
            OpenFolderCommand          = new Command(() => Process.Start(fileWatcher.Folder));
            CopyPathToClipboardCommand = new Command(() => clipboardHandler.WriteToClipboard(fileWatcher.FullName));
            UnClearCommand             = new Command(fileWatcher.Reset);
            ClearCommand             = new Command(fileWatcher.Clear);
            KeyAutoTail              = new Command(() => { AutoTail = true; });
            OpenSearchOptionsCommand = new Command(async() =>
            {
                await Task.Run(() =>
                {
                    var content = objectProvider.Get <SearchOptionsViewModel>(new Argument <ICombinedSearchMetadataCollection>(combinedSearchMetadataCollection));
                    dialogCoordinator.Show(this, content, x => content.Dispose());
                });
            });

            var closeOnDeselect = this.WhenValueChanged(vm => vm.IsSelected, false)
                                  .Where(selected => !selected)
                                  .Subscribe(_ => dialogCoordinator.Close());

            SearchCollection         = searchCollection ?? throw new ArgumentNullException(nameof(searchCollection));
            SearchMetadataCollection = combinedSearchMetadataCollection.Local;

            var horizonalScrollArgs = new ReplaySubject <TextScrollInfo>(1);

            HorizonalScrollChanged = args => horizonalScrollArgs.OnNext(args);

            _tailViewStateControllerFactory = tailViewStateControllerFactory;

            //this deals with state when loading the system at start up and at shut-down
            _persister = new TailViewPersister(this, restorer);

            FileStatus = fileWatcher.Status.ForBinding();

            //command to add the current search to the tail collection
            var searchInvoker = SearchHints.SearchRequested.Subscribe(request => searchInfoCollection.Add(request.Text, request.UseRegEx));

            //An observable which acts as a scroll command
            var autoChanged = this.WhenValueChanged(vm => vm.AutoTail);
            var scroller    = _userScrollRequested.CombineLatest(autoChanged, (user, auto) =>
            {
                var mode = AutoTail ? ScrollReason.Tail : ScrollReason.User;
                return(new ScrollRequest(mode, user.PageSize, user.FirstIndex));
            })
                              .Do(x => logger.Info("Scrolling to {0}/{1}", x.FirstIndex, x.PageSize))
                              .DistinctUntilChanged();

            //User feedback to show file size
            FileSizeText = fileWatcher.Latest.Select(fn => fn.Size)
                           .Select(size => size.FormatWithAbbreviation())
                           .DistinctUntilChanged()
                           .ForBinding();


            //tailer is the main object used to tail, scroll and filter in a file
            var selectedProvider = SearchCollection.Latest.ObserveOn(schedulerProvider.Background);

            var lineScroller = new LineScroller(selectedProvider, scroller);

            MaximumChars = lineScroller.MaximumLines()
                           .ObserveOn(schedulerProvider.MainThread)
                           .ForBinding();

            var lineProxyFactory = new LineProxyFactory(textFormatter, lineMatches, horizonalScrollArgs.DistinctUntilChanged(), themeProvider);

            var loader = lineScroller.Lines.Connect()
                         .LogChanges(logger, "Received")
                         .Transform(lineProxyFactory.Create)
                         .LogChanges(logger, "Sorting")
                         .Sort(SortExpressionComparer <LineProxy> .Ascending(proxy => proxy))
                         .ObserveOn(schedulerProvider.MainThread)
                         .Bind(out _data, 100)
                         .LogChanges(logger, "Bound")
                         .DisposeMany()
                         .LogErrors(logger)
                         .Subscribe();

            //monitor matching lines and start index,
            Count       = searchInfoCollection.All.Select(latest => latest.Count).ForBinding();
            CountText   = searchInfoCollection.All.Select(latest => $"{latest.Count:##,###} lines").ForBinding();
            LatestCount = SearchCollection.Latest.Select(latest => latest.Count).ForBinding();

            ////track first visible index
            var firstIndexMonitor = lineScroller.Lines.Connect()
                                    .Buffer(TimeSpan.FromMilliseconds(25)).FlattenBufferResult()
                                    .ToCollection()
                                    .Select(lines => lines.Count == 0 ? 0 : lines.Select(l => l.Index).Max() - lines.Count + 1)
                                    .ObserveOn(schedulerProvider.MainThread)
                                    .Subscribe(first =>
            {
                FirstIndex = first;
            });

            //Create objects required for inline viewing
            var isUserDefinedChanged = SearchCollection.WhenValueChanged(sc => sc.Selected)
                                       .Where(selected => selected != null)
                                       .Select(selected => selected.IsUserDefined)
                                       .DistinctUntilChanged()
                                       .Replay(1)
                                       .RefCount();

            var showInline          = this.WhenValueChanged(vm => vm.ShowInline);
            var inlineViewerVisible = isUserDefinedChanged.CombineLatest(showInline, (userDefined, showInlne) => userDefined && showInlne);

            CanViewInline       = isUserDefinedChanged.ForBinding();
            InlineViewerVisible = inlineViewerVisible.ForBinding();

            //return an empty line provider unless user is viewing inline - this saves needless trips to the file
            var inline = searchInfoCollection.All.CombineLatest(inlineViewerVisible, (index, ud) => ud ? index : EmptyLineProvider.Instance);

            InlineViewer = inlineViewerFactory.Create(combinedSearchMetadataCollection, inline, this.WhenValueChanged(vm => vm.SelectedItem));

            _cleanUp = new CompositeDisposable(lineScroller,
                                               loader,
                                               firstIndexMonitor,
                                               FileStatus,
                                               Count,
                                               CountText,
                                               LatestCount,
                                               FileSizeText,
                                               CanViewInline,
                                               InlineViewer,
                                               InlineViewerVisible,
                                               SearchCollection,
                                               searchInfoCollection,
                                               searchHints,
                                               SelectionMonitor,
                                               closeOnDeselect,
                                               Disposable.Create(dialogCoordinator.Close),
                                               searchInvoker,
                                               MaximumChars,
                                               _stateMonitor,
                                               combinedSearchMetadataCollection,
                                               horizonalScrollArgs.SetAsComplete(),
                                               _userScrollRequested.SetAsComplete());
        }
 public IPagedList<Movie> GetAllMovies(SearchCollection filter, int pageIndex, int pageSize, string sortingCriteria)
 {
     throw new NotImplementedException();
 }
Example #27
0
        public TailViewModel([NotNull] ILogger logger,
                             [NotNull] ISchedulerProvider schedulerProvider,
                             [NotNull] IEnumerable <IFileWatcher> fileWatcher,
                             [NotNull] ISelectionMonitor selectionMonitor,
                             [NotNull] IClipboardHandler clipboardHandler,
                             [NotNull] ISearchInfoCollection searchInfoCollection,
                             [NotNull] IInlineViewerFactory inlineViewerFactory,
                             [NotNull] ISetting <GeneralOptions> generalOptions,
                             [NotNull] ISearchMetadataCollection searchMetadataCollection,
                             [NotNull] SearchOptionsViewModel searchOptionsViewModel,
                             [NotNull] SearchHints searchHints)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (schedulerProvider == null)
            {
                throw new ArgumentNullException(nameof(schedulerProvider));
            }
            if (fileWatcher == null)
            {
                throw new ArgumentNullException(nameof(fileWatcher));
            }
            if (selectionMonitor == null)
            {
                throw new ArgumentNullException(nameof(selectionMonitor));
            }
            if (clipboardHandler == null)
            {
                throw new ArgumentNullException(nameof(clipboardHandler));
            }
            if (searchInfoCollection == null)
            {
                throw new ArgumentNullException(nameof(searchInfoCollection));
            }
            if (inlineViewerFactory == null)
            {
                throw new ArgumentNullException(nameof(inlineViewerFactory));
            }
            if (generalOptions == null)
            {
                throw new ArgumentNullException(nameof(generalOptions));
            }
            if (searchMetadataCollection == null)
            {
                throw new ArgumentNullException(nameof(searchMetadataCollection));
            }
            if (searchOptionsViewModel == null)
            {
                throw new ArgumentNullException(nameof(searchOptionsViewModel));
            }
            if (searchHints == null)
            {
                throw new ArgumentNullException(nameof(searchHints));
            }

            _stateProvider = new TailViewPersister(this);

            var enumerable = fileWatcher as IFileWatcher[] ?? fileWatcher.ToArray();

            Names            = enumerable.Select(t => t.FullName);
            SelectionMonitor = selectionMonitor;
            SearchOptions    = searchOptionsViewModel;
            SearchHints      = searchHints;
            SearchCollection = new SearchCollection(searchInfoCollection, schedulerProvider);

            CopyToClipboardCommand =
                new Command(() => clipboardHandler.WriteToClipboard(selectionMonitor.GetSelectedText()));
            OpenFileCommand   = new Command(() => Process.Start(enumerable[0].FullName));
            OpenFolderCommand = new Command(() => Process.Start(enumerable[0].Folder));

            UsingDarkTheme = generalOptions.Value
                             .ObserveOn(schedulerProvider.MainThread)
                             .Select(options => options.Theme == Theme.Dark)
                             .ForBinding();

            HighlightTail = generalOptions.Value
                            .ObserveOn(schedulerProvider.MainThread)
                            .Select(options => options.HighlightTail)
                            .ForBinding();

            HighlightDuration = generalOptions.Value
                                .ObserveOn(schedulerProvider.MainThread)
                                .Select(options => new Duration(TimeSpan.FromSeconds(options.HighlightDuration)))
                                .ForBinding();

            //An observable which acts as a scroll command
            var autoChanged = this.WhenValueChanged(vm => vm.AutoTail);
            var scroller    = _userScrollRequested.CombineLatest(autoChanged, (user, auto) =>
            {
                var mode = AutoTail ? ScrollReason.Tail : ScrollReason.User;
                return(new ScrollRequest(mode, user.PageSize, user.FirstIndex));
            })
                              .Do(x => logger.Info("Scrolling to {0}/{1}", x.FirstIndex, x.PageSize))
                              .DistinctUntilChanged();

            FileStatus = enumerable
                         .Select(t => t.Status)
                         .Merge()
                         .Scan(default(FileStatus), (status, fileStatus) => status | fileStatus)
                         .ForBinding();

            //command to add the current search to the tail collection
            var searchInvoker =
                SearchHints.SearchRequested.Subscribe(
                    request => { searchInfoCollection.Add(request.Text, request.UseRegEx); });

            //User feedback to show file size
            FileSizeText = enumerable
                           .Select(t => t.Latest)
                           .Merge()
                           .Select(t => t.Size)
                           .Scan(0f, (previousSize, currentSize) => previousSize + currentSize / 2f)
                           .Select(t => ((long)t).FormatWithAbbreviation())
                           .DistinctUntilChanged()
                           .ForBinding();


            //tailer is the main object used to tail, scroll and filter in a file
            var lineScroller = new LineScroller(SearchCollection.Latest.ObserveOn(schedulerProvider.Background),
                                                scroller);

            //load lines into observable collection
            var lineProxyFactory = new LineProxyFactory(new TextFormatter(searchMetadataCollection),
                                                        new LineMatches(searchMetadataCollection));

            var loader = lineScroller.Lines.Connect()
                         .RecordChanges(logger, "Received")
                         .Transform(lineProxyFactory.Create, new ParallelisationOptions(ParallelType.Ordered, 3))
                         .Sort(SortExpressionComparer <LineProxy> .Ascending(proxy => proxy))
                         .ObserveOn(schedulerProvider.MainThread)
                         .Bind(out _data, 100)
                         .DisposeMany()
                         .LogErrors(logger)
                         .Subscribe();


            //monitor matching lines and start index,
            Count = searchInfoCollection.All
                    .GroupBy(t => t)
                    .Select(groupedProvider => groupedProvider.Key.Count)
                    .Scan(0, (i, providerCount) => i + providerCount)
                    .ForBinding();
            CountText = searchInfoCollection.All
                        .GroupBy(t => t)
                        .Select(groupedProvider => groupedProvider.Key.Count)
                        .Scan(0, (i, providerCount) => i + providerCount)
                        .Select(latestCount => $"{latestCount.ToString("##,###")} lines")
                        .ForBinding();
            //iterate over every items to evaluate the lines' count
            LatestCount = SearchCollection.Latest
                          .GroupBy(t => t)
                          .Do(Console.WriteLine)
                          .Scan(0, (acc, provider) =>
            {
                if (provider.Key is IndexCollection && provider.Key.NumberOfPreviousProvider == 0)
                {
                    acc = 0;
                }
                else if (provider.Key is FileSearchResult && provider.Key.NumberOfPreviousProvider == 0)
                {
                    acc = 0;
                }
                return(provider.Key.Count + acc);
            })
                          .ForBinding();

            ////track first visible index
            var firstIndexMonitor = lineScroller.Lines.Connect()
                                    .Buffer(TimeSpan.FromMilliseconds(25)).FlattenBufferResult()
                                    .ToCollection()
                                    .Select(lines => lines.Count == 0 ? 0 : lines.Select(l => l.Index).Max() - lines.Count + 1)
                                    .ObserveOn(schedulerProvider.MainThread)
                                    .Subscribe(first => { FirstIndex = first; });

            //Create objects required for inline viewing
            var isUserDefinedChanged = SearchCollection.WhenValueChanged(sc => sc.Selected)
                                       .Where(selected => selected != null)
                                       .Select(selected => selected.IsUserDefined)
                                       .DistinctUntilChanged()
                                       .Replay(1)
                                       .RefCount();

            var inlineViewerVisible = isUserDefinedChanged.CombineLatest(this.WhenValueChanged(vm => vm.ShowInline),
                                                                         (userDefined, showInline) => userDefined && showInline);

            CanViewInline       = isUserDefinedChanged.ForBinding();
            InlineViewerVisible = inlineViewerVisible.ForBinding();

            //return an empty line provider unless user is viewing inline - this saves needless trips to the file

            var inline = searchInfoCollection.All.CombineLatest(inlineViewerVisible,
                                                                (index, ud) => ud ? index : new EmptyLineProvider());

            var firstVisibleRow = _data.ToObservableChangeSet().ToCollection()
                                  .Select(collection => collection.FirstOrDefault());

            //var itemToSelect = this.WhenValueChanged(vm => vm.SelectedItem)
            //    .CombineLatest(firstVisibleRow, (selected, first) => selected ?? first);
            ////
            InlineViewer = inlineViewerFactory.Create(inline, this.WhenValueChanged(vm => vm.SelectedItem),
                                                      lineProxyFactory);

            _cleanUp = new CompositeDisposable(lineScroller,
                                               loader,
                                               firstIndexMonitor,
                                               FileStatus,
                                               Count,
                                               LatestCount,
                                               FileSizeText,
                                               CanViewInline,
                                               InlineViewer,
                                               InlineViewerVisible,
                                               SearchCollection,
                                               searchInfoCollection,
                                               HighlightTail,
                                               UsingDarkTheme,
                                               searchHints,
                                               searchMetadataCollection,
                                               searchMetadataCollection,
                                               SelectionMonitor,
                                               SearchOptions,
                                               searchInvoker,
                                               _userScrollRequested.SetAsComplete());
        }