public void SearchResultsShouldReturnInternalError()
        {
            //arrange
            var expectedrecord = new Models.SearchResult
            {
                Id = "testid",
                Name = "test location",
                Address = "test address",
                PostCode = "12345",
                Town = "test town",
                Region = "test region",
                Category = "test category"
            };
            var expectedResult = new List<Models.SearchResult>();
            expectedResult.Add(expectedrecord);

           
           
            mockService.Setup(x => x.GetPaginatedResult(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(),
                It.IsAny<string>(), It.IsAny<bool>())).Throws(new Exception());
           
            mockValidation.Setup(x => x.CleanText(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<List<string>>(), It.IsAny<HashSet<char>>())).Returns("abc");

            //act
            var sut = new SearchController( mockService.Object, mockSession.Object, mockSettings.Object, mockValidation.Object);
            Action act = () => sut.SearchResults("search", 1);

            //assert
            act.Should().Throw<Exception>().Where(ex => ex.Data.Contains("GFCError"));
        }
Example #2
0
        public void SearchResultsShouldGetCorrectFacetResult()
        {
            //arrange
            var expectedrecord = new Models.SearchResult
            {
                Id       = "testid",
                Name     = "test location",
                Address  = "test address",
                PostCode = "12345",
                Town     = "test town",
                Region   = "test region",
                Category = "test category"
            };
            var expectedResult = new SearchServiceResult()
            {
                Facets = new EditableList <string> {
                    "Test Facet"
                },
                Data = new List <Models.SearchResult>()
            };

            expectedResult.Data.Add(expectedrecord);

            var mockSession = new Mock <ISessionService>();
            var mockService = new Mock <ISearchService>();

            mockService.Setup(x => x.GetPaginatedResult(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>(),
                                                        It.IsAny <string>(), It.IsAny <bool>())).ReturnsAsync(expectedResult).Verifiable();
            var mockSettings   = new Mock <IOptions <ApplicationSettings> >();
            var mockValidation = new Mock <IGdsValidation>();

            mockValidation.Setup(x => x.CleanText(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <List <string> >(), It.IsAny <HashSet <char> >())).Returns("abc");
            var mockUrlHelper = new Mock <IUrlHelper>();

            mockUrlHelper.Setup(x => x.Action(It.IsAny <UrlActionContext>())).Returns((UrlActionContext uac) =>
                                                                                      $"{uac.Controller}/{uac.Action}#{uac.Fragment}?" + string.Join("&",
                                                                                                                                                     new RouteValueDictionary(uac.Values).Select(p => p.Key + "=" + p.Value)));


            var tempData = new TempDataDictionary(new DefaultHttpContext(), Mock.Of <ITempDataProvider>());

            tempData["search"] = "";

            //act
            var sut = new SearchController(mockService.Object, mockSession.Object, mockSettings.Object, mockValidation.Object);

            sut.Url      = mockUrlHelper.Object;
            sut.TempData = tempData;

            var result = sut.SearchResults("search", 1, "TestFacet");

            //assert
            var viewResult = result as ViewResult;

            var model = viewResult.Model as SearchResultsVM;

            model.ShowResults.Should().Be(true);
            model.Facets.Count.Should().Be(1);
            mockService.Verify();
        }
Example #3
0
 private void VM_SearchingFinished(object sender, Models.SearchResult e)
 {
     //更新List
     SongResults.ItemsSource   = e.Songs;
     AlbumResults.ItemsSource  = e.Albums;
     ArtistResults.ItemsSource = e.Artists;
     ResultList.Visibility     = Visibility.Visible;
 }
Example #4
0
 public SearchResult(Models.SearchResult searchResult)
 {
     Limit    = searchResult.Limit;
     Offset   = searchResult.Offset;
     NumFound = searchResult.NumFound;
     Results  = (searchResult.Items != null) ? RegisterData.CreateFromList(searchResult.Items) : null;
     Facets   = (searchResult.Facets != null) ? Facet.CreateFromList(searchResult.Facets) : null;
 }
 public SearchResult(Models.SearchResult searchResult, UrlHelper urlHelper)
 {
     Limit    = searchResult.Limit;
     Offset   = searchResult.Offset;
     NumFound = searchResult.NumFound;
     Results  = Metadata.CreateFromList(searchResult.Items, urlHelper);
     Facets   = Facet.CreateFromList(searchResult.Facets);
     Type     = searchResult.Type;
 }
Example #6
0
        /// <summary>
        /// 获取搜索的结果
        /// </summary>
        /// <returns></returns>
        private IEnumerable<Models.SearchResult> GetSearchItems(string file)
        {
            List<Models.SearchResult> items = new List<Models.SearchResult>();
            try
            {
                bool isSearchFilterEnabled = true;

                //找出艺术家
                MatchCollection mc = Regex.Matches(file, @"<div class=\""result-item musician\"".*?>.*?</h3>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match mm in mc)
                {
                    string temp = mm.Groups[0].Value;
                    string titleTemp = Regex.Match(temp, @"<a.*?class=\""nbg\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                    string title = Regex.Match(titleTemp, @".*?title=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string link = Regex.Match(titleTemp, @".*?href=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string pictureTemp = Regex.Match(temp, @"<img.*?class=\""answer_pic\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                    string picture = Regex.Match(pictureTemp, @".*?src=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    Match ma = Regex.Match(temp, @".*?href=\""http://douban\.fm/\?context=([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    string context = null;
                    if (ma != null) context = ma.Groups[1].Value;
                    Models.SearchResult item = new Models.SearchResult(title, picture, link, null, true, context);
                    if (!isSearchFilterEnabled || !string.IsNullOrEmpty(item.Context))
                        items.Add(item);
                }

                //找出专辑
                mc = Regex.Matches(file, @"<tr.*?class=\""item\"">.*?</tr>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match mm in mc)
                {
                    string temp = mm.Groups[0].Value;
                    string titleTemp = Regex.Match(temp, @"<a.*?class=\""nbg\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                    string subject = Regex.Match(titleTemp, @"href=\"".*?subject/(\d+)", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string title = Regex.Match(titleTemp, @".*?title=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string link = Regex.Match(titleTemp, @".*?href=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string pictureTemp = Regex.Match(temp, @"<img.*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                    string picture = Regex.Match(pictureTemp, @".*?src=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    Match ma = Regex.Match(temp, @".*?href=\""http://douban\.fm/\?context=([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline);

                    string context = null;
                    if (ma != null && ma.Success) context = ma.Groups[1].Value;
                    if (string.IsNullOrEmpty(context))
                    {
                        context = MakeContext(subject);
                    }

                    Models.SearchResult item = new Models.SearchResult(title, picture, link, null, false, context);
                    if (!isSearchFilterEnabled || !string.IsNullOrEmpty(item.Context))
                        items.Add(item);
                }
            }
            catch { }

            return items;
        }
Example #7
0
        /// <summary>
        /// 在选中搜索结果时触发的方法
        /// </summary>
        /// <param name="result"></param>
        public void OnChooseSearchResult(Models.SearchResult result)
        {
            if (result == null)
            {
                return;
            }
            var channel = new Models.Channel()
            {
                Id = 0, Name = result.Title, Context = result.Context
            };

            this.CurrentChannel = channel;
        }
Example #8
0
        public void GetFacets_Should_Return_Facets()
        {
            //arrange
            var setupResult = new Models.SearchResult
            {
                Id       = "testid",
                Name     = "test location",
                Address  = "test address",
                PostCode = "12345",
                Town     = "test town",
                Region   = "test region",
                Category = "test category"
            };
            var doc = new Document
            {
                { "rid", setupResult.Id },
                { "locationName", setupResult.Name },
                { "postalAddressLine1", setupResult.Address },
                { "postalAddressTownCity", setupResult.Town },
                { "postalCode", setupResult.PostCode },
                { "region", setupResult.Region },
                { "syeInspectionCategories", new[] { "test category1", "test category2" } }
            };

            var mockedIndexClient = new Mock <ICustomSearchIndexClient>();
            var documentResult    = new DocumentSearchResult
            {
                Count   = 1,
                Facets  = new FacetResults(),
                Results = new List <SearchResult> {
                    new SearchResult {
                        Document = doc
                    }
                }
            };

            documentResult.Facets.Add("key", new List <FacetResult> {
                new FacetResult {
                    Value = "value"
                }
            });

            mockedIndexClient.Setup(x => x.SearchAsync(It.IsAny <string>(), It.IsAny <SearchParameters>())).ReturnsAsync(documentResult);

            //act
            var sut    = new SearchService(mockedIndexClient.Object);
            var result = sut.GetPaginatedResult("searchString", 1, 10, string.Empty, true).Result;

            //assert
            result.Count.Should().Be(1);
        }
Example #9
0
        public void Search_Should_Get_Result()
        {
            //arrange
            var expectedResult = new Models.SearchResult
            {
                Id       = "testid",
                Name     = "test location",
                Address  = "test address",
                PostCode = "12345",
                Town     = "test town",
                Region   = "test region",
                Category = "test category1"
            };
            var doc = new Document
            {
                { "id", expectedResult.Id },
                { "locationName", expectedResult.Name },
                { "postalAddressLine1", expectedResult.Address },
                { "postalAddressTownCity", expectedResult.Town },
                { "postalCode", expectedResult.PostCode },
                { "region", expectedResult.Region },
                { "syeInspectionCategories", new[] { "test category1" } }
            };

            var mockedIndexClient = new Mock <ICustomSearchIndexClient>();
            var documentResult    = new DocumentSearchResult
            {
                Results = new List <SearchResult> {
                    new SearchResult {
                        Document = doc
                    }
                }
            };

            mockedIndexClient.Setup(x => x.SearchAsync(It.IsAny <string>(), It.IsAny <SearchParameters>())).ReturnsAsync(documentResult);

            //act
            var sut    = new SearchService(mockedIndexClient.Object);
            var result = sut.GetPaginatedResult("searchString", 1, 10, string.Empty, true).Result.Data[0];

            //assert
            result.Id.Should().Be(expectedResult.Id);
            result.Name.Should().Be(expectedResult.Name);
            result.Address.Should().Be(expectedResult.Address);
            result.Town.Should().Be(expectedResult.Town);
            result.PostCode.Should().Be(expectedResult.PostCode);
            result.Region.Should().Be(expectedResult.Region);
            result.Category.Should().Be(expectedResult.Category);
            result.Page.Should().Be(1);
            result.Index.Should().Be(1);
        }
        public void SearchResultsShouldGetCorrectResult()
        {
            //arrange
            var expectedRecord = new Models.SearchResult
            {
                Id = "testid",
                Name = "test location",
                Address = "test address",
                PostCode = "12345",
                Town = "test town",
                Region = "test region",
                Category = "test category",
                Index = 1,
                Page = 1
            };
            var expectedResult = new SearchServiceResult() { Data = new List<SearchResult>() };
            expectedResult.Data.Add(expectedRecord);           
            mockService.Setup(x => x.GetPaginatedResult(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(),
                It.IsAny<string>(), It.IsAny<bool>())).ReturnsAsync(expectedResult).Verifiable();            
            mockUrlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns((UrlActionContext uac) =>
                $"{uac.Controller}/{uac.Action}#{uac.Fragment}?" + string.Join("&",
                    new RouteValueDictionary(uac.Values).Select(p => p.Key + "=" + p.Value)));
            mockValidation.Setup(x => x.CleanText(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<List<string>>(), It.IsAny<HashSet<char>>())).Returns("abc");
            
            
            var tempData = new TempDataDictionary(new DefaultHttpContext(), Mock.Of<ITempDataProvider>());
            tempData["search"] = "";
            //act
            var sut = new SearchController(mockService.Object, mockSession.Object, mockSettings.Object, mockValidation.Object);
            sut.Url = mockUrlHelper.Object;
            sut.TempData = tempData;
            var result = sut.SearchResults("search", null);

            //assert
            var viewResult = result as ViewResult;

            var model = viewResult.Model as SearchResultsVM;
            model.ShowResults.Should().Be(true);
            var resultToCompare = model.Data[0];
            resultToCompare.Id.Should().Be(expectedRecord.Id);
            resultToCompare.Name.Should().Be(expectedRecord.Name);
            resultToCompare.Address.Should().Be(expectedRecord.Address);
            resultToCompare.PostCode.Should().Be(expectedRecord.PostCode);
            resultToCompare.Town.Should().Be(expectedRecord.Town);
            resultToCompare.Region.Should().Be(expectedRecord.Region);
            resultToCompare.Category.Should().Be(expectedRecord.Category);
            resultToCompare.Index.Should().Be(1);
            resultToCompare.Page.Should().Be(1);
            mockService.Verify();
        }
Example #11
0
        public static Models.SearchResult Search(string text)
        {
            if (RedisHelper.HasKey(text))
            {
                var result = RedisHelper.GetFromCache(text);
                return(JsonConvert.DeserializeObject <Models.SearchResult>(result));
            }

            var books    = _bookIdxClient.Documents.Search <BookEx>(text).Results.Select(el => el.Document);
            var players  = _playersIdxClient.Documents.Search <PlayerEx>(text).Results.Select(el => el.Document);
            var students = _studentsIdxClient.Documents.Search <StudentEx>(text).Results.Select(el => el.Document);

            var searchResult = new Models.SearchResult
            {
                Books    = books.ToList(),
                Players  = players.ToList(),
                Students = students.ToList()
            };

            RedisHelper.Set(text, JsonConvert.SerializeObject(searchResult));

            return(searchResult);
        }
        public void SearchResultsShouldNotApplyFacetsIfTwoSetsOfFacetsSupplied()
        {
            //arrange
            var search = "test search";
            var expectedrecord = new Models.SearchResult
            {
                Id = "testid",
                Name = "test location",
                Address = "test address",
                PostCode = "12345",
                Town = "test town",
                Region = "test region",
                Category = "test category"
            };
            var expectedResult = new SearchServiceResult() { Data = new List<SearchResult> { expectedrecord } };

            var facets = new List<SelectItem>
            {
                new SelectItem {Text = "Facet1", Selected = true},
                new SelectItem {Text = "Facet2", Selected = false},
                new SelectItem {Text = "Facet3", Selected = true},
                new SelectItem {Text = "Face41", Selected = false}
            };
            var facetsModal = new List<SelectItem>
            {
                new SelectItem {Text = "Facet1", Selected = true},
                new SelectItem {Text = "Facet2", Selected = true},
                new SelectItem {Text = "Facet3", Selected = false},
                new SelectItem {Text = "Face41", Selected = false}
            };
            
            var expectedTotalCount = facets.Count();
            var expectedSelectedCount = 0; //As we are passing content that should never be supplied, we want to never select facets to filter by.

            var facetsList = new EditableList<string>();
            facetsList.AddRange(facets.Select(x => x.Text));
            expectedResult.Facets = facetsList;


            mockSession.Setup(x => x.GetUserSearch()).Returns(search);

            mockService.Setup(x => x.GetPaginatedResult(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(),
                It.IsAny<string>(), It.IsAny<bool>())).ReturnsAsync(expectedResult).Verifiable();

            mockValidation.Setup(x => x.CleanText(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<List<string>>(), It.IsAny<HashSet<char>>())).Returns(search);

            mockUrlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns((UrlActionContext uac) =>
                $"{uac.Controller}/{uac.Action}#{uac.Fragment}?" + string.Join("&",
                    new RouteValueDictionary(uac.Values).Select(p => p.Key + "=" + p.Value)));


            var tempData = new TempDataDictionary(new DefaultHttpContext(), Mock.Of<ITempDataProvider>());
            tempData["search"] = "";

            //act
            var sut = new SearchController(mockService.Object, mockSession.Object, mockSettings.Object, mockValidation.Object);
            sut.Url = mockUrlHelper.Object;
            sut.TempData = tempData;

            var result = sut.SearchResults(search, facets, facetsModal);

            //assert
            var viewResult = result as ViewResult;

            var model = viewResult.Model as SearchResultsVM;
            model.ShowResults.Should().Be(true);

            //check number of facets is correct
            model.Facets.Count.Should().Be(expectedTotalCount);
            model.FacetsModal.Count.Should().Be(expectedTotalCount);
            model.Facets.Count(x => x.Selected).Should().Be(expectedSelectedCount);
            model.FacetsModal.Count(x => x.Selected).Should().Be(expectedSelectedCount);

            //check the selected facets are correct - in this case no facets should be selected
            var selected = model.Facets.Where(x => x.Selected).Select(x => x.Text).ToList();
            selected.Should().BeEmpty();

            var selectedModal = model.FacetsModal.Where(x => x.Selected).Select(x => x.Text).ToList();
            selectedModal.Should().BeEmpty();

            mockService.Verify();
        }
Example #13
0
        public IHttpActionResult streamvideo(string vidid, string title)
        {
            //var mp3OutputFolder = HttpContext.Current.Server.MapPath("/mp3s");
            var mp3OutputFolder = @"C:/Users/Administrator/Desktop/lowdatayt/mp3s/";

            //Models.SearchResult selectedvideo
            Models.SearchResult selectedvideo = new Models.SearchResult()
            {
                vidid = vidid, title = title
            };
            //List<Models.SearchResult> searcheslist
            Boolean alreadydown = false;
            //var di = new DirectoryInfo("C:/Users/Administrator/Desktop/lowdatayt/mp3s");
            var di = new DirectoryInfo("C:/Users/Administrator/Desktop/lowdatayt/mp3s");

            foreach (FileInfo file in di.GetFiles())
            {
                if (selectedvideo.title + ".mp3" == file.Name)
                {
                    alreadydown = true;
                    break;
                }
            }
            if (alreadydown != true)
            {
                var urlToDownload = "https://www.youtube.com/watch?v=" + selectedvideo.vidid;
                var newFilename   = selectedvideo.title;
                //"C:/Users/Administrator/Desktop/lowdatayt/mp3s"
                var downloader = new AudioDownloader(urlToDownload, newFilename, mp3OutputFolder);
                downloader.ProgressDownload += downloader_ProgressDownload;
                downloader.FinishedDownload += downloader_FinishedDownload;
                downloader.Download();

                //var inputFile = new MediaFile { Filename = @"C:/Users/Owen Burns/Desktop/lowdatayt/mp3s/"+selectedvideo.title+".mp3" };
                //var outputFile = new MediaFile { Filename = @"C:/Users/Owen Burns/Desktop/lowdatayt/wavs/" + selectedvideo.title + ".wav" };
                //using (var engine = new Engine())
                //{
                //    engine.Convert(inputFile, outputFile);
                //}
            }
            //"C:/Users/Administrator/Desktop/lowdatayt/mp3s"
            Stream audiostream = File.Open(mp3OutputFolder + selectedvideo.title + ".mp3", FileMode.Open);

            //new code
            MemoryStream memoryStream = new MemoryStream();

            audiostream.CopyTo(memoryStream);
            audiostream.Close();
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(memoryStream.GetBuffer())
            };

            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = selectedvideo.title + ".mp3"
            };
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            var response = ResponseMessage(result);

            //end new code
            return(response);
        }
Example #14
0
        public async Task <ActionResult> Details(string _index, string _type, string _id)
        {
            var qc     = new Controllers.QueryController(_logger, _memoryCache);
            var result = await qc.GetDocument(_index, _type, _id);

            Models.SearchResult searchResult = new Models.SearchResult()
            {
                Id      = result.Id,
                CanRead = true,
                Index   = result.Index,
                Type    = result.Type,
                Summary = result.Source.ToString(),
                Source  = result.Source.ToString()
            };
            try
            {
                searchResult.Path          = ((string)result.Source["Path"]);
                searchResult.ThumbnailPath = ((string)result.Source["ThumbnailPath"]);
            }
            catch (Exception)
            {
            }
            if (!string.IsNullOrEmpty(searchResult.Path))//(searchResult.Type == "directory" || searchResult.Type == "file" || searchResult.Type == "photo")
            {
                searchResult.CanRead = Helpers.QueryHelper.UserHasAccess(User.Identity.Name, searchResult.Path.Substring(0, searchResult.Path.LastIndexOf('/')), _memoryCache);
                if (searchResult.CanRead)
                {
                    //searchResult.Path = searchResult.PrettyPath;
                    try
                    {
                        searchResult.Extension = (string)result.Source["Extension"];
                        DateTime lm = new DateTime();
                        if (DateTime.TryParse((string)result.Source["LastModified"], out lm))
                        {
                            searchResult.LastModified = lm.ToLocalTime(); //convert from UTC
                        }
                    }
                    catch (Exception)
                    {
                    }

                    if (System.IO.File.Exists(searchResult.Path) && result.Type == "photo")
                    {
                        string imageMagicHome = Environment.GetEnvironmentVariable("MAGICK_HOME");
                        if (!string.IsNullOrEmpty(imageMagicHome) && System.IO.Directory.Exists(imageMagicHome))
                        {
                            System.IO.FileInfo fi        = new System.IO.FileInfo(searchResult.Path);
                            string             localname = fi.FullName.GetHashCode() + ".png";
                            var localPath = Path.Combine(Environment.GetEnvironmentVariable("WebRootPathTemp"), localname);
                            //var localPath = Path.Combine(_hostingEnvironment.WebRootPath, "temp", localname);
                            searchResult.ThumbnailPath = "temp/" + localname;
                            if (!System.IO.File.Exists(localPath))
                            {
                                ProcessStartInfo psi = new ProcessStartInfo(Path.Combine(imageMagicHome, "magick.exe"), string.Format("\"{0}\" -resize 300x300 \"{1}\"", fi.FullName, localPath));
                                psi.WorkingDirectory = imageMagicHome;
                                //psi.UseShellExecute = true;
                                var p = Process.Start(psi);
                                p.WaitForExit(2000); //needs 2 sec delay before rendering that page
                            }
                        }
                        else //slow !!!
                        {
                            using (Stream str = System.IO.File.OpenRead(searchResult.Path))
                            {
                                using (MemoryStream data = new MemoryStream())
                                {
                                    str.CopyTo(data);
                                    data.Seek(0, SeekOrigin.Begin);
                                    byte[] buf = new byte[data.Length];
                                    data.Read(buf, 0, buf.Length);
                                    searchResult.Content = buf;
                                }
                            }
                        }

                        ///SystemDrawing is NotFound implemented in Core 1 RC2 yet :(
                        //Image image = Image.FromFile(imagePath, false);
                        //Image thumb = image.GetThumbnailImage(100, 100, () => false, IntPtr.Zero);
                        //thumb.Save(localPath, System.Drawing.Imaging.ImageFormat.Png);
                        //thumb.Dispose();
                    }
                }
            }

            //More Like This request
            Models.Query mltQuery = new Models.Query()
            {
                QueryTerm     = _index + "/" + _type + "/" + _id,
                Size          = 10,
                ChosenOptions = "1_" + _index + "+2_" + _type + "+3_6+"
            };
            var mltResults = await qc.GetSearchResponse(mltQuery);

            searchResult.MoreLikeThis = qc.GetSearchResults(User.Identity.Name, mltResults, mltQuery.QueryTerm)
                                        .Where(sr => sr.Id != _id)
                                        .Take(5);
            //foreach (var item in searchResult.MoreLikeThis)
            //{
            //    if (item.Id == _id)
            //    {
            //        item.Delete()
            //    }
            //}

            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")//(Request.IsAjaxRequest())
            {
                return(PartialView(searchResult));
            }
            return(View(searchResult));
        }
 public SearchResult(Models.SearchResult searchResult)
 {
     Limit    = searchResult.Limit;
     Offset   = searchResult.Offset;
     NumFound = searchResult.NumFound;
 }
Example #16
0
        /// <summary>
        /// 获取搜索的结果
        /// </summary>
        /// <returns></returns>
        private IEnumerable <Models.SearchResult> GetSearchItems(string file)
        {
            List <Models.SearchResult> items = new List <Models.SearchResult>();

            try
            {
                bool isSearchFilterEnabled = true;

                //找出艺术家
                MatchCollection mc = Regex.Matches(file, @"<div class=\""result-item musician\"".*?>.*?</h3>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match mm in mc)
                {
                    string temp        = mm.Groups[0].Value;
                    string titleTemp   = Regex.Match(temp, @"<a.*?class=\""nbg\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                    string title       = Regex.Match(titleTemp, @".*?title=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string link        = Regex.Match(titleTemp, @".*?href=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string pictureTemp = Regex.Match(temp, @"<img.*?class=\""answer_pic\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                    string picture     = Regex.Match(pictureTemp, @".*?src=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    Match  ma          = Regex.Match(temp, @".*?href=\""http://douban\.fm/\?context=([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    string context     = null;
                    if (ma != null)
                    {
                        context = ma.Groups[1].Value;
                    }
                    Models.SearchResult item = new Models.SearchResult(title, picture, link, null, true, context);
                    if (!isSearchFilterEnabled || !string.IsNullOrEmpty(item.Context))
                    {
                        items.Add(item);
                    }
                }

                //找出专辑
                mc = Regex.Matches(file, @"<tr.*?class=\""item\"">.*?</tr>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match mm in mc)
                {
                    string temp        = mm.Groups[0].Value;
                    string titleTemp   = Regex.Match(temp, @"<a.*?class=\""nbg\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                    string subject     = Regex.Match(titleTemp, @"href=\"".*?subject/(\d+)", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string title       = Regex.Match(titleTemp, @".*?title=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string link        = Regex.Match(titleTemp, @".*?href=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    string pictureTemp = Regex.Match(temp, @"<img.*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                    string picture     = Regex.Match(pictureTemp, @".*?src=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                    Match  ma          = Regex.Match(temp, @".*?href=\""http://douban\.fm/\?context=([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline);

                    string context = null;
                    if (ma != null && ma.Success)
                    {
                        context = ma.Groups[1].Value;
                    }
                    if (string.IsNullOrEmpty(context))
                    {
                        context = MakeContext(subject);
                    }

                    Models.SearchResult item = new Models.SearchResult(title, picture, link, null, false, context);
                    if (!isSearchFilterEnabled || !string.IsNullOrEmpty(item.Context))
                    {
                        items.Add(item);
                    }
                }
            }
            catch { }

            return(items);
        }