public static SearchResults Query(HttpContext ctx, string query, int page = 1) { if (string.IsNullOrWhiteSpace(query)) { return new SearchResults { Documents = new SearchResult[0], TotalCount = 0 }; } var indexPath = ctx.Server.MapPath("~/App_Data/Index"); var indexSearcher = new DirectoryIndexSearcher(new DirectoryInfo(indexPath)); using (var searchService = new SearchService(indexSearcher)) { var parser = new MultiFieldQueryParser( Lucene.Net.Util.Version.LUCENE_29, new[] { "Text" }, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29)); Query multiQuery = GetSafeQuery(parser, query); var result = searchService.SearchIndex(multiQuery); return new SearchResults { Documents = result.Results .Skip(PageSize*(page - 1)) .Take(PageSize) .Select(d => new SearchResult { Url = d.Get("Url"), Title = d.Get("Title"), Summary = d.Get("Summary") }), TotalCount = result.Results.Count() }; } }
public void Can_use_the_same_index_writer_for_multiple_index_operations() { var repo = new Repository(); var writer = new MemoryIndexWriter(true); var indexService = new IndexService(writer); var p1p5 = repo.Products.Skip(0).Take(5); var result = indexService.IndexEntities(p1p5, new ProductIndexDefinition()); Assert.AreEqual(5, result.Count); var p6p10 = repo.Products.Skip(5).Take(5); var result2 = indexService.IndexEntities(p6p10, new ProductIndexDefinition()); Assert.AreEqual(5,result2.Count); var searcher = new MemoryIndexSearcher(writer.Directory, true); var searchResult = new SearchService(searcher).SearchIndex(new TermQuery(new Term("type", "product"))); Assert.AreEqual(0, searchResult.Documents.Count(), "Index writer has not yet been committed so should return 0"); // commits writer indexService.Dispose(); searchResult = new SearchService(searcher).SearchIndex(new TermQuery(new Term("type", "product"))); Assert.AreEqual(10, searchResult.Documents.Count()); }
public void ReturnOneResultWhenSearchingByKeyExplicitly() { /* * NOTE: This test uses a manual build-up just as an example. */ // Arrange var config = new SearchServiceConfiguration(Version.LUCENE_30, IndexWriter.MaxFieldLength.UNLIMITED, @"C:\SearchIndex\", "write.lock", 1000); var parser = new SearchQueryParser(); var searchService = new SearchService<Foo, FooSearchData>( config, new SearchIndexClearer(), new SearchIndexOptimizer(), new Searcher<FooSearchData>(parser, new DocumentToFooSearchDataTypeConverter()), new SearchIndexUpdater<Foo, FooSearchData>(new FooSearchDataToDocumentTypeConverter(), new FooToFooSearchDataTypeConverter()), new SearchScoreExplainer(parser)); searchService.ClearIndex(); var entities = new List<Foo> { new Foo{Key = "123", Parrot = "SQUAWK!", Bar = "Cheers"} }; searchService.UpdateIndex(entities); // Act var results = searchService.Search("key:123"); // Assert Assert.That(results.TotalHitCount == 1); }
public void ContextItem_NoSettingsAndNoContext_ShouldThrowException([Substitute, Frozen]ISearchSettings settings, SearchService searchService) { //Arrange //Act Action a = () => { var item = searchService.ContextItem; }; a.ShouldThrow<Exception>(); //Assert }
public void SearchShouldReturnASearchResultForAllSearchableEntityTypes() { var service = new SearchService(_sourceMock.Object); var result = service.Search(null); Assert.IsNotNull(result); Assert.AreEqual(3, result.Data.Select(d => d.TypeName).Distinct().Count()); Assert.AreEqual(6, result.Data.Count); }
public void Can_search_index() { var indexSearcher = new MemoryIndexSearcher(directory, true); var searchService = new SearchService(indexSearcher); var result = searchService.SearchIndex(new ProductQuery().WithId(5).Query); Assert.IsNotNull(result); Assert.AreEqual(1, result.Documents.Count()); }
public List<Paragraph> GetTimetable(SearchService.RouteOptions routeOption) { List<TimetableDTO> timetable = new List<TimetableDTO>(); foreach (SearchService.Timetable obj in service.GetTimetable(routeOption.RouteDetailsID)) { timetable.Add(new TimetableDTO(obj.DayName, obj.Table, obj.Legend)); } return PrepareTimetable(timetable); }
public override Folder GetById(int folderId) { var indexSearcher = getSearcher(); Folder folderInIndex = null; using (var searchService = new SearchService(indexSearcher)) { var results = searchService.SearchIndex(new TermQuery(new Term("folderid", folderId.ToString())), new FolderResultDefinition()); folderInIndex = results.Results.SingleOrDefault(); } return folderInIndex; }
public void SetUp() { DropAllTable(); Database.Initialize(_connectionString); DapperConfig.Initialize(); MarkdownParser.RegisterJsEngineType<V8JsEngine>(); var service = new SearchService(_connectionString); service.RecreateEsIndexAsync().Wait(); }
/// <summary> /// Get the service application by its name /// </summary> /// <param name="appName">Name of the application.</param> /// <returns> /// The search service application. /// </returns> public SearchServiceApplication GetSearchServiceApplicationByName(string appName) { var searchService = new SearchService("OSearch15", SPFarm.Local); var searchApplication = from SearchServiceApplication sapp in searchService.SearchApplications where sapp.GetSearchApplicationDisplayName() == appName select sapp; var serviceApp = searchApplication.First(); return serviceApp; }
public void ContextItem_HasSettingsRoot_ShouldReturnSettingsRoot(Db db, DbItem rootItem, [Substitute]ISearchSettings settings) { db.Add(rootItem); //Arrange settings.Root = db.GetItem(rootItem.ID); var searchService = new SearchService(settings); //Act var item = searchService.ContextItem; //Assert item.Item.ID.ShouldBeEquivalentTo(rootItem.ID); }
public void Can_transform_results_with_result_definition() { var indexSearcher = new MemoryIndexSearcher(directory, true); var searchService = new SearchService(indexSearcher); var result = searchService.SearchIndex( new TermQuery(new Term("type", "product")), new ProductResultDefinition() ); Assert.IsNotNull(result); Assert.AreEqual(10, result.Results.Count()); }
public void Create(params string[] lines) { _textBuffer = CreateTextBuffer(lines); _wordNavigator = WordUtilFactory.GetWordUtil(_textBuffer).CreateTextStructureNavigator(WordKind.NormalWord); _globalSettings = Vim.GlobalSettings; _globalSettings.Magic = true; _globalSettings.IgnoreCase = true; _globalSettings.SmartCase = false; _textSearch = TextSearchService; _searchRaw = new SearchService(_textSearch, _globalSettings); _search = _searchRaw; }
public virtual void Create(ITextSearchService textSearchService, params string[] lines) { _textBuffer = CreateTextBuffer(lines); _wordNavigator = WordUtil.CreateTextStructureNavigator(WordKind.NormalWord, _textBuffer.ContentType); _globalSettings = Vim.GlobalSettings; _globalSettings.Magic = true; _globalSettings.IgnoreCase = true; _globalSettings.SmartCase = false; _textSearch = textSearchService; _searchRaw = new SearchService(_textSearch, _globalSettings); _search = _searchRaw; }
public void Create(params string[] lines) { _textBuffer = EditorUtil.CreateTextBuffer(lines); _navigator = VimUtil.CreateTextStructureNavigator(_textBuffer, WordKind.NormalWord); _globalSettings = new Vim.GlobalSettings(); _globalSettings.Magic = true; _globalSettings.IgnoreCase = true; _globalSettings.SmartCase = false; _textSearch = EditorUtil.FactoryService.TextSearchService; _searchRaw = new SearchService(_textSearch, _globalSettings); _search = _searchRaw; }
public async Task BulkItemsAsyncTest() { var service = new SearchService(_connectionString); var draft1 = Draft.NewDraft(new User("TEST1"), ItemType.Article); draft1.Title = "雪村あおい(ゆきむら あおい)"; draft1.Body = @"本作の主人公。2月19日生まれ。高校1年生。15歳。血液型はB型。身長152cm、体重43kgでカップサイズはAカップ。 亜麻色の、襟足ほどに切りそろえた髪型で、普段は左こめかみ付近に黒い髪飾りを着けている。 小学生の頃にジャングルジムから落ちて以来の高所恐怖症で、ロープウェイなどに乗れなかったりする。また、その頃から料理・裁縫・読書といった屋内での一人遊びが趣味になった[注 2]。 人見知りが激しく、クラスメイトからの誘いも強引な理由をつくって断ってしまう。その一方で、負けん気が強く、ひなたに挑発されて彼女の思惑に乗せられたりもする。時々、「女子力」を気にする。登山については全くの素人だが、ひなたに付き合ううち、自らもインターネットを活用して知識を得るなど、興味を抱きつつある。 ひなたに対しては、再会当初はあまり良い印象を持たず、表に出さないまでも抗議したり悪態をついたりしたが、共に過ごすうちに彼女の気配りや社交性を見直している。"; draft1.ItemTags.Add(new ItemTag("Tag1", "version")); draft1.ItemTags.Add(new ItemTag("Tag2", null)); var item1 = draft1.ToItem(true); var draft2 = Draft.NewDraft(new User("TEST2"), ItemType.Article); draft2.Title = "倉上ひなた(くらうえ ひなた)"; draft2.Body = @"あおいと同学年の幼馴染。11月11日生まれ。15歳。血液型はA型。身長155cm、体重47kgでカップサイズはBカップ(4巻時点)→Cカップ(6巻)。 短めの黒髪を両側頭部でまとめた、いわゆるツインテールの髪型が特徴。 あおいとは中学時代は疎遠だったが、高校で偶然再会した。あおいにとってはかつてあまり愉快でなかった友達で、互いに成長して再会した現在も強引にあおいを引っ張りまわしたり、彼女を巧みに挑発して自分の計画に乗せたりするが、一方であおいのことは友達としてとても大切に思っており、時たまケンカもするが思いやりを持って接している。明るく、人に対して物怖じしない性格。大雑把に見えるが周りのことを良く見ており、繊細な一面も併せ持つ。また頭が良く、成績は学年でも上位に位置する。 父の影響で登山が大好きだが、経験や知識はまだ初心者。"; draft2.ItemTags.Add(new ItemTag("Tag2", "version")); draft2.ItemTags.Add(new ItemTag("Tag3", null)); var item2 = draft2.ToItem(true); var draft3 = Draft.NewDraft(new User("TEST3"), ItemType.Article); draft3.Title = "斉藤楓(さいとう かえで)"; draft3.Body = @"1月16日生まれ。16歳。血液型はAB型。あおい・ひなたと同じ学校の先輩で山友達。身長164cm、体重50kgでブラのサイズはG70だが、下着店の店員が脇の肉を寄せたところ1カップ増えた。 登山用品店でシュラフ選びで迷っていたところあおいと出会う。あおいにとってひなた以外での最初の友達で、あおいの良き相談相手でもある。腰丈のロングストレートの黒髪で眼鏡をかけていて、あおいによると「背が高くスタイルも良い、かっこいい」。山登りが趣味で、一人で縦走登山[注 4]をするなどしている。ただし料理は苦手。登山費用や備品費用はアルバイト代などでやり繰りしている。 山のこと以外の日常にはあまり関心を持っていない。特にファッションには無頓着で、自室にいる時はスポーツブラにスパッツという下着姿でいる事が多く、外出する時も女の子らしくないラフないでたちが多い。あおいや友人のゆうかからは「スタイルが良いのにもったいない」と言われており、ゆうかに女の子っぽい恰好をさせられたりしている。勉強についても決して苦手ではないが切羽詰まらないと動かないタイプで、ゆうかに「本気を出してやればできるのにもったいない」と言われている。 登山に関してはもともと単独行指向だったが、あおいたちと山に登るようになってからは、あおいたちの登山の先生として自身の知識や経験を教える一方、あおいたちのことを気遣うことで自身の登山に対するスタンスも変わってきている。 小春から登山部に誘われているが、「自分のやりたい登山ではない」として断っている。"; draft3.ItemTags.Add(new ItemTag("Tag3", "version")); draft3.ItemTags.Add(new ItemTag("Tag4", null)); var item3 = draft3.ToItem(true); var draft4 = Draft.NewDraft(new User("TEST4"), ItemType.Article); draft4.Title = "青羽ここな(あおば ここな)"; draft4.Body = @"中学2年生(13歳)の少女。8月11日生まれ。13歳。血液型はO型。身長144cm、体重38kgでカップサイズは「まだほんのり」。あおいたちの山友達。 高尾山でモモンガを探していたところ下山途中のあおい達と出会う。両親は共働きのため、家事全般が得意。ウェーブのかかった長い茶色の髪で、前髪の一部を三つ編み状に結っている。あおいによる第一印象は、森ガール。モモンガに限らずかわいいもの、特に動物全般が好き。なかでも馬には目がなく、実際の馬以外にも夢馬くん(飯能市のゆるキャラ)やぐんまちゃんといった馬をモチーフとしたゆるキャラも大好き。 華奢な体格だが体力と運動神経はあり、手先も器用。また中学生ながら頭も良く博識で、あおいたちも感心するほどの雑学の知識を披露することも。ただ、時おり妄想にふける癖がある。"; draft4.ItemTags.Add(new ItemTag("Tag3", "version")); draft4.ItemTags.Add(new ItemTag("Tag4", null)); var item4 = draft4.ToItem(true); await service.BulkItemsAsync(new[] {item1, item2, item3, item4}); }
public async Task IndexItemAsyncTest() { var service = new SearchService(_connectionString); var draft = Draft.NewDraft(new User("TEST"), ItemType.Article); draft.Title = "Title"; draft.Body = "Body"; draft.ItemTags.Add(new ItemTag("Tag1", "version")); draft.ItemTags.Add(new ItemTag("Tag2", null)); var item = draft.ToItem(true); await service.IndexItemAsync(item); }
public ActionResult Items(string search) { var indexSearcher = IndexManager.GetIndexSearcher(); OnTimeItemQuery query = query = new OnTimeItemQuery(); using (var searchService = new SearchService(indexSearcher)) { if (!string.IsNullOrEmpty(search)) { query = query.WithKeywords(search); } var result = searchService.SearchIndex<OnTimeItem>(query.Query, new OnTimeItemResultDefinition()); return Json(result.Results, JsonRequestBehavior.AllowGet); } }
public void Can_transform_results_with_delegate_definition() { var indexSearcher = new MemoryIndexSearcher(directory, true); var searchService = new SearchService(indexSearcher); var result = searchService.SearchIndex( new TermQuery(new Term("id", "1")), doc => { return new Product { Name = doc.Get("name") }; }); Assert.AreEqual(result.Results.Count(), 1); Assert.AreEqual(result.Results.First().Name, "Football"); }
public static IEnumerable<Page> Find(String searchText) { if (!Directory.Exists(IndexDirectoryPath)) { return new List<Page>(); } DirectoryIndexSearcher indexSearcher = new DirectoryIndexSearcher(IndexDirectoryInfo); using (SearchService searchService = new SearchService(indexSearcher)) { QueryBase query = new PageQuery().WithKeywords(searchText); SearchResult<Page> result = searchService. SearchIndex(query.Query, new PageResultDefinition()); return result.Results; } }
public void SearchShouldReturnASearchResultForAllEntitiesMatchingTheFilter() { var service = new SearchService(_sourceMock.Object); var options = new FilterOptions(); options.Filter = new Filter(); options.Filter.Logic = FilterType.Or; options.Filter.Filters = new List<FilterField>() { new FilterField(FilterFieldOperator.Contains, "Name", "My"), new FilterField(FilterFieldOperator.Contains, "Body", "My"), new FilterField(FilterFieldOperator.Contains, "Description", "My") }; var result = service.Search(options); Assert.IsNotNull(result); Assert.AreEqual(3, result.Data.Select(d => d.TypeName).Distinct().Count()); Assert.AreEqual(3, result.Data.Count); }
public void AuthWinNTTest() { using (RpcServer.CreateRpc(iid, new SearchService.ServerStub(new AuthenticatedSearch())) .AddAuthWinNT() .AddProtocol("ncacn_ip_tcp", "12345") .StartListening()) { using ( SearchService client = new SearchService( RpcClient.ConnectRpc(iid, "ncacn_ip_tcp", "127.0.0.1", "12345").Authenticate( RpcAuthenticationType.Self))) { SearchResponse results = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test Criteria").Build()); Assert.AreEqual(1, results.ResultsCount); } } }
public static SearchResult[] ConvertToLocalSearchResult(SearchService.SearchResult[] results) { ArrayList list = new ArrayList(); foreach (SearchService.SearchResult result in results) { SearchResult r = new SearchResult(); if (result.Link_URL.Length > 5) r.IsLink = true; else r.IsLink = false; r.Link_ID = result.Link_ID; r.Link_Title = result.Link_Title; r.Link_URL = result.Link_URL; r.Page_ID = result.Page_ID; r.Page_Title = result.Page_Title; list.Add(r); } return (SearchResult[])list.ToArray(typeof(SearchResult)); }
public void CanScaleServiceUpAndDown() { Run(() => { SearchManagementClient searchMgmt = GetSearchManagementClient(); SearchService service = CreateServiceForSku(searchMgmt, SkuName.Standard); WaitForProvisioningToComplete(searchMgmt, service); // Scale up to 2 replicas x 2 partitions. service = searchMgmt.Services.Update( Data.ResourceGroupName, service.Name, new SearchService() { ReplicaCount = 2, PartitionCount = 2 }); service = WaitForProvisioningToComplete(searchMgmt, service); Assert.Equal(2, service.ReplicaCount); Assert.Equal(2, service.PartitionCount); // Scale back down to 1 replica x 1 partition. service = searchMgmt.Services.Update( Data.ResourceGroupName, service.Name, new SearchService() { ReplicaCount = 1, PartitionCount = 1 }); service = WaitForProvisioningToComplete(searchMgmt, service); Assert.Equal(1, service.ReplicaCount); Assert.Equal(1, service.PartitionCount); searchMgmt.Services.Delete(Data.ResourceGroupName, service.Name); }); }
public override CommandState QueryState(CommandContext context) { if (Settings.MissingKeys()) { return(CommandState.Disabled); } Item ctxItem = DataWrapper?.ExtractItem(context); if (ctxItem == null || !MediaWrapper.IsMediaFile(ctxItem)) { return(CommandState.Hidden); } var hasPersons = PersonGroupService.GetAllPersonItems(ctxItem.Database.Name).Any(); if (!hasPersons) { return(CommandState.Hidden); } var faces = SearchService .GetImageAnalysis(ctxItem.ID.ToString(), ctxItem.Language.Name, ctxItem.Database.Name) ?.FacialAnalysis; var hasOneFace = faces != null && faces.Length == 1; if (!hasOneFace) { return(CommandState.Hidden); } //show on images that have no face item pointing to them var links = Globals.LinkDatabase.GetItemReferrers(ctxItem, false); var hasFaceLink = links .Any(a => a.GetSourceItem().TemplateID.Guid == Settings.PersonFaceTemplateId.Guid); return(hasFaceLink ? CommandState.Hidden : CommandState.Enabled); }
public static async Task <List <SearchOutputData> > SearchHotels(SearchInputData value, string SessionID) { try { //yyyy-mm-dd // var searchdata= SearchMapper.MapInputData(value); SearchService service = new SearchService(); var data = await service.GetHotelsData(value, SessionID); List <SearchOutputData> OutPutData = new List <SearchOutputData>(); List <SearchOutputData> OutPutHotel = new List <SearchOutputData>(); ResponseMapper map = new ResponseMapper(); if (data.Data.hotelX.search.errors == null) { OutPutData = map.MappingData(data, SessionID); DataEntry db = new DataEntry(); db.SaveSMRHotelRates(OutPutData, SessionID); } else { return(new List <SearchOutputData>()); } foreach (var item in value.hotels) { var lstofHotels = OutPutData.Where(a => a.hotelCode == item).ToList(); var lstofSortedHotel = lstofHotels.Where(a => a.price.net == lstofHotels.Min(x => x.price.net)).FirstOrDefault(); if (lstofSortedHotel != null) { OutPutHotel.Add(lstofSortedHotel); } } return(OutPutHotel); } catch (Exception ex) { var requestData = JsonConvert.SerializeObject(ex); LoggerHelper.WriteToFile("SMLogs/SearchException", "SearchException_" + SessionID, "SearchException", requestData); return(new List <SearchOutputData>()); } }
public void Search_IfNameFound_ReturnListOfContacts() { //Arrange var contactRepository = new Mock <IGenericRepository <Contact> >(); contactRepository.Setup( e => e.Get(It.IsAny <Expression <Func <Contact, bool> > >(), "Address")) .Returns(new List <Contact> { new Contact { FirstName = "Mickey", LastName = "Mouse" } }); var searchService = new SearchService(contactRepository.Object); //Act List <Contact> contacts = searchService.SearchByName("Mick"); //Assert Assert.True(contacts.Count > 0); }
public void TestAddPeoplePostReturnsViewWhenInvalid2() { #region Arrange SetupDataForPeopleList(); var postModel = new WorkgroupPeoplePostModel(); postModel.Role = new Role(); postModel.Role.SetIdTo(Role.Codes.DepartmentalAdmin); postModel.Role.Level = 1; postModel.Users = new List <string>(); postModel.Users.Add("1"); postModel.Users.Add("2"); #endregion Arrange #region Act var result = Controller.AddPeople(3, postModel, null) .AssertViewRendered() .WithViewData <WorgroupPeopleCreateModel>(); #endregion Act #region Assert SearchService.AssertWasNotCalled(a => a.FindUser(Arg <string> .Is.Anything)); Controller.ModelState.AssertErrorsAre("Invalid Role Selected"); Assert.IsNotNull(result); Assert.AreEqual(Role.Codes.DepartmentalAdmin, result.Role.Id); Assert.AreEqual(4, result.Roles.Count()); Assert.AreEqual(Role.Codes.Requester, result.Roles[0].Id); Assert.AreEqual(Role.Codes.Approver, result.Roles[1].Id); Assert.AreEqual(Role.Codes.AccountManager, result.Roles[2].Id); Assert.AreEqual(Role.Codes.Purchaser, result.Roles[3].Id); Assert.AreEqual(2, result.Users.Count()); Assert.AreEqual("FirstName1 LastName1 (1)", result.Users[0].DisplayNameAndId); Assert.AreEqual("FirstName2 LastName2 (2)", result.Users[1].DisplayNameAndId); Assert.AreEqual("Name3", result.Workgroup.Name); #endregion Assert }
public void GetSearchResults() { String searchText = FoodSearchView.SearchText; if (searchText.Trim() != "") { IList<Food> searchResults = new List<Food>(); searchResults = FoodTracker.GetAllFood(); String[] searchstrings = searchText.Split(new char[] { ' ' }); foreach (string s in searchstrings) { String key; String exp; String val; SearchService SearchService = new SearchService(); if (s.Contains("=") || s.Contains(">") || s.Contains("<")) { SearchService.ConvertComparison(s, out key, out exp, out val); } else { key = "name"; exp = "="; val = s; } searchResults = SearchForFood(SearchService, searchResults, key, exp, val); } IList<FoodCategory> finalCatList = GetNonEmptyFoodCategories(searchResults); FoodLookupPresenter.SetCatList(finalCatList); FoodLookupPresenter.SetFoodList(searchResults); } }
public SearchResultRecordV3_1 GetSearchResultDetail(SearchResultRecordV3_1 record) { List <SearchResultRecordTiny> listTiny = new List <SearchResultRecordTiny>(); listTiny.Add(new SearchResultRecordTiny { AdjustTime = record.AdjustTime, ObjectDetailRect = record.ObjDetailRect, ObjectKey = record.ObjKey, ObjectType = record.ObjType, Similar = record.Similar, TargetEndTs = record.EndTime, TargetStartTs = record.BeginTime, }); var list = SearchService.GET_OBJ_DETAIL_INFO(m_searchParam.CameraID, m_searchHandle, listTiny); if (list != null && list.Count > 0) { return(list[0]); } return(null); }
public async Task SearchProgrammingLanguageResults() { string programmingLanguage = "C#"; int googleTotal = 9878987; int bingTotal = 3434234; var searchHttpClient = new Mock <ISearchHttpClient>(); searchHttpClient .Setup(x => x.GetGoogleResults(programmingLanguage)) .Returns(Task.FromResult(googleTotal)); searchHttpClient .Setup(x => x.GetBingResults(programmingLanguage)) .Returns(Task.FromResult(bingTotal)); var searchService = new SearchService(searchHttpClient.Object); var result = await searchService.SearchProgrammingLanguageResults(programmingLanguage); Assert.AreEqual(programmingLanguage, result.ProgrammingLanguage); Assert.AreEqual(googleTotal, result.GoogleTotal); Assert.AreEqual(bingTotal, result.BingTotal); }
public void Setup() { _container = new MocksAndStubsContainer(); _applicationSettings = _container.ApplicationSettings; _context = _container.UserContext; _repository = _container.Repository; _settingsService = _container.SettingsService; _userService = _container.UserService; _pageCache = _container.PageViewModelCache; _listCache = _container.ListCache; _siteCache = _container.SiteCache; _cache = _container.MemoryCache; _pageService = _container.PageService; _wikiImporter = new ScrewTurnImporter(_applicationSettings, _repository); _pluginFactory = _container.PluginFactory; _searchService = _container.SearchService; _controller = new UserManagementController(_applicationSettings, _userService, _settingsService, _pageService, _searchService, _context, _listCache, _pageCache, _siteCache, _wikiImporter, _repository, _pluginFactory); }
public IActionResult Index(String search) { if (search != null) { List <SearchViewModel> searchviewmodels = new List <SearchViewModel>(); var middlewares = SearchService.SearchMiddleware(search); var techniques = SearchService.SearchTechnique(search); var trades = SearchService.SearchTrade(search); var expertises = SearchService.SearchExpertise(search); var trainings = SearchService.SearchTraining(search); var assignments = SearchService.SearchAssignment(search); List <SearchViewModel> allResults = searchviewmodels.Concat(middlewares).Concat(techniques).Concat(trades).Concat(expertises).Concat(trainings).Concat(assignments).ToList(); return(View(allResults.OrderBy(x => x.EmployeeName))); } else { return(View()); } }
private async Task CompleteSearchDialog(IDialogContext context, IAwaitable <string> result) { String searchTerm; try { searchTerm = await result; } catch (OperationCanceledException) { await context.PostAsync("No problem, we'll look again some other time. I'll go back to browsing the internet."); return; } Activity reply = context.MakeMessage() as Activity; await SearchService.GenerateResultForSearch(searchTerm, reply); await context.PostAsync(reply); context.Wait(MessageReceived); }
/// <summary> /// Search method to query Locations in the Custom Locations Search Index using postcode as the QueryText /// </summary> /// <param name="query"></param> /// <returns>A list of Location Search Result items</returns> public List <LocationSearchResultItem> SearchLocationsByPostcodeOrSuburb(Query query) { if (query == null || string.IsNullOrEmpty(query.QueryText)) { return(null); } if (string.IsNullOrEmpty(query.SelectedSearchIndex)) { query.SelectedSearchIndex = "g8_locations_index_web"; } var centresBucketItem = _glassMapperService.GetItem <Item>(Guid.Parse(Constants.LocationsItemBucketGuid)); var searchService = new SearchService <LocationSearchResultItem>(); var predicate = PredicateBuilder.True <LocationSearchResultItem>(); //filter out the results to JUST be of the right template we want (IE no bucket folder items) ID locationsItemTemplateID = new ID(Guid.Parse(Constants.LocationsItemTemplateGuid)); predicate = predicate.And(x => x.TemplateId == locationsItemTemplateID); //lets build a sub-predicate to handle postcode OR Suburb var postcodeOrSuburbPredicate = PredicateBuilder.True <LocationSearchResultItem>(); postcodeOrSuburbPredicate = postcodeOrSuburbPredicate.Or(x => x.Postcode.StartsWith(query.QueryText)); postcodeOrSuburbPredicate = postcodeOrSuburbPredicate.Or(x => x.Suburb.Contains(query.QueryText)); //lets plug the base predicate back with an AND so we should have "must be X template AND either a Postcode OR a Suburb" as a predicate logic tree predicate = predicate.And(postcodeOrSuburbPredicate); var searchResults = searchService.Search(query, predicate); if (searchResults != null) { return(searchResults.Results.Select(x => x.Document).ToList()); } return(null); }
public async Task FindEmailByEmailId_Test() { var id = 2; var options = TestUtilities.GetOptions(nameof(FindEmailByEmailId_Test)); using (var actContext = new E_MailApplicationsManagerContext(options)) { await actContext.Emails.AddAsync(new Email { Id = id }); await actContext.SaveChangesAsync(); } using (var assertContext = new E_MailApplicationsManagerContext(options)) { var sut = new SearchService(assertContext); var findEmail = await sut.FindEmailAsync(id); Assert.IsNotNull(findEmail); } }
public SearchController(SearchService customSearchService, IKeywordService keywordService, IConfiguration configuration) { _customSearchService = customSearchService; _keywordService = keywordService; _configuration = configuration; customSearchService.AddSearcher(new YandexCustomSeacher( _configuration["YandexSearch:SubscriptionKey"], _configuration["YandexSearch:UserName"], new HttpClientHandler() )); customSearchService.AddSearcher(new GoogleCustomSearcher( _configuration["GoogleSearch:SubscriptionKey"], _configuration["GoogleSearch:ConfigID"], new GoogleCustomsearchServiceHandler() )); customSearchService.AddSearcher(new BingCustomSeacher( _configuration["BingSearch:SubscriptionKey"], _configuration["BingSearch:ConfigID"], new HttpClientHandler() )); }
public static List <PositionController> FindPosition(string key) { List <PositionController> positions = null; List <PositionService> getPositions = SearchService.FindPositions(key); if (getPositions != null && getPositions.Count > 0) { positions = new List <PositionController>(); foreach (var item in getPositions) { positions.Add(new PositionController( item.PositionId, item.Name, item.Hours, item.Payment)); } } return(positions); }
public void CheckSearchService() { var mock = new[] { new SearchItem { Id = 1, Text = "Chop Suey" }, new SearchItem { Id = 2, Text = "Toxicity" }, new SearchItem { Id = 2, Text = "ATWA" }, new SearchItem { Id = 2, Text = "Aerials" }, }; var searchService = new SearchService(mock); Assert.NotNull(searchService); Assert.Throws <ArgumentNullException>(() => new SearchService(null)); }
public void CanCreateServiceWithIdentity() { Run(() => { SearchManagementClient searchMgmt = GetSearchManagementClient(); string serviceName = SearchTestUtilities.GenerateServiceName(); SearchService service = DefineServiceWithSku(SkuName.Basic); service.Identity = new Identity(IdentityType.SystemAssigned); service = searchMgmt.Services.CreateOrUpdate(Data.ResourceGroupName, serviceName, service); Assert.NotNull(service); Assert.NotNull(service.Identity); Assert.Equal(IdentityType.SystemAssigned, service.Identity.Type); string principalId = string.IsNullOrWhiteSpace(service.Identity.PrincipalId) ? null : service.Identity.PrincipalId; Assert.NotNull(principalId); string tenantId = string.IsNullOrWhiteSpace(service.Identity.TenantId) ? null : service.Identity.TenantId; Assert.NotNull(tenantId); searchMgmt.Services.Delete(Data.ResourceGroupName, service.Name); }); }
public void InprocPerformanceTest() { using ( SearchService client = new SearchService(new InprocRpcClient(new SearchService.ServerStub(new AuthenticatedSearch())))) { SearchResponse previous = client.Search(SearchRequest.CreateBuilder() .AddCriteria("one").AddCriteria("two").AddCriteria("three"). Build()); RefineSearchRequest req = RefineSearchRequest.CreateBuilder() .AddCriteria("four").SetPreviousResults(previous).Build(); Stopwatch w = new Stopwatch(); w.Start(); for (int i = 0; i < 1000; i++) { client.RefineSearch(req); } w.Stop(); Trace.TraceInformation("Inproc Performance = {0}", w.ElapsedMilliseconds); } }
public StartPageViewModel(INavigationService navigator, IHub messageHub, IDialogService dialogService, SearchService searchService, UndoRedoService undoRedoService) { _navigator = navigator; _messageHub = messageHub; _dialogService = dialogService; _searchService = searchService; _undoRedoService = undoRedoService; TopN = 10; UndoCommand = _undoRedoService.UndoCommand; RedoCommand = _undoRedoService.RedoCommand; UndoEnabled = _undoRedoService.UndoEnabled; RedoEnabled = _undoRedoService.RedoEnabled; _undoRedoService.UndoEvent += UndoRedoServiceUndoEvent; _undoRedoService.RedoEvent += UndoRedoServiceRedoEvent; }
public void MultiPartMessageFailsWithoutHandler() { //Notice that both client and server must enable multi-part messages... using (RpcServer.CreateRpc(iid, new SearchService.ServerStub(new AuthenticatedSearch())) .AddAuthNegotiate() .AddProtocol("ncacn_ip_tcp", "12345") //Omit server response: .EnableMultiPart() .StartListening()) { using ( SearchService client = new SearchService(RpcClient.ConnectRpc(iid, "ncacn_ip_tcp", "::1", "12345") .Authenticate(RpcAuthenticationType.Self). EnableMultiPart(1000000))) { SearchRequest.Builder criteria = SearchRequest.CreateBuilder(); byte[] bytes = new byte[1000000]; new Random().NextBytes(bytes); SearchResponse results = client.Search(criteria.AddCriteria(Convert.ToBase64String(bytes)).Build()); Assert.AreEqual(2500, results.ResultsCount); } } }
static void Main(string[] args) { var node = new Uri(ConfigurationManager.AppSettings["Search-Uri"]); var settings = new ConnectionSettings(node); settings.ThrowExceptions(alwaysThrow: true); settings.DisableDirectStreaming(); var client = new ElasticClient(settings); System.Console.WriteLine("Starting indexing..."); var service = new SearchService(client, new ConsoleContextFactory()); service.CreateIndex(IndexDefinition.Actor, autoReindex: true); System.Console.WriteLine("Actor [done]"); service.CreateIndex(IndexDefinition.Movie, autoReindex: true); System.Console.WriteLine("Movie [done]"); service.FullRefresh(); System.Console.WriteLine("Completed!"); }
public void TestClientServerWithCustomFormat() { ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl()); //Setup our custom mime-type format as the only format supported: server.Options.MimeInputTypes.Clear(); server.Options.MimeInputTypes.Add("foo/bar", CodedInputStream.CreateInstance); server.Options.MimeOutputTypes.Clear(); server.Options.MimeOutputTypes.Add("foo/bar", CodedOutputStream.CreateInstance); //obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting IHttpTransfer wire = server; ExampleClient exclient = new ExampleClient(wire, "foo/bar"); //Add our custom mime-type format exclient.Options.MimeInputTypes.Add("foo/bar", CodedInputStream.CreateInstance); exclient.Options.MimeOutputTypes.Add("foo/bar", CodedOutputStream.CreateInstance); ISearchService client = new SearchService(exclient); //now the client has a real, typed, interface to work with: SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build()); Assert.AreEqual(1, result.ResultsCount); Assert.AreEqual("Test", result.ResultsList[0].Name); Assert.AreEqual("http://search.com", result.ResultsList[0].Url); //The test part of this, call the only other method result = client.RefineSearch( RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build()); Assert.AreEqual(2, result.ResultsCount); Assert.AreEqual("Test", result.ResultsList[0].Name); Assert.AreEqual("http://search.com", result.ResultsList[0].Url); Assert.AreEqual("Refine", result.ResultsList[1].Name); Assert.AreEqual("http://refine.com", result.ResultsList[1].Url); }
static void Main() { NGramService ngrammer = new NGramService(); ConcordanceService concordancer = new ConcordanceService(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); MainWindow main = new MainWindow(); CSVLoader loader = new CSVLoader(); LinearHeatmapForm heatmap = new LinearHeatmapForm(); DelimiterStep delim = new DelimiterStep(); ChartForm chart = new ChartForm(); Suggester suggester = new Suggester(); CSVReadService fileReader = new CSVReadService(); SearchService searcher = new SearchService(); HeatmapService heater = new HeatmapService(); FolderService folder = new FolderService(); DatasetStatisticsService dataset = new DatasetStatisticsService(); TaggedCollectionStatisticsService corpus = new TaggedCollectionStatisticsService(); //var tagger = main; TagService service = new TagService(); TagsetEditor editor = new TagsetEditor(); TagFileWriter writer = new TagFileWriter(); TagPresenter tagPresenter = new TagPresenter(main, main, service, editor, writer); TagsetPresenter tagsetPresenter = new TagsetPresenter(editor, service, main); SuggestPresenter suggestPresenter = new SuggestPresenter(suggester, main, main); MainPresenter presenter = new MainPresenter(main, main, service, loader, searcher, folder, dataset, corpus, concordancer, ngrammer); CSVPresenter csv = new CSVPresenter(main, loader, fileReader, delim); HeatmapPresenter heatmapPresenter = new HeatmapPresenter(main, heatmap, heater); ChartPresenter chartPresenter = new ChartPresenter(main, chart); main.AddOwnedForm(delim); Application.Run(main); }
public void LrpcPerformanceTest() { Win32RpcServer.VerboseLogging = false; try { using (RpcServer.CreateRpc(iid, new SearchService.ServerStub(new AuthenticatedSearch())) .AddAuthNegotiate() .AddProtocol("ncalrpc", "lrpctest") .StartListening()) { using ( SearchService client = new SearchService( RpcClient.ConnectRpc(iid, "ncalrpc", null, "lrpctest").Authenticate( RpcAuthenticationType.Self))) { SearchResponse previous = client.Search(SearchRequest.CreateBuilder() .AddCriteria("one").AddCriteria("two").AddCriteria( "three").Build()); RefineSearchRequest req = RefineSearchRequest.CreateBuilder() .AddCriteria("four").SetPreviousResults(previous).Build(); Stopwatch w = new Stopwatch(); w.Start(); for (int i = 0; i < 1000; i++) { client.RefineSearch(req); } w.Stop(); Trace.TraceInformation("Lrpc Performance = {0}", w.ElapsedMilliseconds); } } } finally { Win32RpcServer.VerboseLogging = true; } }
public void SearchServiceTest() { //Arrange var mock_db = new Mock <IHypermartContext>(); var Product1 = new Product { ID = 1, Title = "First Product", Description = "First Product In Database" }; var Product2 = new Product { ID = 2, Title = "Second Product", Description = "Second Product after the first product" }; var Product3 = new Product { ID = 3, Title = "Third Product", Description = "Third Product." }; var ProductsList = new List <Product> { Product1, Product2, Product3 }; var mockProducts = TestAPI.GenerateDBSet.CreateMockDBSet <Product>(ProductsList); mock_db.Setup(x => x.Products).Returns(mockProducts.Object); var SUT = new SearchService(mock_db.Object); var SearchTerm = "First"; //Act var result = SUT.PerformSearch(SearchTerm); //Assert mock_db.VerifyAll(); Assert.AreEqual(2, result.Count()); Assert.IsTrue(result.Contains(Product1)); Assert.IsTrue(result.Contains(Product2)); }
public override void Initialize(MockContext context) { base.Initialize(context); MockContext = context; ResourceManagementClient rmClient = context.GetServiceClient <ResourceManagementClient>(); // Register subscription for storage and networking Provider provider = rmClient.Providers.Register("Microsoft.Storage"); Assert.NotNull(provider); provider = rmClient.Providers.Register("Microsoft.Network"); Assert.NotNull(provider); StorageAccountName = SearchTestUtilities.GenerateStorageAccountName(); StorageManagementClient client = MockContext.GetServiceClient <StorageManagementClient>(); StorageAccount account = client.StorageAccounts.Create( ResourceGroupName, StorageAccountName, new StorageAccountCreateParameters( new Sku("Standard_LRS"), kind: "StorageV2", location: "eastus2euap")); Assert.NotNull(account); StorageAccountId = account.Id; SearchManagementClient searchMgmt = context.GetServiceClient <SearchManagementClient>(); ServiceName = SearchTestUtilities.GenerateServiceName(); SearchService service = DefineServiceWithSku(Management.Search.Models.SkuName.Basic); searchMgmt.Services.CreateOrUpdate(ResourceGroupName, ServiceName, service); }
public async Task CheckIfArtistsGetCorrectlyReturnedAsync(string searchValue) { var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()); var dbContext = new ApplicationDbContext(optionsBuilder.Options); var beatRepo = new EfDeletableEntityRepository <Beat>(dbContext); var userRepo = new EfDeletableEntityRepository <ApplicationUser>(dbContext); var searchService = new SearchService(userRepo, beatRepo); var artistIds = new List <string>(); artistIds.Add("user"); await userRepo.AddAsync(new ApplicationUser { Id = "user", UserName = searchValue, }); for (int i = 1; i <= 100; i++) { await userRepo.AddAsync(new ApplicationUser { Id = "1" + i, UserName = Guid.NewGuid().ToString(), }); artistIds.Add("1" + i); } ; await userRepo.SaveChangesAsync(); AutoMapperConfig.RegisterMappings(typeof(ArtistsSearchServiceModel).Assembly); var result = await searchService.GetArtistsByTermAsync(searchValue, artistIds); dbContext.Database.EnsureDeleted(); Assert.True(result.FirstOrDefault(x => x.UserName == searchValue).Id == "user"); }
public async Task TestSimplifiedSearcNGramAlgorythm() { //arrange var article = new Article { Name = "Нова стаття для тестування", Annotation = "Анотація до статті, що буде використано при тестуванні", Authors = "Світлана Вермська", ArticlePath = "somepath\\here" }; var addedArticle = await ArticleWriteRepository.AddArticle(article); var query = "Вермська нова"; //act var result = await SearchService.DoSearch(query); //assert Assert.IsNotNull(result); Assert.IsTrue(result.Count() >= 1); Assert.IsTrue(result.First().Id == addedArticle.Id); }
public void TestFindUsersWhenFound() { #region Arrange var user = new DirectoryUser(); user.LoginId = "test"; user.EmailAddress = "*****@*****.**"; user.FirstName = "FN"; user.LastName = "LN"; new FakeUsers(3, UserRepository); SearchService.Expect(a => a.FindUser("test")).Return(user); #endregion Arrange #region Act var result = Controller.FindUser("Test") .AssertResultIs <JsonNetResult>(); #endregion Act #region Assert Assert.IsNotNull(result); Assert.AreEqual("[{\"id\":\"test\",\"FirstName\":\"FN\",\"LastName\":\"LN\",\"Email\":\"[email protected]\",\"IsActive\":true}]", result.JsonResultString); SearchService.AssertWasCalled(a => a.FindUser("test")); #endregion Assert }
public void search_by_tagsfield_returns_multiple_results() { // Arrange SearchService searchService = CreateSearchService(); searchService.CreateIndex(); PageViewModel page1 = CreatePage(1, "admin", "random name1", "homepage1, tag1", "title content"); PageViewModel page2 = CreatePage(2, "admin", "random name2", "tag1, tag", "title content"); PageViewModel page3 = CreatePage(3, "admin", "random name3", "tag3, tag", "title content"); PageViewModel page4 = CreatePage(4, "admin", "random name4", "tag4, tag", "title content"); searchService.Add(page1); searchService.Add(page2); searchService.Add(page3); searchService.Add(page4); // Act List <SearchResultViewModel> results = searchService.Search("tags:\"tag1\"").ToList(); // Assert Assert.That(results.Count, Is.EqualTo(2)); }
public void Given_Item_Should_Add_To_Index() { var writer = new MemoryIndexWriter(true); var processor = new LuceneProcessor(writer); var item = new Item { Url = "http://dotnetgroup.lt", Tags = new[] { "c#", "dotnet" }, Content = "<b>sample content</b>", Title = "title", AuthorName = "author" }; processor.Process(item); var searcher = new MemoryIndexSearcher(writer.Directory, readOnly: false); var searchService = new SearchService(searcher); var results = searchService.SearchIndex(new MatchAllDocsQuery()).Results; Assert.AreEqual(1, results.Count()); }
public void search_by_title() { // Arrange SearchService searchService = CreateSearchService(); searchService.CreateIndex(); PageViewModel page1 = CreatePage(1, "admin", "the title", "tag1", "title content"); PageViewModel page2 = CreatePage(2, "admin", "random name1", "tag1", "title content"); PageViewModel page3 = CreatePage(3, "admin", "random name2", "tag1", "title content"); PageViewModel page4 = CreatePage(4, "admin", "random name3", "tag1", "title content"); searchService.Add(page1); searchService.Add(page2); searchService.Add(page3); searchService.Add(page4); // Act List <SearchResultViewModel> results = searchService.Search("title:\"the title\"").ToList(); // Assert Assert.That(results.Count, Is.EqualTo(1)); }
public Dictionary<string, List<SearchService.SearchResult>> MakeSearchDictionaries(SearchService.SearchResult[] searchResults) { Dictionary<string, List<SearchService.SearchResult>> dictionary = new Dictionary<string, List<SearchService.SearchResult>>(); int headersUniqueNumber = 0; //make sure we returned some results if (searchResults != null) { //loop through everything foreach (SearchService.SearchResult result in searchResults) { List<SearchService.SearchResult> list; //if url is empty, it must be a header if (string.IsNullOrEmpty(result.Link_URL)) { result.Link_URL = "" + headersUniqueNumber; headersUniqueNumber++; } //check if the url is an internal link..then continue so it doesn't get added if (!result.Link_URL.Contains("http://") && !(result.Link_URL.Contains("https://"))) continue; //see if the url exists in the dictionary if (dictionary.ContainsKey(result.Link_URL)) { //if it successfully got the list if (dictionary.TryGetValue(result.Link_URL, out list)) { list.Add(result); } } else { //add the list to the dictionary; list = new List<SearchService.SearchResult>(); list.Add(result); dictionary.Add(result.Link_URL, list); } } } return dictionary; }
public Dictionary<string, List<SearchService.SearchResult>> MakeSearchDictionaries(SearchService.SearchResult[] searchResults) { var dictionary = new Dictionary<string, List<SearchService.SearchResult>>(); var headersUniqueNumber = 0; //make sure we returned some results if (searchResults != null) { //loop through everything foreach (SearchService.SearchResult result in searchResults) { List<SearchService.SearchResult> list; //if url is empty, it must be a header if (string.IsNullOrEmpty(result.Link_URL)) { result.Link_URL = "" + headersUniqueNumber; headersUniqueNumber++; } //see if the url exists in the dictionary if (dictionary.ContainsKey(result.Link_URL)) { //if it successfully got the list if (dictionary.TryGetValue(result.Link_URL, out list)) { list.Add(result); } } else { //add the list to the dictionary; list = new List<SearchService.SearchResult> {result}; dictionary.Add(result.Link_URL, list); } } } return dictionary; }
public void SetUp() { _factory = new MockRepository(MockBehavior.Strict); _settings = _factory.Create<IVimGlobalSettings>(); _settings.SetupGet(x => x.Magic).Returns(true); _settings.SetupGet(x => x.IgnoreCase).Returns(true); _settings.SetupGet(x => x.SmartCase).Returns(false); _textSearch = _factory.Create<ITextSearchService>(); _searchRaw = new SearchService(_textSearch.Object, _settings.Object); _search = _searchRaw; }
public void SetUp() { _factory = new MockFactory(MockBehavior.Strict); _settings = _factory.Create<IVimGlobalSettings>(); _textSearch = _factory.Create<ITextSearchService>(); _searchRaw = new SearchService(_textSearch.Object, _settings.Object); _search = _searchRaw; }