public ServiceOperationResult Create(int departureId, int arrivalId, DateTime departureDate, DateTime?arrivalDate, byte bookingType, int passengers) { var result = new ServiceOperationResult(); using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config)) { var newSearch = new SearchHistory() { Id = Guid.NewGuid(), FlyerId = _accountId, DepartureId = departureId, DepartureDate = departureDate, ArrivalId = arrivalId, ArrivalDate = arrivalDate, BookingType = bookingType, CreatedOn = DateTime.UtcNow, Passengers = passengers }; dbContext.SearchHistories.Add(newSearch); try { dbContext.SaveChanges(); result.IsSuccessfull = true; } catch (Exception e) { result.IsSuccessfull = false; result.Errors = new List <ErrorCodes>() { ErrorCodes.UnKnown }; } } return(result); }
public void Load() { using (var xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) { this.PluginName = xmlreader.GetValueAsString("youtubevideos", "PluginName", "YouTube.fm"); this.Region = xmlreader.GetValueAsString("youtubevideos", "Region", "Ask"); this.InitialDisplay = xmlreader.GetValueAsInt("youtubevideos", "InitialDisplay", 3); this.User = xmlreader.GetValueAsString("youtubevideos", "user", string.Empty); this.Password = xmlreader.GetValueAsString("youtubevideos", "password", string.Empty); this.InitialCat = xmlreader.GetValueAsInt("youtubevideos", "InitialCat", 1); this.VideoQuality = xmlreader.GetValueAsInt("youtubevideos", "VideoQuality", 0); this.InstantAction = (Action.ActionType)xmlreader.GetValueAsInt("youtubevideos", "InstantAction", (int)(Action.ActionType.REMOTE_1)); this.InitialSearch = xmlreader.GetValueAsString("youtubevideos", "InitialSearch", string.Empty); this.InstantChar = xmlreader.GetValueAsInt("youtubevideos", "InstantCharInt", 01); this.MusicFilter = xmlreader.GetValueAsBool("youtubevideos", "MusicFilter", true); this.UseSMSStyleKeyBoard = xmlreader.GetValueAsBool("youtubevideos", "UseSMSStyleKeyBoard", true); string his = xmlreader.GetValueAsString("youtubevideos", "searchhistory", string.Empty); this.Time = xmlreader.GetValueAsBool("youtubevideos", "time", false); this.ShowNowPlaying = xmlreader.GetValueAsBool("youtubevideos", "ShowNowPlaying", true); this.UseYouTubePlayer = xmlreader.GetValueAsBool("youtubevideos", "UseYouTubePlayer", false); this.UseExtremFilter = xmlreader.GetValueAsBool("youtubevideos", "UseExtremFilter", false); this.LoadOnlineFanart = xmlreader.GetValueAsBool("youtubevideos", "LoadOnlineFanart", true); this.FanartDir = xmlreader.GetValueAsString("youtubevideos", "FanartFolder", string.Empty); this.DownloadFolder = xmlreader.GetValueAsString("youtubevideos", "DownloadFolder", Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\My Videos"); foreach (string s in his.Split('|')) { if (!string.IsNullOrEmpty(s.Trim())) { SearchHistory.Add(s); } } } this.LocalFile.Load(); }
public OperationResultDTO AddSearchHistory(SearchHistory searchHistory) { context.SearchHistory.Add(searchHistory); context.SaveChanges(); return new OperationSuccessDTO<Module> { Message = "Success" }; }
private Task Find() { Action <object> search = o => { if (string.IsNullOrWhiteSpace(this.KeyWord)) { this.FindFiles = new List <FileResult>(); } var serach = new SearchHistory() { KeyWord = this.KeyWord, DateTime = DateTime.Now }; this._repository.AddOrUpdateAsync(serach); var serachResult = SearchHelper.Search(this.KeyWord, this.AllFiles.AsParallel().Select(p => p.FileName)); this.FindFiles = this.AllFiles.AsParallel().Join(serachResult.AsParallel(), outer => outer.FileName, inner => inner, (outer, inner) => outer); }; if (this._loadAllTask.IsCompleted) { return(Task.Factory.StartNew(search, null)); } else { return(this._loadAllTask.ContinueWith(search)); } }
internal void OnSearchHistorySelected(SearchHistory item) { SearchText.Value = item.Keyword; SelectedTarget.Value = TargetListItems.Single(x => x == item.Target); DoSearchCommand.Execute(); }
/// <summary> /// FindTaggedPages pages matching a search criterion in the background. /// </summary> /// <param name="query">query. If null or empty just all page tags are collected</param> /// <param name="scope">Range of the search</param> internal async Task FindPagesAsync(string query, SearchScope scope) { switch (scope) { case SearchScope.Notebook: LastScopeID = OneNoteApp.CurrentNotebookID; break; case SearchScope.SectionGroup: LastScopeID = OneNoteApp.CurrentSectionGroupID; break; case SearchScope.Section: LastScopeID = OneNoteApp.CurrentSectionID; break; default: LastScopeID = String.Empty; break; } if (!string.IsNullOrEmpty(query)) { query = query.Trim().Replace(',', ' '); SearchHistory.Remove(query); SearchHistory.Insert(0, query); // update settings StringBuilder history = new StringBuilder(); for (int i = 0; i < SearchHistory.Count() && i < Properties.Settings.Default.SearchHistory_Size; i++) { if (history.Length > 0) { history.Append(','); } history.Append(SearchHistory[i]); } Properties.Settings.Default.SearchHistory = history.ToString(); // construct the query pattern string[] words = query.Split(new char[] { ',', ' ', ':', ';' }, StringSplitOptions.RemoveEmptyEntries); _highlighter = new TextSplitter(from w in words select w.Replace("'", "").Replace("\"", "")); } else { _highlighter = new TextSplitter(); } await Task.Run(() => _searchResult.Find(query, LastScopeID), _cancelWorker.Token); // restore filter tag selection foreach (string filterTag in _searchResult.Filter) { TagSelectorModel mdl; if (Tags.TryGetValue(filterTag, out mdl)) { mdl.IsChecked = true; } } }
public virtual List <Int32> Search(Series series, dynamic options, ProgressNotification notification) { if (options == null) { throw new ArgumentNullException(options); } var searchResult = new SearchHistory { SearchTime = DateTime.Now, SeriesId = series.SeriesId, EpisodeId = options.GetType().GetProperty("Episode") != null ? options.Episode.EpisodeId : null, SeasonNumber = options.GetType().GetProperty("SeasonNumber") != null ? options.SeasonNumber : null }; List <EpisodeParseResult> reports = PerformSearch(series, options, notification); logger.Debug("Finished searching all indexers. Total {0}", reports.Count); notification.CurrentMessage = "Processing search results"; ProcessReports(series, options, reports, searchResult, notification); _searchHistoryProvider.Add(searchResult); if (searchResult.Successes.Any()) { return(searchResult.Successes); } FinalizeSearch(series, options, reports.Any(), notification); return(new List <Int32>()); }
public async Task <object> PostSearchHistory(SearchHistory searchHistory) { dynamic cResponse = new ExpandoObject(); try { if (!ModelState.IsValid) { cResponse.Result = "-1"; cResponse.Description = ModelState; return(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(cResponse))); } searchHistory.SearchDate = DateTime.Now; // will count searchHistory.CountResult = 0; db.SearchHistory.Add(searchHistory); await db.SaveChangesAsync(); cResponse.Result = "0"; cResponse.Description = "Search History added to database"; return(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(cResponse))); } catch { cResponse.Result = "-1"; cResponse.Description = "Exception, your request could not be executed"; return(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(cResponse))); } }
public async Task <IHttpActionResult> PutSearchHistory(int id, SearchHistory searchHistory) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != searchHistory.SearchID) { return(BadRequest()); } db.Entry(searchHistory).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SearchHistoryExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
private async void searchbar_SearchButtonPressed(object sender, EventArgs e) { var keyword = searchbar.Text; SearchHistory s = new SearchHistory() { BookTitle = keyword }; using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) { conn.CreateTable <SearchHistory>(); int rows = conn.Insert(s); if (rows > 0) { await DisplayAlert(null, "book added", "ok"); await Navigation.PushAsync(new Search()); } else { await DisplayAlert(null, "book cannot be added", "ok"); } } }
public static void AddSearchHistory(SearchHistory searchHistory) { using (var db = Db) { db.Execute("Insert into SearchHistory values (@Text, @Date)", new { searchHistory.Text, DateTime.Now }); } }
public async Task <IActionResult> PutSearchHistory(int id, SearchHistory searchHistory) { if (id != searchHistory.Id) { return(BadRequest()); } _context.Entry(searchHistory).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SearchHistoryExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
private void DeleteHistoryCommandImpl(string key) { if (!string.IsNullOrEmpty(key)) { SearchHistory.Remove(key); } }
public List <SearchHistory> GetUserSearchHistory(User user) { List <SearchHistory> searchHistoryList = new List <SearchHistory>(); using (SqlConnection sqlCon = new SqlConnection(_conn)) { SqlCommand sqlCmd = new SqlCommand("GetHistory", sqlCon); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Parameters.AddWithValue("@userId", user.Id); sqlCon.Open(); var rdr = sqlCmd.ExecuteReader(); if (rdr.HasRows) { var dt = new DataTable(); dt.Load(rdr); foreach (DataRow row in dt.Rows) { SearchHistory history = new SearchHistory(); history.Id = (long)Convert.ToDouble(row["Id"].ToString()); history.UserId = (long)Convert.ToDouble(row["userId"].ToString()); history.SearchTerm = row["searchHistory"].ToString(); searchHistoryList.Add(history); } } sqlCon.Close(); } return(searchHistoryList); }
public void SaveZipCodeToSearchHistory(int memberId, string zipCode) { using (var transaction = _context.Database.BeginTransaction()) { try { var check = _context.UserHistory.Where(zip => zip.ZipCode.Equals(zipCode) && zip.MemberId == memberId); //ensure data integrity. if (check.Count <SearchHistory>() == 0) { SearchHistory item = new SearchHistory() { MemberId = memberId, ZipCode = zipCode }; _context.Add(item); Task task = _context.SaveChangesAsync(); task.Wait(); transaction.Commit(); } } catch (DbUpdateConcurrencyException) { transaction.Rollback(); throw; } } }
public MainWindow() { InitializeComponent(); // TODO: Разобраться с файлом настроек и не городить такие безобразные строчки GlobalSettings.EightWay = Properties.Settings.Default.EightWay; // Data _searchingAlg = new DijkstraSearch(); _nodeGrid = SquareGrid.CreateWithForest(); _start = _nodeGrid[3, 3]; _start.Type = NodeType.Start; _goal = _nodeGrid[8, 7]; _goal.Type = NodeType.Goal; _nodeGrid.AddWall(8, 1); _history = _history = _searchingAlg.SearchWithHistory(_nodeGrid, _start, _goal); // View GridView.Init(_history); GridView.ShowStep(-1); GridView.WallAdded += GridView_WallAdded; GridView.WallRemoved += GridView_WallRemoved; GridView.StartChanged += GridView_StartChanged; GridView.GoalChanged += GridView_GoalChanged; }
public virtual List<Int32> Search(Series series, dynamic options, ProgressNotification notification) { if (options == null) throw new ArgumentNullException(options); var searchResult = new SearchHistory { SearchTime = DateTime.Now, SeriesId = series.SeriesId, EpisodeId = options.GetType().GetProperty("Episode") != null ? options.Episode.EpisodeId : null, SeasonNumber = options.GetType().GetProperty("SeasonNumber") != null ? options.SeasonNumber : null }; List<EpisodeParseResult> reports = PerformSearch(series, options, notification); logger.Debug("Finished searching all indexers. Total {0}", reports.Count); notification.CurrentMessage = "Processing search results"; ProcessReports(series, options, reports, searchResult, notification); _searchHistoryProvider.Add(searchResult); if(searchResult.Successes.Any()) return searchResult.Successes; FinalizeSearch(series, options, reports.Any(), notification); return new List<Int32>(); }
private void CreateIndexer() { ServiceLocator.Resolve <UIPackage>(); ServiceLocator.RegisterInstance(new IndexFilterManager()); PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new SnowballAnalyzer("English")); analyzer.AddAnalyzer(SandoField.Source.ToString(), new KeywordAnalyzer()); analyzer.AddAnalyzer(SandoField.AccessLevel.ToString(), new KeywordAnalyzer()); analyzer.AddAnalyzer(SandoField.ProgramElementType.ToString(), new KeywordAnalyzer()); ServiceLocator.RegisterInstance <Analyzer>(analyzer); var currentIndexer = new DocumentIndexer(TimeSpan.FromSeconds(10), GetTimeToCommit()); ServiceLocator.RegisterInstance(currentIndexer); ServiceLocator.RegisterInstance(new IndexUpdateManager()); currentIndexer.ClearIndex(); ServiceLocator.Resolve <InitialIndexingWatcher>().InitialIndexingStarted(); var dictionary = new DictionaryBasedSplitter(); dictionary.Initialize(PathManager.Instance.GetIndexPath(ServiceLocator.Resolve <SolutionKey>())); var reformer = new QueryReformerManager(dictionary); reformer.Initialize(null); ServiceLocator.RegisterInstance(reformer); var history = new SearchHistory(); history.Initialize(PathManager.Instance.GetIndexPath (ServiceLocator.Resolve <SolutionKey>())); ServiceLocator.RegisterInstance(history); }
public bool Equals(ApplicationSetting other) { return (SkipFirstBlankRows == other.skipFirstBlankRows && SkipFirstBlankColumns == other.SkipFirstBlankColumns && TrimLastBlankRows == other.TrimLastBlankRows && TrimLastBlankColumns == other.TrimLastBlankColumns && ExternalCommands.SequenceEqual(other.ExternalCommands) && FileSettings.SequenceEqual(other.FileSettings) && RecentFileSets.SequenceEqual(other.RecentFileSets) && CellWidth == other.cellWidth && AlternatingColorStrings.SequenceEqual(other.AlternatingColorStrings) && ColumnHeaderColorString.Equals(other.ColumnHeaderColorString) && RowHeaderColorString.Equals(other.RowHeaderColorString) && AddedColorString.Equals(other.AddedColorString) && RemovedColorString.Equals(other.RemovedColorString) && ModifiedColorString.Equals(other.ModifiedColorString) && ModifiedRowColorString.Equals(other.ModifiedRowColorString) && ColorModifiedRow.Equals(other.ColorModifiedRow) && SearchHistory.Equals(other.SearchHistory) && FontName.Equals(other.FontName) && LogFormat.Equals(other.LogFormat) && AddedRowLogFormat.Equals(other.AddedRowLogFormat) && RemovedRowLogFormat.Equals(other.RemovedRowLogFormat)); }
private async static Task AddRepositoriesToSearchHistory( IActorStateManager stateManager, List <Repository> repositories) { SearchHistory oldHistory = await GetSearchHistoryAsync(stateManager); SearchHistory newHistory = Serializer.DeepCopy(oldHistory); List <CachedItem <Repository> > newRepositories = new List <CachedItem <Repository> >(); List <string> oldRepositoryIds = oldHistory.Repositories .Select(item => RepositoryId(item.Data)).ToList(); foreach (var repository in repositories) { if (!oldRepositoryIds.Contains(RepositoryId(repository))) { newRepositories.Add(new CachedItem <Repository> { Data = repository }); } } int skip = newRepositories.Count - Constants.MAX_HISTORY_COUNT; newRepositories = newRepositories.Skip(skip).ToList(); newRepositories.AddRange(oldHistory.Repositories); newHistory.Repositories = newRepositories; await SetSearchHistoryAsync(stateManager, newHistory); }
internal void AddToSearchHistory(string searchText) { if (!CodeIDXSettings.Search.EnableSearchHistory) { return; } if (string.IsNullOrEmpty(searchText)) { return; } if (SearchHistory.Contains(searchText)) { int index = SearchHistory.IndexOf(searchText); if (index != 0) { _SearchHistory.Move(index, 0); } } else { _SearchHistory.Insert(0, searchText); while (_SearchHistory.Count > 20) { _SearchHistory.Remove(_SearchHistory.LastOrDefault()); } } }
public SearchHistoryListItemViewModel(SearchHistory source, SearchPageViewModel parentVM) { SearchHistory = source; SearchPageVM = parentVM; Keyword = source.Keyword; Target = source.Target; }
//[CheckLogin] public ActionResult HistoryDeal(DateTime?startDate, DateTime?expirationDate, int?typePay, int?status) { if ((CheckUser)Session["Account"] != null) { CheckUser current = (CheckUser)Session["Account"]; if (startDate != null || expirationDate != null || typePay != null || status != null) { SearchHistory search = new SearchHistory { ID_Acc = current.ID_User, StartDate = startDate, ExpirationDate = expirationDate, TypePay = typePay, Status = status }; List <Order> data = db.SearchHistory(search); ViewBag.startDate = startDate; ViewBag.expirationDate = expirationDate; ViewBag.typePay = typePay; ViewBag.orders = data; ViewBag.count = data.Count; return(Json(data, JsonRequestBehavior.AllowGet)); } else { var orders = db.GetOrderByIDAcc(current.ID_User); ViewBag.orders = orders; ViewBag.count = orders.Count; return(View()); } } else { return(RedirectToAction("Index", "Home")); } }
public async Task <ActionResult <SearchHistory> > PostSearchHistory(SearchHistory searchHistory) { searchHistory.DateCreated = DateTime.Now; _context.SearchHistories.Add(searchHistory); await _context.SaveChangesAsync(); return(CreatedAtAction("GetSearchHistory", new { id = searchHistory.Id }, searchHistory)); }
public ActionResult DeleteConfirmed(int id) { SearchHistory searchHistory = db.SearchHistories.Find(id); db.SearchHistories.Remove(searchHistory); db.SaveChanges(); return(RedirectToAction("Index")); }
public SearchHistory Post([FromBody] string value) { SearchHistory searchHistory = new SearchHistory(); searchHistory = db.searchhistory.Add(searchHistory).Entity; db.SaveChanges(); return(searchHistory); }
public async Task <List <SearchResult> > GetVideos([FromBody] SearchHistory searchHistory) { var ya = new YoutubeApi(); await ya.Run(searchHistory.SearchTerm); _service.InsertHistory(searchHistory); return(ya.Videos); }
public ActionResult Index(string searchTerm = null) { if (Session["CustomerID"] != null && searchTerm != null && searchTerm != "") //to add to search history { var id = Convert.ToInt32(Session["CustomerID"]); var modelSH = new SearchHistory(); modelSH.Customer_ID = id; modelSH.SearchTag = searchTerm; modelSH.Date = DateTime.Now; _db.SearchHistory.Add(modelSH); _db.SaveChanges(); } var modelP = _db.Product.Where(p => searchTerm == null || p.ProductName.StartsWith(searchTerm)).ToList(); var modelPR = _db.ProductRequest.Select(p => p.Product_ID).ToList(); //requested product wating for verification var modelDP = _db.DeletedProduct.Select(p => p.Product_ID).ToList(); //deleted product foreach (var pro in modelPR) { var model = _db.Product.Where(p => p.ID == pro).FirstOrDefault(); modelP.Remove(model); } foreach (var pro in modelDP) { var model = _db.Product.Where(p => p.ID == pro).FirstOrDefault(); modelP.Remove(model); } var modelT = _db.Trend.Select(p => p.Product).ToList(); ViewData["TrendingProduct"] = modelT; var obj = new HomePageProductSuggestion(); ViewData["SuggestedProduct"] = obj.ProductSuggestion(); //need to create view //making quantity 0 in kart to relese products to sale var modelK = _db.Kart.ToList(); foreach (var kartProduct in modelK) { var timeDifference = DateTime.Now.Subtract(kartProduct.DateTime).TotalMinutes; if (timeDifference >= 120) //if difference is 2 Hour or more { kartProduct.Quantity = 0; } _db.Entry(kartProduct).State = EntityState.Modified; } _db.SaveChanges(); return(View(modelP)); }
private void SearchHistoryList_ItemClick_1(object sender, ItemClickEventArgs e) { SearchHistory sh = (SearchHistory)e.ClickedItem; if (sh != null) { this.Frame.Navigate(typeof(TravelAdvicePage), sh); } }
private void DeleteHistory() { PlannerService.DeleteSearchHistoryAsync(); SearchHistory.Clear(); RaisePropertyChanged(() => SearchHistory); SelectedReisMogelijkheid = null; SelectedSearch = null; }
void Reset() { input = ""; hits.Clear(); var json = EditorPrefs.GetString(SearchHistoryKey, JsonUtility.ToJson(new SearchHistory())); history = JsonUtility.FromJson <SearchHistory>(json); Focus(); }
public virtual int Add(SearchHistory searchHistory) { logger.Trace("Adding new search result"); searchHistory.SuccessfulDownload = searchHistory.SearchHistoryItems.Any(s => s.Success); var id = Convert.ToInt32(_database.Insert(searchHistory)); searchHistory.SearchHistoryItems.ForEach(s => s.SearchHistoryId = id); logger.Trace("Adding search result items"); _database.InsertMany(searchHistory.SearchHistoryItems); return id; }
public virtual List<int> SeasonSearch(ProgressNotification notification, int seriesId, int seasonNumber) { var searchResult = new SearchHistory { SearchTime = DateTime.Now, SeriesId = seriesId, SeasonNumber = seasonNumber }; var series = _seriesProvider.GetSeries(seriesId); if (series == null) { _logger.Error("Unable to find an series {0} in database", seriesId); return new List<int>(); } //Return false if the series is a daily series (we only support individual episode searching if (series.IsDaily) return new List<int>(); notification.CurrentMessage = String.Format("Searching for {0} Season {1}", series.Title, seasonNumber); var reports = PerformSearch(notification, series, seasonNumber); _logger.Debug("Finished searching all indexers. Total {0}", reports.Count); if (reports.Count == 0) return new List<int>(); _logger.Debug("Getting episodes from database for series: {0} and season: {1}", seriesId, seasonNumber); var episodeNumbers = _episodeProvider.GetEpisodeNumbersBySeason(seriesId, seasonNumber); if (episodeNumbers == null || episodeNumbers.Count == 0) { _logger.Warn("No episodes in database found for series: {0} and season: {1}.", seriesId, seasonNumber); return new List<int>(); } notification.CurrentMessage = "Processing search results"; reports.Where(p => p.FullSeason && p.SeasonNumber == seasonNumber).ToList().ForEach( e => e.EpisodeNumbers = episodeNumbers.ToList() ); searchResult.SearchHistoryItems = ProcessSearchResults(notification, reports, searchResult, series, seasonNumber); _searchHistoryProvider.Add(searchResult); return searchResult.Successes; }
public void CreateIndexer() { TestUtils.InitializeDefaultExtensionPoints(); _indexerPath = Path.GetTempPath() + "luceneindexer"; Directory.CreateDirectory(_indexerPath); _solutionKey = new SolutionKey(Guid.NewGuid(), "C:/SolutionPath"); ServiceLocator.RegisterInstance(_solutionKey); ServiceLocator.RegisterInstance<Analyzer>(new SimpleAnalyzer()); _indexer = new DocumentIndexer(); ServiceLocator.RegisterInstance(_indexer); ServiceLocator.RegisterInstance<ISandoOptionsProvider>(new FakeOptionsProvider(String.Empty, 20, false, new List<string>())); // xige var dictionary = new DictionaryBasedSplitter(); dictionary.Initialize(PathManager.Instance.GetIndexPath(ServiceLocator.Resolve<SolutionKey>())); ServiceLocator.RegisterInstance(dictionary); var reformer = new QueryReformerManager(dictionary); reformer.Initialize(null); ServiceLocator.RegisterInstance(reformer); var history = new SearchHistory(); history.Initialize(PathManager.Instance.GetIndexPath (ServiceLocator.Resolve<SolutionKey>())); ServiceLocator.RegisterInstance(history); ClassElement classElement = SampleProgramElementFactory.GetSampleClassElement( accessLevel: AccessLevel.Public, definitionLineNumber: 11, extendedClasses: "SimpleClassBase", fullFilePath: "C:/Projects/SimpleClass.cs", implementedInterfaces: "IDisposable", name: "SimpleName", namespaceName: "Sanod.Indexer.UnitTests" ); SandoDocument sandoDocument = DocumentFactory.Create(classElement); _indexer.AddDocument(sandoDocument); MethodElement methodElement = SampleProgramElementFactory.GetSampleMethodElement( accessLevel: AccessLevel.Protected, name: "SimpleName", returnType: "Void", fullFilePath: "C:/stuff" ); sandoDocument = DocumentFactory.Create(methodElement); _indexer.AddDocument(sandoDocument); Thread.Sleep(2000); }
public string GetDisplayName(SearchHistory searchResult) { if (!searchResult.EpisodeNumber.HasValue) { return String.Format("{0} - Season {1}", searchResult.SeriesTitle, searchResult.SeasonNumber); } string episodeString; if (searchResult.IsDaily) episodeString = searchResult.AirDate.ToShortDateString().Replace('/', '-'); else episodeString = String.Format("S{0:00}E{1:00}", searchResult.SeasonNumber, searchResult.EpisodeNumber); return String.Format("{0} - {1} - {2}", searchResult.SeriesTitle, episodeString, searchResult.EpisodeTitle); }
public void Setup() { _series = Builder<Series>.CreateNew() .Build(); _episode = Builder<Episode>.CreateNew() .Build(); var items = Builder<SearchHistoryItem>.CreateListOfSize(10) .All() .With(c => c.Quality = QualityTypes.SDTV) .Build().ToList(); _searchHistory = Builder<SearchHistory>.CreateNew() .With(h => h.EpisodeId = _episode.EpisodeId) .With(h => h.SeriesId - _series.SeriesId) .With(h => h.SearchHistoryItems = items) .Build(); }
public void Setup() { _matchingSeries = Builder<Series>.CreateNew() .With(s => s.SeriesId = 79488) .With(s => s.Title = "30 Rock") .Build(); _mismatchedSeries = Builder<Series>.CreateNew() .With(s => s.SeriesId = 12345) .With(s => s.Title = "Not 30 Rock") .Build(); _searchHistory = new SearchHistory(); _notification = new ProgressNotification("Test"); _episodes = Builder<Episode> .CreateListOfSize(1) .Build(); Mocker.GetMock<EpisodeProvider>() .Setup(s => s.GetEpisodesByParseResult(It.IsAny<EpisodeParseResult>())) .Returns(_episodes); }
public void CreateIndexer() { ServiceLocator.Resolve<UIPackage>(); ServiceLocator.RegisterInstance(new IndexFilterManager()); Analyzer analyzer = SnowballAndWordSplittingAnalyzer.GetAnalyzer(); ServiceLocator.RegisterInstance<Analyzer>(analyzer); var currentIndexer = new DocumentIndexer(); ServiceLocator.RegisterInstance(currentIndexer); ServiceLocator.RegisterInstance(new IndexUpdateManager()); currentIndexer.ClearIndex(); ServiceLocator.Resolve<InitialIndexingWatcher>().SetInitialIndexingStarted(); var dictionary = new DictionaryBasedSplitter(); dictionary.Initialize(PathManager.Instance.GetIndexPath(ServiceLocator.Resolve<SolutionKey>())); ServiceLocator.RegisterInstance(dictionary); var reformer = new QueryReformerManager(dictionary); reformer.Initialize(null); ServiceLocator.RegisterInstance(reformer); var history = new SearchHistory(); history.Initialize(PathManager.Instance.GetIndexPath (ServiceLocator.Resolve<SolutionKey>())); ServiceLocator.RegisterInstance(history); ServiceLocator.RegisterType<IIndexerSearcher<SimpleSearchCriteria>, SimpleIndexerSearcher>(); }
public void AddToSearchHistories(SearchHistory searchHistory) { base.AddObject("SearchHistories", searchHistory); }
public static SearchHistory CreateSearchHistory(int searchHistoryID, int userID, string searchText) { SearchHistory searchHistory = new SearchHistory(); searchHistory.SearchHistoryID = searchHistoryID; searchHistory.UserID = userID; searchHistory.SearchText = searchText; return searchHistory; }
private void SetupRecommenderSystem() { // xige var dictionary = new DictionaryBasedSplitter(taskScheduler); ServiceLocator.RegisterInstance(dictionary); dictionary.Initialize(PathManager.Instance.GetIndexPath(ServiceLocator.Resolve<SolutionKey>())); ServiceLocator.Resolve<IndexUpdateManager>().indexUpdated += dictionary.UpdateProgramElement; ServiceLocator.RegisterInstance(dictionary); var reformer = new QueryReformerManager(dictionary); reformer.Initialize(null); ServiceLocator.RegisterInstance(reformer); var history = new SearchHistory(); history.Initialize(PathManager.Instance.GetIndexPath (ServiceLocator.Resolve<SolutionKey>())); ServiceLocator.RegisterInstance(history); }
public List<SearchHistoryItem> ProcessSearchResults(ProgressNotification notification, IEnumerable<EpisodeParseResult> reports, SearchHistory searchResult, Series series, int seasonNumber, int? episodeNumber = null) { var items = new List<SearchHistoryItem>(); searchResult.Successes = new List<int>(); foreach (var episodeParseResult in reports.OrderByDescending(c => c.Quality) .ThenBy(c => c.EpisodeNumbers.MinOrDefault()) .ThenBy(c => c.Age)) { try { logger.Trace("Analysing report " + episodeParseResult); var item = new SearchHistoryItem { ReportTitle = episodeParseResult.OriginalString, NzbUrl = episodeParseResult.NzbUrl, Indexer = episodeParseResult.Indexer, Quality = episodeParseResult.Quality.Quality, Proper = episodeParseResult.Quality.Proper, Size = episodeParseResult.Size, Age = episodeParseResult.Age, Language = episodeParseResult.Language }; items.Add(item); //Get the matching series episodeParseResult.Series = _seriesProvider.FindSeries(episodeParseResult.CleanTitle); //If series is null or doesn't match the series we're looking for return if (episodeParseResult.Series == null || episodeParseResult.Series.SeriesId != series.SeriesId) { logger.Trace("Unexpected series for search: {0}. Skipping.", episodeParseResult.CleanTitle); item.SearchError = ReportRejectionType.WrongSeries; continue; } //If SeasonNumber doesn't match or episode is not in the in the list in the parse result, skip the report. if (episodeParseResult.SeasonNumber != seasonNumber) { logger.Trace("Season number does not match searched season number, skipping."); item.SearchError = ReportRejectionType.WrongSeason; continue; } //If the EpisodeNumber was passed in and it is not contained in the parseResult, skip the report. if (episodeNumber.HasValue && !episodeParseResult.EpisodeNumbers.Contains(episodeNumber.Value)) { logger.Trace("Searched episode number is not contained in post, skipping."); item.SearchError = ReportRejectionType.WrongEpisode; continue; } //Make sure we haven't already downloaded a report with this episodenumber, if we have, skip the report. if (searchResult.Successes.Intersect(episodeParseResult.EpisodeNumbers).Any()) { logger.Trace("Episode has already been downloaded in this search, skipping."); item.SearchError = ReportRejectionType.Skipped; continue; } episodeParseResult.Episodes = _episodeProvider.GetEpisodesByParseResult(episodeParseResult); item.SearchError = _allowedDownloadSpecification.IsSatisfiedBy(episodeParseResult); if (item.SearchError == ReportRejectionType.None) { logger.Debug("Found '{0}'. Adding to download queue.", episodeParseResult); try { if (_downloadProvider.DownloadReport(episodeParseResult)) { notification.CurrentMessage = String.Format("{0} Added to download queue", episodeParseResult); //Add the list of episode numbers from this release searchResult.Successes.AddRange(episodeParseResult.EpisodeNumbers); item.Success = true; } else { item.SearchError = ReportRejectionType.DownloadClientFailure; } } catch (Exception e) { logger.ErrorException("Unable to add report to download queue." + episodeParseResult, e); notification.CurrentMessage = String.Format("Unable to add report to download queue. {0}", episodeParseResult); item.SearchError = ReportRejectionType.DownloadClientFailure; } } } catch (Exception e) { logger.ErrorException("An error has occurred while processing parse result items from " + episodeParseResult, e); } } return items; }
public void processSearchResults_Successes_should_not_be_null_or_empty() { var parseResults = Builder<EpisodeParseResult>.CreateListOfSize(5) .All() .With(e => e.SeasonNumber = 1) .With(e => e.EpisodeNumbers = new List<int> { 1 }) .With(c => c.Quality = new QualityModel(QualityTypes.DVD, true)) .With(c => c.Age = 10) .Random(1) .With(c => c.Quality = new QualityModel(QualityTypes.Bluray1080p, true)) .With(c => c.Age = 100) .Build(); var searchHistory = new SearchHistory(); WithMatchingSeries(); WithSuccessfulDownload(); Mocker.GetMock<AllowedDownloadSpecification>() .Setup(s => s.IsSatisfiedBy(It.Is<EpisodeParseResult>(d => d.Quality.Quality == QualityTypes.Bluray1080p))) .Returns(ReportRejectionType.None); //Act var result = Mocker.Resolve<SearchProvider>().ProcessSearchResults(new ProgressNotification("Test"), parseResults, searchHistory, _matchingSeries, 1, 1); //Assert searchHistory.Successes.Should().NotBeNull(); searchHistory.Successes.Should().NotBeEmpty(); Mocker.GetMock<AllowedDownloadSpecification>().Verify(c => c.IsSatisfiedBy(It.IsAny<EpisodeParseResult>()), Times.Once()); Mocker.GetMock<DownloadProvider>().Verify(c => c.DownloadReport(It.IsAny<EpisodeParseResult>()), Times.Once()); }
public virtual List<int> PartialSeasonSearch(ProgressNotification notification, int seriesId, int seasonNumber) { var searchResult = new SearchHistory { SearchTime = DateTime.Now, SeriesId = seriesId, SeasonNumber = seasonNumber }; var series = _seriesProvider.GetSeries(seriesId); if (series == null) { _logger.Error("Unable to find an series {0} in database", seriesId); return new List<int>(); } //Return empty list if the series is a daily series (we only support individual episode searching if (series.IsDaily) return new List<int>(); notification.CurrentMessage = String.Format("Searching for {0} Season {1}", series.Title, seasonNumber); var episodes = _episodeProvider.GetEpisodesBySeason(seriesId, seasonNumber); var reports = PerformSearch(notification, series, seasonNumber, episodes); _logger.Debug("Finished searching all indexers. Total {0}", reports.Count); if (reports.Count == 0) return new List<int>(); notification.CurrentMessage = "Processing search results"; searchResult.SearchHistoryItems = ProcessSearchResults(notification, reports, searchResult, series, seasonNumber); _searchHistoryProvider.Add(searchResult); return searchResult.Successes; }
public virtual List<int> SeasonSearch(ProgressNotification notification, int seriesId, int seasonNumber) { var searchResult = new SearchHistory { SearchTime = DateTime.Now, SeriesId = seriesId, SeasonNumber = seasonNumber }; var series = _seriesProvider.GetSeries(seriesId); if (series == null) { logger.Error("Unable to find an series {0} in database", seriesId); return new List<int>(); } if (series.IsDaily) { logger.Trace("Daily series detected, skipping season search: {0}", series.Title); return new List<int>(); } logger.Debug("Getting episodes from database for series: {0} and season: {1}", seriesId, seasonNumber); var episodes = _episodeProvider.GetEpisodesBySeason(seriesId, seasonNumber); if (episodes == null || episodes.Count == 0) { logger.Warn("No episodes in database found for series: {0} and season: {1}.", seriesId, seasonNumber); return new List<int>(); } notification.CurrentMessage = String.Format("Searching for {0} Season {1}", series.Title, seasonNumber); List<EpisodeParseResult> reports; if (series.UseSceneNumbering) { var sceneSeasonNumbers = episodes.Select(e => e.SceneSeasonNumber).ToList(); var sceneEpisodeNumbers = episodes.Select(e => e.SceneEpisodeNumber).ToList(); if (sceneSeasonNumbers.Distinct().Count() > 1) { logger.Trace("Uses scene numbering, but multiple seasons found, skipping."); return new List<int>(); } reports = PerformSeasonSearch(series, sceneSeasonNumbers.First()); reports.Where(p => p.FullSeason && p.SeasonNumber == sceneSeasonNumbers.First()).ToList().ForEach( e => e.EpisodeNumbers = sceneEpisodeNumbers.ToList() ); } else { reports = PerformSeasonSearch(series, seasonNumber); reports.Where(p => p.FullSeason && p.SeasonNumber == seasonNumber).ToList().ForEach( e => e.EpisodeNumbers = episodes.Select(ep => ep.EpisodeNumber).ToList() ); } logger.Debug("Finished searching all indexers. Total {0}", reports.Count); if (reports.Count == 0) return new List<int>(); notification.CurrentMessage = "Processing search results"; searchResult.SearchHistoryItems = ProcessSearchResults(notification, reports, searchResult, series, seasonNumber); _searchHistoryProvider.Add(searchResult); return searchResult.Successes; }
public InFileSearchHistoryTests() { queries = new List<string>(); history = new SearchHistory(); }
public SearchHistoryTests() { history = new SearchHistory(); }
public virtual SearchHistory ProcessReports(Series series, dynamic options, List<EpisodeParseResult> episodeParseResults, SearchHistory searchResult, ProgressNotification notification) { var items = new List<SearchHistoryItem>(); searchResult.Successes = new List<Int32>(); foreach(var episodeParseResult in episodeParseResults .OrderByDescending(c => c.Quality) .ThenBy(c => c.EpisodeNumbers.MinOrDefault()) .ThenBy(c => c.Age)) { try { var item = new SearchHistoryItem { ReportTitle = episodeParseResult.OriginalString, NzbUrl = episodeParseResult.NzbUrl, Indexer = episodeParseResult.Indexer, Quality = episodeParseResult.Quality.Quality, Proper = episodeParseResult.Quality.Proper, Size = episodeParseResult.Size, Age = episodeParseResult.Age, Language = episodeParseResult.Language }; items.Add(item); logger.Trace("Analysing report " + episodeParseResult); episodeParseResult.Series = _seriesProvider.FindSeries(episodeParseResult.CleanTitle); if(episodeParseResult.Series == null || episodeParseResult.Series.SeriesId != series.SeriesId) { item.SearchError = ReportRejectionType.WrongSeries; continue; } episodeParseResult.Episodes = _episodeProvider.GetEpisodesByParseResult(episodeParseResult); if (searchResult.Successes.Intersect(episodeParseResult.Episodes.Select(e => e.EpisodeId)).Any()) { item.SearchError = ReportRejectionType.Skipped; continue; } CheckReport(series, options, episodeParseResult, item); if (item.SearchError != ReportRejectionType.None) continue; item.SearchError = _allowedDownloadSpecification.IsSatisfiedBy(episodeParseResult); if(item.SearchError == ReportRejectionType.None) { if(DownloadReport(notification, episodeParseResult, item)) searchResult.Successes.AddRange(episodeParseResult.Episodes.Select(e => e.EpisodeId)); } } catch(Exception e) { logger.ErrorException("An error has occurred while processing parse result items from " + episodeParseResult, e); } } searchResult.SearchHistoryItems = items; return searchResult; }
private void Upsert(string keyword) { SearchHistory existKeyword = modelContext.SearchHistory.FirstOrDefault(z => z.Keyword.Equals(keyword)); if (existKeyword == null) { existKeyword = new SearchHistory(); existKeyword.Keyword = keyword; existKeyword.Count = 1; existKeyword.LastDate = DateTime.Now; modelContext.SearchHistory.Add(existKeyword); } else { existKeyword.Count += 1; existKeyword.LastDate = DateTime.Now; } modelContext.SaveChanges(); }
public virtual bool EpisodeSearch(ProgressNotification notification, int episodeId) { var episode = _episodeProvider.GetEpisode(episodeId); if (episode == null) { logger.Error("Unable to find an episode {0} in database", episodeId); return false; } if (!_upgradePossibleSpecification.IsSatisfiedBy(episode)) { logger.Info("Search for {0} was aborted, file in disk meets or exceeds Profile's Cutoff", episode); notification.CurrentMessage = String.Format("Skipping search for {0}, the file you have is already at cutoff", episode); return false; } notification.CurrentMessage = "Looking for " + episode; List<EpisodeParseResult> reports; var searchResult = new SearchHistory { SearchTime = DateTime.Now, SeriesId = episode.Series.SeriesId, EpisodeId = episodeId }; if (episode.Series.IsDaily) { if (!episode.AirDate.HasValue) { logger.Warn("AirDate is not Valid for: {0}", episode); notification.CurrentMessage = String.Format("Search for {0} Failed, AirDate is invalid", episode); return false; } reports = PerformDailyEpisodeSearch(episode.Series, episode); logger.Debug("Finished searching all indexers. Total {0}", reports.Count); notification.CurrentMessage = "Processing search results"; searchResult.SearchHistoryItems = ProcessSearchResults(notification, reports, episode.Series, episode.AirDate.Value); _searchHistoryProvider.Add(searchResult); if (searchResult.SearchHistoryItems.Any(r => r.Success)) return true; } else if (episode.Series.UseSceneNumbering) { var seasonNumber = episode.SceneSeasonNumber; var episodeNumber = episode.SceneEpisodeNumber; if (seasonNumber == 0 && episodeNumber == 0) { seasonNumber = episode.SeasonNumber; episodeNumber = episode.EpisodeNumber; } reports = PerformEpisodeSearch(episode.Series, seasonNumber, episodeNumber); searchResult.SearchHistoryItems = ProcessSearchResults( notification, reports, searchResult, episode.Series, seasonNumber, episodeNumber ); _searchHistoryProvider.Add(searchResult); if (searchResult.SearchHistoryItems.Any(r => r.Success)) return true; } else { reports = PerformEpisodeSearch(episode.Series, episode.SeasonNumber, episode.EpisodeNumber); searchResult.SearchHistoryItems = ProcessSearchResults(notification, reports, searchResult, episode.Series, episode.SeasonNumber, episode.EpisodeNumber); _searchHistoryProvider.Add(searchResult); if (searchResult.SearchHistoryItems.Any(r => r.Success)) return true; } logger.Warn("Unable to find {0} in any of indexers.", episode); notification.CurrentMessage = reports.Any() ? String.Format("Sorry, couldn't find {0}, that matches your preferences.", episode) : String.Format("Sorry, couldn't find {0} in any of indexers.", episode); return false; }