Beispiel #1
0
        /// <summary>
        /// Search tMDB using the value
        /// </summary>
        /// <param name="value">The Search results</param>
        /// <returns>
        /// The series search.
        /// </returns>
        public List <SearchDetails> SeriesSearch(string value)
        {
            var seriesResults = new List <SearchDetails>();

            string searchXml =
                Downloader.ProcessDownload(
                    string.Format("http://cache.thetvdb.com/api/GetSeries.php?seriesname={0}", value),
                    DownloadType.Html,
                    Section.Tv);

            if (string.IsNullOrEmpty(searchXml))
            {
                return(seriesResults);
            }

            var document = new XmlDocument();

            document.LoadXml(searchXml.Replace("<br>", string.Empty));

            XmlNodeList results = document.GetElementsByTagName("Series");

            // Itterate through series
            foreach (XmlNode result in results)
            {
                var singleDocument = new XmlDocument();
                singleDocument.LoadXml(result.OuterXml);

                // Populate object with series details
                var modelSeriesSearchDetails = new SearchDetails();
                modelSeriesSearchDetails.PopulateSeriesDetail(singleDocument);
                seriesResults.Add(modelSeriesSearchDetails);
            }

            return(seriesResults);
        }
Beispiel #2
0
        public async Task SearchNestedOrderBy_Async()
        {
            // Arrange
            TestItemBare.Modulo = 2;
            TestItemBare.Count  = 1;
            await CreateItemAsync(TypeOfTestDataEnum.Variant1); // 1, 1
            await CreateItemAsync(TypeOfTestDataEnum.Variant2); // 2, 0
            await CreateItemAsync(TypeOfTestDataEnum.Variant2); // 3, 1
            await CreateItemAsync(TypeOfTestDataEnum.Variant2); // 4, 0
            await CreateItemAsync(TypeOfTestDataEnum.Variant2); // 5, 1

            // Act
            var search = CrudStorage as ISearch <TestItemSort <TId>, TId>;

            Assert.IsNotNull(search, $"{CrudStorage.GetType().Name} was expected to implement {nameof(ISearch<TestItemSort<TId>, TId>)}");

            var searchDetails = new SearchDetails <TestItemSort <TId> >(new { Value = "Variant2" }, new { NumberModulo = true, IncreasingNumber = false });
            var page          = await search.SearchAsync(searchDetails, 0, 10);

            // Assert
            Assert.AreEqual(4, page.PageInfo.Returned);
            var array = page.Data.ToArray();

            Assert.AreEqual(0, array[0].NumberModulo);
            Assert.AreEqual(4, array[0].IncreasingNumber);
            Assert.AreEqual(0, array[1].NumberModulo);
            Assert.AreEqual(2, array[1].IncreasingNumber);
            Assert.AreEqual(1, array[2].NumberModulo);
            Assert.AreEqual(5, array[2].IncreasingNumber);
            Assert.AreEqual(1, array[3].NumberModulo);
            Assert.AreEqual(3, array[3].IncreasingNumber);
        }
Beispiel #3
0
        public static IEnumerable <TModel> Sort <TModel>(IEnumerable <TModel> items, SearchDetails <TModel> details)
        {
            var list = items.ToList();

            list.Sort((item1, item2) => Compare(item1, item2, details));
            return(list);
        }
Beispiel #4
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string zi    = context.Request["zi"];
            int    count = Convert.ToInt32(context.Request["count"]);

            List <Books> list = (List <Books>)CacheHelper.GetCache("books");

            if (list == null)
            {
                list = bbl.GetModelList("");
                CacheHelper.SetCache("books", list);
            }
            PinYin p     = new PinYin();
            var    books = list.Where(b => p.GetFirstLetter(b.Title).Contains(zi.ToUpper())).Take(count);

            //每次搜索之后都要将搜索的字存到数据库中
            SearchDetails sd = new SearchDetails()
            {
                KeyWords       = zi,
                SearchDateTime = DateTime.Now
            };

            new SearchDetailsBll().Add(sd);
            //序列化
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = jss.Serialize(books);

            //输出
            context.Response.Write(json);
        }
        public static SearchDetailsResult GetSearchDetailsResult()
        {
            var searchDetailsResult = new SearchDetailsResult {PersonDetails = new List<SearchDetails>()};
            var searchDetails = new SearchDetails
            {
                DigipostAddress = "testulf#123",
                FirstName = "testulf",
                MiddleName = "the king",
                LastName = "testesen",
                MobileNumber = "12312312",
                OrganizationName = "123456",
                SearchDetailsAddress = new SearchDetailsAddress
                {
                    AdditionalAddressLine = "Testveien 1",
                    City = "Andeby",
                    HouseLetter = "1",
                    HouseNumber = "1",
                    Street = "Testveien",
                    ZipCode = "1212"
                }
            };

            searchDetailsResult.PersonDetails.Add(searchDetails);
            return searchDetailsResult;
        }
Beispiel #6
0
        public void Search(IParameter parameter)
        {
            if (IsSearching)
            {
                // if they don't cancel, do nothing
                if (MessageBox.Show("There is a search in progress.  Do you want to cancel the existing search?", "Search", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }

                // if they said yes, cancel existing search and continue with new one
                CancelSearch();
            }

            // Get results asynchronously
            ResultSQL = null;
            var details = new SearchDetails()
            {
                Target  = SelectedSubject,
                Columns = RetrieveFields.Adapter.UseFields ? RetrieveFields.Adapter.Fields : PathFactory.GetFields(SelectedSubject),
                Where   = parameter
            };

            SearchCanceller = _dbService.GetResults(details, new ResultCallback(SearchComplete, details));
        }
        public ActionResult Index(SearchDetails search)
        {
            if (ModelState.IsValid)
            {
                Search text = new Search();
                // details.inputString = search.newText;
                text.query = "User:"******"JabberJaw:" + response;
                mystrings.Add(text2);
                var model = details;
                if (response.Equals("I don't understand that"))
                {
                    model.isResponse = true;
                }
                else
                {
                    model.isResponse = false;
                }
                return(View(model));
            }
            else
            {
                return(View(details));
            }

            //return RedirectToRoute("Home", "Index");
            // return View();
        }
Beispiel #8
0
        private List <ContentViewModel> ShowSearchContent()
        {
            string        indexPath    = System.Configuration.ConfigurationManager.AppSettings["LuceneNetDir"];
            string        searchString = Request["txtSearch"];
            List <string> list         = LuceneCommon.PanGuSplitWord("Title", searchString);  //对用户输入的搜索条件进行拆分。
            FSDirectory   directory    = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader   reader       = IndexReader.Open(directory, true);
            IndexSearcher searcher     = new IndexSearcher(reader);
            //搜索条件
            PhraseQuery queryBody = new PhraseQuery();

            ////多部分查询
            //PhraseQuery queryTitle = new PhraseQuery();
            //先用空格,让用户去分词,空格分隔的就是词“计算机   专业”
            foreach (string word in list)
            {
                queryBody.Add(new Term("Price", word));
                //queryTitle.Add(new Term("Title", word));
            }
            //多个查询条件的词之间的最大距离.在文章中相隔太远 也就无意义.(例如 “大学生”这个查询条件和"简历"这个查询条件之间如果间隔的词太多也就没有意义了。)
            queryBody.Slop = 100;
            //queryTitle.SetSlop(100);

            #region 多部分查询

            //BooleanQuery query = new BooleanQuery();
            //query.Add(queryTitle, BooleanClause.Occur.SHOULD);
            //query.Add(queryBody, BooleanClause.Occur.SHOULD);

            #endregion

            //TopScoreDocCollector是盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, true);
            //根据query查询条件进行查询,查询结果放入collector容器
            searcher.Search(queryBody, null, collector);
            //得到所有查询结果中的文档,GetTotalHits():表示总条数   TopDocs(300, 20);//表示得到300(从300开始),到320(结束)的文档内容.
            ScoreDoc[] docs = collector.TopDocs(0, collector.TotalHits).ScoreDocs;
            //可以用来实现分页功能
            List <ContentViewModel> viewModelList = new List <ContentViewModel>();
            for (int i = 0; i < docs.Length; i++)
            {
                //搜索ScoreDoc[]只能获得文档的id,这样不会把查询结果的Document一次性加载到内存中。降低了内存压力,需要获得文档的详细内容的时候通过searcher.Doc来根据文档id来获得文档的详细内容对象Document.
                ContentViewModel viewModel = new ContentViewModel();
                int      docId             = docs[i].Doc;                                          //得到查询结果文档的id(Lucene内部分配的id)
                Document doc = searcher.Doc(docId);                                                //找到文档id对应的文档详细信息
                viewModel.Id      = Convert.ToInt32(doc.Get("Id"));                                // 取出放进字段的值
                viewModel.Title   = doc.Get("Title");
                viewModel.Content = LuceneCommon.CreateHightLight(searchString, doc.Get("Price")); //将搜索的关键字高亮显示。
                viewModelList.Add(viewModel);
            }
            //先将搜索的词插入到明细表。
            SearchDetails searchDetail = new SearchDetails();
            searchDetail.Id         = Guid.NewGuid();
            searchDetail.KeyWords   = Request["txtSearch"];
            searchDetail.SearchTime = DateTime.Now;
            SearchDetailsService.AddEntity(searchDetail);

            return(viewModelList);
        }
Beispiel #9
0
        /// <summary>
        /// Handles the Click event of the ButUse control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        private void ButUse_Click(object sender, EventArgs e)
        {
            string id =
                Regex.Match(this.cmbSearchResults.SelectedValue.ToString(), @"(?<id>\d*?):.*?").Groups["id"].Value;

            this.SelectedSeries = this.searchDetails.Single(s => s.ID.ToString() == id.ToString());
            this.Close();
        }
Beispiel #10
0
        private List <BookSearchModel> SearchBookContent(string searchWords)
        {
            List <BookSearchModel> bookSearchModelList = new List <BookSearchModel>();
            //1.对搜索条件进行分词
            Analyzer    analyzer    = new PanGuAnalyzer();
            TokenStream tokenStream = analyzer.TokenStream("", new StringReader(searchWords));

            Lucene.Net.Analysis.Token token = null;
            string indexPath = @"D:\lucenedir";
            //string kw = "面向对象";//对用户输入的搜索条件进行拆分。
            FSDirectory   directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader   reader    = IndexReader.Open(directory, true);
            IndexSearcher searcher  = new IndexSearcher(reader);
            //搜索条件
            PhraseQuery query = new PhraseQuery();

            //foreach (string word in kw.Split(' '))//先用空格,让用户去分词,空格分隔的就是词“计算机   专业”
            //{
            //    query.Add(new Term("body", word));
            //}
            //query.Add(new Term("body","语言"));--可以添加查询条件,两者是add关系.顺序没有关系.
            // query.Add(new Term("body", "大学生"));
            while ((token = tokenStream.Next()) != null)
            {
                query.Add(new Term("body", token.TermText()));
            }
            // query.Add(new Term("body", kw));//body中含有kw的文章
            query.SetSlop(100);//多个查询条件的词之间的最大距离.在文章中相隔太远 也就无意义.(例如 “大学生”这个查询条件和"简历"这个查询条件之间如果间隔的词太多也就没有意义了。)
            //TopScoreDocCollector是盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);

            searcher.Search(query, null, collector);                                    //根据query查询条件进行查询,查询结果放入collector容器
            ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs; //得到所有查询结果中的文档,GetTotalHits():表示总条数   TopDocs(300, 20);//表示得到300(从300开始),到320(结束)的文档内容.
            //可以用来实现分页功能
            for (int i = 0; i < docs.Length; i++)
            {
                //
                //搜索ScoreDoc[]只能获得文档的id,这样不会把查询结果的Document一次性加载到内存中。降低了内存压力,需要获得文档的详细内容的时候通过searcher.Doc来根据文档id来获得文档的详细内容对象Document.
                int             docId       = docs[i].doc;         //得到查询结果文档的id(Lucene内部分配的id)
                Document        doc         = searcher.Doc(docId); //找到文档id对应的文档详细信息
                BookSearchModel searchModel = new BookSearchModel();
                searchModel.Id                = int.Parse(doc.Get("ID"));
                searchModel.Title             = doc.Get("title");
                searchModel.ContenDescription = SearchWordHighlight.CreateHightLight(searchWords, doc.Get("body"));
                //this.listBox1.Items.Add(doc.Get("number") + "\n");// 取出放进字段的值
                //this.listBox1.Items.Add(doc.Get("body") + "\n");
                //this.listBox1.Items.Add("-----------------------\n");
                bookSearchModelList.Add(searchModel);
            }
            //将搜索的此插入词库之中
            SearchDetails entity = new SearchDetails()
            {
                Id = Guid.NewGuid(), KeyWords = searchWords, SearchDateTime = DateTime.Now
            };

            SearchDetailsService.AddEntity(entity);
            return(bookSearchModelList);
        }
        public async Task <String> InsertPeopleWithTitleDocObject([FromBody] SearchDetails searchobj)
        {
            IStatefulSearchApi infoDoc = ServiceProxy.Create <IStatefulSearchApi>(
                new Uri(uriString: "fabric:/ObjectSearchApp/ObjectSearchApi"),
                new ServicePartitionKey(0));
            String response = await infoDoc.SetPeopleWithTitleDoc(searchobj);

            return(response);
        }
 /// <summary>
 /// Clean up any resources being used.
 /// </summary>
 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
 protected override void Dispose(bool disposing)
 {
     if (disposing && (components != null))
     {
         components.Dispose();
         SearchDetails.Dispose();
     }
     base.Dispose(disposing);
 }
        public async Task <String> EditingText_GroupDocObject([FromBody] SearchDetails searchobj)
        {
            IStatefulSearchApi infoDoc = ServiceProxy.Create <IStatefulSearchApi>(
                new Uri(uriString: "fabric:/ObjectSearchApp/ObjectSearchApi"),
                new ServicePartitionKey(0));

            String response = await infoDoc.UpdateLocGroupObjectDoc(searchobj);

            return(response);
        }
        private static string Comparison <T>(SearchDetails <T> details, string columnName)
        {
            var whereCondition = details.GetWhereCondition(columnName, "%", "_");

            if (whereCondition.Object == null)
            {
                return($"[{columnName}] IS NULL");
            }
            return(whereCondition.IsWildCard ? $"[{columnName}] LIKE @{columnName}" : $"[{columnName}] = @{columnName}");
        }
Beispiel #15
0
        public async Task SearchOrderBy_Async(string value, bool orderByNumber, bool ascending)
        {
            // Arrange
            await CreateItemAsync(TypeOfTestDataEnum.Variant1);
            await CreateItemAsync(TypeOfTestDataEnum.Variant2);
            await CreateItemAsync(TypeOfTestDataEnum.Variant1);
            await CreateItemAsync(TypeOfTestDataEnum.Variant2);
            await CreateItemAsync(TypeOfTestDataEnum.NullValue);

            // Act
            var search = CrudStorage as ISearch <TestItemSort <TId>, TId>;

            Assert.IsNotNull(search, $"{CrudStorage.GetType().Name} was expected to implement {nameof(ISearch<TestItemSort<TId>, TId>)}");
            PageEnvelope <TestItemSort <TId> > page;

            if (orderByNumber)
            {
                var searchDetails = new SearchDetails <TestItemSort <TId> >(new { Value = value }, new { IncreasingNumber = ascending });
                page = await search.SearchAsync(searchDetails, 0, 10);
            }
            else
            {
                var searchDetails = new SearchDetails <TestItemSort <TId> >(new { Value = value }, new { DecreasingString = @ascending });
                page = await search.SearchAsync(searchDetails, 0, 10);
            }



            // Assert
            Assert.AreEqual(2, page.PageInfo.Returned);
            var array = page.Data.ToArray();

            if (orderByNumber)
            {
                if (ascending)
                {
                    Assert.IsTrue(array[0].IncreasingNumber < array[1].IncreasingNumber);
                }
                else
                {
                    Assert.IsTrue(array[0].IncreasingNumber > array[1].IncreasingNumber);
                }
            }
            else
            {
                if (ascending)
                {
                    Assert.IsTrue(string.Compare(array[0].DecreasingString, array[1].DecreasingString, StringComparison.InvariantCulture) == -1);
                }
                else
                {
                    Assert.IsTrue(string.Compare(array[0].DecreasingString, array[1].DecreasingString, StringComparison.InvariantCulture) == 1);
                }
            }
        }
Beispiel #16
0
 /// <summary>
 /// Handles the Click event of the ButUse control.
 /// </summary>
 /// <param name="sender">
 /// The source of the event.
 /// </param>
 /// <param name="e">
 /// The <see cref="System.EventArgs"/> instance containing the event data.
 /// </param>
 private void ButUse_Click(object sender, EventArgs e)
 {
     //fix for situation when user click on "OK" button and didn't choose any option from cmbSearchResults
     if (this.cmbSearchResults.SelectedValue != null)
     {
         string id =
             Regex.Match(this.cmbSearchResults.SelectedValue.ToString(), @"(?<id>\d*?):.*?").Groups["id"].Value;
         this.SelectedSeries = this.searchDetails.Single(s => s.ID.ToString() == id.ToString());
         this.Close();
     }
 }
Beispiel #17
0
        /// <summary>
        /// Update the statistics labels based on the current algorithm
        /// </summary>
        /// <param name="details"></param>
        private void StatsUpdate(SearchDetails details)
        {
            var labelCollection = _labels.First(x => x.AlgorithmId == _currentAlgorithm);

            labelCollection.Labels[0].BeginInvoke((MethodInvoker) delegate { labelCollection.Labels[0].Text = @"Algorithm: " + _algorithms[_currentAlgorithm].AlgorithmName; });
            labelCollection.Labels[1].BeginInvoke((MethodInvoker) delegate { labelCollection.Labels[1].Text = details.Operations.ToString(); });
            labelCollection.Labels[2].BeginInvoke((MethodInvoker) delegate { labelCollection.Labels[2].Text = details.UnexploredListSize.ToString(); });
            labelCollection.Labels[3].BeginInvoke((MethodInvoker) delegate { labelCollection.Labels[3].Text = details.OpenListSize.ToString(); });
            labelCollection.Labels[4].BeginInvoke((MethodInvoker) delegate { labelCollection.Labels[4].Text = details.ClosedListSize.ToString(); });
            labelCollection.Labels[5].BeginInvoke((MethodInvoker) delegate { labelCollection.Labels[5].Text = details.PathFound ? $"{details.Path.Length}/{details.PathCost}" : "?/?"; });
        }
        /// <summary>
        /// Constructs an ORDER BY statement from search details
        /// </summary>
        public static string GetOrderByStatement <T>(SearchDetails <T> details)
        {
            if (!details.OrderByPropertyNames.Any())
            {
                return(null);
            }
            var orderItems = details.OrderByPropertyNames.Select(name => $"[{name}] {AscOrDesc(name, details)}");
            var orderBy    = string.Join(", ", orderItems);

            return(orderBy);
        }
        /// <summary>
        /// 创建索引库
        /// </summary>
        //private void CreateSearchIndex()
        //{
        //    string indexPath = @"C:\lucenedir";//注意和磁盘上文件夹的大小写一致,否则会报错。将创建的分词内容放在该目录下。
        //    FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());//指定索引文件(打开索引目录) FS指的是就是FileSystem
        //    bool isUpdate = IndexReader.IndexExists(directory);//IndexReader:对索引进行读取的类。该语句的作用:判断索引库文件夹是否存在以及索引特征文件是否存在。
        //    if (isUpdate)
        //    {
        //        //同时只能有一段代码对索引库进行写操作。当使用IndexWriter打开directory时会自动对索引库文件上锁。
        //        //如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁(提示一下:如果我现在正在写着已经加锁了,但是还没有写完,这时候又来一个请求,那么不就解锁了吗?这个问题后面会解决)
        //        if (IndexWriter.IsLocked(directory))
        //        {
        //            IndexWriter.Unlock(directory);
        //        }
        //    }
        //    IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);//向索引库中写索引。这时在这里加锁。
        //    List<SearchContent> articelList = ArticelService.LoadEntities(a => a.DelFlag == 0).Select(a => new SearchContent() { Id = a.ID, Content = a.ArticleContent, Title = a.Title }).ToList();

        //    List<SearchContent> photoList = PhotoInfoService.LoadEntities(a => a.DelFlag == 0).Select(a => new SearchContent() { Id = a.ID, Content = a.PictureContent, Title = a.Title }).ToList();
        //    List<SearchContent> videoList = VideoFileInfoService.LoadEntities(a => a.DelFlag == 0).Select(a => new SearchContent() { Id = a.ID, Content = a.VideoContent, Title = a.Title }).ToList();

        //    articelList.AddRange(photoList);

        //    articelList.AddRange(videoList);
        //    foreach (var model in articelList)
        //    {
        //        writer.DeleteDocuments(new Term("Id", model.Id.ToString()));//删除
        //        Document document = new Document();//表示一篇文档。
        //        //Field.Store.YES:表示是否存储原值。只有当Field.Store.YES在后面才能用doc.Get("number")取出值来.Field.Index. NOT_ANALYZED:不进行分词保存
        //        document.Add(new Field("Id", model.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

        //        //Field.Index. ANALYZED:进行分词保存:也就是要进行全文的字段要设置分词 保存(因为要进行模糊查询)

        //        //Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS:不仅保存分词还保存分词的距离。
        //        document.Add(new Field("Title", model.Title, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
        //        document.Add(new Field("Content", model.Content, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
        //        writer.AddDocument(document);

        //    }

        //    writer.Close();//会自动解锁。
        //    directory.Close();//不要忘了Close,否则索引结果搜不到
        //}
        /// <summary>
        /// 搜索的实现
        /// </summary>
        /// <returns></returns>
        private List <SearchContent> SearchIndexContent()
        {
            string indexPath = @"C:\lucenedir";
            string k         = Request["txtSearch"];

            string[]      kw        = Common.WebCommon.GetPanGuWord(k).ToArray();
            FSDirectory   directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader   reader    = IndexReader.Open(directory, true);
            IndexSearcher searcher  = new IndexSearcher(reader);
            //搜索条件
            PhraseQuery query = new PhraseQuery();

            foreach (string word in kw)//先用空格,让用户去分词,空格分隔的就是词“计算机   专业”
            {
                query.Add(new Term("Content", word));
            }
            //query.Add(new Term("body","语言"));--可以添加查询条件,两者是add关系.顺序没有关系.
            // query.Add(new Term("body", "大学生"));
            // query.Add(new Term("body", kw));//body中含有kw的文章
            query.SetSlop(100);//多个查询条件的词之间的最大距离.在文章中相隔太远 也就无意义.(例如 “大学生”这个查询条件和"简历"这个查询条件之间如果间隔的词太多也就没有意义了。)
            //TopScoreDocCollector是盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);

            searcher.Search(query, null, collector);                                    //根据query查询条件进行查询,查询结果放入collector容器
            ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs; //得到所有查询结果中的文档,GetTotalHits():表示总条数   TopDocs(300, 20);//表示得到300(从300开始),到320(结束)的文档内容.
            //可以用来实现分页功能
            List <SearchContent> list = new List <SearchContent>();

            for (int i = 0; i < docs.Length; i++)
            {
                SearchContent searchContent = new SearchContent();
                //
                //搜索ScoreDoc[]只能获得文档的id,这样不会把查询结果的Document一次性加载到内存中。降低了内存压力,需要获得文档的详细内容的时候通过searcher.Doc来根据文档id来获得文档的详细内容对象Document.
                int      docId = docs[i].doc;                           //得到查询结果文档的id(Lucene内部分配的id)
                Document doc   = searcher.Doc(docId);                   //找到文档id对应的文档详细信息
                searchContent.Id      = Convert.ToInt32(doc.Get("Id")); // 取出放进字段的值
                searchContent.Flag    = Convert.ToInt32(doc.Get("Flag"));
                searchContent.AddDate = Convert.ToDateTime(doc.Get("AddDate"));
                searchContent.Title   = doc.Get("Title");
                searchContent.Content = Common.WebCommon.CreateHightLight(k, doc.Get("Content"));
                list.Add(searchContent);
            }
            //搜索一个词向明细表中插入一条记录
            SearchDetails searchDetail = new SearchDetails();

            searchDetail.Id             = Guid.NewGuid();
            searchDetail.KeyWords       = k;
            searchDetail.SearchDateTime = DateTime.Now;
            SearchDetailsService.AddEntity(searchDetail);

            return(list);
        }
Beispiel #20
0
        /// <inheritdoc />
        public async Task <TModel> FindUniqueChildAsync(TId parentId, SearchDetails <TModel> details, CancellationToken cancellationToken = default)
        {
            InternalContract.RequireNotNull(details, nameof(details));
            InternalContract.RequireValidated(details, nameof(details));
            var page = await _service.SearchChildrenAsync(parentId, details, 0, 2, cancellationToken);

            if (page.PageInfo.Returned > 1)
            {
                throw new FulcrumContractException($"Expected to find unique value, but found multiple items for search for model {typeof(TModel).Name} with {nameof(details)}:\r{details}");
            }

            return(page.Data.FirstOrDefault());
        }
Beispiel #21
0
        /// <inheritdoc />
        public async Task <TModel> FindUniqueAsync(SearchDetails <TModel> details, CancellationToken cancellationToken = default)
        {
            InternalContract.RequireNotNull(details, nameof(details));
            InternalContract.RequireValidated(details, nameof(details));
            var page = await _service.SearchAsync(details, 0, 2, cancellationToken);

            if (page.PageInfo.Returned > 1)
            {
                throw new FulcrumBusinessRuleException($"Expected to find one unique value, but found multiple items when searching for model {typeof(TModel).Name} with search details {nameof(details)}:\r{details}");
            }

            return(page.Data.FirstOrDefault());
        }
Beispiel #22
0
        /// <summary>
        /// Draw the found path onto the maze
        /// </summary>
        /// <param name="details"></param>
        private void BuildPath(SearchDetails details)
        {
            for (var i = 1; i < details.Path.Length - 1; i++)
            {
                var step = details.Path[i];
                _mazeDrawer.Grid.SetCell(step.X, step.Y, Enums.CellType.Path);
                _mazeDrawer.Draw();
                _soundManager.PlaySound(details.Path.Length - i);
                System.Threading.Thread.Sleep(25);
            }

            _soundManager.PlaySound(50);
        }
        /// <inheritdoc />
        public Task <PageEnvelope <TModel> > SearchAsync(SearchDetails <TModel> details, int offset, int?limit = null,
                                                         CancellationToken cancellationToken = default)
        {
            throw new FulcrumNotImplementedException();
            //if (!(_service is ISearch<TModel, TId> searcher))
            //{
            //    throw new FulcrumContractException(
            //        $"The service {_service.GetType().FullName} must implement {nameof(ISearch<TModel, TId>)}.");
            //}

            //var page = await searcher.SearchAsync(details, offset, limit, cancellationToken);
            //return new PageEnvelope<TModel>(page.PageInfo, page.Data.Select(Decrypt));
        }
Beispiel #24
0
        public static bool IsMatch <TModel>(TModel item, SearchDetails <TModel> details)
        {
            if (!details.WherePropertyNames.Any())
            {
                return(true);
            }

            var modelType = typeof(TModel);

            foreach (var propertyName in details.WherePropertyNames)
            {
                var propertyInfo = modelType.GetProperty(propertyName);
                if (propertyInfo == null)
                {
                    continue;
                }
                var itemValue      = propertyInfo.GetValue(item);
                var whereCondition = details.GetWhereCondition(propertyName, ".*", ".");
                if (whereCondition.Object == null)
                {
                    return(itemValue == null);
                }
                if (itemValue == null)
                {
                    return(false);
                }
                if (itemValue.GetType() != whereCondition.Object.GetType())
                {
                    return(false);
                }
                if (whereCondition.IsWildCard)
                {
                    var regexp = new Regex((string)whereCondition.Object);
                    if (!regexp.IsMatch(itemValue.ToString()))
                    {
                        return(false);
                    }
                }
                else
                {
                    if (itemValue.ToString() != whereCondition.Object.ToString())
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Constructs a WHERE statement from search details
        /// </summary>
        public static string GetWhereStatement <T>(SearchDetails <T> details, params string[] extraColumnNames)
        {
            if (!details.WherePropertyNames.Any() && extraColumnNames == null)
            {
                return(null);
            }
            var comparisons = details.WherePropertyNames
                              .Select(key => Comparison(details, key))
                              .ToList();

            comparisons.AddRange(extraColumnNames.Select(columnName => $"[{columnName}] = @{columnName}"));

            var where = string.Join(" AND ", comparisons);

            return(string.IsNullOrWhiteSpace(@where) ? null : @where);
        }
        //private void CreateSearchContent()
        //{
        //    string indexPath = @"D:\WebSites\lucenedir";//注意和磁盘上文件夹的大小写一致,否则会报错。将创建的分词内容放在该目录下。
        //    FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());//指定索引文件(打开索引目录) FS指的是就是FileSystem
        //    bool isUpdate = IndexReader.IndexExists(directory);//IndexReader:对索引进行读取的类。该语句的作用:判断索引库文件夹是否存在以及索引特征文件是否存在。
        //    if (isUpdate)
        //    {
        //        //同时只能有一段代码对索引库进行写操作。当使用IndexWriter打开directory时会自动对索引库文件上锁。
        //        //如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁(提示一下:如果我现在正在写着已经加锁了,但是还没有写完,这时候又来一个请求,那么不就解锁了吗?这个问题后面会解决)
        //        if (IndexWriter.IsLocked(directory))
        //        {
        //            IndexWriter.Unlock(directory);
        //        }
        //    }
        //    IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);//向索引库中写索引。这时在这里加锁。
        //    List<Books> list = BooksService.LoadEntities(t => true).ToList();
        //    foreach (var booksModel in list)
        //    {
        //        Document document = new Document();//表示一篇文档。
        //        //Field.Store.YES:表示是否存储原值。只有当Field.Store.YES在后面才能用doc.Get("number")取出值来.Field.Index. NOT_ANALYZED:不进行分词保存
        //        document.Add(new Field("Id", booksModel.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

        //        //Field.Index. ANALYZED:进行分词保存:也就是要进行全文的字段要设置分词 保存(因为要进行模糊查询)

        //        //Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS:不仅保存分词还保存分词的距离。
        //        document.Add(new Field("Title", booksModel.Title, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
        //        document.Add(new Field("ContentDescription", booksModel.ContentDescription, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
        //        writer.AddDocument(document);
        //    }
        //    writer.Dispose();//会自动解锁。
        //    directory.Dispose();//不要忘了Close,否则索引结果搜不到
        //}

        private List <ViewModelContent> ShowSearchContent()
        {
            string        indexPath = @"D:\WebSites\lucenedir";
            List <string> list      = Common.WebCommon.PanGuSplitWord(Request["txtSearch"]);//对用户输入的搜索条件进行拆分。
            FSDirectory   directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader   reader    = IndexReader.Open(directory, true);
            IndexSearcher searcher  = new IndexSearcher(reader);
            //搜索条件
            PhraseQuery query = new PhraseQuery();

            foreach (string word in list)//先用空格,让用户去分词,空格分隔的就是词“计算机   专业”
            {
                query.Add(new Term("ContentDescription", word));
            }
            //query.Add(new Term("body", "语言")); --可以添加查询条件,两者是add关系.顺序没有关系.
            // query.Add(new Term("body", "大学生"));
            //query.Add(new Term("body", kw));//body中含有kw的文章
            query.Slop = 100;//多个查询条件的词之间的最大距离.在文章中相隔太远 也就无意义.(例如 “大学生”这个查询条件和"简历"这个查询条件之间如果间隔的词太多也就没有意义了。)
            //TopScoreDocCollector是盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.Create(100, true);

            searcher.Search(query, null, collector);                               //根据query查询条件进行查询,查询结果放入collector容器
            ScoreDoc[] docs = collector.TopDocs(0, collector.TotalHits).ScoreDocs; //得到所有查询结果中的文档,GetTotalHits():表示总条数   TopDocs(300, 20);//表示得到300(从300开始),到320(结束)的文档内容.
            List <ViewModelContent> ViewModelList = new List <ViewModelContent>();

            for (int i = 0; i < docs.Length; i++)
            {
                //
                //搜索ScoreDoc[]只能获得文档的id,这样不会把查询结果的Document一次性加载到内存中。降低了内存压力,需要获得文档的详细内容的时候通过searcher.Doc来根据文档id来获得文档的详细内容对象Document.
                int              docId            = docs[i].Doc;         //得到查询结果文档的id(Lucene内部分配的id)
                Document         doc              = searcher.Doc(docId); //找到文档id对应的文档详细信息
                ViewModelContent viewModelContent = new ViewModelContent();
                viewModelContent.Id    = Convert.ToInt32(doc.Get("Id"));
                viewModelContent.Title = doc.Get("Title");
                viewModelContent.ContentDescription = WebCommon.CreateHightLight(Request["txtSearch"], doc.Get("ContentDescription"));
                ViewModelList.Add(viewModelContent);
            }
            SearchDetails searchDetails = new SearchDetails()
            {
                Id             = Guid.NewGuid(),
                KeyWords       = Request["txtSearch"],
                SearchDateTime = DateTime.Now
            };

            SearchDetailsService.AddEntity(searchDetails);
            return(ViewModelList);
        }
Beispiel #27
0
        /// <summary>
        /// This method will get all items and then do the filter and sorting in memory.
        /// </summary>
        /// <param name="parentId">The specific parent to search the child items for.</param>
        /// <param name="details">The search details</param>
        /// <param name="offset">The number of items that will be skipped in result.</param>
        /// <param name="limit">The maximum number of items to return.</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled</param>
        /// <returns>A page of the found items.</returns>
        /// <remarks>If your persistence layer supports search, then avoid using this, at it always reads all the items.</remarks>
        public async Task <PageEnvelope <TModel> > SearchChildrenAsync(TId parentId, SearchDetails <TModel> details, int offset, int?limit = null,
                                                                       CancellationToken cancellationToken = default)
        {
            limit = limit ?? PageInfo.DefaultLimit;
            InternalContract.RequireNotNull(details, nameof(details));
            InternalContract.RequireValidated(details, nameof(details));
            InternalContract.RequireGreaterThanOrEqualTo(0, offset, nameof(offset));
            InternalContract.RequireGreaterThan(0, limit.Value, nameof(limit));

            var allItems = (await _service.ReadChildrenAsync(parentId, int.MaxValue, cancellationToken))
                           .ToList();

            var list = SearchHelper.FilterAndSort(allItems, details)
                       .Skip(offset)
                       .Take(limit.Value);
            var page = new PageEnvelope <TModel>(offset, limit.Value, allItems.Count(), list);

            return(page);
        }
        public ActionResult Index()
        {
            //var model = new DatabaseRetrieval();
            //model.AllWithPartOfSpeech = _db.getAllbyPartOfSpeech("noun");
            if (Session["details"] != null)
            {
                //If so access it here
                SearchDetails dete  = Session["details"] as SearchDetails;
                var           model = dete;
                dbData.input = dete.inputString;
                //Console.WriteLine(dete.inputString);

                return(View(model));
            }
            else
            {
                return(RedirectToRoute("Home", "Index"));
            }
        }
Beispiel #29
0
        /// <summary>
        /// Populate series search details into object.
        /// </summary>
        /// <param name="seriesSearchDetails">The series Search Details.</param>
        /// <returns>
        /// The series object.
        /// </returns>
        public Series OpenNewSeries(SearchDetails seriesSearchDetails)
        {
            SeriesXml rawData = this.GetSeriesDetails(seriesSearchDetails.SeriesID, seriesSearchDetails.Language);

            var details = new Series();

            details.PopulateFullDetails(rawData);

            if (!string.IsNullOrEmpty(details.SeriesBannerUrl))
            {
                string url = "http://cache.thetvdb.com/banners/_cache/" + details.SeriesBannerUrl;

                string imagePath = Downloader.ProcessDownload(url, DownloadType.Binary, Section.Tv);

                details.SmallBanner = ImageHandler.LoadImage(imagePath);
            }

            return(details);
        }
Beispiel #30
0
        public async Task FindUnique_NotFound_Async()
        {
            // Arrange
            await CreateItemAsync(TypeOfTestDataEnum.Variant2);
            await CreateItemAsync(TypeOfTestDataEnum.Variant2);
            await CreateItemAsync(TypeOfTestDataEnum.NullValue);

            // Act
            var search = CrudStorage as ISearch <TestItemSort <TId>, TId>;

            Assert.IsNotNull(search, $"{CrudStorage.GetType().Name} was expected to implement {nameof(ISearch<TestItemSort<TId>, TId>)}");
            const string variant       = "Variant1";
            var          searchDetails = new SearchDetails <TestItemSort <TId> >(new { Value = variant });

            var item = await search.FindUniqueAsync(searchDetails);

            // Assert
            Assert.IsNull(item);
        }
        /// <summary>
        ///     Possible since 5.7
        ///     Search for issues, with a CQL (e.g. from a filter) see
        ///     <a href="https://docs.atlassian.com/confluence/REST/latest/#d2e4539">here</a>
        /// </summary>
        /// <param name="confluenceClient">IContentDomain to bind the extension method to</param>
        /// <param name="cqlClause">Confluence Query Language, like SQL, for the search</param>
        /// <param name="cqlContext">
        ///     the execution context for CQL functions, provides current space key and content id. If this is
        ///     not provided some CQL functions will not be available.
        /// </param>
        /// <param name="pagingInformation">PagingInformation</param>
        /// <param name="expandSearch">The expand value for the search, when null the value from the ConfluenceClientConfig.ExpandSearch is taken</param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>Result with content items</returns>
        public static Task <Result <Content> > SearchAsync(this IContentDomain confluenceClient, IFinalClause cqlClause, string cqlContext = null, PagingInformation pagingInformation = null, IEnumerable <string> expandSearch = null,
                                                           CancellationToken cancellationToken = default)
        {
            var searchDetails = new SearchDetails(cqlClause)
            {
                Start = pagingInformation?.Start,
                Limit = pagingInformation?.Limit
            };

            if (cqlContext != null)
            {
                searchDetails.CqlContext = cqlContext;
            }
            if (expandSearch != null)
            {
                searchDetails.ExpandSearch = expandSearch;
            }
            return(confluenceClient.SearchAsync(searchDetails, cancellationToken));
        }
 public static SendModel SearchDetailsToSendModel(SearchDetails searchDetails)
 {
     var sendModel = new SendModel();
     if (searchDetails.SearchDetailsAddress != null)
     {
         sendModel.AdditionalAddressLine = searchDetails.SearchDetailsAddress.AdditionalAddressLine;
         sendModel.City = searchDetails.SearchDetailsAddress.City;
         sendModel.HouseLetter = searchDetails.SearchDetailsAddress.HouseLetter;
         sendModel.HouseNumber = searchDetails.SearchDetailsAddress.HouseNumber;
         sendModel.Street = searchDetails.SearchDetailsAddress.Street;
         sendModel.ZipCode = searchDetails.SearchDetailsAddress.ZipCode;
     }
     sendModel.DigipostAddress = searchDetails.DigipostAddress;
     sendModel.FirstName = searchDetails.FirstName;
     sendModel.MiddleName = searchDetails.MiddleName;
     sendModel.LastName = searchDetails.LastName;
     sendModel.MobileNumber = searchDetails.MobileNumber;
     sendModel.OrganizationName = searchDetails.OrganizationName;
     return sendModel;
 }
Beispiel #33
0
        /// <summary>
        /// Search tMDB using the value
        /// </summary>
        /// <param name="value">The Search results</param>
        /// <returns>
        /// The series search.
        /// </returns>
        public List<SearchDetails> SeriesSearch(string value)
        {
            var seriesResults = new List<SearchDetails>();

            string searchXml =
                Downloader.ProcessDownload(
                    string.Format("http://cache.thetvdb.com/api/GetSeries.php?seriesname={0}", value), 
                    DownloadType.Html, 
                    Section.Tv);

            if (string.IsNullOrEmpty(searchXml))
            {
                return seriesResults;
            }

            var document = new XmlDocument();
            document.LoadXml(searchXml.Replace("<br>", string.Empty));

            XmlNodeList results = document.GetElementsByTagName("Series");

            // Itterate through series
            foreach (XmlNode result in results)
            {
                var singleDocument = new XmlDocument();
                singleDocument.LoadXml(result.OuterXml);

                // Populate object with series details
                var modelSeriesSearchDetails = new SearchDetails();
                modelSeriesSearchDetails.PopulateSeriesDetail(singleDocument);
                seriesResults.Add(modelSeriesSearchDetails);
            }

            return seriesResults;
        }
Beispiel #34
0
        /// <summary>
        /// Populate series search details into object.
        /// </summary>
        /// <param name="seriesSearchDetails">The series Search Details.</param>
        /// <returns>
        /// The series object.
        /// </returns>
        public Series OpenNewSeries(SearchDetails seriesSearchDetails)
        {
            SeriesXml rawData = this.GetSeriesDetails(seriesSearchDetails.SeriesID, seriesSearchDetails.Language);

            var details = new Series();
            details.PopulateFullDetails(rawData);

            if (!string.IsNullOrEmpty(details.SeriesBannerUrl))
            {
                string url = "http://cache.thetvdb.com/banners/_cache/" + details.SeriesBannerUrl;

                string imagePath = Downloader.ProcessDownload(url, DownloadType.Binary, Section.Tv);

                details.SmallBanner = ImageHandler.LoadImage(imagePath);
            }

            return details;
        }
Beispiel #35
0
        public static List<SearchDetails> SearchDefaultShowDatabase(string showName)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "TV", "Defaults", "DefaultShows.xml");

            if (!File.Exists(path))
            {
                return new List<SearchDetails>();
            }

            var xml = XRead.OpenPath(path);
            var shows = xml.GetElementsByTagName("show");

            var returnList = new List<SearchDetails>();

            foreach (XmlNode show in shows)
            {
                if (show.Attributes != null)
                {
                    if (show.Attributes["name"].Value.Equals(showName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        var searchDetails = new SearchDetails();

                        searchDetails.SeriesName = show.Attributes["name"].Value;
                        searchDetails.SeriesID = show.Attributes["id"].Value;

                        returnList.Add(searchDetails);

                        return returnList;
                    }
                }
            }

            return new List<SearchDetails>();
        }
 private static RequestContext MockedRequestContextWithSessionState(SearchDetails person)
 {
     var mockedContext = new Mock<HttpContextBase>();
     var session = new Mock<HttpSessionStateBase>();
     session.Setup(x => x[SessionConstants.PersonModel]).Returns(person);
     mockedContext.Setup(x => x.Session).Returns(session.Object);
     var requestContext = new RequestContext(mockedContext.Object, new RouteData());
     return requestContext;
 }
 private static SendController SendControllerWithMockedRequestContext(SearchDetails person)
 {
     var digipostServiceMock = new Mock<IDigipostService>();
     var controller = new SendController(digipostServiceMock.Object);
     var mockedRequestContext = MockedRequestContextWithSessionState(person);
     controller.ControllerContext = new ControllerContext(mockedRequestContext, controller);
     return controller;
 }
Beispiel #38
0
 /// <summary>
 /// Handles the Click event of the ButUse control.
 /// </summary>
 /// <param name="sender">
 /// The source of the event.
 /// </param>
 /// <param name="e">
 /// The <see cref="System.EventArgs"/> instance containing the event data.
 /// </param>
 private void ButUse_Click(object sender, EventArgs e)
 {
     string id =
         Regex.Match(this.cmbSearchResults.SelectedValue.ToString(), @"(?<id>\d*?):.*?").Groups["id"].Value;
     this.SelectedSeries = this.searchDetails.Single(s => s.ID.ToString() == id.ToString());
     this.Close();
 }
Beispiel #39
0
 /// <summary>
 /// Handles the Click event of the ButUse control.
 /// </summary>
 /// <param name="sender">
 /// The source of the event.
 /// </param>
 /// <param name="e">
 /// The <see cref="System.EventArgs"/> instance containing the event data.
 /// </param>
 private void ButUse_Click(object sender, EventArgs e)
 {
     //fix for situation when user click on "OK" button and didn't choose any option from cmbSearchResults
     if (this.cmbSearchResults.SelectedValue != null)
     {
         string id =
             Regex.Match(this.cmbSearchResults.SelectedValue.ToString(), @"(?<id>\d*?):.*?").Groups["id"].Value;
         this.SelectedSeries = this.searchDetails.Single(s => s.ID.ToString() == id.ToString());
         this.Close();
     }
 }