Example #1
0
		/// <summary>
		/// Performs a search using the specified <paramref name="query"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="query">The <see cref="Query"/> on which to search.</param>
		/// <returns>Returns the resulting <see cref="RecordSet"/>.</returns>
		/// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception>
		/// <exception cref="ConnectionException">Thrown if a error occurred while executing the search query.</exception>
		public RecordSet Search(IMansionContext context, Query query)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (query == null)
				throw new ArgumentNullException("query");

			// find the root type for this query
			var rootType = query.TypeHints.FindCommonAncestor(context);

			// resolve the index definitions of this record
			var indexDefinitions = indexDefinitionResolver.Resolve(context, rootType);

			// determine the index which to use to perform the search
			var indexDefinitionTypeMappingPair = SelectBestIndexForQuery(rootType, query, indexDefinitions);

			// create a search descriptor
			var search = new SearchQuery(indexDefinitionTypeMappingPair.Item1, indexDefinitionTypeMappingPair.Item2);

			// map all the query components to the search descriptor
			foreach (var component in query.Components)
				converters.Elect(context, component).Map(context, query, component, search);

			// execute the query
			return Search(context, search);
		}
        protected override List<SearchProviderResult> DoSearch(SearchQuery q)
        {
            var query = q.QueryString.ToLower();

            var list = new List<SearchProviderResult>(0);

            if (query.StartsWith("prov") || query.StartsWith("rest"))
                list.Add(GenerateResult("Provider Stats", GetProvidersDescription()));

            if (query.StartsWith("rel") || query.StartsWith("rest"))
                list.Add(GenerateResult(reloadXlaunch));

            if (query.StartsWith("ex") || query.StartsWith("qu"))
            {
                var searchProviderResult = GenerateResult("exit").SetEnterKeyAction((a) =>
                {
                    Application.Current.Shutdown(0);
                    return true;

                });

                list.Add(searchProviderResult);
            }

            return list;
        }
    public void InitControl(SearchQuery q)
    {
        if (q == null)
        {
            return;
        }

        SearchQuery = q;

        gv1.DataSource = q.GetData();
        gv1.DataBind();

        string recName = Uc.CategoryID == 0 ? "article" : Uc.Category.Name;

        if (q.Count > 0)
        {
            lc.Text = q.Count.ToString() + " matching " + recName + (q.Count > 1 ? "s" : "") + " found";
            lp.Text = "Page " + (gv1.PageIndex + 1).ToString() + " of " + gv1.PageCount;
            lp.Visible = true;
        }
        else
        {
            lc.Text = "No matching " + recName + " found.";
            lc.Visible = false;
        }

        lc.Visible = true;
    }
Example #4
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid) {
                var query = new SearchQuery<UserModel>();
                //   query.AddFilter(product => product.UserName =="");
                //this is the same as the following

                query.AddFilter(c => c.UserName == model.UserName);
                query.Take = 1;

                var result = unitOfWork.UserRepository.Search(query).Entities.FirstOrDefault();
                if (result != null)
                {
                    if (result.Password == model.Password)
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, false);
                        return RedirectToAction("Index", "Location");

                    } ModelState.AddModelError("", "Login data is incorrect!");
                    return View(model);
                }
                ModelState.AddModelError("", "Login data is incorrect!");
                return View(model);
            }
            return View();
        }
 void SearchDbUc1_SearchClick(object sender, SearchQuery q)
 {
     if (SearchClick != null)
     {
         SearchClick(this, q);
     }
 }
        private static Dictionary<string, string> GetParameters(SearchQuery searchQuery)
        {
            var parameters = new Dictionary<string, string>();

            UrlHelper.AddStringParameter(parameters, "q", searchQuery.Query);

            if (searchQuery.Type != null)
            {
                UrlHelper.AddStringParameter(parameters, "type", searchQuery.Type.ToString().ToLower());
            }

            UrlHelper.AddStringParameter(parameters, "title", searchQuery.Title);
            UrlHelper.AddStringParameter(parameters, "release_title", searchQuery.Release_title);
            UrlHelper.AddStringParameter(parameters, "credit", searchQuery.Credit);
            UrlHelper.AddStringParameter(parameters, "artist", searchQuery.Artist);
            UrlHelper.AddStringParameter(parameters, "anv", searchQuery.Anv);
            UrlHelper.AddStringParameter(parameters, "label", searchQuery.Label);
            UrlHelper.AddStringParameter(parameters, "genre", searchQuery.Genre);
            UrlHelper.AddStringParameter(parameters, "style", searchQuery.Style);
            UrlHelper.AddStringParameter(parameters, "country", searchQuery.Country);
            UrlHelper.AddStringParameter(parameters, "format", searchQuery.Format);
            UrlHelper.AddStringParameter(parameters, "catno", searchQuery.Catno);
            UrlHelper.AddStringParameter(parameters, "barcode", searchQuery.Barcode);
            UrlHelper.AddStringParameter(parameters, "track", searchQuery.Track);
            UrlHelper.AddStringParameter(parameters, "submitter", searchQuery.Submitter);
            UrlHelper.AddStringParameter(parameters, "contributor", searchQuery.Contributor);

            return parameters;
        }
        public static string BuildSearchUrl(SearchQuery searchQuery)
        {
            var parameters = GetParameters(searchQuery);
            var url = UrlHelper.BuildUri("https://api.discogs.com//database/search", parameters);

            return url;
        }
Example #8
0
        public IEnumerable<SyndicationItem> Search(SearchQuery query)
        {
            var queryable = App.Get().DataContext.Where<UserProfile>(u => u.UserName.Contains(query.Terms)
                || (!string.IsNullOrEmpty(u.DisplayName) && (u.DisplayName.Contains(query.Terms)
                || u.Signature.Contains(query.Terms))));

            var skipCount = query.Index * query.Size;
            IQueryable<UserProfile> result = null;
            var size = 50;
            if (query.Size > 0)
                size = query.Size;

            if (skipCount > 0)
                result = queryable.Skip(skipCount).Take(size);
            else
                result = queryable.Take(size);

            query.TotalItems = queryable.Count();

            var searchResults = from u in result
                                orderby u.DisplayName
                                select new SyndicationItem(u.DisplayName, u.Signature, new Uri(u.Link));

            return searchResults.ToList();
            //return result.OrderBy(u => u.DisplayName).ToList().Select(u => new SearchResultItem()
            //{
            //    Title = u.DisplayName,
            //    Author = u.UserName,
            //    ImageUrl = u.Avatar,
            //    Link = u.Link,
            //    Source = this.Name,
            //    Summary = u.Signature
            //});
        }
        private IEnumerable<SearchResult> Search(SearchQuery query, RepoInfo repo, bool includeRepoName = false)
        {
            var allTerms = string.Join(" --or ", query.Terms.Select(t => "-e " + GitUtilities.Q(t)));
            var commandResult = GitUtilities.Execute("grep --line-number --fixed-strings --ignore-case --context 3 --null --all-match " + allTerms + " HEAD", repo.RepoPath);

            var repoResults = commandResult.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

            return from m in repoResults
                   where m != "--"
                   where !m.StartsWith("Binary file")
                   let parts = m.Split('\0')
                   let filePath = parts[0].Split(':')[1]
                   let searchLine = new SearchLine
                   {
                       Line = parts[2],
                       LineNumber = int.Parse(parts[1]),
                   }
                   group searchLine by filePath into g
                   select new SearchResult
                   {
                       LinkText = (includeRepoName ? repo.Name + " " : string.Empty) + "/" + g.Key,
                       ActionName = "ViewBlob",
                       ControllerName = "Browse",
                       RouteValues = new { repo = repo.Name, @object = "HEAD", path = g.Key },
                       Lines = g.ToList(),
                   };
        }
 public IEnumerable<Subtitle> SearchSubtitles(SearchQuery query)
 {
     var token = _api.Login();
     var languages = query.Languages.Select(l => l.TwoLetterIsoName).ToArray();
     var fileHashEnhancement = query.Enhancements.OfType<OpenSubtitlesFileHashEnhancement>().SingleOrDefault();
     var hashResults = SearchByHash(fileHashEnhancement, token, languages);
     return hashResults.Any() ? hashResults : SearchByQuery(query, token, languages);
 }
        public IEnumerable<Subtitle> SearchSubtitles(SearchQuery query)
        {
            var fileHash = GetFileHash(query);
            var languageCodes = _api.Search(fileHash);

            var languages = languageCodes.Select(KnownLanguages.GetLanguageByTwoLetterIso);
            var availableLanguages = GetAvailableLanguagesMatchingSearchQuery(query, languages);
            return availableLanguages.Select(language => CreateSubtitle(fileHash, language, query));
        }
 public IEnumerable<Subtitle> SearchSubtitles(SearchQuery query)
 {
     if (SupportedLanguages.Any() && !query.Languages.Intersect(SupportedLanguages).Any())
     {
         _logger.Debug(_name, "The downloader only provides texts for the languages: {0}. Aborting search.", string.Join(", ", SupportedLanguages.Select(l => l.TwoLetterIsoName).ToArray()));
         return Enumerable.Empty<Subtitle>();
     }
     return _downloader.SearchSubtitles(query, GetShowId, SearchTimeout);
 }
        public IEnumerable<Subtitle> SearchSubtitles(SearchQuery query)
        {
            int? seriesId = _scraper.FindSeries(query.SeriesTitle);
            if (!seriesId.HasValue)
                return Enumerable.Empty<Subtitle>();

            var listedSubtitles = _scraper.SearchSubtitles(seriesId.Value, query.Season);
            var subtitles = _mapper.Map(listedSubtitles, query.SeriesTitle);
            return _filter.Apply(subtitles, query);
        }
Example #14
0
 IEnumerator<object> BeginSearch()
 {
     ActiveSearchQuery = PendingSearchQuery;
     PendingSearchQuery = null;
     ActiveSearch = Program.Scheduler.Start(
         PerformSearch(ActiveSearchQuery),
         TaskExecutionPolicy.RunAsBackgroundTask
     );
     yield break;
 }
 private static Subtitle CreateSubtitle(string fileHash, Language language, SearchQuery query)
 {
     return new Subtitle(fileHash, "", language)
     {
         SeriesName = query.SeriesTitle,
         Season = query.Season,
         Episode = query.Episode,
         EndEpisode = query.Episode,
         ReleaseGroup = query.ReleaseGroup
     };
 }
        public IEnumerable<Subtitle> SearchSubtitles(SearchQuery query)
        {
            var languages = BuildLanguageString(query);
            var queryString = BuildQueryString(query);
            var document = GetSearchPage(languages, queryString);
            var subtitles = GetSubtitlesFromPage(document);
            subtitles = FilterOutInvalidEpisodes(subtitles, query);
            var result = ConvertToGlobalSubtitles(subtitles);

            return FilterOutLanguageNotInQuery(query, result);
        }
Example #17
0
        public void FileCommandObjectCreatedIsSameAsAConstructedObject(CommandType commandType)
        {
            ISearchQuery searchQuery = new SearchQuery("");
            IFileCommand commandFromFactory = (FileCommand)commandFactory.NewFileCommand(commandType, searchQuery);
            IFileCommand commandConstructedDirectly = new FileCommand(commandType, searchQuery);

            Assert.IsNotNull(commandFromFactory);
            Assert.AreEqual(typeof(FileCommand), commandFromFactory.GetType());
            Assert.AreEqual(commandConstructedDirectly.CommandType, commandFromFactory.CommandType);
            Assert.AreEqual(commandConstructedDirectly.Search, commandFromFactory.Search);
        }
        public IEnumerable<SearchResult> Search(SearchQuery query, FileManager fileManager)
        {
            var repos = from dir in fileManager.DirectoryInfo.EnumerateDirectories()
                        let repoInfo = GitUtilities.GetRepoInfo(dir.FullName)
                        where repoInfo.IsGitRepo
                        select repoInfo;

            return from repo in repos
                   from searchResult in Search(query, repo, includeRepoName: true)
                   select searchResult;
        }
 public Task<IList<SearchResult>> Search(SearchQuery query, FileManager fileManager, RepoInfo repository, int skip, int count)
 {
     if (repository != null)
     {
         return Task.Factory.StartNew(() => (IList<SearchResult>)Search(query, repository).Skip(skip).Take(count).ToList());
     }
     else
     {
         return Task.Factory.StartNew(() => (IList<SearchResult>)Search(query, fileManager).Skip(skip).Take(count).ToList());
     }
 }
Example #20
0
        public ActionResult Search(string terms, string source, string locale, int index = 1, int size = 20, string format = "")
        {
            //App.Get().SetCulture(locale);
            var src = string.IsNullOrEmpty(source) ? App.Get().Searcher.Sources.First().Name : source;
            if (terms == null)
            {
                ViewBag.Query = new SearchQuery()
                {
                    Source = src,
                    Locale = locale
                };
                return View();
            }

            var searchQuery = new SearchQuery()
            {
                Index = index - 1,
                Size = size,
                Source = src,
                Terms = terms,
                Locale = locale
            };

            var model = App.Get().Searcher.Search(searchQuery);
            var feed = new SyndicationFeed(string.Format("Search for {0}", terms), src, Request.Url, model);
            feed.Generator = "DotNetAge";

            if (format.Equals("rss", System.StringComparison.OrdinalIgnoreCase) ||
                format.Equals("atom", System.StringComparison.OrdinalIgnoreCase))
            {
                var sb = new StringBuilder();
                using (var writer = System.Xml.XmlWriter.Create(sb))
                {
                    if (format.Equals("rss", System.StringComparison.OrdinalIgnoreCase))
                    {
                        feed.SaveAsRss20(writer);
                        writer.Flush();
                        return Content(sb.ToString(), "text/xml", Encoding.UTF8);
                    }

                    if (format.Equals("atom", System.StringComparison.OrdinalIgnoreCase))
                    {
                        feed.SaveAsAtom10(writer);
                        writer.Flush();
                        return Content(sb.ToString(), "text/xml", Encoding.UTF8);
                    }
                }
            }
            ViewBag.Query = searchQuery;

            return Json(feed,JsonRequestBehavior.AllowGet);
        }
        protected override List<SearchProviderResult> DoSearch(SearchQuery query)
        {
            int priority = SearchProviderResult.PriorityUltraLow;
            var eval = new MathEvaluator();

            if (arr.Any(query.RawQueryString.Contains))
            {
                priority = SearchProviderResult.PriorityHigh;
            }

            double result = eval.Evaluate(query.RawQueryString);
            return ConstructSingleResult(result.ToString(CultureInfo.InvariantCulture), result.ToString(CultureInfo.InvariantCulture), priority);
        }
        protected override List<SearchProviderResult> DoSearch(SearchQuery q)
        {
            var list = new List<SearchProviderResult>();

            foreach (var process in Process.GetProcesses().Where(t => t.SessionId == currentSessionId))
            {

                var procLower = process.ProcessName.ToLower();
                var query = q.QueryString;
                var searchLower = query.ToLower();

                if (procLower.Contains(searchLower) || searchLower.Contains(procLower) || query == "*")
                {

                    var result = new SearchProviderResult(this)
                    {
                        DisplayName = string.Format("{0}", process.ProcessName),
                        ProviderMetadata = process,
                        Priority = SearchProviderResult.PriorityLow,
                        Description = "<h3><img src='data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7' />" + process.ProcessName + "</h3>"
                        // GroupName = "Kill"
                    };

                    result.SetEnterKeyAction((x) =>
                    {
                        var p = result.ProviderMetadata as Process;

                        if (p != null)
                            p.Kill();
                        return true;
                    });

                    try
                    {
                        if (!String.IsNullOrEmpty(process.MainModule.FileName))
                        {
                            result.SetIconFromFilePath(process.MainModule.FileName);
                        }

                    }
                    catch (Exception)
                    {

                        result.SetIcon(Properties.Resources.Application);
                    }
                    list.Add(result);
                }
            };

            return list;
        }
		public async Task RemoveFromHistory( SearchQuery query, CancellationToken cancellationToken )
		{
			//if any call add to history without initialization
			await GetHistory( cancellationToken );

			//move to top
			var exits = _searchQueries.FirstOrDefault( x => x.SearchString.ToLower().Equals( query.SearchString.ToLower() ) );
			if( exits != null )
			{
				_searchQueries.Remove( exits );
			}
			
			_dataCacheService.PutItem( _searchQueries, CacheItemName, cancellationToken );
		}
Example #24
0
 public IEnumerable<Subtitle> SearchSubtitles(SearchQuery query)
 {
     var results = _api.SearchByTitle(query.SeriesTitle, new S4ULimits {Season = query.Season, Episode = query.Episode});
     return results.Series.SelectMany(serie =>
         serie.Subs.Select(sub =>
             new Subtitle(sub.DownloadFile, sub.FileName + "." + sub.FileType, SupportedLanguages.Single())
             {
                 SeriesName = serie.Title,
                 Season = sub.Season,
                 Episode = sub.Episode,
                 EndEpisode = sub.Episode,
                 ReleaseGroup = sub.ReleaseGroup
             }));
 }
Example #25
0
        public static SearchResultModel SearchResultModel(string query,int pageIndex)
        {
            var searchQuery = new SearchQuery(query,pageIndex);
            var model = new SearchResultModel();
            var queryResults = MvcApplication.DbClient.Execute(searchQuery);
            model.Results = queryResults.Items;
            model.Query = queryResults.Query;
            model.TotalResults = queryResults.TotalResults;
            model.PageIndex = pageIndex;
            model.Skipped = (pageIndex*100);

            ReplaceUrl(model.Results);

            return model;
        }
Example #26
0
        public StaticPagedList<LocationModel> getLocations(int? pageNo)
        {
            //create the query
            var query = new SearchQuery<LocationModel>();
            //   query.AddFilter(product => product.UserName =="");

            //this is the same as the following
            query.AddFilter(c => c.IsDelete == false);
            var pageNumber = pageNo ?? 1;
            query.Take = 10;
            query.Skip = pageNumber - 1;
            var result = unitOfWork.LocationRepository.Search(query);

            return new StaticPagedList<LocationModel>(result.Entities, pageNumber, query.Take, result.Count);
        }
Example #27
0
        public StaticPagedList<ProductModel> getProducts(int? pageNo)
        {
            //create the query
            var query = new SearchQuery<ProductModel>();
            //   query.AddFilter(product => product.UserName =="");

            //this is the same as the following
            query.AddFilter(c => c.IsDelete == false);
            query.AddSortCriteria(new FieldSortCriteria<ProductModel>("LastUpdate", SortDirection.Descending));
            var pageNumber = pageNo ?? 1;
            query.Take = 10;
            query.Skip = pageNumber - 1;
            var result = unitOfWork.ProductRepository.Search(query);

            return new StaticPagedList<ProductModel>(result.Entities, pageNumber, query.Take, result.Count);
        }
        protected override List<SearchProviderResult> DoSearch(SearchQuery searchQuery)
        {
            string text = QueryParser.Escape(searchQuery.RawQueryString);

            var query = new QueryParser(Version.LUCENE_30, "displayName description customQuickName groupName", analyzer).Parse(
                    string.Format("displayName:{0}* or description:{0}* or displayName:{0}~ or customQuickName:{0}* or customQuickName:{0}~  or groupName:{0}* or groupName:{0} or path:{0}~ ", text));

            var searcher = new IndexSearcher(directory, true);

            var hits = searcher.Search(query, maxResultSize);

            var resultList = new List<SearchProviderResult>(hits.ScoreDocs.Length);

            foreach (var doc in hits.ScoreDocs)
            {
                var eDoc = searcher.Doc(doc.Doc);
                var path = eDoc.GetField("path").StringValue;
                var displayName = eDoc.GetField("displayName").StringValue;
                var desc = eDoc.GetField("description").StringValue;
                var customQuickName = eDoc.GetField("customQuickName").StringValue;

                // var iconBuffer = eDoc.GetBinaryValue("icon");

                Bitmap i;
                iconCache.TryGetValue(path, out i);

                var launchCount = Convert.ToInt32(eDoc.GetField("launchCount").StringValue);

                var result = ConstructResult<LuceneProviderResult>(customQuickName, desc, displayName, path, launchCount);

                result.SetEnterKeyAction((e) =>
                {
                    if (String.IsNullOrEmpty(e.Result.Path))
                        return false;
                    Process.Start(e.Result.Path, String.Empty);
                    return true;
                });

                if (i != null)
                {
                    result.SetIcon(i);
                }
                resultList.Add(result);
            }
            return resultList;
        }
Example #29
0
        public void ObjectCreatedIsSameAsAConstructedObject()
        {
            ISearchQuery sqFromFactory = searchQueryFactory.NewSearchQuery("");
            ISearchQuery sqConstructedDirectly = new SearchQuery("");

            //not worth implementing SearchQuery.Equals() just for testing
            Assert.IsNotNull(sqFromFactory);
            Assert.AreEqual(typeof(SearchQuery), sqFromFactory.GetType());
            Assert.AreEqual(sqConstructedDirectly.WantedAtoms.Count, sqFromFactory.WantedAtoms.Count);
            Assert.AreEqual(sqConstructedDirectly.UnwantedAtoms.Count, sqFromFactory.UnwantedAtoms.Count);

            for (int i = 0; i < sqConstructedDirectly.WantedAtoms.Count; i++)
                Assert.AreEqual(sqConstructedDirectly.WantedAtoms[i],sqFromFactory.WantedAtoms[i]);

            for (int i = 0; i < sqConstructedDirectly.UnwantedAtoms.Count; i++)
                Assert.AreEqual(sqConstructedDirectly.UnwantedAtoms[i], sqFromFactory.UnwantedAtoms[i]);
        }
Example #30
0
        public ActionResult PerformSearch(string searchText, IEnumerable<int> selectedIndexes)
        {
            //get the indexes
            IList<RetreaveIndex> indexesToSearch = ServiceLayer.IndexQueuerService.GetIndexesByIdList(selectedIndexes).ToList();

            RegisteredUser user = ServiceLayer.UserDetailsService.GetUserByUserName(HttpContext.User.Identity.Name);

            //create a new SearchQuery
            SearchQuery query = new SearchQuery { IndexesToSearch = indexesToSearch, Querier = user, QueryText = searchText };

            ResultSet results;
            using (ISearchEngineService service = ServiceLayer.SearchEngineService)
            {
                results = service.Search(query);
            }
            return View(results);
        }
Example #31
0
        public HttpResponseMessage FindHotel(string description = null, string location = null)
        {
            var query = new ConjunctionQuery(
                new TermQuery("hotel").Field("type")
                );

            if (!string.IsNullOrEmpty(description) && description != "*")
            {
                query.And(new DisjunctionQuery(
                              new PhraseQuery(description).Field("name"),
                              new PhraseQuery(description).Field("description")
                              ));
            }

            if (!string.IsNullOrEmpty(location) && location != "*")
            {
                query.And(new DisjunctionQuery(
                              new PhraseQuery(location).Field("address"),
                              new PhraseQuery(location).Field("city"),
                              new PhraseQuery(location).Field("state"),
                              new PhraseQuery(location).Field("country")
                              ));
            }

            var search = new SearchQuery();

            search.Index = "hotel";
            search.Query = query;
            search.Limit(100);

            var queryJson = query.Export().ToString(Formatting.None);
            var hotels    = new List <dynamic>();

            var result = _bucket.Query(search);

            foreach (var row in result)
            {
                var fragment = _bucket.LookupIn <dynamic>(row.Id)
                               .Get("name")
                               .Get("description")
                               .Get("address")
                               .Get("city")
                               .Get("state")
                               .Get("country")
                               .Execute();

                var address = string.Join(", ", new[]
                {
                    fragment.Content <string>("address"),
                    fragment.Content <string>("city"),
                    fragment.Content <string>("state"),
                    fragment.Content <string>("country")
                }.Where(x => !string.IsNullOrEmpty(x)));

                hotels.Add(new
                {
                    name        = fragment.Content <string>("name"),
                    description = fragment.Content <string>("description"),
                    address     = address
                });
            }

            return(Request.CreateResponse(new Result(hotels, queryJson)));
        }
Example #32
0
 /// <summary>
 /// Sends a <see cref="IFtsQuery" /> request to an FTS enabled node and returns the <see cref="ISearchQueryResult" />response.
 /// </summary>
 /// <param name="searchQuery"></param>
 /// <returns>
 /// A <see cref="Task{ISearchQueryResult}" /> representing the response from the FTS service.
 /// </returns>
 /// <exception cref="System.NotImplementedException"></exception>
 public virtual Task <ISearchQueryResult> SendWithRetryAsync(SearchQuery searchQuery)
 {
     throw new NotImplementedException();
 }
Example #33
0
        /// <summary>
        /// Gets the search hints.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{SearchHintResult}.</returns>
        /// <exception cref="System.ArgumentNullException">searchTerm</exception>
        private Task <IEnumerable <SearchHintInfo> > GetSearchHints(SearchQuery query, User user)
        {
            var searchTerm = query.SearchTerm;

            if (string.IsNullOrWhiteSpace(searchTerm))
            {
                throw new ArgumentNullException("searchTerm");
            }

            searchTerm = searchTerm.RemoveDiacritics();

            var terms = GetWords(searchTerm);

            var hints = new List <Tuple <BaseItem, string, int> >();

            var excludeItemTypes = new List <string>();
            var includeItemTypes = (query.IncludeItemTypes ?? new string[] { }).ToList();

            excludeItemTypes.Add(typeof(Year).Name);

            if (query.IncludeGenres && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Genre", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Genre).Name);
                    AddIfMissing(includeItemTypes, typeof(GameGenre).Name);
                    AddIfMissing(includeItemTypes, typeof(MusicGenre).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Genre).Name);
                AddIfMissing(excludeItemTypes, typeof(GameGenre).Name);
                AddIfMissing(excludeItemTypes, typeof(MusicGenre).Name);
            }

            if (query.IncludePeople && (includeItemTypes.Count == 0 || includeItemTypes.Contains("People", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Person).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Person).Name);
            }

            if (query.IncludeStudios && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Studio", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Studio).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Studio).Name);
            }

            if (query.IncludeArtists && (includeItemTypes.Count == 0 || includeItemTypes.Contains("MusicArtist", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(MusicArtist).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(MusicArtist).Name);
            }

            var mediaItems = _libraryManager.GetItems(new InternalItemsQuery
            {
                NameContains      = searchTerm,
                ExcludeItemTypes  = excludeItemTypes.ToArray(),
                IncludeItemTypes  = includeItemTypes.ToArray(),
                MaxParentalRating = user == null ? null : user.Policy.MaxParentalRating,
                Limit             = query.Limit.HasValue ? query.Limit * 3 : null
            }).Items;

            // Add search hints based on item name
            hints.AddRange(mediaItems.Where(i => IncludeInSearch(i) && IsVisible(i, user) && !(i is CollectionFolder)).Select(item =>
            {
                var index = GetIndex(item.Name, searchTerm, terms);

                return(new Tuple <BaseItem, string, int>(item, index.Item1, index.Item2));
            }));

            var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
            {
                Item        = i.Item1,
                MatchedTerm = i.Item2
            });

            return(Task.FromResult(returnValue));
        }
Example #34
0
        private async Task <bool> TrySendSearchResults(string username, int token, string query)
        {
            if (SoulseekClient.Options.SearchResponseResolver == default)
            {
                return(false);
            }

            SearchResponse searchResponse = null;

            try
            {
                searchResponse = await SoulseekClient.Options.SearchResponseResolver(username, token, SearchQuery.FromText(query)).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Diagnostic.Warning($"Error resolving search response for query '{query}' requested by {username} with token {token}: {ex.Message}", ex);
                return(false);
            }

            if (searchResponse == null)
            {
                return(false);
            }

            if (searchResponse.FileCount <= 0)
            {
                return(false);
            }

            try
            {
                Diagnostic.Debug($"Resolved {searchResponse.FileCount} files for query '{query}' with token {token} from {username}");

                var endpoint = await SoulseekClient.GetUserEndPointAsync(username).ConfigureAwait(false);

                var peerConnection = await SoulseekClient.PeerConnectionManager.GetOrAddMessageConnectionAsync(username, endpoint, CancellationToken.None).ConfigureAwait(false);

                await peerConnection.WriteAsync(searchResponse.ToByteArray()).ConfigureAwait(false);

                Diagnostic.Debug($"Sent response containing {searchResponse.FileCount} files to {username} for query '{query}' with token {token}");

                return(true);
            }
            catch (Exception ex)
            {
                Diagnostic.Debug($"Failed to send search response for {query} to {username}: {ex.Message}", ex);
            }

            return(false);
        }
Example #35
0
        public async Task TestLockingWithEmailBackedRemoteLockImplementation()
        {
            using var kernel = new FakeItEasyMockingKernel();
            kernel.Rebind <ILogger>().ToConstant(Log.Logger);
            kernel.Rebind <Configuration>().ToConstant(config);
            kernel.Rebind <ImapStore>().ToSelf().InSingletonScope();
            kernel.Rebind <ImapConnectionFactory>().ToSelf().InSingletonScope();
            var remoteLock = kernel.Get <ImapBackedRemoteLock>();
            var imapFac    = kernel.Get <ImapConnectionFactory>();
            var logger     = kernel.Get <ILogger>();

            logger.Debug("=====> START");

            using var con1 = await imapFac.GetImapConnectionAsync();

            var parentFolder = await con1.GetFolderAsync(con1.PersonalNamespaces[0].Path);

            var lockFolder = parentFolder.GetSubfolder(testFolderName);

            lockFolder.Open(FolderAccess.ReadWrite);
            lockFolder.Append(GetMessage("Counter inside", "0"));

            var lockFolderName = "locktest";
            // release any old lock
            await remoteLock.ReleaseLock(lockFolder, lockFolderName, -1);

            con1.Disconnect(true);
            var taskCount = 2;
            var loopCount = 20;

            for (var loop = 0; loop < loopCount; loop++)
            {
                var tasks = new List <Task>();
                for (var i = 0; i < taskCount; i++)
                {
                    CreateTask createTask = (int index) => Task.Run(async() =>
                    {
                        var taskIndex = index;
                        logger.Debug("{0:00} Starting task", taskIndex);

                        using var con2   = imapFac.GetImapConnectionAsync().Result;
                        var parentFolder = con2.GetFolder(con2.PersonalNamespaces[0].Path);
                        var lockFolder   = parentFolder.GetSubfolder(testFolderName);
                        var lockResult   = await remoteLock.AcquireLockRetry(lockFolder, lockFolderName, agressiveMode: true);
                        Assert.IsTrue(lockResult.IsSuccess);
                        Assert.IsNotNull(lockResult.ResultingLockCookie);


                        logger.Debug("{0:00} Increasing count section", taskIndex);
                        lockFolder.Open(FolderAccess.ReadWrite);
                        var idOfCounterEmail = lockFolder.Search(SearchQuery.SubjectContains("Counter inside")).Single();
                        // increase count
                        var loadedMessage = lockFolder.GetMessage(idOfCounterEmail);
                        var count         = int.Parse(loadedMessage.TextBody);
                        logger.Debug("{0:00} Got old count: {1}", taskIndex, count);
                        var newBody = $"{count + 1}";
                        // note: the UniqueId does change
                        logger.Debug("{0:00} Updating count mail", taskIndex);
                        idOfCounterEmail = lockFolder.Replace(idOfCounterEmail, GetMessage("Counter inside", newBody), MessageFlags.None).Value;
                        Assert.IsNotNull(idOfCounterEmail);
                        Assert.IsTrue(idOfCounterEmail.IsValid);

                        await remoteLock.ReleaseLock(lockFolder, lockFolderName, lockResult.ResultingLockCookie.Value);

                        con2.Disconnect(true);
                    });
                    tasks.Add(createTask(i));
                }
                await Task.WhenAll(tasks);
            }

            using var con3 = await imapFac.GetImapConnectionAsync();

            var parentFolder2 = await con3.GetFolderAsync(con3.PersonalNamespaces[0].Path);

            var mailFolder2 = parentFolder2.GetSubfolder(testFolderName);

            mailFolder2.Open(FolderAccess.ReadWrite);
            var idOfCounterEmail = mailFolder2.Search(SearchQuery.SubjectContains("Counter inside")).Single();
            var msg = mailFolder2.GetMessage(idOfCounterEmail);

            con3.Disconnect(true);
            Assert.AreEqual(taskCount * loopCount, int.Parse(msg.TextBody));
        }
Example #36
0
        /// <summary>
        /// Gets the search hints.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{SearchHintResult}.</returns>
        /// <exception cref="ArgumentNullException">searchTerm</exception>
        private List <SearchHintInfo> GetSearchHints(SearchQuery query, User user)
        {
            var searchTerm = query.SearchTerm;

            if (string.IsNullOrEmpty(searchTerm))
            {
                throw new ArgumentNullException("SearchTerm can't be empty.", nameof(searchTerm));
            }

            searchTerm = searchTerm.Trim().RemoveDiacritics();

            var excludeItemTypes = query.ExcludeItemTypes.ToList();
            var includeItemTypes = (query.IncludeItemTypes ?? Array.Empty <string>()).ToList();

            excludeItemTypes.Add(typeof(Year).Name);
            excludeItemTypes.Add(typeof(Folder).Name);

            if (query.IncludeGenres && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Genre", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Genre).Name);
                    AddIfMissing(includeItemTypes, typeof(MusicGenre).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Genre).Name);
                AddIfMissing(excludeItemTypes, typeof(MusicGenre).Name);
            }

            if (query.IncludePeople && (includeItemTypes.Count == 0 || includeItemTypes.Contains("People", StringComparer.OrdinalIgnoreCase) || includeItemTypes.Contains("Person", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Person).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Person).Name);
            }

            if (query.IncludeStudios && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Studio", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Studio).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Studio).Name);
            }

            if (query.IncludeArtists && (includeItemTypes.Count == 0 || includeItemTypes.Contains("MusicArtist", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(MusicArtist).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(MusicArtist).Name);
            }

            AddIfMissing(excludeItemTypes, typeof(CollectionFolder).Name);
            AddIfMissing(excludeItemTypes, typeof(Folder).Name);
            var mediaTypes = query.MediaTypes.ToList();

            if (includeItemTypes.Count > 0)
            {
                excludeItemTypes.Clear();
                mediaTypes.Clear();
            }

            var searchQuery = new InternalItemsQuery(user)
            {
                SearchTerm         = searchTerm,
                ExcludeItemTypes   = excludeItemTypes.ToArray(),
                IncludeItemTypes   = includeItemTypes.ToArray(),
                Limit              = query.Limit,
                IncludeItemsByName = string.IsNullOrEmpty(query.ParentId),
                ParentId           = string.IsNullOrEmpty(query.ParentId) ? Guid.Empty : new Guid(query.ParentId),
                OrderBy            = new[] { (ItemSortBy.SortName, SortOrder.Ascending) },
Example #37
0
        /// <summary>
        /// Search an index.
        /// </summary>
        /// <param name="indexName"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public Task <IApiResponse <SearchQueryResult> > SearchAsync(string indexName, SearchQuery query)
        {
            var request = new ApiRequest("indexes/{0}/docs", HttpMethod.Get);

            if (!String.IsNullOrEmpty(query.Query))
            {
                request.AddQueryParameter("search", query.Query);
            }
            if (query.Mode.HasValue)
            {
                request.AddQueryParameter("searchMode", query.Mode.ToString().ToLower());
            }
            if (!String.IsNullOrEmpty(query.SearchFields))
            {
                request.AddQueryParameter("searchFields", query.SearchFields);
            }
            if (query.Skip > 0)
            {
                request.AddQueryParameter("$skip", query.Skip.ToString(CultureInfo.InvariantCulture));
            }
            if (query.Top > 0)
            {
                request.AddQueryParameter("$top", query.Top.ToString(CultureInfo.InvariantCulture));
            }
            if (query.Count)
            {
                request.AddQueryParameter("$count", query.Count.ToString().ToLower());
            }
            if (!String.IsNullOrEmpty(query.OrderBy))
            {
                request.AddQueryParameter("$orderby", query.OrderBy);
            }
            if (!String.IsNullOrEmpty(query.Select))
            {
                request.AddQueryParameter("$select", query.Select);
            }
            if (query.Facets != null && query.Facets.Any())
            {
                request.AddQueryParameter("facet", query.Facets);
            }
            if (!String.IsNullOrEmpty(query.Filter))
            {
                request.AddQueryParameter("$filter", query.Filter);
            }
            if (!String.IsNullOrEmpty(query.Highlight))
            {
                request.AddQueryParameter("highlight", query.Highlight);
            }
            if (!String.IsNullOrEmpty(query.ScoringProfile))
            {
                request.AddQueryParameter("scoringProfile", query.ScoringProfile);
            }
            if (query.ScoringParameters != null && query.ScoringParameters.Any())
            {
                request.AddQueryParameter("scoringParameter", query.ScoringParameters);
            }

            return(_connection.Execute <SearchQueryResult>(request
                                                           .WithUriParameter(indexName)));
        }
Example #38
0
        /// <summary>
        /// Configure query used to make facet
        /// </summary>
        /// <param name="parameter">Parameter to configure</param>
        /// <param name="value">Query used to make facet</param>
        public static IFacetQueryParameter <TDocument> Query <TDocument>(this IFacetQueryParameter <TDocument> parameter, SearchQuery <TDocument> value)
            where TDocument : Document
        {
            parameter.Query = value;

            return(parameter);
        }
Example #39
0
 public ActionResult <IEnumerable <Hero> > Search([FromQuery] SearchQuery query)
 {
     return(Ok(this.businessLayer.SearchHeroByName(query.Term)));
 }
Example #40
0
            public async Task <ImmutableArray <SymbolResult <ISymbol> > > FindDeclarationsAsync(
                string name, TSimpleNameSyntax nameNode, SymbolFilter filter)
            {
                if (name != null && string.IsNullOrWhiteSpace(name))
                {
                    return(ImmutableArray <SymbolResult <ISymbol> > .Empty);
                }

                using var query = Exact ? SearchQuery.Create(name, ignoreCase: true) : SearchQuery.CreateFuzzy(name);
                var symbols = await FindDeclarationsAsync(filter, query).ConfigureAwait(false);

                if (Exact)
                {
                    // We did an exact, case insensitive, search.  Case sensitive matches should
                    // be preferred though over insensitive ones.
                    return(symbols.SelectAsArray(s =>
                                                 SymbolResult.Create(s.Name, nameNode, s, weight: s.Name == name ? 0 : 1)));
                }

                // TODO(cyrusn): It's a shame we have to compute this twice.  However, there's no
                // great way to store the original value we compute because it happens deep in the
                // compiler bowels when we call FindDeclarations.
                var similarityChecker = WordSimilarityChecker.Allocate(name, substringsAreSimilar: false);

                var result = symbols.SelectAsArray(s =>
                {
                    var areSimilar = similarityChecker.AreSimilar(s.Name, out var matchCost);

                    Debug.Assert(areSimilar);
                    return(SymbolResult.Create(s.Name, nameNode, s, matchCost));
                });

                similarityChecker.Free();

                return(result);
            }
 public override void SetSearchQuery(SearchQuery query)
 {
     model.Search(query);
     bodyContent.Rebuild();
 }
Example #42
0
        /// <summary>
        /// Configure value to include in query
        /// </summary>
        /// <param name="parameter">Parameter to configure</param>
        /// <param name="query">Value to include in query</param>
        public static ILocalParameter <TDocument> Query <TDocument>(this ILocalParameter <TDocument> parameter, SearchQuery <TDocument> query)
            where TDocument : Document
        {
            parameter.Query = query;

            return(parameter);
        }
Example #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:MailKit.Search.BinarySearchQuery"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new binary search query.
 /// </remarks>
 /// <param name="term">THe search term.</param>
 /// <param name="left">The left expression.</param>
 /// <param name="right">The right expression.</param>
 public BinarySearchQuery(SearchTerm term, SearchQuery left, SearchQuery right) : base(term)
 {
     Right = right;
     Left  = left;
 }
Example #44
0
        void InitializeSettings()
        {
            var ui = UiSettings.Instance;

            this.WithLayoutSuspended(() => {
                uiQuery.Text                  = ui.LastSearch;
                uiLogLevel.SelectedItem       = ui.TraceLevel;
                uiSearchLocalOnly.Checked     = ui.SearchLocalOnly;
                uiSearchFavouriteOnly.Checked = ui.SearchFavouritesOnly;
                ToggleFullScreen(ui.FullScreen);
                ToggleLog(UiSettings.Instance.LogCollapsed);
                TogglePlayerFull(UiSettings.Instance.PlayerFull);
                ToggleSearch(UiSettings.Instance.SearchCollapsed);
                ToggleNotifications(UiSettings.Instance.NotificationsCollapsed);
                ToggleCurrentControls(UiSettings.Instance.CurrentControlsCollapsed);
            });
            if (ui.CurrentTrack != null)
            {
                uiBrowser.IsBrowserInitializedChanged += (s, e) => {
                    if (e.IsBrowserInitialized)
                    {
                        BeginInvoke(new Action(() => LoadResult(ui.CurrentTrack, false)));
                    }
                }
            }
            ;
        }

        void InitializeLog()
        {
            logger        = new StreamWriter(AppSettings.LogFilePath, false);
            Logger.Trace += (s, e) => WriteLog(e.Level, e.Message);
            Logger.Trace += (s, e) => {
                lock (shutdownLock) {
                    string now = DateTime.Now.ToLongTimeString();
                    if (!shutdown)
                    {
                        logger.WriteLine(string.Format("{0}: {1}: {2}.", now, e.Level, e.Message));
                        if (e.Level == LogLevel.Error)
                        {
                            logger.Flush();
                        }
                    }
                }
            };
        }

        void InitializeSuggestions()
        {
            this.WithLayoutSuspended(() => {
                foreach (var s in Library.GetOpenSuggestions())
                {
                    AddToResultsViews(uiSuggestions, SuggestionScanner.SuggestionToSearchResult(s), ResultViewType.Suggestion);
                }
            });
        }

        void InitializePlaylist()
        {
            Playlist.Instance.Next += OnPlaylistNext;
            this.WithLayoutSuspended(() => {
                uiPlaylistModeAll.Checked    = Playlist.Instance.Mode == PlaylistMode.RepeatAll;
                uiPlaylistModeRandom.Checked = Playlist.Instance.Mode == PlaylistMode.Random;
                uiPlaylistModeTrack.Checked  = Playlist.Instance.Mode == PlaylistMode.RepeatTrack;
                foreach (var item in Playlist.Instance.Items)
                {
                    AddToResultsViews(uiPlaylist, item, ResultViewType.Playlist);
                }
            });
        }

        void WriteLog(LogLevel level, string text)
        {
            BeginInvoke(new Action(() => {
                if (level < (LogLevel)uiLogLevel.SelectedItem)
                {
                    return;
                }
                var line    = DateTime.Now.ToLongTimeString() + ": ";
                line       += level + ": " + text + Environment.NewLine;
                var newText = uiLog.Text + line;
                if (newText.Length > 10000)
                {
                    newText = newText.Substring(newText.Length - 10000);
                }
                uiLog.Text           = newText;
                uiLog.SelectionStart = uiLog.TextLength;
                uiLog.ScrollToCaret();
            }));
        }

        void AddToPlaylist(SearchResult result)
        {
            if (Playlist.Instance.Add(result))
            {
                AddToResultsViews(uiPlaylist, result, ResultViewType.Playlist);
            }
        }

        void ReplacePlaylist(FlowLayoutPanel container)
        {
            Playlist.Instance.Clear();
            this.WithLayoutSuspended(() => {
                UiUtility.ClearContainer <ResultView>(uiPlaylist);
                foreach (var view in container.Controls)
                {
                    AddToPlaylist(((ResultView)view).Result);
                }
                uiLeftTabs.SelectedIndex = TabIndexPlaylist;
            });
            Playlist.Instance.Start();
        }

        ResultView AddToResultsViews(FlowLayoutPanel container, SearchResult result, ResultViewType type)
        {
            var view = new ResultView(type);

            ConnectResultViewEventHandlers(view);
            container.Controls.Add(view);
            view.SetResult(result);
            return(view);
        }

        void AppendResults(SearchResponse response)
        {
            if (response.Error != null)
            {
                Logger.Error(response.Error, "Search error.");
            }
            else
            {
                BeginInvoke(new Action(() => {
                    this.WithLayoutSuspended(() => {
                        foreach (SearchResult result in response.Results)
                        {
                            var view = AddToResultsViews(uiResults, result, ResultViewType.Search);
                            if (AppSettings.Instance.ScrollToEndOnMoreResults)
                            {
                                appendingResult = true;
                                uiResults.ScrollControlIntoView(view);
                                appendingResult = false;
                            }
                        }
                    });
                }));
            }
        }

        void StartSearch()
        {
            var ui = UiSettings.Instance;

            UiUtility.ClearContainer <ResultView>(uiResults);
            searchRelated = null;
            searchQuery   = uiQuery.Text.Trim();
            UiSettings.Instance.LastSearch = searchQuery;
            var pageSize    = AppSettings.Instance.SearchPageSize;
            var credentials = UserSettings.Instance.Credentials;
            var query       = new SearchQuery(credentials, searchQuery, ui.SearchFavouritesOnly, ui.SearchLocalOnly ? true : (bool?)null, pageSize);

            searchState = SearchEngine.Start(query, AppendResults);
        }

        void PlayResult(SearchResult result)
        {
            AddToPlaylist(result);
            Playlist.Instance.Start();
            Playlist.Instance.Play(result);
            SetPlaylistPlaying(result);
        }

        void SetPlaylistPlaying(SearchResult result)
        {
            this.WithLayoutSuspended(() => {
                foreach (ResultView view in uiPlaylist.Controls)
                {
                    view.SetPlaying(false);
                    if (result != null && view.Result.TypeId.Equals(result.TypeId) && view.Result.VideoId.Equals(result.VideoId))
                    {
                        view.SetPlaying(true);
                    }
                }
            });
        }

        void LoadResult(SearchResult result, bool start)
        {
            try {
                uiPlayer.Ctlcontrols.stop();
            } catch (AxHost.InvalidActiveXStateException) {
            }
            uiBrowser.Load(AppSettings.EmptyHtmlFilePath);
            if (result == null)
            {
                return;
            }
            uiCurrentResult.SetResult(result);
            uiSplitBrowserPlayer.Panel1Collapsed = false;
            uiSplitBrowserPlayer.Panel2Collapsed = false;
            if (result == null)
            {
                return;
            }
            UiSettings.Instance.CurrentTrack = result;
            Logger.Debug("Loading {0} ({1}: {2}) in player.", result.Title, result.TypeId, result.VideoId);
            if (result.Local)
            {
                LoadLocalResult(result, start);
            }
            else
            {
                LoadWebResult(result, start);
            }
        }

        void LoadLocalResult(SearchResult result, bool start)
        {
            uiSplitBrowserPlayer.Panel1Collapsed = true;
            uiPlayer.URL = result.VideoId;
            if (start)
            {
                uiPlayer.Ctlcontrols.play();
            }
            else
            {
                uiPlayer.Ctlcontrols.stop();
            }
        }

        void LoadWebResult(SearchResult result, bool start)
        {
            startPlaying = start;
            var provider = AppSettings.GetProvider(result.TypeId);

            uiSplitBrowserPlayer.Panel2Collapsed = true;
            uiBrowser.RequestHandler             = new RefererRequestHandler(provider.HttpReferer);
            uiBrowser.Load(provider.GetEmbedFilePath());
        }

        void LoadMoreResults()
        {
            var ui     = UiSettings.Instance;
            var typeId = searchRelated?.TypeId;
            SearchCredentials searchCredentials = null;
            var pageSize    = AppSettings.Instance.SearchPageSize;
            var credentials = UserSettings.Instance.Credentials;

            if (typeId != null)
            {
                credentials.TryGetValue(typeId, out searchCredentials);
            }
            SearchQuery q = searchRelated == null ?
                            new SearchQuery(credentials, searchQuery, ui.SearchFavouritesOnly, ui.SearchLocalOnly ? true : (bool?)null, pageSize) :
                            new SearchQuery(typeId, searchCredentials, searchRelated.VideoId, pageSize);

            SearchEngine.Continue(q, searchState, AppendResults);
        }

        void ConnectResultViewEventHandlers(ResultView view)
        {
            view.PlayClicked      += OnResultPlayClicked;
            view.QueueClicked     += OnResultQueueClicked;
            view.RelatedClicked   += OnResultRelatedClicked;
            view.SimilarClicked   += OnResultSimilarClicked;
            view.FavouriteChanged += OnResultFavouriteChanged;
            if (view.Type != ResultViewType.Suggestion)
            {
                view.DownloadClicked += OnResultDownloadClicked;
            }
            else
            {
                view.DownloadClicked += (s, e) => AcceptSuggestion(view);
            }
            if (view.Type == ResultViewType.Playlist)
            {
                view.RemoveClicked += (s, e) => RemoveFromPlaylist(view);
            }
            if (view.Type == ResultViewType.Suggestion)
            {
                view.RemoveClicked += (s, e) => DeclineSuggestion(view);
            }
        }

        void RemoveFromPlaylist(ResultView view)
        {
            view.Dispose();
            uiPlaylist.Controls.Remove(view);
            Playlist.Instance.Remove(view.Result);
        }

        void AcceptSuggestion(ResultView view)
        {
            Library.HandleSuggestion(view.Result.TypeId, view.Result.VideoId, true);
            view.Dispose();
            uiSuggestions.Controls.Remove(view);
            DownloadResult(view.Result);
        }

        void DeclineSuggestion(ResultView view)
        {
            Library.HandleSuggestion(view.Result.TypeId, view.Result.VideoId, false);
            view.Dispose();
            uiSuggestions.Controls.Remove(view);
        }

        void DownloadResult(SearchResult result)
        {
            uiDownloadQueue.Enqueue(new QueueItem(result));
        }

        void HandleSuggestions(SearchResponse response)
        {
            BeginInvoke(new Action(() => {
                this.WithLayoutSuspended(() => {
                    if (response.Results != null)
                    {
                        foreach (var result in response.Results)
                        {
                            AddToResultsViews(uiSuggestions, result, ResultViewType.Suggestion);
                        }
                    }
                });
            }));
        }

        void ToggleFullScreen(bool fullScreen)
        {
            if (fullScreen)
            {
                TopMost                 = true;
                WindowState             = FormWindowState.Normal;
                FormBorderStyle         = FormBorderStyle.None;
                WindowState             = FormWindowState.Maximized;
                uiToggleFullScreen.Text = UnicodeBlackLowerLeftTriangle;
            }
            else
            {
                TopMost                 = false;
                WindowState             = FormWindowState.Maximized;
                FormBorderStyle         = FormBorderStyle.Sizable;
                uiToggleFullScreen.Text = UnicodeBlackUpperRightTriangle;
            }
        }

        void TogglePlayerFull(bool full)
        {
            var ui = UiSettings.Instance;

            ToggleSearch(ui.SearchCollapsed);
            ToggleNotifications(ui.NotificationsCollapsed);
            ToggleCurrentControls(ui.CurrentControlsCollapsed);
            uiToggleSearch.Visible               = !full;
            uiToggleNotifications.Visible        = !full;
            uiToggleCurrentControls.Visible      = !full;
            uiBrowserPlayerContainer.BorderStyle = full ? BorderStyle.None : BorderStyle.FixedSingle;
            uiTogglePlayerFull.Text              = full ? UnicodeWhiteLowerLeftTriangle : UnicodeWhiteUpperRightTriangle;
        }

        void ToggleLog(bool collapsed)
        {
            bool realCollapsed = collapsed || Width < ShowLogMinWidth;

            uiToggleLog.Text = realCollapsed ? UnicodeBlackLeftPointingTriangle : UnicodeBlackRightPointingTriangle;
            uiSplitNotificationsLog.Panel2Collapsed = realCollapsed;
        }

        void ToggleSearch(bool collapsed)
        {
            bool realCollapsed = collapsed || UiSettings.Instance.PlayerFull;

            uiToggleSearch.Text           = realCollapsed ? UnicodeBlackRightPointingTriangle : UnicodeBlackLeftPointingTriangle;
            uiSplitSearch.Panel1Collapsed = realCollapsed;
        }

        void ToggleNotifications(bool collapsed)
        {
            bool realCollapsed = collapsed || UiSettings.Instance.PlayerFull;

            uiToggleNotifications.Text           = realCollapsed ? UnicodeBlackUpPointingTriangle : UnicodeBlackDownPointingTriangle;
            uiSplitNotifications.Panel2Collapsed = realCollapsed;
        }

        void ToggleCurrentControls(bool collapsed)
        {
            bool realCollapsed = collapsed || UiSettings.Instance.PlayerFull;

            uiToggleCurrentControls.Text = realCollapsed ? UnicodeBlackDownPointingTriangle : UnicodeBlackUpPointingTriangle;
            uiSplitBrowserCurrentControls.Panel1Collapsed = realCollapsed;
        }
    }
Example #45
0
        /// <summary>
        /// Gets the search hints.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{SearchHintResult}.</returns>
        /// <exception cref="System.ArgumentNullException">searchTerm</exception>
        private Task <IEnumerable <SearchHintInfo> > GetSearchHints(SearchQuery query, User user)
        {
            var searchTerm = query.SearchTerm;

            if (searchTerm != null)
            {
                searchTerm = searchTerm.Trim().RemoveDiacritics();
            }

            if (string.IsNullOrWhiteSpace(searchTerm))
            {
                throw new ArgumentNullException("searchTerm");
            }

            var terms = GetWords(searchTerm);

            var excludeItemTypes = query.ExcludeItemTypes.ToList();
            var includeItemTypes = (query.IncludeItemTypes ?? new string[] { }).ToList();

            excludeItemTypes.Add(typeof(Year).Name);
            excludeItemTypes.Add(typeof(Folder).Name);

            if (query.IncludeGenres && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Genre", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Genre).Name);
                    AddIfMissing(includeItemTypes, typeof(GameGenre).Name);
                    AddIfMissing(includeItemTypes, typeof(MusicGenre).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Genre).Name);
                AddIfMissing(excludeItemTypes, typeof(GameGenre).Name);
                AddIfMissing(excludeItemTypes, typeof(MusicGenre).Name);
            }

            if (query.IncludePeople && (includeItemTypes.Count == 0 || includeItemTypes.Contains("People", StringComparer.OrdinalIgnoreCase) || includeItemTypes.Contains("Person", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Person).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Person).Name);
            }

            if (query.IncludeStudios && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Studio", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(Studio).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(Studio).Name);
            }

            if (query.IncludeArtists && (includeItemTypes.Count == 0 || includeItemTypes.Contains("MusicArtist", StringComparer.OrdinalIgnoreCase)))
            {
                if (!query.IncludeMedia)
                {
                    AddIfMissing(includeItemTypes, typeof(MusicArtist).Name);
                }
            }
            else
            {
                AddIfMissing(excludeItemTypes, typeof(MusicArtist).Name);
            }

            AddIfMissing(excludeItemTypes, typeof(CollectionFolder).Name);
            AddIfMissing(excludeItemTypes, typeof(Folder).Name);
            var mediaTypes = query.MediaTypes.ToList();

            if (includeItemTypes.Count > 0)
            {
                excludeItemTypes.Clear();
                mediaTypes.Clear();
            }

            var searchQuery = new InternalItemsQuery(user)
            {
                NameContains       = searchTerm,
                ExcludeItemTypes   = excludeItemTypes.ToArray(excludeItemTypes.Count),
                IncludeItemTypes   = includeItemTypes.ToArray(includeItemTypes.Count),
                Limit              = query.Limit,
                IncludeItemsByName = string.IsNullOrWhiteSpace(query.ParentId),
                ParentId           = string.IsNullOrWhiteSpace(query.ParentId) ? (Guid?)null : new Guid(query.ParentId),
                OrderBy            = new[] { new Tuple <string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) },
                Recursive          = true,

                IsKids     = query.IsKids,
                IsMovie    = query.IsMovie,
                IsNews     = query.IsNews,
                IsSeries   = query.IsSeries,
                IsSports   = query.IsSports,
                MediaTypes = mediaTypes.ToArray(),

                DtoOptions = new DtoOptions
                {
                    Fields = new ItemFields[]
                    {
                        ItemFields.AirTime,
                        ItemFields.DateCreated,
                        ItemFields.ChannelInfo,
                        ItemFields.ParentId
                    }
                }
            };

            List <BaseItem> mediaItems;

            if (searchQuery.IncludeItemTypes.Length == 1 && string.Equals(searchQuery.IncludeItemTypes[0], "MusicArtist", StringComparison.OrdinalIgnoreCase))
            {
                if (searchQuery.ParentId.HasValue)
                {
                    searchQuery.AncestorIds = new string[] { searchQuery.ParentId.Value.ToString("N") };
                }
                searchQuery.ParentId           = null;
                searchQuery.IncludeItemsByName = true;
                searchQuery.IncludeItemTypes   = new string[] { };
                mediaItems = _libraryManager.GetArtists(searchQuery).Items.Select(i => i.Item1).ToList();
            }
            else
            {
                mediaItems = _libraryManager.GetItemList(searchQuery);
            }

            var returnValue = mediaItems.Select(item =>
            {
                var index = GetIndex(item.Name, searchTerm, terms);

                return(new Tuple <BaseItem, string, int>(item, index.Item1, index.Item2));
            }).OrderBy(i => i.Item3).ThenBy(i => i.Item1.SortName).Select(i => new SearchHintInfo
            {
                Item        = i.Item1,
                MatchedTerm = i.Item2
            });

            return(Task.FromResult(returnValue));
        }
        internal IEnumerable <GroupedDetailView> GetGroupedDetailViews(SearchQuery searchQuery, int userSearchTypeId, out int totalHits, out bool more)
        {
            var searchResults = SearchController.Instance.SiteSearch(searchQuery);

            totalHits = searchResults.TotalHits;
            more      = totalHits > searchQuery.PageSize * searchQuery.PageIndex;

            var groups    = new List <GroupedDetailView>();
            var tabGroups = new Dictionary <string, IList <SearchResult> >();

            foreach (var result in searchResults.Results)
            {
                //var key = result.TabId + result.Url;
                var key = result.Url;
                if (!tabGroups.ContainsKey(key))
                {
                    tabGroups.Add(key, new List <SearchResult> {
                        result
                    });
                }
                else
                {
                    //when the result is a user search type, we should only show one result
                    // and if duplicate, we should also reduce the totalHit number.
                    if (result.SearchTypeId != userSearchTypeId ||
                        tabGroups[key].All(r => r.Url != result.Url))
                    {
                        tabGroups[key].Add(result);
                    }
                    else
                    {
                        totalHits--;
                    }
                }
            }

            var showFriendlyTitle = ActiveModule == null ||
                                    !ActiveModule.ModuleSettings.ContainsKey("ShowFriendlyTitle") ||
                                    Convert.ToBoolean(ActiveModule.ModuleSettings["ShowFriendlyTitle"]);

            foreach (var results in tabGroups.Values)
            {
                var group = new GroupedDetailView();

                //first entry
                var first = results[0];
                group.Title       = showFriendlyTitle ? GetFriendlyTitle(first) : first.Title;
                group.DocumentUrl = first.Url;

                //Find a different title for multiple entries with same url
                if (results.Count > 1)
                {
                    if (first.TabId > 0)
                    {
                        var tab = TabController.Instance.GetTab(first.TabId, first.PortalId, false);
                        if (tab != null)
                        {
                            group.Title = showFriendlyTitle && !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName;
                        }
                    }
                    else if (first.ModuleId > 0)
                    {
                        var tabTitle = GetTabTitleFromModuleId(first.ModuleId);
                        if (!string.IsNullOrEmpty(tabTitle))
                        {
                            group.Title = tabTitle;
                        }
                    }
                }
                else if (first.ModuleDefId > 0 && first.ModuleDefId == HtmlModuleDefitionId) //special handling for Html module
                {
                    var tabTitle = GetTabTitleFromModuleId(first.ModuleId);
                    if (!string.IsNullOrEmpty(tabTitle))
                    {
                        group.Title = tabTitle;
                        if (first.Title != "Enter Title" && first.Title != "Text/HTML")
                        {
                            group.Title += " > " + first.Title;
                        }
                        first.Title = group.Title;
                    }
                }

                foreach (var result in results)
                {
                    var title  = showFriendlyTitle ? GetFriendlyTitle(result) : result.Title;
                    var detail = new DetailedView
                    {
                        Title               = title != null && title.Contains("<") ? HttpUtility.HtmlEncode(title) : title,
                        DocumentTypeName    = InternalSearchController.Instance.GetSearchDocumentTypeDisplayName(result),
                        DocumentUrl         = result.Url,
                        Snippet             = result.Snippet,
                        Description         = result.Description,
                        DisplayModifiedTime = result.DisplayModifiedTime,
                        Tags             = result.Tags.ToList(),
                        AuthorProfileUrl = result.AuthorUserId > 0 ? Globals.UserProfileURL(result.AuthorUserId) : string.Empty,
                        AuthorName       = result.AuthorName
                    };
                    group.Results.Add(detail);
                }

                groups.Add(group);
            }

            return(groups);
        }
Example #47
0
        public async Task TestModSeqBasedLockingInGeneral()
        {
            using var kernel = new FakeItEasyMockingKernel();
            kernel.Rebind <ILogger>().ToConstant(Log.Logger);
            kernel.Rebind <Configuration>().ToConstant(config);
            kernel.Rebind <ImapStore>().ToSelf().InSingletonScope();
            kernel.Rebind <ImapConnectionFactory>().ToSelf().InSingletonScope();
            var imapFac = kernel.Get <ImapConnectionFactory>();
            var logger  = kernel.Get <ILogger>();

            logger.Debug("=====> START");

            using var con1 = await imapFac.GetImapConnectionAsync();

            var parentFolder = await con1.GetFolderAsync(con1.PersonalNamespaces[0].Path);

            var mailFolder = parentFolder.GetSubfolder(testFolderName);

            mailFolder.Open(FolderAccess.ReadWrite);

            var id = mailFolder.Append(GetMessage("Lock", "0"));

            mailFolder.Fetch(new List <UniqueId>()
            {
                id.Value
            }, MessageSummaryItems.ModSeq);
            mailFolder.Append(GetMessage("Counter inside", "0"));
            con1.Disconnect(true);

            var taskCount = 9;
            var loopCount = 20;

            for (var loop = 0; loop < loopCount; loop++)
            {
                var tasks = new List <Task>();
                for (var i = 0; i < taskCount; i++)
                {
                    CreateTask createTask = (int index) => Task.Run(() =>
                    {
                        var taskIndex = index;
                        logger.Debug("{0:00} Starting task", taskIndex);
                        int cookie;
                        lock (rand)
                        {
                            cookie = rand.Next();
                        }

#pragma warning disable CS0618 // Type or member is obsolete
                        var cookiestring = $"{taskIndex}-{AppDomain.GetCurrentThreadId()}-{cookie}";
#pragma warning restore CS0618 // Type or member is obsolete
                        logger.Debug("{0:00} Cookiestring: {1}", taskIndex, cookiestring);
                        using var con2   = imapFac.GetImapConnectionAsync().Result;
                        var parentFolder = con2.GetFolder(con2.PersonalNamespaces[0].Path);
                        var mailFolder   = parentFolder.GetSubfolder(testFolderName);
                        mailFolder.UidValidityChanged += (a, b) => { logger.Warning("0:00 UI VALIDITY changed!", taskIndex); };
                        mailFolder.Open(FolderAccess.ReadWrite);
                        var idOfLockEmail = mailFolder.Search(SearchQuery.SubjectContains("Lock")).Single();
                        logger.Debug("{0:00} Lock email ID: {1}", taskIndex, idOfLockEmail);

                        try
                        {
                            IMessageSummary summary;
                            IList <UniqueId> failList;
                            var keywords = new HashSet <string>()
                            {
                                cookiestring, DateTime.UtcNow.ToFileTimeUtc().ToString()
                            };
                            ulong modSeqMax;
                            do
                            {
                                // might return multiple unrelated summaries...
                                var summaries = mailFolder.Fetch(new List <UniqueId>()
                                {
                                    idOfLockEmail
                                }, MessageSummaryItems.Flags | MessageSummaryItems.UniqueId | MessageSummaryItems.ModSeq);

                                if (summaries.Where(s => s.UniqueId == idOfLockEmail && s.Keywords?.Count > 0).Any())
                                {
                                    logger.Debug("{0:00} Got summary with keywords, need to wait", taskIndex);
                                    Task.Delay(rand.Next(100, 2000)).Wait();
                                    continue;
                                }
                                logger.Debug("{0:00} Got summary without keywords - trying to set them", taskIndex);

                                summary   = summaries.Where(s => s.UniqueId == idOfLockEmail).Single();
                                modSeqMax = summary.ModSeq.Value;
                                //summary = mailFolder.Fetch(indizes, MessageSummaryItems.ModSeq | MessageSummaryItems.UniqueId);
                                failList = mailFolder.SetFlags(new List <UniqueId>()
                                {
                                    idOfLockEmail
                                }, modSeqMax, MessageFlags.UserDefined, keywords, false);
                                if (failList.Count > 0)
                                {
                                    logger.Debug("{0:00} Could not set keywords with modSeq {1}, starting over", taskIndex, modSeqMax);
                                    Task.Delay(rand.Next(100, 2000)).Wait();
                                    continue;
                                }
                                else
                                {
                                    logger.Debug("{0:00} Successfully set keywords, modSeq was {1}", taskIndex, modSeqMax);
                                    // really?? check this...

                                    var lockMessageSummary = mailFolder
                                                             .Fetch(new List <UniqueId>()
                                    {
                                        idOfLockEmail
                                    }, MessageSummaryItems.Flags | MessageSummaryItems.UniqueId | MessageSummaryItems.ModSeq)
                                                             .Where(s => s.UniqueId == idOfLockEmail)
                                                             .SingleOrDefault();
                                    if (lockMessageSummary == null)
                                    {
                                        logger.Error("{0:00} Could not fetch lock message summary!", taskIndex);
                                    }
                                    logger.Debug("{0:00} Got lock messgage keywords: {1}", taskIndex, lockMessageSummary.Keywords);
                                    if (lockMessageSummary.Keywords.Count > 2)
                                    {
                                        cookie = rand.Next();
#pragma warning disable CS0618 // Type or member is obsolete
                                        cookiestring = $"{taskIndex}-{AppDomain.GetCurrentThreadId()}-{cookie}";
#pragma warning restore CS0618 // Type or member is obsolete
                                        keywords = new HashSet <string>()
                                        {
                                            cookiestring, DateTime.UtcNow.ToFileTimeUtc().ToString()
                                        };
                                        // with Dovecot it sometimes happened that two threads succeed in setting their keywords although only one should succeed (as both use the same modSeq number)
                                        logger.Warning("{0:00} Got wrong number of keywords, starting over with new keywords for thread: {1}", taskIndex, keywords);
                                        mailFolder.RemoveFlags(new List <UniqueId>()
                                        {
                                            idOfLockEmail
                                        }, MessageFlags.UserDefined, lockMessageSummary.Keywords, true);
                                        continue;
                                    }
                                    if (!lockMessageSummary.Keywords.Contains(cookiestring))
                                    {
                                        // with Dovecot it sometimes happened that sometimes the keywords cannot be set but failList nevertheless is empty
                                        logger.Warning("{0:00} Control keyword f-up: {1} (expected cookiestring {2}); starting over", lockMessageSummary.Keywords, cookiestring);
                                        continue;
                                    }
                                    Assert.AreEqual(2, lockMessageSummary.Keywords.Count);

                                    break;
                                }
                            } while (true);
                            logger.Debug("{0:00} Increasing count section", taskIndex);

                            summary = mailFolder
                                      .Fetch(new List <UniqueId>()
                            {
                                idOfLockEmail
                            }, MessageSummaryItems.ModSeq)
                                      .Where(s => s.UniqueId == idOfLockEmail)
                                      .Single();

                            var idOfCounterEmail = mailFolder.Search(SearchQuery.SubjectContains("Counter inside")).Single();
                            // increase count
                            var loadedMessage = mailFolder.GetMessage(idOfCounterEmail);
                            var count         = int.Parse(loadedMessage.TextBody);
                            logger.Debug("{0:00} Got old count: {1}", taskIndex, count);
                            var newBody = $"{count + 1}";
                            // note: the UniqueId does change
                            logger.Debug("{0:00} Updating count mail", taskIndex);
                            idOfCounterEmail = mailFolder.Replace(idOfCounterEmail, GetMessage("Counter inside", newBody), MessageFlags.None).Value;
                            Assert.IsNotNull(idOfCounterEmail);
                            Assert.IsTrue(idOfCounterEmail.IsValid);

                            //Assert.AreEqual(modSeqMax + 4, mailFolder.HighestModSeq);
                            logger.Debug("{0:00} Removing keywords", taskIndex);
                            mailFolder.RemoveFlags(new List <UniqueId>()
                            {
                                idOfLockEmail
                            }, MessageFlags.UserDefined, keywords, true);
                            //Assert.AreEqual(0, failList.Count, "Somebody removed keywords in parallel which must not happen");
                            logger.Debug("{0:00} DONE", taskIndex);
                        }
                        catch
                        {
                            Debugger.Break();
                        }
                        finally
                        {
                            con2.Disconnect(true);
                        }
                        logger.Debug("Exiting task {0}", taskIndex);
                    });
                    tasks.Add(createTask(i));
                }
                await Task.WhenAll(tasks);
            }

            using var con3 = await imapFac.GetImapConnectionAsync();

            var parentFolder2 = await con3.GetFolderAsync(con3.PersonalNamespaces[0].Path);

            var mailFolder2 = parentFolder2.GetSubfolder(testFolderName);

            mailFolder2.Open(FolderAccess.ReadWrite);
            var idOfCounterEmail = mailFolder2.Search(SearchQuery.SubjectContains("Counter inside")).Single();
            var msg = mailFolder2.GetMessage(idOfCounterEmail);

            con3.Disconnect(true);
            Assert.AreEqual(taskCount * loopCount, int.Parse(msg.TextBody));
        }
Example #48
0
        public void TestDefaultSearchQuery()
        {
            var query = new SearchQuery();

            Assert.AreEqual(SearchTerm.All, query.Term, "Default .ctor");
        }
Example #49
0
        /// <summary>
        /// Configure filter or list of filters to be intersected with the incoming domain before faceting
        /// </summary>
        /// <typeparam name="TDocument"></typeparam>
        /// <param name="parameter"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static IFacetSpatialParameter <TDocument> Filter <TDocument>(this IFacetSpatialParameter <TDocument> parameter, SearchQuery <TDocument> filter)
            where TDocument : Document
        {
            parameter.Filter = filter;

            return(parameter);
        }
Example #50
0
        public void TestArgumentExceptions()
        {
            Assert.Throws <ArgumentNullException> (() => SearchQuery.And(null, SearchQuery.All));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.And(SearchQuery.All, null));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.AnnotationsContain(null, AnnotationAttribute.Value, "value"));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.AnnotationsContain(AnnotationEntry.AltSubject, null, "value"));
            Assert.Throws <ArgumentException> (() => SearchQuery.AnnotationsContain(AnnotationEntry.AltSubject, AnnotationAttribute.Size, "value"));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.BccContains(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.BccContains(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.BodyContains(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.BodyContains(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.CcContains(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.CcContains(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.DoesNotHaveCustomFlag(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.DoesNotHaveCustomFlag(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.DoesNotHaveCustomFlags(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.DoesNotHaveCustomFlags(new string[0]));
            Assert.Throws <ArgumentException> (() => SearchQuery.DoesNotHaveFlags(MessageFlags.None));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.Filter(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.Filter(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.FromContains(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.FromContains(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.Fuzzy(null));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.GMailRawSearch(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.GMailRawSearch(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.HasCustomFlag(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.HasCustomFlag(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.HasCustomFlags(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.HasCustomFlags(new string[0]));
            Assert.Throws <ArgumentException> (() => SearchQuery.HasFlags(MessageFlags.None));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.HasKeyword(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.HasKeyword(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.HasKeywords(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.HasKeywords(new string[0]));
            Assert.Throws <ArgumentException> (() => SearchQuery.HasKeywords(new string[] { "keyword", null }));
            Assert.Throws <ArgumentException> (() => SearchQuery.NotFlags(MessageFlags.None));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.NotKeyword(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.NotKeyword(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.NotKeywords(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.NotKeywords(new string[0]));
            Assert.Throws <ArgumentException> (() => SearchQuery.NotKeywords(new string [] { "keyword", null }));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.HasGMailLabel(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.HasGMailLabel(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.HeaderContains(null, "text"));
            Assert.Throws <ArgumentException> (() => SearchQuery.HeaderContains(string.Empty, "text"));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.HeaderContains("name", null));
            Assert.Throws <ArgumentOutOfRangeException> (() => SearchQuery.LargerThan(-1));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.MessageContains(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.MessageContains(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.Not(null));
            Assert.Throws <ArgumentOutOfRangeException> (() => SearchQuery.OlderThan(-1));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.Or(null, SearchQuery.All));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.Or(SearchQuery.All, null));
            Assert.Throws <ArgumentOutOfRangeException> (() => SearchQuery.SmallerThan(-1));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.SubjectContains(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.SubjectContains(string.Empty));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.ToContains(null));
            Assert.Throws <ArgumentException> (() => SearchQuery.ToContains(string.Empty));
            Assert.Throws <ArgumentOutOfRangeException> (() => SearchQuery.YoungerThan(-1));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.All.And(null));
            Assert.Throws <ArgumentNullException> (() => SearchQuery.All.Or(null));

            Assert.Throws <ArgumentNullException> (() => new BinarySearchQuery(SearchTerm.And, null, SearchQuery.All));
            Assert.Throws <ArgumentNullException> (() => new BinarySearchQuery(SearchTerm.And, SearchQuery.All, null));
            Assert.Throws <ArgumentNullException> (() => new FilterSearchQuery(null));
            Assert.Throws <ArgumentException> (() => new FilterSearchQuery(string.Empty));
            Assert.Throws <ArgumentException> (() => new FilterSearchQuery(MetadataTag.Create("/dev/null")));
            Assert.Throws <ArgumentNullException> (() => new HeaderSearchQuery(null, "text"));
            Assert.Throws <ArgumentException> (() => new HeaderSearchQuery(string.Empty, "text"));
            Assert.Throws <ArgumentNullException> (() => new HeaderSearchQuery("name", null));
            Assert.Throws <ArgumentNullException> (() => new TextSearchQuery(SearchTerm.BodyContains, null));
            Assert.Throws <ArgumentNullException> (() => new UidSearchQuery(null));
            Assert.Throws <ArgumentException> (() => new UidSearchQuery(new UniqueIdSet()));
            Assert.Throws <ArgumentException> (() => new UidSearchQuery(UniqueId.Invalid));
            Assert.Throws <ArgumentNullException> (() => new UnarySearchQuery(SearchTerm.Not, null));
        }
Example #51
0
        //[Fact(DisplayName = "Payment full integration test - request, pay, receipt, verify")]
        public async Task SendPaymentRequest()
        {
            // Create two agent hosts and establish pairwise connection between them
            var agents = await InProcAgent.CreatePairedAsync(true);

            // Get each agent payment address records
            var paymentAddress1 = await agents.Agent1.Payments.GetDefaultPaymentAddressAsync(agents.Agent1.Context);

            var paymentAddress2 = await agents.Agent2.Payments.GetDefaultPaymentAddressAsync(agents.Agent2.Context);

            // Internal reference number for this payment
            const string paymentReference = "INVOICE# 0001";

            // Setup a basic use case for payments by using basic messages
            // Any AgentMessage can be used to attach payment requests and receipts
            var basicMessage = new BasicMessage {
                Content = "This is payment request"
            };

            // Attach the payment request to the agent message
            var paymentRecord1 = await agents.Agent1.Payments.AttachPaymentRequestAsync(
                context : agents.Agent1.Context,
                agentMessage : basicMessage,
                details : new PaymentDetails
            {
                Id    = paymentReference,
                Items = new List <PaymentItem>
                {
                    new PaymentItem {
                        Label = "Item 1", Amount = 8
                    },
                    new PaymentItem {
                        Label = "Tax", Amount = 2
                    }
                },
                Total = new PaymentItem
                {
                    Amount = new PaymentAmount
                    {
                        Currency = "sov",
                        Value    = 10
                    },
                    Label = "Total"
                }
            },
                payeeAddress : paymentAddress1);

            // PaymentRecord expectations
            Assert.NotNull(paymentRecord1);
            Assert.Equal(10UL, paymentRecord1.Amount);
            Assert.Equal(paymentAddress1.Address, paymentRecord1.Address);
            Assert.Equal(PaymentState.Requested, paymentRecord1.State);

            // Ensure the payment request is attached to the message
            var decorator = basicMessage.FindDecorator <PaymentRequestDecorator>("payment_request");

            Assert.NotNull(decorator);

            // Send the message to agent 2
            await agents.Agent1.Messages.SendAsync(agents.Agent1.Context.Wallet, basicMessage, agents.Connection1);

            // Find the payment record in the context of agent 2
            var search = await agents.Agent2.Records.SearchAsync <PaymentRecord>(
                wallet : agents.Agent2.Context.Wallet,
                query : SearchQuery.And(
                    SearchQuery.Equal(nameof(PaymentRecord.ReferenceId), paymentReference),
                    SearchQuery.Equal(nameof(PaymentRecord.ConnectionId), agents.Connection2.Id)));

            var paymentRecord2 = search.FirstOrDefault();

            Assert.Single(search);
            Assert.NotNull(paymentRecord2);
            Assert.Equal(PaymentState.RequestReceived, paymentRecord2.State);

            // Fund payment address of agent 2 so we can make payment to agent 1
            await FundAccountAsync(50UL, paymentAddress2.Address);

            // Refresh balance to ensure it is funded correctly
            await agents.Agent2.Payments.RefreshBalanceAsync(agents.Agent2.Context, paymentAddress2);

            Assert.Equal(50UL, paymentAddress2.Balance);

            // Make payment for received request
            await agents.Agent2.Payments.MakePaymentAsync(agents.Agent2.Context, paymentRecord2, paymentAddress2);

            Assert.Equal(PaymentState.Paid, paymentRecord2.State);
            Assert.Equal(40UL, paymentAddress2.Balance);
            Assert.NotNull(paymentRecord2.ReceiptId);

            // Send a basic message back to agent 1 and attach a payment receipt
            var message2 = new BasicMessage {
                Content = "Here's a receipt"
            };

            // Attach a payment receipt to the basic message
            // Receipts can be attached to any agent message
            agents.Agent2.Payments.AttachPaymentReceipt(agents.Agent2.Context, message2, paymentRecord2);

            // Send the message to agent 1
            await agents.Agent2.Messages.SendAsync(agents.Agent2.Context.Wallet, message2, agents.Connection2);

            // Fetch payment record 1 again, to refresh state
            paymentRecord1 = await agents.Agent1.Records.GetAsync <PaymentRecord>(agents.Agent1.Context.Wallet, paymentRecord1.Id);

            // Check payment record 1 for receipt

            Assert.Equal(PaymentState.ReceiptReceived, paymentRecord1.State);
            Assert.NotNull(paymentRecord1.ReceiptId);

            // Check agent 1 balance
            await agents.Agent1.Payments.RefreshBalanceAsync(agents.Agent1.Context, paymentAddress1);

            Assert.Equal(10UL, paymentAddress1.Balance);

            // Verify the payment receipt on the ledger
            var verified = await agents.Agent1.Payments.VerifyPaymentAsync(agents.Agent1.Context, paymentRecord1);

            Assert.True(verified);

            // Clean things up and shut down hosts gracefully
            await agents.Agent1.DisposeAsync();

            await agents.Agent2.DisposeAsync();
        }
Example #52
0
 private bool ElementFilter(FactorioObject data, SearchQuery query) => data.Match(query);
 /// ------------------------------------------------------------------------------------
 public CIEOptions()
 {
     SearchQuery = new SearchQuery();
     Type        = IdenticalType.Both;
     CieType     = CIEType.None;
 }
Example #54
0
 /// <summary>
 /// Sends a <see cref="IFtsQuery" /> request to an FTS enabled node and returns the <see cref="ISearchQueryResult" />response.
 /// </summary>
 /// <returns>
 /// A <see cref="ISearchQueryResult" /> representing the response from the FTS service.
 /// </returns>
 /// <exception cref="System.NotImplementedException"></exception>
 public virtual ISearchQueryResult SendWithRetry(SearchQuery searchQuery)
 {
     throw new NotImplementedException();
 }
Example #55
0
        public static SearchResultsViewModel SearchWithSuggestions(SearchQuery searchQuery, bool suggestOnlyWhenNoResults = false)
        {
            var ret = new SearchResultsViewModel
            {
                SearchResults = new List <SearchResultsViewModel.SearchResult>(PageSize), Query = searchQuery
            };

            // Parse query, possibly throwing a ParseException
            Query query;

            if (searchQuery.TitlesOnly)
            {
                var qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Title",
                                         new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)
                                         );
                query = qp.Parse(searchQuery.Query);
            }
            else
            {
                query = MultiFieldQueryParser.Parse(Lucene.Net.Util.Version.LUCENE_29, searchQuery.Query,
                                                    SearchFields, SearchFlags,
                                                    new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)
                                                    );
            }

            // Perform the actual search
            var tsdc = TopScoreDocCollector.create(PageSize * searchQuery.CurrentPage, true);

            Searcher.Search(query, tsdc);
            ret.TotalResults = tsdc.GetTotalHits();
            var hits = tsdc.TopDocs().ScoreDocs;

            // Do the suggestion magic
            if (suggestOnlyWhenNoResults && ret.TotalResults == 0 || (!suggestOnlyWhenNoResults))
            {
                ret.Suggestions = new List <string>();
                var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(Searcher.GetIndexReader().Directory());

                // This is kind of a hack to get things working quickly
                // for real-world usage we probably want to get the analyzed terms from the Query object
                var individualTerms = searchQuery.Query.Split(new[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var term in individualTerms)
                {
                    // we only specify field name if we actually got results,
                    // to improve suggestions relevancy
                    ret.Suggestions.AddRange(spellChecker.SuggestSimilar(term,
                                                                         searchQuery.MaxSuggestions,
                                                                         null,
                                                                         ret.TotalResults == 0 ? null : "Title",
                                                                         true));
                }
            }

            // Init the highlighter instance
            var fvh = new FastVectorHighlighter(FastVectorHighlighter.DEFAULT_PHRASE_HIGHLIGHT,
                                                FastVectorHighlighter.DEFAULT_FIELD_MATCH,
                                                new SimpleFragListBuilder(),
                                                new ScoreOrderFragmentsBuilder(new[] { "[b]" }, new[] { "[/b]" }));


            int i;

            for (i = (searchQuery.CurrentPage - 1) * PageSize; i < hits.Length; ++i)
            {
                var d        = Searcher.Doc(hits[i].doc);
                var fq       = fvh.GetFieldQuery(query);
                var fragment = fvh.GetBestFragment(fq, Searcher.GetIndexReader(),
                                                   hits[i].doc, "Content", 400);

                ret.SearchResults.Add(new SearchResultsViewModel.SearchResult
                {
                    Id          = d.Get("Id"),
                    Title       = d.Get("Title"),
                    Score       = hits[i].score,
                    LuceneDocId = hits[i].doc,
                    Fragment    = MvcHtmlString.Create(fragment.HtmlStripFragment()),
                });
            }
            return(ret);
        }
Example #56
0
 public IEnumerable <SyndicationItem> Search(SearchQuery query)
 {
     throw new NotImplementedException();
 }
Example #57
0
 protected abstract Task <ImmutableArray <ISymbol> > FindDeclarationsAsync(SymbolFilter filter, SearchQuery query);
        public async Task <ActionResult <List <Article> > > Search([FromBody] SearchQuery searchQuery)
        {
            var articles = await _articleService.Search(searchQuery);

            return(articles);
        }
Example #59
0
        /// <summary>
        /// Queries the RMS Classic database using the given SearchQuery and performs field-level
        /// comparisons against the query data. Each result's total aggregate confidence rating is
        /// computed before being yielded to the iterator along with the master link. Only results
        /// that cross the search confidence threshold are returned.
        /// </summary>
        private IEnumerable <SearchResult> GetSearchResults(SearchQuery query)
        {
            //Boolean streetAddress = false;  //used for reverse interesction

            // Connect to RMS Classic with a data reader for low-level, very fast access.
            string connectionString = AppConfig.GetConnectionString(AppConfig.KnownConnectionStrings.VsiData);
            string dbQuery          = GenerateSqlQuery(query);

            //string reversedValue = "";

            using (var ctx = new SqlConnection(connectionString))
            {
                try
                {
                    ctx.Open();
                    SqlCommand command = ctx.CreateCommand();
                    command.CommandText = dbQuery;
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var ruleResults = new List <SearchResult>();
                            foreach (var ruleSet in query.RuleSets.OrderBy(r => (int)r.Priority))
                            {
                                var result = new SearchResult()
                                {
                                    Priority = ruleSet.Priority, Fields = new List <SearchResultField>()
                                };


                                foreach (var field in ruleSet.Fields)
                                {
                                    // Get the corresponding database field as a string.
                                    string dbData      = reader.GetValue(reader.GetOrdinal(field.ColumnName)).ToString();
                                    var    resultField = new SearchResultField()
                                    {
                                        Name = field.Name, Value = dbData
                                    };

                                    // Convert to empty string if null.
                                    field.QueryValue = field.QueryValue ?? "";

                                    // If the query doesn't provide the property, then don't do the comparison.
                                    if (!String.IsNullOrWhiteSpace(field.QueryValue) || field.Required)
                                    {
                                        double comparison = EvaluateFieldRules(field.QueryValue.ToLower().Trim(),
                                                                               dbData.ToLower().Trim(),
                                                                               field.SearchType);

                                        // Apply field weight.
                                        resultField.Confidence = comparison * field.Weight;
                                    }
                                    result.Fields.Add(resultField);

                                    if (resultField.Confidence < 1)           //don't invert if record found
                                    {
                                        if (IsIntersection(field.QueryValue)) //only intersections may pass
                                        {
                                            field.QueryValue = ReverseIntersection(field.QueryValue);

                                            // If the query doesn't provide the property, then don't do the comparison.
                                            if (!String.IsNullOrWhiteSpace(field.QueryValue) || field.Required)
                                            {
                                                double comparison = EvaluateFieldRules(field.QueryValue.ToLower().Trim(),
                                                                                       dbData.ToLower().Trim(),
                                                                                       field.SearchType);

                                                // Apply field weight.
                                                resultField.Confidence = comparison * field.Weight;
                                            }
                                            result.Fields.Add(resultField);
                                        }
                                    }
                                }// foreach (var field in ruleSet.Fields) - end

                                // Calculate the total confidence.
                                // Note: Crossing the confidence threshold means that a match was found, thus, no
                                // more rule sets need to be run.
                                result.Confidence = NullAverage(result.Fields.Select(f => f.Confidence));
                                ruleResults.Add(result);

                                if (result.Confidence >= query.ConfidenceThreshold)
                                {
                                    break;
                                }
                            } // foreach (var ruleSet in query.RuleSets.OrderBy(r => (int)r.Priority)) - end
                            yield return(ruleResults.OrderByDescending(r => r.Confidence).FirstOrDefault());
                        }     // while (reader.Read()) - end
                    }         // using (SqlDataReader reader = command.ExecuteReader()) - end
                }             // try - end
                finally
                {
                    ctx.Close();
                }
            }
        }
Example #60
0
        internal static ISpanBuilder BuildSpan(this ITracer tracer, SearchQuery query)
        {
            const string operationName = "fts";

            return(tracer.BuildSpan(query, operationName));
        }