Ejemplo n.º 1
0
        public async Task<SearchResults> Search(SearchFilter filter)
        {
            // Convert the query
            string query = BuildLuceneQuery(filter.SearchTerm);

            // Query!
            var result = await _client.Search(
                query,
                projectTypeFilter: null,
                includePrerelease: filter.IncludePrerelease,
                curatedFeed: filter.CuratedFeed == null ? null : filter.CuratedFeed.Name,
                sortBy: filter.SortOrder,
                skip: filter.Skip,
                take: filter.Take,
                isLuceneQuery: true,
                countOnly: filter.CountOnly,
                explain: false,
                getAllVersions: false);

            result.HttpResponse.EnsureSuccessStatusCode();
            var content = await result.ReadContent();
            if (filter.CountOnly || content.TotalHits == 0)
            {
                return new SearchResults(content.TotalHits);
            }
            return new SearchResults(
                content.TotalHits, 
                content.Data.Select(ReadPackage).AsQueryable());
        }
Ejemplo n.º 2
0
 public SavedFilter(string name, SearchFilter filter, int depth, float previewSize)
 {
   this.m_Name = name;
   this.m_Depth = depth;
   this.m_Filter = filter;
   this.m_PreviewSize = previewSize;
 }
Ejemplo n.º 3
0
        public static SearchFilter GetSearchFilter(string q, int page, string sortOrder, string context)
        {
            var searchFilter = new SearchFilter(context)
            {
                SearchTerm = q,
                Skip = (page - 1) * Constants.DefaultPackageListPageSize, // pages are 1-based. 
                Take = Constants.DefaultPackageListPageSize,
                IncludePrerelease = true
            };

            switch (sortOrder)
            {
                case Constants.AlphabeticSortOrder:
                    searchFilter.SortOrder = SortOrder.TitleAscending;
                    break;

                case Constants.RecentSortOrder:
                    searchFilter.SortOrder = SortOrder.Published;
                    break;

                default:
                    searchFilter.SortOrder = SortOrder.Relevance;
                    break;
            }

            return searchFilter;
        }
Ejemplo n.º 4
0
        public async Task<IEnumerable<SiteExtensionInfo>> GetRemoteExtensions(string filter, bool allowPrereleaseVersions, string feedUrl)
        {
            ITracer tracer = _traceFactory.GetTracer();
            var extensions = new List<SiteExtensionInfo>();
            SourceRepository remoteRepo = GetRemoteRepository(feedUrl);

            SearchFilter filterOptions = new SearchFilter();
            filterOptions.IncludePrerelease = allowPrereleaseVersions;

            IEnumerable<UIPackageMetadata> packages = null;

            using (tracer.Step("Search site extensions by filter: {0}", filter))
            {
                packages = (await remoteRepo.Search(string.IsNullOrWhiteSpace(filter) ? string.Empty : filter, filterOptions: filterOptions))
                            .OrderByDescending(p => p.DownloadCount);
            }

            using (tracer.Step("Convert search result to SiteExtensionInfos"))
            {
                var convertedResult = await ConvertNuGetPackagesToSiteExtensionInfos(
                    packages,
                    async (uiPackage) =>
                    {
                        return await ConvertRemotePackageToSiteExtensionInfo(uiPackage, feedUrl);
                    });

                extensions.AddRange(convertedResult);
            }

            return extensions;
        }
 internal static SearchFilter CreateFilter(string searchString, SearchableEditorWindow.SearchMode searchMode)
 {
   SearchFilter filter = new SearchFilter();
   if (string.IsNullOrEmpty(searchString))
     return filter;
   switch (searchMode)
   {
     case SearchableEditorWindow.SearchMode.All:
       if (!SearchUtility.ParseSearchString(searchString, filter))
       {
         filter.nameFilter = searchString;
         filter.classNames = new string[1]{ searchString };
         filter.assetLabels = new string[1]{ searchString };
         filter.assetBundleNames = new string[1]{ searchString };
         filter.showAllHits = true;
         break;
       }
       break;
     case SearchableEditorWindow.SearchMode.Name:
       filter.nameFilter = searchString;
       break;
     case SearchableEditorWindow.SearchMode.Type:
       filter.classNames = new string[1]{ searchString };
       break;
     case SearchableEditorWindow.SearchMode.Label:
       filter.assetLabels = new string[1]{ searchString };
       break;
     case SearchableEditorWindow.SearchMode.AssetBundleName:
       filter.assetBundleNames = new string[1]{ searchString };
       break;
   }
   return filter;
 }
 public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dropPos)
 {
     if (targetItem == null)
     {
         return DragAndDropVisualMode.None;
     }
     object genericData = DragAndDrop.GetGenericData(ProjectWindowUtil.k_DraggingFavoriteGenericData);
     if (genericData != null)
     {
         int instanceID = (int) genericData;
         if ((targetItem is SearchFilterTreeItem) && (parentItem is SearchFilterTreeItem))
         {
             bool flag = SavedSearchFilters.CanMoveSavedFilter(instanceID, parentItem.id, targetItem.id, dropPos == TreeViewDragging.DropPosition.Below);
             if (flag && perform)
             {
                 SavedSearchFilters.MoveSavedFilter(instanceID, parentItem.id, targetItem.id, dropPos == TreeViewDragging.DropPosition.Below);
                 int[] selectedIDs = new int[] { instanceID };
                 base.m_TreeView.SetSelection(selectedIDs, false);
                 base.m_TreeView.NotifyListenersThatSelectionChanged();
             }
             return (!flag ? DragAndDropVisualMode.None : DragAndDropVisualMode.Copy);
         }
         return DragAndDropVisualMode.None;
     }
     if ((targetItem is SearchFilterTreeItem) && (parentItem is SearchFilterTreeItem))
     {
         string str = DragAndDrop.GetGenericData(ProjectWindowUtil.k_IsFolderGenericData) as string;
         if (str != "isFolder")
         {
             return DragAndDropVisualMode.None;
         }
         if (perform)
         {
             Object[] objectReferences = DragAndDrop.objectReferences;
             if (objectReferences.Length > 0)
             {
                 string assetPath = AssetDatabase.GetAssetPath(objectReferences[0].GetInstanceID());
                 if (!string.IsNullOrEmpty(assetPath))
                 {
                     string name = new DirectoryInfo(assetPath).Name;
                     SearchFilter filter = new SearchFilter();
                     filter.folders = new string[] { assetPath };
                     bool addAsChild = targetItem == parentItem;
                     float listAreaGridSize = ProjectBrowserColumnOneTreeViewGUI.GetListAreaGridSize();
                     int num3 = SavedSearchFilters.AddSavedFilterAfterInstanceID(name, filter, listAreaGridSize, targetItem.id, addAsChild);
                     int[] numArray2 = new int[] { num3 };
                     base.m_TreeView.SetSelection(numArray2, false);
                     base.m_TreeView.NotifyListenersThatSelectionChanged();
                 }
                 else
                 {
                     Debug.Log("Could not get asset path from id " + objectReferences[0].GetInstanceID());
                 }
             }
         }
         return DragAndDropVisualMode.Copy;
     }
     return base.DoDrag(parentItem, targetItem, perform, dropPos);
 }
Ejemplo n.º 7
0
 private void AddSearchFilter (TrackFilterType id, string field, string title)
 {
     SearchFilter filter = new SearchFilter ();
     filter.Id = (int)id;
     filter.Field = field;
     filter.Title = title;
     search_filters.Add (filter.Id, filter);
 }
 internal virtual void BeginCreateSavedFilter(SearchFilter filter)
 {
     string displayName = "New Saved Search";
     this.m_IsCreatingSavedFilter = true;
     int id = SavedSearchFilters.AddSavedFilter(displayName, filter, GetListAreaGridSize());
     base.m_TreeView.Frame(id, true, false);
     base.m_TreeView.state.renameOverlay.BeginRename(displayName, id, 0f);
 }
 public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dropPos)
 {
     if (targetItem == null)
     {
         return DragAndDropVisualMode.None;
     }
     object genericData = DragAndDrop.GetGenericData(ProjectWindowUtil.k_DraggingFavoriteGenericData);
     if (genericData != null)
     {
         int instanceID = (int) genericData;
         if (!(targetItem is SearchFilterTreeItem) || !(parentItem is SearchFilterTreeItem))
         {
             return DragAndDropVisualMode.None;
         }
         bool flag = SavedSearchFilters.CanMoveSavedFilter(instanceID, parentItem.id, targetItem.id, true);
         if (flag && perform)
         {
             SavedSearchFilters.MoveSavedFilter(instanceID, parentItem.id, targetItem.id, true);
         }
         return (!flag ? DragAndDropVisualMode.None : DragAndDropVisualMode.Copy);
     }
     if (!(targetItem is SearchFilterTreeItem) || !(parentItem is SearchFilterTreeItem))
     {
         return base.DoDrag(parentItem, targetItem, perform, dropPos);
     }
     string str = DragAndDrop.GetGenericData(ProjectWindowUtil.k_IsFolderGenericData) as string;
     if (!(str == "isFolder"))
     {
         return DragAndDropVisualMode.None;
     }
     if (perform)
     {
         UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences;
         if (objectReferences.Length > 0)
         {
             HierarchyProperty property = new HierarchyProperty(HierarchyType.Assets);
             if (property.Find(objectReferences[0].GetInstanceID(), null))
             {
                 SearchFilter filter = new SearchFilter();
                 string assetPath = AssetDatabase.GetAssetPath(property.instanceID);
                 if (!string.IsNullOrEmpty(assetPath))
                 {
                     filter.folders = new string[] { assetPath };
                     bool addAsChild = targetItem == parentItem;
                     float listAreaGridSize = ProjectBrowserColumnOneTreeViewGUI.GetListAreaGridSize();
                     Selection.activeInstanceID = SavedSearchFilters.AddSavedFilterAfterInstanceID(property.name, filter, listAreaGridSize, targetItem.id, addAsChild);
                 }
                 else
                 {
                     Debug.Log("Could not get asset path from id " + property.name);
                 }
             }
         }
     }
     return DragAndDropVisualMode.Copy;
 }
Ejemplo n.º 10
0
 private void FilterSettingsChanged()
 {
     SearchFilter searchFilter = new SearchFilter();
     searchFilter.SearchFieldStringToFilter(this.m_SearchFilter);
     if (!string.IsNullOrEmpty(this.m_RequiredType))
     {
         searchFilter.classNames = new string[] { this.m_RequiredType };
     }
     this.m_ListArea.Init(this.listPosition, !this.m_IsShowingAssets ? HierarchyType.GameObjects : HierarchyType.Assets, searchFilter, true);
 }
Ejemplo n.º 11
0
        private static async Task<IQueryable<Package>> GetRawResultsFromSearchService(ISearchService searchService, SearchFilter searchFilter)
        {
            var externalSearchService = searchService as ExternalSearchService;
            if (externalSearchService != null)
            {
                var result = await externalSearchService.RawSearch(searchFilter);
                return FormatResults(searchFilter, result);
            }

            return await GetResultsFromSearchService(searchService, searchFilter);
        }
Ejemplo n.º 12
0
 public ActionResult Index(SearchFilter filter)
 {
     if (ModelState.IsValid)
     {
         FileSearchResult result = _searchService.GetFile(filter);
         if(result != null)
             return PartialView("SearchResult",result);
         ModelState.AddModelError("", ErrorResources.NotFound);
     }
     return PartialView(filter);
 }
Ejemplo n.º 13
0
 internal void SetSearchFilter(SearchFilter filter)
 {
     if (UnityConnect.instance.userInfo.whitelisted && Collab.instance.collabInfo.whitelisted)
     {
         this.SetSearchFilterINTERNAL(SearchFilter.Split(filter.nameFilter), filter.classNames, filter.assetLabels, filter.assetBundleNames, filter.versionControlStates, filter.referencingInstanceIDs, filter.scenePaths, filter.showAllHits);
     }
     else
     {
         this.SetSearchFilterINTERNAL(SearchFilter.Split(filter.nameFilter), filter.classNames, filter.assetLabels, filter.assetBundleNames, new string[0], filter.referencingInstanceIDs, filter.scenePaths, filter.showAllHits);
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Query result by search term, always include pre-released
        /// </summary>
        public static async Task<IEnumerable<UISearchMetadata>> Search(this SourceRepository srcRepo, string searchTerm, SearchFilter filterOptions = null, int skip = 0, int take = 1000)
        {
            // always include pre-release package
            if (filterOptions == null)
            {
                filterOptions = new SearchFilter();
            }

            filterOptions.IncludePrerelease = true; // keep the good old behavior
            var searchResource = await srcRepo.GetResourceAsync<UISearchResource>();
            return await searchResource.Search(searchTerm, filterOptions, skip, take, CancellationToken.None);
        }
        private async Task<SearchResults> SearchCore(SearchFilter filter, bool raw)
        {
            // Query!
            var sw = new Stopwatch();
            sw.Start();
            var result = await _client.Search(
                filter.SearchTerm,
                projectTypeFilter: null,
                includePrerelease: filter.IncludePrerelease,
                curatedFeed: filter.CuratedFeed == null ? null : filter.CuratedFeed.Name,
                sortBy: filter.SortOrder,
                skip: filter.Skip,
                take: filter.Take,
                isLuceneQuery: raw,
                countOnly: filter.CountOnly,
                explain: false,
                getAllVersions: filter.IncludeAllVersions);
			sw.Stop();

            SearchResults results = null;
            if (result.IsSuccessStatusCode)
            {
                var content = await result.ReadContent();
                if (filter.CountOnly || content.TotalHits == 0)
                {
                    results = new SearchResults(content.TotalHits);
                }
                else
                {
                    results = new SearchResults(
                        content.TotalHits,
                        content.Data.Select(ReadPackage).AsQueryable());
                }
            }

            Trace.PerfEvent(
                SearchRoundtripTimePerfCounter,
                sw.Elapsed,
                new Dictionary<string, object>() {
                    {"Term", filter.SearchTerm},
                    {"Context", filter.Context},
                    {"Raw", raw},
                    {"Hits", results == null ? -1 : results.Hits},
                    {"StatusCode", (int)result.StatusCode},
                    {"SortOrder", filter.SortOrder.ToString()},
                    {"CuratedFeed", filter.CuratedFeed == null ? null : filter.CuratedFeed.Name},
                    {"Url", TryGetUrl()}
                });

            result.HttpResponse.EnsureSuccessStatusCode();
            return results;
        }
Ejemplo n.º 16
0
		internal static bool ParseSearchString(string searchText, SearchFilter filter)
		{
			if (string.IsNullOrEmpty(searchText))
			{
				return false;
			}
			filter.ClearSearch();
			string text = string.Copy(searchText);
			SearchUtility.RemoveUnwantedWhitespaces(ref text);
			bool result = false;
			int i = SearchUtility.FindFirstPositionNotOf(text, " \t,");
			if (i == -1)
			{
				i = 0;
			}
			while (i < text.Length)
			{
				int num = text.IndexOfAny(" \t,".ToCharArray(), i);
				int num2 = text.IndexOf('"', i);
				int num3 = -1;
				if (num2 != -1)
				{
					num3 = text.IndexOf('"', num2 + 1);
					if (num3 != -1)
					{
						num = text.IndexOfAny(" \t,".ToCharArray(), num3);
					}
					else
					{
						num = -1;
					}
				}
				if (num == -1)
				{
					num = text.Length;
				}
				if (num > i)
				{
					string text2 = text.Substring(i, num - i);
					if (SearchUtility.ParseSingleWord(text2, filter, num2, num3))
					{
						result = true;
					}
					else
					{
						filter.nameFilter = filter.nameFilter + ((!string.IsNullOrEmpty(filter.nameFilter)) ? " " : string.Empty) + text2;
					}
				}
				i = num + 1;
			}
			return result;
		}
Ejemplo n.º 17
0
 internal static bool ParseSearchString(string searchText, SearchFilter filter)
 {
     if (string.IsNullOrEmpty(searchText))
     {
         return false;
     }
     filter.ClearSearch();
     string searchString = string.Copy(searchText);
     RemoveUnwantedWhitespaces(ref searchString);
     bool flag = false;
     int startIndex = FindFirstPositionNotOf(searchString, " \t,");
     if (startIndex == -1)
     {
         startIndex = 0;
     }
     while (startIndex < searchString.Length)
     {
         int length = searchString.IndexOfAny(" \t,".ToCharArray(), startIndex);
         int index = searchString.IndexOf('"', startIndex);
         int num4 = -1;
         if (index != -1)
         {
             num4 = searchString.IndexOf('"', index + 1);
             if (num4 != -1)
             {
                 length = searchString.IndexOfAny(" \t,".ToCharArray(), num4);
             }
             else
             {
                 length = -1;
             }
         }
         if (length == -1)
         {
             length = searchString.Length;
         }
         if (length > startIndex)
         {
             string str3 = searchString.Substring(startIndex, length - startIndex);
             if (ParseSingleWord(str3, filter, index, num4))
             {
                 flag = true;
             }
             else
             {
                 filter.nameFilter = filter.nameFilter + (!string.IsNullOrEmpty(filter.nameFilter) ? " " : string.Empty) + str3;
             }
         }
         startIndex = length + 1;
     }
     return flag;
 }
Ejemplo n.º 18
0
 private static List<UnityEngine.Object> FindAssetsOfType(string[] classNames)
 {
     HierarchyProperty property = new HierarchyProperty(HierarchyType.Assets);
     SearchFilter filter = new SearchFilter {
         classNames = classNames
     };
     property.SetSearchFilter(filter);
     List<UnityEngine.Object> list = new List<UnityEngine.Object>();
     while (property.Next(null))
     {
         list.Add(property.pptrValue);
     }
     return list;
 }
Ejemplo n.º 19
0
        public Entities.Event GetEventByName(string eventName)
        {
            var eventNameFilter = new SearchFilter<Entities.Event>
                                      {
                                          Conditional = SearchConditional.Equals,
                                          PropertyName = "Name",
                                          PropertyValue = eventName
                                      };

            var eventSearchCriteria = new EventsSearchCriteria
                                          {
                                              Filters = new List<SearchFilter<Entities.Event>> {eventNameFilter}
                                          };
            return Repository.List<Entities.Event>(eventSearchCriteria.BuildCriteria()).FirstOrDefault();
        }
 /// <summary>
 /// Tries to read element from XML.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <returns>True if element was read.</returns>
 internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
 {
     switch (reader.LocalName)
     {
         case XmlElementNames.BaseFolderIds:
             this.RootFolderIds.InternalClear();
             this.RootFolderIds.LoadFromXml(reader, reader.LocalName);
             return true;
         case XmlElementNames.Restriction:
             reader.Read();
             this.searchFilter = SearchFilter.LoadFromXml(reader);
             return true;
         default:
             return false;
     }
 }
Ejemplo n.º 21
0
        private static IQueryable<Package> FormatResults(SearchFilter searchFilter, SearchResults result)
        {
            // For count queries, we can ask the SearchService to not filter the source results. This would avoid hitting the database and consequently make it very fast.
            if (searchFilter.CountOnly)
            {
                // At this point, we already know what the total count is. We can have it return this value very quickly without doing any SQL.
                return result.Data.InterceptWith(new CountInterceptor(result.Hits));
            }

            // For relevance search, Lucene returns us a paged/sorted list. OData tries to apply default ordering and Take / Skip on top of this.
            // It also tries to filter to latest versions, but the search service already did that!
            // We avoid it by yanking these expressions out of out the tree.
            return result.Data
                .InterceptWith(new CountInterceptor(result.Hits))
                .InterceptWith(new DisregardODataInterceptor());
        }
Ejemplo n.º 22
0
        public SearchFilter GetSearchFilterForNode(NodeContent nodeContent)
        {
            var configFilter = new SearchFilter
            {
                field = BaseCatalogIndexBuilder.FieldConstants.Node,
                Descriptions = new Descriptions
                {
                    defaultLocale = _preferredCulture.Name
                },
                Values = new SearchFilterValues()
            };

            var desc = new Description
            {
                locale = "en",
                Value = _localizationService.GetString("/Facet/Category")
            };
            configFilter.Descriptions.Description = new[] { desc };

            var nodes = _contentLoader.GetChildren<NodeContent>(nodeContent.ContentLink).ToList();
            var nodeValues = new SimpleValue[nodes.Count];
            var index = 0;
            foreach (var node in nodes)
            {
                var val = new SimpleValue
                {
                    key = node.Code,
                    value = node.Code,
                    Descriptions = new Descriptions
                    {
                        defaultLocale = _preferredCulture.Name
                    }
                };
                var desc2 = new Description
                {
                    locale = _preferredCulture.Name,
                    Value = node.DisplayName
                };
                val.Descriptions.Description = new[] { desc2 };

                nodeValues[index] = val;
                index++;
            }
            configFilter.Values.SimpleValue = nodeValues;
            return configFilter;
        }
Ejemplo n.º 23
0
 public virtual PostalCodeResult BrowsePostalCodeListByFilter(SearchFilter obj)
 {
     PostalCodeResult result = new PostalCodeResult();
     result.page = obj.page;
     result.page_size = obj.page_size;
     DataSet ds = data.BrowsePostalCodeListByFilter(obj);
     if(ds != null) {
         foreach(DataTable dt in ds.Tables){
             foreach(DataRow dr in dt.Rows){
                PostalCode postal_code  = FillPostalCode(dr);
                 result.data.Add(postal_code);
                 if (dr["total_rows"] != null)
                     result.total_rows = dataType.FillDataInt(dr, "total_rows");
             }
         }
     }
     return result;
 }
Ejemplo n.º 24
0
 public virtual AppTypeResult BrowseAppTypeListByFilter(SearchFilter obj)
 {
     AppTypeResult result = new AppTypeResult();
     result.page = obj.page;
     result.page_size = obj.page_size;
     DataSet ds = data.BrowseAppTypeListByFilter(obj);
     if(ds != null) {
         foreach(DataTable dt in ds.Tables){
             foreach(DataRow dr in dt.Rows){
                AppType app_type  = FillAppType(dr);
                 result.data.Add(app_type);
                 if (dr["total_rows"] != null)
                     result.total_rows = dataType.FillDataInt(dr, "total_rows");
             }
         }
     }
     return result;
 }
Ejemplo n.º 25
0
 public virtual ChannelResult BrowseChannelListByFilter(SearchFilter obj)
 {
     ChannelResult result = new ChannelResult();
     result.page = obj.page;
     result.page_size = obj.page_size;
     DataSet ds = data.BrowseChannelListByFilter(obj);
     if(ds != null) {
         foreach(DataTable dt in ds.Tables){
             foreach(DataRow dr in dt.Rows){
                Channel channel  = FillChannel(dr);
                 result.data.Add(channel);
                 if (dr["total_rows"] != null)
                     result.total_rows = dataType.FillDataInt(dr, "total_rows");
             }
         }
     }
     return result;
 }
Ejemplo n.º 26
0
 private void FilterSettingsChanged()
 {
     SearchFilter searchFilter = new SearchFilter();
     searchFilter.SearchFieldStringToFilter(this.m_SearchFilter);
     if (!string.IsNullOrEmpty(this.m_RequiredType))
     {
         searchFilter.classNames = new string[] { this.m_RequiredType };
     }
     HierarchyType hierarchyType = !this.m_IsShowingAssets ? HierarchyType.GameObjects : HierarchyType.Assets;
     if ((EditorSceneManager.preventCrossSceneReferences && (hierarchyType == HierarchyType.GameObjects)) && (this.m_ObjectBeingEdited != null))
     {
         Scene sceneFromObject = this.GetSceneFromObject(this.m_ObjectBeingEdited);
         if (sceneFromObject.IsValid())
         {
             searchFilter.scenePaths = new string[] { sceneFromObject.path };
         }
     }
     this.m_ListArea.Init(this.listPosition, hierarchyType, searchFilter, true);
 }
Ejemplo n.º 27
0
        public override Task<IEnumerable<JObject>> Search(string searchTerm, SearchFilter filters, int skip, int take, CancellationToken cancellationToken)
        {
            NuGetTraceSources.V2SourceRepository.Verbose("search", "Searching for '{0}'", searchTerm);
            return Task.Factory.StartNew(() =>
            {
                var query = _repository.Search(
                    searchTerm,
                    filters.SupportedFrameworks,
                    filters.IncludePrerelease,
                    filters.IncludeDelisted);

                // V2 sometimes requires that we also use an OData filter for latest/latest prerelease version
                if (filters.IncludePrerelease)
                {
                    query = query.Where(p => p.IsAbsoluteLatestVersion);
                }
                else
                {
                    query = query.Where(p => p.IsLatestVersion);
                }

                if (_repository is LocalPackageRepository)
                {
                    // if the repository is a local repo, then query contains all versions of packages.
                    // we need to explicitly select the latest version.
                    query = query.OrderBy(p => p.Id)
                        .ThenByDescending(p => p.Version)
                        .GroupBy(p => p.Id)
                        .Select(g => g.First());
                }

                // Now apply skip and take and the rest of the party
                return (IEnumerable<JObject>)query
                    .Skip(skip)
                    .Take(take)
                    .ToList()
                    .AsParallel()
                    .AsOrdered()
                    .Select(p => CreatePackageSearchResult(p, cancellationToken))
                    .ToList();
            }, cancellationToken);
        }
Ejemplo n.º 28
0
 internal static bool ParseSearchString(string searchText, SearchFilter filter)
 {
   if (string.IsNullOrEmpty(searchText))
     return false;
   filter.ClearSearch();
   string searchString1 = string.Copy(searchText);
   SearchUtility.RemoveUnwantedWhitespaces(ref searchString1);
   bool flag = false;
   int startIndex = SearchUtility.FindFirstPositionNotOf(searchString1, " \t,");
   if (startIndex == -1)
     startIndex = 0;
   int num1;
   for (; startIndex < searchString1.Length; startIndex = num1 + 1)
   {
     num1 = searchString1.IndexOfAny(" \t,".ToCharArray(), startIndex);
     int quote1 = searchString1.IndexOf('"', startIndex);
     int num2 = -1;
     if (quote1 != -1)
     {
       num2 = searchString1.IndexOf('"', quote1 + 1);
       num1 = num2 == -1 ? -1 : searchString1.IndexOfAny(" \t,".ToCharArray(), num2);
     }
     if (num1 == -1)
       num1 = searchString1.Length;
     if (num1 > startIndex)
     {
       string searchString2 = searchString1.Substring(startIndex, num1 - startIndex);
       if (SearchUtility.CheckForKeyWords(searchString2, filter, quote1, num2))
       {
         flag = true;
       }
       else
       {
         SearchFilter searchFilter = filter;
         string str = searchFilter.nameFilter + (!string.IsNullOrEmpty(filter.nameFilter) ? " " : string.Empty) + searchString2;
         searchFilter.nameFilter = str;
       }
     }
   }
   return flag;
 }
        public Task<IEnumerable<VisualStudioUISearchMetadata>> GetSearchResultsForVisualStudioUI(string searchTerm, SearchFilter filters, int skip, int take, System.Threading.CancellationToken cancellationToken)
        {
            return Task.Factory.StartNew(() =>
            {
                var query = V2Client.Search(
                    searchTerm,
                    filters.SupportedFrameworks,
                    filters.IncludePrerelease,
                    filters.IncludeDelisted);

                // V2 sometimes requires that we also use an OData filter for latest/latest prerelease version
                if (filters.IncludePrerelease)
                {
                    query = query.Where(p => p.IsAbsoluteLatestVersion);
                }
                else
                {
                    query = query.Where(p => p.IsLatestVersion);
                }

                if (V2Client is LocalPackageRepository)
                {
                    // if the repository is a local repo, then query contains all versions of packages.
                    // we need to explicitly select the latest version.
                    query = query.OrderBy(p => p.Id)
                        .ThenByDescending(p => p.Version)
                        .GroupBy(p => p.Id)
                        .Select(g => g.First());
                }

                // Now apply skip and take and the rest of the party
                return (IEnumerable<VisualStudioUISearchMetadata>)query
                    .Skip(skip)
                    .Take(take)
                    .ToList()
                    .AsParallel()
                    .AsOrdered()
                    .Select(p => CreatePackageSearchResult(p, cancellationToken))
                    .ToList();
            }, cancellationToken);
        }
Ejemplo n.º 30
0
        public ActionResult Index(SearchFilter filter, int page = 1)
        {
            //page = page == 0 ?  1 : page;

            const int pageSize = 10;
            var viewModel = new ViewModel();

            var list = Builder<Data>.CreateListOfSize(100).Build();
            //var pagedList = list.Where(x => x.Name.Contains(filter.Name)).AsPagination(pageNumber, pageSize);
            var pagedList = list.AsPagination(page, pageSize);

            viewModel.List = pagedList;
            viewModel.SearchFilter = filter ?? new SearchFilter();
            viewModel.Test = "HAHAHAH";
            if (Request.IsAjaxRequest())
            {
                return PartialView("Partial/PagedGrid", viewModel);
            }

            return View(viewModel);
        }
 // GET api/<controller>
 /// <summary>
 /// Gets this instance.
 /// </summary>
 /// <returns></returns>
 public T_COM_Master_LocationCollection Post(string method, [FromBody] SearchFilter value)
 {
     return(T_COM_Master_LocationManager.Search(value));
 }
Ejemplo n.º 32
0
            public Task <SearchResult <IPackageSearchMetadata> > SearchAsync(string searchText, SearchFilter filter, CancellationToken cancellationToken)
            {
                var results = new SearchResult <IPackageSearchMetadata>
                {
                    RefreshToken       = new RefreshToken {
                    },
                    SourceSearchStatus = new Dictionary <string, LoadingStatus> {
                        { "test", LoadingStatus.Loading }
                    }
                };

                return(Task.FromResult(results));
            }
Ejemplo n.º 33
0
        /// <summary>
        /// Basic search
        /// </summary>
        public override async Task <IEnumerable <SimpleSearchMetadata> > Search(string searchTerm, SearchFilter filters, int skip, int take, CancellationToken cancellationToken)
        {
            var results = new List <SimpleSearchMetadata>();

            foreach (var result in await _rawSearch.Search(searchTerm, filters, skip, take, cancellationToken))
            {
                var version  = NuGetVersion.Parse(result["version"].ToString());
                var identity = new PackageIdentity(result["id"].ToString(), version);

                var description = result["description"].ToString();

                var allVersions = new List <NuGetVersion>();

                foreach (var versionObj in ((JArray)result["versions"]))
                {
                    allVersions.Add(NuGetVersion.Parse(versionObj["version"].ToString()));
                }

                var data = new SimpleSearchMetadata(identity, description, allVersions);

                results.Add(data);
            }

            return(results);
        }
Ejemplo n.º 34
0
 private static async Task <SearchResults> GetResultsFromSearchService(ISearchService searchService, SearchFilter searchFilter)
 {
     return(await searchService.Search(searchFilter));
 }
Ejemplo n.º 35
0
 public abstract Task <IEnumerable <PSSearchMetadata> > Search(string search, SearchFilter filters, int skip, int take, CancellationToken token);
        public async Task <IEnumerable <IPackageSearchMetadata> > LoadAsync(string searchTerm, PageContinuation pageContinuation, SearchFilter searchFilter, CancellationToken token)
        {
            try
            {
                if (pageContinuation.Current <= 0)
                {
                    //start search from begin, don't skip packages
                    _discardedPackagesSet.Clear();
                }

                var localContinuation = new PageContinuation(pageContinuation, !pageContinuation.Source.PackageSources.Any());

                var installedPackagesMetadatas = (await _projectRepositoryLoader.Value.LoadAsync(searchTerm, localContinuation, searchFilter, token));

                pageContinuation.GetNext();

                Log.Info("Local packages queryed for further available update searching");

                List <IPackageSearchMetadata> updateList = new List <IPackageSearchMetadata>();

                //getting last metadata
                foreach (var package in installedPackagesMetadatas)
                {
                    if (_discardedPackagesSet.Contains(package.Identity.Id))
                    {
                        continue;
                    }

                    var clonedMetadata = await PackageMetadataProvider.GetHighestPackageMetadataAsync(package.Identity.Id, searchFilter.IncludePrerelease, token);

                    if (clonedMetadata is null)
                    {
                        Log.Warning($"Couldn't retrieve update metadata for installed {package.Identity}");
                        continue;
                    }

                    if (clonedMetadata.Identity.Version > package.Identity.Version)
                    {
                        var combinedMetadata = UpdatePackageSearchMetadataBuilder.FromMetadatas(clonedMetadata as ClonedPackageSearchMetadata, package).Build();
                        updateList.Add(combinedMetadata);
                    }

                    _discardedPackagesSet.Add(package.Identity.Id);


                    if (updateList.Count >= pageContinuation.Size)
                    {
                        break;
                    }
                }

                return(updateList);
            }
            catch (Exception ex) when(token.IsCancellationRequested)
            {
                throw new OperationCanceledException("Search request was canceled", ex, token);
            }
        }
Ejemplo n.º 37
0
 // GET api/<controller>
 /// <summary>
 /// Gets this instance.
 /// </summary>
 /// <returns></returns>
 public LocaleStringResourceCollection Post(string method, [FromBody] SearchFilter value)
 {
     return(LocaleStringResourceManager.Search(value));
 }
        public async void Test_Repository_selectAsync_ByFilter(BookingModel booking, StayModel stay)
        {
            await _connection.OpenAsync();

            try
            {
                using (var ctx = new BookingContext(_options))
                {
                    await ctx.Database.EnsureCreatedAsync();

                    await ctx.Bookings.AddAsync(booking);

                    await ctx.Stays.AddAsync(stay);

                    await ctx.SaveChangesAsync();
                }

                using (var ctx = new BookingContext(_options))
                {
                    var bookings = new Repository <BookingModel>(ctx);

                    var actual = await bookings.SelectAsync(null, null, "", 0, 50);

                    Assert.NotEmpty(actual);

                    actual = await bookings.SelectAsync(null, null, "", 0, 50);

                    Assert.NotEmpty(actual);
                }

                using (var ctx = new BookingContext(_options))
                {
                    var stays = new Repository <StayModel>(ctx);

                    var actual = await stays.SelectAsync(null, null, "", 0, 50);

                    Assert.NotEmpty(actual);
                }

                using (var ctx = new BookingContext(_options))
                {
                    var stays = new Repository <StayModel>(ctx);
                    List <Expression <Func <StayModel, bool> > > _filters = new List <Expression <Func <StayModel, bool> > >();
                    _filters.Add(s => s.Id > 0);

                    SearchFilter <StayModel> searchFilter = new SearchFilter <StayModel>
                    {
                        Includes = "Booking",
                        Filters  = _filters,
                        OrderBy  = stays => stays.OrderBy(stay => stay.Id),
                    };
                    var actual = await stays.SelectAsync(searchFilter);

                    Assert.NotNull(actual);
                }
            }
            finally
            {
                _connection.Close();
            }
        }
Ejemplo n.º 39
0
 public CatalogSearchQuery PublishedOnly(bool value)
 {
     return(WithFilter(SearchFilter.ByField("published", value).Mandatory().ExactMatch().NotAnalyzed()));
 }
Ejemplo n.º 40
0
 // GET api/<controller>
 /// <summary>
 /// Gets this instance.
 /// </summary>
 /// <returns></returns>
 public EPActivityTypeCollection Post(string method, [FromBody] SearchFilter value)
 {
     return(EPActivityTypeManager.Search(value));
 }
        // GET: Contact
        public ActionResult Index(SearchFilter filter, int?VehicleTypeID, int?MakerId, int?AutoModelID, string Status, string Price, string MinYear, string MaxYear, string EngineName, string Transmission, string Title, string SortOrder, int?page)
        {
            try
            {
                var mod                  = new WebsiteInventory();
                var pageIndex            = (page ?? 1); //MembershipProvider expects a 0 for the first page
                var pageSize             = 10;
                var inv                  = "";
                InventoryRespository rep = new InventoryRespository();
                var data                 = new List <VehicleViewModel>(rep.GetInventoryStatusVM(System.Globalization.CultureInfo.CurrentCulture.Name == "ar").Data as List <VehicleViewModel>);
                mod.Type = GetTypeList();
                List <SelectListItem> makerlist = new List <SelectListItem>();
                if (System.Globalization.CultureInfo.CurrentCulture.Name == "ar")
                {
                    makerlist.Insert(0, new SelectListItem {
                        Value = "", Text = "حدد صانع"
                    });
                }
                else
                {
                    makerlist.Insert(0, new SelectListItem {
                        Value = "", Text = "Select Make"
                    });
                }

                mod.Name = makerlist;
                if (VehicleTypeID != null)
                {
                    var allType = GetVehicleType(1);
                    var t       = allType.Where(x => x.VehicleTypeID == VehicleTypeID).FirstOrDefault();
                    data               = data.Where(x => x.VehicleType != null && (x.VehicleType == t.Type || x.VehicleType == t.ArabicType)).ToList();
                    mod.Name           = GetMakersList(VehicleTypeID.Value);
                    filter.FilterExist = true;
                    inv += "&VehicleTypeID=" + VehicleTypeID;
                }

                if (MakerId != null)
                {
                    var m = GetMakers(-1).Where(x => x.MakerID == MakerId).FirstOrDefault();
                    if (VehicleTypeID != 0)
                    {
                        data               = data.Where(x => x.Maker != null && (x.Maker == m.Name || x.Maker == m.ArabicName)).ToList();
                        mod.Name           = GetMakersList(VehicleTypeID.Value); //new SelectList(db.Makers.Where(x => x.VehicleTypeID == t.VehicleTypeID), DataHelper.GetDropDown("Name"), DataHelper.GetDropDown("Name"), mak.Name);
                        filter.FilterExist = true;                               //filter.FilterExist = true;
                        inv += "&MakerId=" + MakerId;
                    }
                }

                if (AutoModelID != null)
                {
                    var m = GetModels(1, VehicleTypeID.Value, MakerId.Value).Where(x => x.AutoModelID == AutoModelID).FirstOrDefault();
                    data = data.Where(x => x.AutoModelName != null && (x.AutoModelName == m.ModelName || x.AutoModelName == m.ArabicModelName)).ToList();
                    filter.FilterExist = true;
                    mod.ModelName      = GetModelList(1, VehicleTypeID.Value, MakerId.Value);
                    inv            += "&AutoModelID=" + AutoModelID.Value;
                    mod.AutoModelID = AutoModelID.Value;
                }
                else
                {
                    List <SelectListItem> list = new List <SelectListItem>();
                    if (System.Globalization.CultureInfo.CurrentCulture.Name == "ar")
                    {
                        list.Insert(0, new SelectListItem {
                            Value = "", Text = "حدد موديل"
                        });
                    }
                    else
                    {
                        list.Insert(0, new SelectListItem {
                            Value = "", Text = "Select Model"
                        });
                    }
                    mod.ModelName = list;
                }
                if (!string.IsNullOrEmpty(EngineName))
                {
                    data = data.Where(x => x.EngineName != null && x.EngineName == filter.EngineName).ToList();
                    filter.FilterExist = true;
                    mod.EngineName     = new SelectList(db.AutoEngines, DataHelper.GetDropDown("EngineName"), DataHelper.GetDropDown("EngineName"), EngineName);
                    inv += "&EngineName=" + EngineName;
                }
                else
                {
                    mod.EngineName = new SelectList(db.AutoEngines, DataHelper.GetDropDown("EngineName"), DataHelper.GetDropDown("EngineName"), EngineName);
                }


                if (!string.IsNullOrEmpty(MinYear))
                {
                    data = data.Where(x => x.YearName != null && int.Parse(x.YearName) >= int.Parse(MinYear)).ToList();
                    filter.FilterExist = true;
                    inv += "&MinYear=" + MinYear;
                }
                if (!string.IsNullOrEmpty(MaxYear))
                {
                    data = data.Where(x => x.YearName != null && int.Parse(x.YearName) <= int.Parse(MaxYear)).ToList();
                    filter.FilterExist = true;
                }
                if (!string.IsNullOrEmpty(Transmission))
                {
                    data = data.Where(x => x.AutoTransmission != null && x.AutoTransmission == Transmission).ToList();
                    filter.FilterExist = true;
                    mod.Transmission   = new SelectList(db.AutoTransmissions, "Transmission", DataHelper.GetDropDown("Transmission"), Transmission);
                    inv += "&Transmission=" + Transmission;
                }
                else
                {
                    mod.Transmission = new SelectList(db.AutoTransmissions, "Transmission", DataHelper.GetDropDown("Transmission"), Transmission);
                }
                if (!string.IsNullOrEmpty(Title))
                {
                    data = data.Where(x => x.VehicleTitle != null && x.VehicleTitle == Title).ToList();
                    filter.FilterExist = true;
                    inv += "&Title=" + Title;
                }
                if (!string.IsNullOrEmpty(Status) && Status != "Any")
                {
                    data = data.Where(x => x.AutoUsedStatus != null && x.AutoUsedStatus == filter.Status).ToList();
                    filter.FilterExist = true;
                    inv += "&Status=" + Status;
                }
                if (Status == "Any")
                {
                    filter.FilterExist = true;
                }
                if (!string.IsNullOrEmpty(Price))
                {
                    filter.Price = Price;
                    if (!Price.ToString().Contains("–"))
                    {
                        data = data.Where(x => x.VehiclePrice != null && float.Parse(x.VehiclePrice.ToString()) >= float.Parse(Price.ToString())).ToList();
                        filter.FilterExist = true;
                    }
                    else
                    {
                        var arr = Price.ToString().Split('–');
                        data = data.Where(x => x.VehiclePrice != null && (float.Parse(x.VehiclePrice.ToString()) >= float.Parse(arr[0].ToString()) && float.Parse(x.VehiclePrice.ToString()) <= float.Parse(arr[1].ToString()))).ToList();
                        filter.FilterExist = true;
                    }
                    inv += "&Price=" + Price;
                }
                if (!string.IsNullOrEmpty(SortOrder))
                {
                    if (SortOrder == "Price Low to High")
                    {
                        data = data.OrderBy(x => x.VehiclePrice).ToList();
                    }
                    else if (SortOrder == "High to Low")
                    {
                        data = data.OrderByDescending(x => x.VehiclePrice).ToList();
                    }
                    else if (SortOrder == "Name A - Z")
                    {
                        data = data.OrderBy(x => x.VehicleTitle).ToList();
                    }
                    else if (SortOrder == "Name A - Z")
                    {
                        data = data.OrderByDescending(x => x.VehicleTitle).ToList();
                    }
                    else if (SortOrder == "Newest First")
                    {
                        data = data.OrderBy(x => x.CreatedDate).ToList();
                    }
                    else if (SortOrder == "Newest First")
                    {
                        data = data.OrderByDescending(x => x.CreatedDate).ToList();
                    }
                    filter.FilterExist = true;
                    inv += "&SortOrder=" + SortOrder;
                }
                var t1         = (data.Count() / pageSize);
                int totalPages = (int)Math.Ceiling((double)data.Count() / 10);  // Math.Ceiling((decimal)(data.Count() / pageSize));
                int total      = data.Count();
                mod.Filter      = filter;
                mod.Make        = new MakeOfferViewModel();
                mod.VehicleList = data.ToPagedList(pageIndex, pageSize);
                // mod.Name = new SelectList(db.Makers, "Name", "Name", Name);


                // mod.ModelName = new SelectList(db.AutoModels, "ModelName", "ModelName", ModelName);


                var root        = Umbraco.TypedContentAtRoot().First();
                var vehiclePage = root.Children(x => x.DocumentTypeAlias == "vehicle").FirstOrDefault();
                mod.VehiclePageUrl = vehiclePage.Url;
                var url = root.GetPropertyValue <string>("applicationUrl").ToString();
                mod.Url = url;
                // int pageSize = 2;
                int pageNumber = (page ?? 1);
                //Used the following two formulas so that it doesn't round down on the returned integer

                ViewBag.TotalPages = totalPages;
                //These next two functions could maybe be reduced to one function....would require some testing and building
                //mod.VehicleList = new StaticPagedList<VehicleViewModel>(data, 1, pageSize, totalPages);
                ViewBag.inv        = inv;
                ViewBag.total      = total;
                ViewBag.PageNumber = pageNumber;

                return(View("Inventory", mod));
            }
            catch (Exception ex)
            {
                return(View("ErrorPage"));
            }
        }
Ejemplo n.º 42
0
        public void Draw(Rect fullRect)
        {
            Rect listRect;

            if (ShowSortPane)
            {
                var searchRect = new Rect(fullRect.xMin, fullRect.yMin, fullRect.width, _settings.IconRowHeight);
                DrawSearchPane(searchRect);

                listRect = Rect.MinMaxRect(
                    fullRect.xMin, fullRect.yMin + _settings.IconRowHeight, fullRect.xMax, fullRect.yMax);
            }
            else
            {
                listRect = fullRect;
            }

            var searchFilter   = SearchFilter.Trim().ToLowerInvariant();
            var visibleEntries = _entries.Where(x => x.Name.ToLowerInvariant().Contains(searchFilter)).ToList();

            var viewRect = new Rect(0, 0, listRect.width - 30.0f, visibleEntries.Count * _settings.ItemHeight);

            var isListUnderMouse = listRect.Contains(Event.current.mousePosition);

            ImguiUtil.DrawColoredQuad(listRect, GetListBackgroundColor(isListUnderMouse));

            switch (Event.current.type)
            {
            case EventType.MouseUp:
            {
                break;
            }

            case EventType.ContextClick:
            {
                if (isListUnderMouse)
                {
                    ContextMenuOpenRequested();
                    Event.current.Use();
                }

                break;
            }
            }

            bool clickedItem = false;

            float yPos         = 0;
            var   newScrollPos = GUI.BeginScrollView(listRect, ScrollPos, viewRect);

            {
                foreach (var entry in visibleEntries)
                {
                    var labelRect = new Rect(0, yPos, listRect.width, _settings.ItemHeight);

                    bool isItemUnderMouse = labelRect.Contains(Event.current.mousePosition);

                    Color itemColor;

                    if (entry.IsSelected)
                    {
                        itemColor = _settings.Theme.ListItemSelectedColor;
                    }
                    else if (GUI.enabled && isItemUnderMouse)
                    {
                        itemColor = _settings.Theme.ListItemHoverColor;
                    }
                    else if (entry.Name == ActiveScene)
                    {
                        itemColor = _settings.Theme.ActiveSceneSelectedColor;
                    }
                    else
                    {
                        itemColor = _settings.Theme.ListItemColor;
                    }

                    ImguiUtil.DrawColoredQuad(labelRect, itemColor);

                    switch (Event.current.type)
                    {
                    case EventType.MouseUp:
                    {
                        if (isItemUnderMouse && Event.current.button == 0)
                        {
                            if (!Event.current.shift && !Event.current.control)
                            {
                                ClearSelected();
                                ClickSelect(entry);
                            }
                        }

                        break;
                    }

                    case EventType.MouseDown:
                    {
                        if (isItemUnderMouse)
                        {
                            // Unfocus on text field
                            GUI.FocusControl(null);

                            clickedItem = true;
                            ClickSelect(entry);

                            Event.current.Use();
                        }
                        break;
                    }
                    }

                    GUI.Label(labelRect, entry.Name, _settings.ItemTextStyle);

                    yPos += _settings.ItemHeight;
                }
            }
            GUI.EndScrollView();

            if (newScrollPos != ScrollPos)
            {
                ScrollPositionChanged(newScrollPos);
            }

            if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && !clickedItem && isListUnderMouse)
            {
                // Unfocus on text field
                GUI.FocusControl(null);

                ClearSelected();
            }
        }
Ejemplo n.º 43
0
 static IEnumerable <Contact> FilterContacts(SearchFilter filter)
 {
     return(TestData.Contacts.Where(c => c.Name.Contains(filter.Term ?? string.Empty)).OrderBy(nm => nm.Name).Take(100));
 }
Ejemplo n.º 44
0
 public PartialViewResult Search(SearchFilter filter)
 {
     return(PartialView("Display", FilterContacts(filter)));
 }
        public string BuildGetPackagesUri(
            string searchTerm,
            SearchFilter filters,
            int?skip,
            int?take)
        {
            var filterParameter  = BuildFilter(searchTerm, filters.Filter);
            var orderByParameter = BuildOrderBy(filters.OrderBy);
            var skipParameter    = BuildSkip(skip);
            var topParameter     = BuildTop(take);

            // The parenthesis right after the "/Packages" path in the URL are excluded if the filter, orderby, and
            // top parameters are not used. This is a quirk of the NuGet 2.x implementation.
            var useParenthesis = filterParameter != null || orderByParameter != null || topParameter != null;

            // Start building the URI.
            var builder = new StringBuilder();

            builder.AppendFormat(GetPackagesFormat, useParenthesis ? EndpointParenthesis : string.Empty);

            var hasParameters = false;

            // Append each query parameter.
            if (filterParameter != null)
            {
                builder.AppendFormat(
                    hasParameters ? ParameterFormat : FirstParameterFormat,
                    filterParameter);
                hasParameters = true;
            }

            if (orderByParameter != null)
            {
                builder.AppendFormat(
                    hasParameters ? ParameterFormat : FirstParameterFormat,
                    orderByParameter);
                hasParameters = true;
            }

            if (skipParameter != null)
            {
                builder.AppendFormat(
                    hasParameters ? ParameterFormat : FirstParameterFormat,
                    skipParameter);
                hasParameters = true;
            }

            if (topParameter != null)
            {
                builder.AppendFormat(
                    hasParameters ? ParameterFormat : FirstParameterFormat,
                    topParameter);
                hasParameters = true;
            }

            builder.AppendFormat(
                hasParameters ? ParameterFormat : FirstParameterFormat,
                SemVerLevel);
            hasParameters = true;

            return(builder.ToString());
        }
Ejemplo n.º 46
0
 public CatalogSearchQuery VisibleIndividuallyOnly(bool value)
 {
     return(WithFilter(SearchFilter.ByField("visibleindividually", value).Mandatory().ExactMatch().NotAnalyzed()));
 }
Ejemplo n.º 47
0
        public static async Task <IPackageSearchMetadata[]> SearchAsync(this SourceRepository sourceRepository, string searchText, SearchFilter searchFilter, int pageSize, CancellationToken cancellationToken)
        {
            var searchResource = await sourceRepository.GetResourceAsync <PackageSearchResource>(cancellationToken).ConfigureAwait(false);

            if (searchResource != null)
            {
                var searchResults = await searchResource.SearchAsync(
                    searchText,
                    searchFilter,
                    0,
                    pageSize,
                    NullLogger.Instance,
                    cancellationToken).ConfigureAwait(false);

                if (searchResults != null)
                {
                    return(searchResults.ToArray());
                }
            }

            return(Array.Empty <IPackageSearchMetadata>());
        }
Ejemplo n.º 48
0
 public CatalogSearchQuery HomePageProductsOnly(bool value)
 {
     return(WithFilter(SearchFilter.ByField("showonhomepage", value).Mandatory().ExactMatch().NotAnalyzed()));
 }
Ejemplo n.º 49
0
 /// <inheritdoc cref="IDrawer.OnFilterChanged" />
 public override void OnFilterChanged(SearchFilter filter)
 {
     UpdateActiveMemberBuildList();
     base.OnFilterChanged(filter);
 }
Ejemplo n.º 50
0
 public CatalogSearchQuery IsProductType(ProductType type)
 {
     return(WithFilter(SearchFilter.ByField("typeid", (int)type).Mandatory().ExactMatch().NotAnalyzed()));
 }
Ejemplo n.º 51
0
        private static async Task <SearchResults> GetRawResultsFromSearchService(ISearchService searchService, SearchFilter searchFilter)
        {
            var externalSearchService = searchService as ExternalSearchService;

            if (externalSearchService != null)
            {
                return(await externalSearchService.RawSearch(searchFilter));
            }

            return(await GetResultsFromSearchService(searchService, searchFilter));
        }
Ejemplo n.º 52
0
 public CatalogSearchQuery AvailableOnly(bool value)
 {
     return(WithFilter(SearchFilter.ByField("available", value).Mandatory().ExactMatch().NotAnalyzed()));
 }
Ejemplo n.º 53
0
        private static bool TryReadSearchFilter(
            bool allVersionsInIndex,
            string url,
            bool ignoreLatestVersionFilter,
            SortOrder defaultSortOrder,
            out SearchFilter searchFilter)
        {
            if (url == null)
            {
                searchFilter = null;
                return(false);
            }

            string path  = string.Empty;
            string query = string.Empty;
            int    indexOfQuestionMark = url.IndexOf('?');

            if (indexOfQuestionMark > -1)
            {
                path  = url.Substring(0, indexOfQuestionMark);
                query = url.Substring(indexOfQuestionMark + 1);
            }

            searchFilter = new SearchFilter(SearchFilter.ODataSearchContext)
            {
                // The way the default paging works is WCF attempts to read up to the MaxPageSize elements. If it finds as many, it'll assume there
                // are more elements to be paged and generate a continuation link. Consequently we'll always ask to pull MaxPageSize elements so WCF generates the
                // link for us and then allow it to do a Take on the results. Further down, we'll also parse $skiptoken as a custom IDataServicePagingProvider
                // sneakily injects the Skip value in the continuation token.
                Take      = MaxPageSize,
                Skip      = 0,
                CountOnly = path.EndsWith("$count", StringComparison.Ordinal)
            };

            string[] props = query.Split('&');

            IDictionary <string, string> queryTerms = new Dictionary <string, string>();

            foreach (string prop in props)
            {
                string[] nameValue = prop.Split('=');
                if (nameValue.Length == 2)
                {
                    queryTerms[Uri.UnescapeDataString(nameValue[0])] = nameValue[1];
                }
            }

            // We'll only use the index if we the query searches for latest / latest-stable packages *or* the index contains all versions
            string filter;

            if (queryTerms.TryGetValue("$filter", out filter))
            {
                if (!ignoreLatestVersionFilter &&
                    !(filter.Equals(ODataQueryFilter.IsLatestVersion, StringComparison.Ordinal) ||
                      filter.Equals(ODataQueryFilter.IsAbsoluteLatestVersion, StringComparison.Ordinal)))
                {
                    searchFilter = null;
                    return(false);
                }
            }
            else if (!allVersionsInIndex)
            {
                searchFilter = null;
                return(false);
            }

            string skipStr;

            if (queryTerms.TryGetValue("$skip", out skipStr))
            {
                int skip;
                if (int.TryParse(skipStr, out skip))
                {
                    searchFilter.Skip = skip;
                }
            }

            string topStr;

            if (queryTerms.TryGetValue("$top", out topStr))
            {
                int top;
                if (int.TryParse(topStr, out top))
                {
                    searchFilter.Take = Math.Max(top, MaxPageSize);
                }
            }

            //  only certain orderBy clauses are supported from the Lucene search
            string orderBy;

            if (queryTerms.TryGetValue("$orderby", out orderBy))
            {
                if (string.IsNullOrEmpty(orderBy))
                {
                    searchFilter.SortOrder = defaultSortOrder;
                }
                else if (orderBy.StartsWith("DownloadCount", StringComparison.Ordinal))
                {
                    searchFilter.SortOrder = SortOrder.Relevance;
                }
                else if (orderBy.StartsWith("Published", StringComparison.Ordinal))
                {
                    searchFilter.SortOrder = SortOrder.Published;
                }
                else if (orderBy.StartsWith("LastEdited", StringComparison.Ordinal))
                {
                    searchFilter.SortOrder = SortOrder.LastEdited;
                }
                else if (orderBy.StartsWith("Id", StringComparison.Ordinal))
                {
                    searchFilter.SortOrder = SortOrder.TitleAscending;
                }
                else if (orderBy.StartsWith("concat", StringComparison.Ordinal))
                {
                    searchFilter.SortOrder = SortOrder.TitleAscending;

                    if (orderBy.Contains("%20desc"))
                    {
                        searchFilter.SortOrder = SortOrder.TitleDescending;
                    }
                }
                else if (orderBy.StartsWith("Created", StringComparison.Ordinal))
                {
                    searchFilter.SortOrder = SortOrder.CreatedAscending;

                    if (orderBy.Contains("%20desc"))
                    {
                        searchFilter.SortOrder = SortOrder.CreatedDescending;
                    }
                }
                else
                {
                    searchFilter = null;
                    return(false);
                }
            }
            else
            {
                searchFilter.SortOrder = defaultSortOrder;
            }

            return(true);
        }
Ejemplo n.º 54
0
 /// <summary>
 /// Adds the specified filter.
 /// </summary>
 /// <param name="filter">The filter.</param>
 public virtual void Add(SearchFilter filter)
 {
     _Filters.Add(filter);
 }
Ejemplo n.º 55
0
        public ActionResult ProviderModelQuery(string keyWord)
        {
            // Create criteria
            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria
            {
                RecordsToRetrieve = 200, // there is a default of 50
                // Locale have to be there... else no hits
                Locale       = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName,
                SearchPhrase = keyWord
            };

            // Add more to the criteria
            criteria.Sort = CatalogEntrySearchCriteria.DefaultSortOrder;
            criteria.CatalogNames.Add("Fashion"); // ...if we know what catalog to search in, not mandatory
            //criteria.IgnoreFilterOnLanguage = true; // if we want to search all languages... need the locale anyway

            criteria.ClassTypes.Add(EntryType.Variation);
            criteria.MarketId = MarketId.Default; // should use the ICurrentMarket service, of course...

            criteria.IsFuzzySearch      = true;
            criteria.FuzzyMinSimilarity = 0.7F;

            criteria.IncludeInactive = true;

            // the _outline field
            System.Collections.Specialized.StringCollection sc =
                new System.Collections.Specialized.StringCollection
            {
                "Fashion/Clothes_1/Men_1/Shirts_1",
                "Fashion/Clothes_1/UniSex_1"
            };
            criteria.Outlines = sc; // another "AND"

            #region SimpleWalues
            ///*
            // Add facets to the criteria... and later prepare them for the "search result" as FacetGroups
            // With the below only these values are in the result... no Red or RollsRoys
            Mediachase.Search.SimpleValue svWhite = new SimpleValue
            {
                value        = "white",
                key          = "white",
                locale       = "en",
                Descriptions = new Descriptions {
                    defaultLocale = "en"
                }
            };
            var descWhite = new Description
            {
                locale = "en",
                Value  = "White"
            };
            svWhite.Descriptions.Description = new[] { descWhite };

            // If added like this it ends up in "ActiveFields" of the criteria and the result is filtered
            //criteria.Add("color", svWhite);
            // ...also the facetGroups on the "result" are influenced

            Mediachase.Search.SimpleValue svBlue = new SimpleValue
            {
                value        = "blue",
                key          = "blue",
                locale       = "en",
                Descriptions = new Descriptions {
                    defaultLocale = "en"
                }
            };
            var descBlue = new Description
            {
                locale = "en",
                Value  = "Blue"
            };
            svBlue.Descriptions.Description = new[] { descBlue };
            //criteria.Add("color", svBlue);

            Mediachase.Search.SimpleValue svVolvo = new SimpleValue
            {
                value        = "volvo",
                key          = "volvo",
                locale       = "en",
                Descriptions = new Descriptions {
                    defaultLocale = "en"
                }
            };
            var descVolvo = new Description
            {
                locale = "en",
                Value  = "volvo"
            };
            svVolvo.Descriptions.Description = new[] { descVolvo };
            //criteria.Add("brand", svVolvo);

            Mediachase.Search.SimpleValue svSaab = new SimpleValue
            {
                value        = "saab",
                key          = "saab",
                locale       = "en",
                Descriptions = new Descriptions {
                    defaultLocale = "en"
                }
            };
            var descSaab = new Description
            {
                locale = "en",
                Value  = "saab"
            };
            svSaab.Descriptions.Description = new[] { descSaab };
            //criteria.Add("brand", svSaab);

            #region Debug

            // the above filters the result so only saab (the blue) is there
            // With the above only we see only the Blue shirt... is that a saab - yes
            // New: no xml --> gives one Active and an empty filter even searchFilter.Values.SimpleValue below is there
            // New: outcommenting the above line --> and add XML file ... no "Active Fileds"
            // Have the Filters added - but no actice fields
            // New: trying this... Brand gets "ActiveField" with volvo & saab.. but the result shows all brands
            // New: outcommenting the below line and adding above only one, the saab
            //criteria.Add("brand", new List<ISearchFilterValue> { svSaab, svVolvo });
            // ...get a FacetGroups "in there"... like with the XML-file ... a manual way to add...
            // ...stuff that is not in the XML-file, or skip the XML File
            // New: taking out the single saab filter added

            #endregion

            SearchFilter searchFilterColor = new SearchFilter
            {
                //field = BaseCatalogIndexBuilder.FieldConstants.Catalog, // Have a bunch
                field = "color",

                // mandatory
                Descriptions = new Descriptions
                {
                    // another way of getting the language
                    defaultLocale = _langResolver.Service.GetPreferredCulture().Name
                },

                Values = new SearchFilterValues(),
            };

            SearchFilter searchFilterBrand = new SearchFilter
            {
                field = "brand",

                Descriptions = new Descriptions
                {
                    defaultLocale = _langResolver.Service.GetPreferredCulture().Name
                },

                Values = new SearchFilterValues(),
            };

            var descriptionColor = new Description
            {
                locale = "en",
                Value  = "Color"
            };

            var descriptionBrand = new Description
            {
                locale = "en",
                Value  = "Brand"
            };


            searchFilterColor.Descriptions.Description = new[] { descriptionColor };
            searchFilterBrand.Descriptions.Description = new[] { descriptionBrand };

            searchFilterColor.Values.SimpleValue = new SimpleValue[] { svWhite, svBlue };
            searchFilterBrand.Values.SimpleValue = new SimpleValue[] { svVolvo, svSaab };

            // can do like the below or us the loop further down...
            // the "foreach (SearchFilter item in _NewSearchConfig.SearchFilters)"
            // use these in the second part of the demo... "without XML" ... saw that with XML-style
            criteria.Add(searchFilterColor);
            criteria.Add(searchFilterBrand);

            #region Debug

            // gets the "filters" without this below and the XML... further checks...
            // do we need this? ... seems not... or it doesn't work like this
            // New: Have XML and commenting out the below lines Looks the same as with it
            // New: second...outcommenting the criteria.Add(searchFilter);
            // the Facets prop is empty......without the XML
            // the below line seems not to work
            // New: adding these again together with the saab above active
            //... difference is the "VariationFilter"
            // We get the Facets on the criteria, but no facets in the "result" without the XML

            //criteria.Filters = searchFilter; // read-only

            // Without the XML...

            // boom... on a missing "key"... the description
            // when commenting out the criteria.Add() for the simple values...??
            // When adding more to the SearchFilter it works...
            // ... the Simple values are there in the only instance if the filter
            // commenting out and check with the XML
            // when using the XML the groups sit in FacetGroups
            // when using the above... no facet-groups added

            // The same facets added a second time, Filter number 2 and no facet-groups
            //SearchConfig sConf = new SearchConfig();

            #endregion Debug

            //*/
            #endregion SimpleValues

            // use the manager for search and for index management
            SearchManager manager = new SearchManager("ECApplication");

            #region Facets/Filters

            // Filters from the XML file, populates the FacetGroups on the Search result
            string _SearchConfigPath =
                @"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config";

            TextReader    reader     = new StreamReader(_SearchConfigPath);
            XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig)));
            _SearchConfig = (SearchConfig)serializer.Deserialize(reader);
            reader.Close();

            foreach (SearchFilter filter in _SearchConfig.SearchFilters)
            {
                // Step 1 - use the XML file
                //criteria.Add(filter);
            }

            // Manual...
            SearchConfig _NewSearchConfig = new SearchConfig
            {
                SearchFilters = new SearchFilter[] { searchFilterColor, searchFilterBrand }
            };

            // can do like this, but there is another way (a bit above)
            foreach (SearchFilter item in _NewSearchConfig.SearchFilters)
            {
                // Step 2 - skip the XML file
                //criteria.Add(item);
            }

            #endregion

            // Do search
            ISearchResults results = manager.Search(criteria);

            #region Debug


            // doens't work
            //FacetGroup facetGroup = new FacetGroup("Bogus", "Bummer");
            //results.FacetGroups = new[] { facetGroup };

            // ...different return types - same method
            //SearchFilterHelper.Current.SearchEntries()

            // out comment and do a new try
            //ISearchFacetGroup[] facets = results.FacetGroups;

            // NEW: adding these ... for the provider, last line doesn's assign
            //ISearchFacetGroup[] searchFacetGroup0 = new SearchFacetGroup() { };
            FacetGroup facetGroup0 = new FacetGroup("colorgroup", "dummy"); //{ "",""}; // FacetGroup("brand","volvo");
            Facet      f1          = new Facet(facetGroup0, svWhite.key, svWhite.value, 1);
            facetGroup0.Facets.Add(f1);
            //facets[1] = facetGroup0;
            ISearchFacetGroup[] searchFacetGroup = new FacetGroup[] { facetGroup0 };
            //searchFacetGroup.Facets.Add(f1);
            //results.FacetGroups = searchFacetGroup; // nothing happens here, facet-group still empty

            #endregion

            int[] ints = results.GetKeyFieldValues <int>();

            // The DTO-way
            CatalogEntryDto dto = _catalogSystem.GetCatalogEntriesDto(ints);

            // CMS style (better)... using ReferenceConverter and ContentLoader
            List <ContentReference> refs = new List <ContentReference>();
            ints.ToList().ForEach(i => refs.Add(_referenceConverter.GetContentLink(i, CatalogContentType.CatalogEntry, 0)));

            localContent = _contentLoader.GetItems(refs, new LoaderOptions()); //

            // ToDo: Facets
            List <string> facetList = new List <string>();

            int facetGroups = results.FacetGroups.Count();

            foreach (ISearchFacetGroup item in results.FacetGroups)
            {
                foreach (var item2 in item.Facets)
                {
                    facetList.Add(String.Format("{0} {1} ({2})", item.Name, item2.Name, item2.Count));
                }
            }

            var searchResultViewModel = new SearchResultViewModel
            {
                totalHits = new List <string> {
                    ""
                },                                   // change
                nodes      = localContent.OfType <FashionNode>(),
                products   = localContent.OfType <ShirtProduct>(),
                variants   = localContent.OfType <ShirtVariation>(),
                allContent = localContent,
                facets     = facetList
            };


            return(View(searchResultViewModel));
        }
Ejemplo n.º 56
0
        public HttpResponseMessage GetCompanyRequests(SearchFilter searchFilter)
        {
            Result <CompanyRequestDto> result = companyRequestManager.GetCompanyRequests(searchFilter);

            return(Request.CreateResponse <Result <CompanyRequestDto> >(HttpStatusCode.OK, result));
        }
Ejemplo n.º 57
0
 public RejtingDescendingSort(SearchFilter form)
     : base(form)
 {
     comparer = new RejtingDescendingComparer();
 }
Ejemplo n.º 58
0
        public async Task <SearchResult <IPackageSearchMetadata> > SearchAsync(string searchText, SearchFilter filter, CancellationToken cancellationToken)
        {
            var searchTasks = TaskCombinators.ObserveErrorsAsync(
                _sourceRepositories,
                r => r.PackageSource.Name,
                (r, t) => r.SearchAsync(searchText, filter, PageSize, t),
                LogError,
                cancellationToken);

            return(await WaitForCompletionOrBailOutAsync(searchText, searchTasks, cancellationToken));
        }
Ejemplo n.º 59
0
 public Task <IEnumerable <Card> > Search(string query, int limit = 10, SearchFilter filter = null, bool partial = false)
 {
     return(_restClient.RequestAsync <SearchResults>(new SearchRequest(query, limit, filter, new[] { ModelType.Cards }, null, partial))
            .ContinueWith <IEnumerable <Card> >(r => r.Result.Cards));
 }
Ejemplo n.º 60
0
 // GET api/<controller>
 /// <summary>
 /// Gets this instance.
 /// </summary>
 /// <returns></returns>
 public UsersInRolesCollection PutSearch(string method, [FromBody] SearchFilter value)
 {
     return(UsersInRolesManager.Search(value));
 }