Beispiel #1
0
 public SearchController(CategoryRepository categoryRepository,
     SearchRepository searchRepository, UserRepository userRepository)
 {
     _categoryRepository = categoryRepository;
     _searchRepository = searchRepository;
     _userRepository = userRepository;
 }
        public async Task<ActionResult> Search(Search search)
        {
            try
            {
                var searchRepo = new SearchRepository();
                var documentId = ObjectId.GenerateNewId();
                searchRepo.Create(new Search 
                {
                    Id = documentId,
                    Address = search.Address,
                    Username = User.Identity.Name,
                    Radius = search.Radius,
                    lat = search.lat,
                    lng = search.lng,
                    SearchDate = Helper.SetDateForMongo(DateTime.UtcNow)
                });

                return Json(new { success = true, responseText = "Added.", id = documentId.ToString(), isAuthenticated = User.Identity.IsAuthenticated }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return Json(new { success = false, responseText = ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }
    public void ShouldGetProducts()
    {
      // arrange
      var searchIndex = Substitute.For<ISearchIndex>();
      searchIndex
        .CreateSearchContext()
        .GetQueryable<ProductSearchResultItem>()
        .Returns(new[]
          {
            new ProductSearchResultItem {Free = true},
            new ProductSearchResultItem {Free = false},
            new ProductSearchResultItem {Free = true}
          }.AsQueryable());

      ContentSearchManager.SearchConfiguration.Indexes["fake_index"] = searchIndex;

      var repository = new SearchRepository();

      var indexable = Substitute.For<IIndexable>();
      var provider = Substitute.For<SearchProvider>();
      provider.GetContextIndexName(indexable, Arg.Any<ICorePipeline>()).Returns("fake_index");

      using (new Switcher<SearchProvider>(provider))
      {
        // act
        var products = repository.GetProducts(indexable);

        // assert
        Assert.Equal(2, products.Count());
      }
    }
        public static async System.Threading.Tasks.Task <IEnumerable <Bag> > UpdateBagsAsync(DocumentClient client, IImageRepository imageservice)
        {
            var bagsRepository       = new SearchRepository <Bag>(client, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Bags);
            var updateBagsRepository = new UpdateRepository <Bag>(client, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Bags);
            var bags = await bagsRepository.SearchItemsAsync(bag => bag.ImageId == null && bag.MainID != 165 && bag.MainID != 1193, 50);

            System.Console.WriteLine($"Fetched {bags.Count()} bags");
            var images = await ImportImages2Async(client, bags, imageservice);

            bags.ToList().ForEach(bag => {
                bag.ImageId = images.FirstOrDefault(image => image.Filename == $"{bag.MainID}.jpg")?.Id;
            });

            System.Console.WriteLine($"Attempting to update {bags.Count()} bags");
            var insertCounter = 0;
            await bags.ToList().ForEachAsync(async bag => {
                var bagid = await updateBagsRepository.UpdateItemAsync(bag.Id, bag);
                insertCounter++;
                System.Console.WriteLine($"Update bag: {insertCounter} - {bag.MainID}");
            });

            System.Console.WriteLine($"Completed updateing {insertCounter} bags");

            return(bags);
        }
Beispiel #5
0
        public void TestSimpleTaskSearch()
        {
            //Arrange
            ISearchRepository repository = new SearchRepository();
            User u = new User();
            u.Username = "******";
            u.Password = "******";
            Project p = new Project();
            p.Name = "Testprojekt";
            p.Owner = u;
            Task t1 = new Task();
            t1.Title = "Schreiben des Rhbs";
            t1.Project = p;
            Task t2 = new Task();
            t2.Title = "Dialog implementieren";
            t2.Project = p;
            Task t3 = new Task();
            t3.Title = "Schreiben von Unit test";
            t3.Project = p;
            p.ProductBacklog.Add(t1);
            p.ProductBacklog.Add(t2);
            p.ProductBacklog.Add(t3);
            IProjectRepository projectRepository = new ProjectRepository();
            projectRepository.SaveOrUpdate(p);

            //Act
            IList result = repository.Search("Title:Schreiben*");

            //Assert
            Assert.AreEqual(2, result.Count);
        }
        public async Task RepositoryReturnsDataFromDB()
        {
            var searchEngine = new Mock <ISearchEngine>();

            searchEngine.Setup(x => x.GetSearchResultAsync(query)).ReturnsAsync(testViewObject);

            var searchEngines = new List <ISearchEngine> {
                searchEngine.Object
            };

            List <SearchResultViewModel> searchResult;
            List <SearchResult>          expectedResult;

            using (var context = new MultiSearchEngineContext(options))
            {
                var repository = new SearchRepository(context, searchEngines);

                searchResult = (List <SearchResultViewModel>) await repository.GetFromDbAsync(query);

                expectedResult = await context.SearchResults.Where(r => r.Query.Contains(query)).ToListAsync();
            }

            Assert.Equal(expectedResult.Count(), searchResult.Count());
            Assert.Equal(expectedResult[0].Date, searchResult[0].Date);
            Assert.Equal(expectedResult[0].Query, searchResult[0].Query);
            Assert.Equal(expectedResult[0].SearchEngineName, searchResult[0].SearchEngineName);
            Assert.Equal(expectedResult[1].Date, searchResult[1].Date);
            Assert.Equal(expectedResult[1].Query, searchResult[1].Query);
            Assert.Equal(expectedResult[1].SearchEngineName, searchResult[1].SearchEngineName);
        }
        public DP_SearchRepository ToSearchRepositoryDTO(SearchRepository SearchRepository)
        {
            DP_SearchRepository searchRepository = null;

            if (SearchRepository.SourceRelationID == null)
            {
                searchRepository       = new DP_SearchRepository(SearchRepository.TableDrivedEntityID);
                searchRepository.Title = SearchRepository.TableDrivedEntity.Alias;
            }
            else
            {
                var relDTO = new BizRelationship().ToRelationshipDTO(SearchRepository.Relationship);
                searchRepository       = new DP_SearchRepository(relDTO.EntityID2);
                searchRepository.Title = relDTO.Name;
                searchRepository.HasNotRelationshipCheck = SearchRepository.HasNotRelationshipCheck;
                searchRepository.RelationshipFromCount   = SearchRepository.RelationshipFromCount;
                searchRepository.RelationshipToCount     = SearchRepository.RelationshipToCount;
                //searchRepository.SourceEntityID = relDTO.EntityID1;
                searchRepository.SourceRelationship = relDTO;
            }
            searchRepository.ID             = SearchRepository.ID;
            searchRepository.Title          = SearchRepository.Title;
            searchRepository.EntitySearchID = SearchRepository.EntitySearchID ?? 0;
            searchRepository.IsSimpleSearch = SearchRepository.IsSimpleSearch;

            SetLogicPhraseDTO(SearchRepository.LogicPhrase, searchRepository);

            return(searchRepository);
        }
Beispiel #8
0
        public async Task <IActionResult> SearchPublishedProviderLocalAuthorities(
            string searchText,
            string fundingStreamId,
            string fundingPeriodId)
        {
            string facetName = "localAuthority";

            FilterHelper filterHelper = new FilterHelper();

            AddFiltersForNotification(fundingStreamId, fundingPeriodId, filterHelper);

            SearchResults <PublishedProviderIndex> searchResults = await Task.Run(() =>
            {
                return(SearchRepository.Search(string.Empty, new SearchParameters
                {
                    Facets = new[] { $"{facetName},count:1000" },
                    Top = 0,
                    Filter = filterHelper.BuildAndFilterQuery()
                }));
            });

            IEnumerable <string> distinctFacetValues = searchResults
                                                       .Facets
                                                       .SingleOrDefault(x => x.Name == facetName)
                                                       ?.FacetValues
                                                       .Where(x => x.Name?.Split()
                                                              .Any(s => searchText == null || s.ToLowerInvariant().StartsWith(searchText.ToLowerInvariant())) == true)
                                                       .Select(x => x.Name);

            return(new OkObjectResult(distinctFacetValues));
        }
        public void LoadSearchDataIntoCache_DoesNotInclude_RetiredOrganisationsInScope()
        {
            // Arrange
            var retiredOrganisationInScope = new Organisation
            {
                OrganisationId     = 1,
                OrganisationName   = "Test organisation",
                SectorType         = SectorTypes.Private,
                Status             = OrganisationStatuses.Retired,
                OrganisationScopes = new List <OrganisationScope>
                {
                    new OrganisationScope {
                        Status = ScopeRowStatuses.Active, ScopeStatus = ScopeStatuses.InScope
                    }
                }
            };

            Global.ContainerIoC = UiTestHelper.BuildContainerIoC(retiredOrganisationInScope);

            // Act
            SearchRepository.LoadSearchDataIntoCache();

            // Assert
            AssertOrganisationIsNotIncludedInViewingService(retiredOrganisationInScope);
        }
        public async Task <IQueryResult> ExecuteAsync(SearchOwnedQuery query)
        {
            //var activity = await ActivityRepository.GetAll(x => x.Name == $"{typeof(TEntity)}{nameof(SearchOwnedCommand<TEntity>)}");
            if (await Authorizer.IsAuthorized(Activity))
            {
                return(new ForbidResult());
            }

            if (query.SearchTerm.IsNullOrWhiteSpace())
            {
                return(new ErrorResult("Search cannot be empty"));
            }

            var entities = await SearchRepository.SearchAsync(query.SearchTerm, query.PageSize);

            if (ResultSorter != null)
            {
                entities = ResultSorter(entities);
            }

            var count = await SearchRepository.SearchRowCountAsync(query.SearchTerm);

            var result = new SearchResult <TViewModel>(entities.Select(Translator.Translate), count);

            return(new OkResult(result));
        }
        public void LoadSearchDataIntoCache_Includes_ActiveOrganisationsWithDraftReports()
        {
            // Arrange
            var activeOrganisationWithDraftReports = new Organisation
            {
                OrganisationId   = 1,
                OrganisationName = "Test organisation",
                SectorType       = SectorTypes.Private,
                Status           = OrganisationStatuses.Active,
                Returns          = new List <Return> {
                    new Return {
                        Status = ReturnStatuses.Draft
                    }
                },
                OrganisationScopes = new List <OrganisationScope>
                {
                    new OrganisationScope {
                        Status = ScopeRowStatuses.Active, ScopeStatus = ScopeStatuses.PresumedInScope
                    }
                }
            };

            Global.ContainerIoC = UiTestHelper.BuildContainerIoC(activeOrganisationWithDraftReports);

            // Act
            SearchRepository.LoadSearchDataIntoCache();

            // Assert
            AssertOrganisationIsIncludedInViewingService(activeOrganisationWithDraftReports);
        }
        public async Task SearchById_GivenIdDoesNotReturnSearchResult_ReturnsNull()
        {
            SearchRepositorySettings searchRepositorySettings = new SearchRepositorySettings
            {
                SearchKey         = string.Empty,
                SearchServiceName = string.Empty
            };

            ISearchInitializer searchInitializer = Substitute.For <ISearchInitializer>();

            ISearchIndexClient searchIndexClient = Substitute.For <ISearchIndexClient>();

            AzureOperationResponse <DocumentSearchResult <SpecificationIndex> > documentSearchResult =
                new AzureOperationResponse <DocumentSearchResult <SpecificationIndex> >
            {
                Body = new DocumentSearchResult <SpecificationIndex>(null, null, null, null, null)
            };

            IDocumentsOperations documentsOperations = Substitute.For <IDocumentsOperations>();

            documentsOperations.SearchWithHttpMessagesAsync <SpecificationIndex>(Arg.Any <string>(), Arg.Any <SearchParameters>()).Returns(Task.FromResult(documentSearchResult));

            ISearchServiceClient searchServiceClient = Substitute.For <ISearchServiceClient>();

            searchIndexClient.Documents.Returns(documentsOperations);

            SearchRepository <SpecificationIndex> searchRepository = new SearchRepository <SpecificationIndex>(searchRepositorySettings, searchInitializer, searchServiceClient, searchIndexClient);

            string notFoundId = "notFound";

            SpecificationIndex specificationIndex = await searchRepository.SearchById(notFoundId);

            specificationIndex.Should().BeNull();
        }
Beispiel #13
0
        public void GetSearchResultsByQueryId_SearchQueryIdLesserThanOne_ReturnsNull()
        {
            //Arrange
            int searchQueryId = 0;
            var listOfResults = new List <SearchResult>();

            listOfResults.Add(new SearchResult
            {
                Id            = 111,
                Link          = "www.skateboard.com",
                Title         = "Best skateboards in the world",
                SearchQueryId = 222
            });

            var listOfQueries = new List <SearchQuery>();

            listOfQueries.Add(new SearchQuery
            {
                Id        = 222,
                QueryText = "Skateboard"
            });

            var contextMockHelper = new ContextMockHelper()
                                    .Build <SearchQuery>(listOfQueries)
                                    .Build <SearchResult>(listOfResults);

            _searchRepository = new SearchRepository(contextMockHelper.FakeContext);

            //Act
            IEnumerable <SearchResult> result = _searchRepository.GetSearchResultsByQueryId(searchQueryId);

            //Assert
            Assert.IsNull(result);
        }
Beispiel #14
0
 public SearchController(UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager, ApplicationDbContext dbContext)
 {
     _userManager      = userManager;
     _signInManager    = signInManager;
     _dbContext        = dbContext;
     _searchRepository = new SearchRepository(userManager, signInManager, dbContext);
 }
Beispiel #15
0
 public SearchIndex(SearchRepository searchRepository, IElasticClient elasticClient,
                    IConfiguration configuration)
 {
     _searchRepository = searchRepository;
     _elasticClient    = elasticClient;
     _indexName        = configuration["elasticsearch:index"];
 }
        public async Task RepositoryAddsDataIntoDB()
        {
            var testObject = new SearchResult()
            {
                Id               = 1,
                Date             = new DateTime(2020, 01, 01),
                Query            = query,
                SearchEngineName = SearchEngineName.Google
            };

            var searchEngine = new Mock <ISearchEngine>();

            searchEngine.Setup(x => x.GetSearchResultAsync(query)).ReturnsAsync(testViewObject);

            var searchEngines = new List <ISearchEngine> {
                searchEngine.Object
            };

            using (var context = new MultiSearchEngineContext(options))
            {
                var repository = new SearchRepository(context, searchEngines);

                await repository.CreateAsync(testViewObject);

                var actualResult    = context.SearchResults.FirstOrDefault(r => r.Id == 1);
                var actualtemResult = context.SearchResultItems.FirstOrDefault(r => r.SearchResultId == 1);

                Assert.Equal(testObject.Id, actualResult.Id);
                Assert.Equal(testObject.Date, actualResult.Date);
                Assert.Equal(testObject.Query, actualResult.Query);
                Assert.Equal(testObject.SearchEngineName, actualResult.SearchEngineName);
                Assert.Equal(testObject.Id, actualtemResult.SearchResultId);
            }
        }
Beispiel #17
0
        public async Task <IQueryResult> ExecuteAsync(SearchQuery query)
        {
            var activity = await ActivityRepository.SearchItemsAsync(x => x.Name == $"{typeof(TEntity)}{nameof(SearchQueryHandler<TViewModel, TEntity>)}");

            if (await Authorizer.IsAuthorized(activity.FirstOrDefault()))
            {
                return(new ForbidResult());
            }

            if (query.SearchTerm.IsNullOrWhiteSpace())
            {
                return(new ErrorResult("Search cannot be empty"));
            }

            var entities = await SearchRepository.SearchAsync(query.SearchTerm, query.PageSize);

            var result = new List <TViewModel>();

            foreach (var entity in entities)
            {
                var viewModel = await Translator.Translate(entity);

                result.Add(viewModel);
            }

            var count = await SearchRepository.SearchRowCountAsync(query.SearchTerm);

            return(new OkResult(new SearchResult <TViewModel>(result, count)));
        }
Beispiel #18
0
        public string StopSearch([FromBody] JObject JsonReferralCode)
        {
            var referralCode = JsonReferralCode["referralCode"]?.ToString();
            var ip           = HttpContext.Connection.RemoteIpAddress;

            searchRepository = new SearchRepository();
            errorRepository  = new ErrorRepository();
            userRepository   = new UserRepository();


            errorRepository.LogIpAndCheckForDDOS(ip.ToString());

            var validationPass = ValidationHelper.ValidateReferralCode(referralCode);

            if (!validationPass)
            {
                return("Invalid Referral Code");
            }

            if (!bool.Parse(userRepository.CheckIfUserExists(referralCode)))
            {
                return("Error. User does not exist.");
            }

            var removedSuccessfully = searchRepository.RemoveSearchingRecord(referralCode);

            if (!removedSuccessfully)
            {
                return("Error Occurred.");
            }

            userRepository.InsertTrackingRecord(referralCode, "User Stopped Searching", $"{referralCode} has cancelled search.");

            return("Successfully Removed.");
        }
Beispiel #19
0
        public void ShouldGetFreeProducts(
            SearchRepository sut,
            ISearchIndex searchIndex,
            IIndexable indexable,
            [Frozen] SearchProvider provider,
            Switcher <SearchProvider> switcher)
        {
            // arrange
            searchIndex
            .CreateSearchContext()
            .GetQueryable <ProductSearchResultItem>()
            .Returns(new[]
            {
                new ProductSearchResultItem {
                    Free = true
                },
                new ProductSearchResultItem {
                    Free = false
                },
                new ProductSearchResultItem {
                    Free = true
                }
            }.AsQueryable());

            ContentSearchManager.SearchConfiguration.Indexes["indexName"] = searchIndex;
            provider.GetContextIndexName(indexable, Arg.Any <ICorePipeline>()).Returns("indexName");

            // act
            var products = sut.GetProducts(indexable);

            // assert
            Assert.Equal(2, products.Count());
        }
Beispiel #20
0
        public void GetAllSearchQueries_SearchQueriesExist_ReturnsListOfSearchQueries()
        {
            //Arrange
            int notExpectedCount = 0;

            var listOfQueries = new List <SearchQuery>();

            listOfQueries.Add(new SearchQuery
            {
                Id        = 222,
                QueryText = "Skateboard"
            });

            var contextMockHelper = new ContextMockHelper()
                                    .Build <SearchQuery>(listOfQueries);

            _searchRepository = new SearchRepository(contextMockHelper.FakeContext);

            //Act
            IEnumerable <SearchQuery> result = _searchRepository.GetAllSearchQueries();

            //Assert
            Assert.IsInstanceOf <IEnumerable <SearchQuery> >(result);
            Assert.AreNotEqual(result?.Count(), notExpectedCount);
        }
        public async Task <ActionResult> Search(Search search)
        {
            try
            {
                var searchRepo = new SearchRepository();
                var documentId = ObjectId.GenerateNewId();
                searchRepo.Create(new Search
                {
                    Id         = documentId,
                    Address    = search.Address,
                    Username   = User.Identity.Name,
                    Radius     = search.Radius,
                    lat        = search.lat,
                    lng        = search.lng,
                    SearchDate = Helper.SetDateForMongo(DateTime.UtcNow)
                });

                return(Json(new { success = true, responseText = "Added.", id = documentId.ToString(), isAuthenticated = User.Identity.IsAuthenticated }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(new { success = false, responseText = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
    public void ShouldGetFreeProducts(
      SearchRepository sut,
      ISearchIndex searchIndex,
      IIndexable indexable,
      [Frozen]SearchProvider provider,
      Switcher<SearchProvider> switcher)
    {
      // arrange
      searchIndex
        .CreateSearchContext()
        .GetQueryable<ProductSearchResultItem>()
        .Returns(new[]
          {
            new ProductSearchResultItem { Free = true },
            new ProductSearchResultItem { Free = false },
            new ProductSearchResultItem { Free = true }
          }.AsQueryable());

      ContentSearchManager.SearchConfiguration.Indexes["indexName"] = searchIndex;
      provider.GetContextIndexName(indexable, Arg.Any<ICorePipeline>()).Returns("indexName");

      // act
      var products = sut.GetProducts(indexable);

      // assert
      Assert.Equal(2, products.Count());
    }
        public void NameSearchTest()
        {
            var searchRepository = new SearchRepository(new Data.Models.SearchContext());
            var people           = searchRepository.GetPeople("tony");

            Assert.IsNotNull(people);
            Assert.IsTrue(people.Count() > 0);
        }
        public async Task<ActionResult> HeatMap()
        {
            var searchRepository = new SearchRepository();
            var search = await searchRepository.GetAllSearches();


            return View(search);
        }
Beispiel #25
0
        public void CanRetrieveMultipleSearches()
        {
            var searchRepository = new SearchRepository();
            var result = searchRepository.GetAll();

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Count(), Is.GreaterThan(0));
        }
Beispiel #26
0
        public void CanRetrieveDataFromRaven()
        {
            var searchRepository = new SearchRepository();
            var result = searchRepository.GetById("searches/1");

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Term, Is.EqualTo("Bouvet"));
        }
        public ActionResult Search(string phrase)
        {
            phrase = string.IsNullOrEmpty(phrase) ? "*" : phrase;

            var result = SearchRepository <Product> .SearchPhrase(phrase);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Beispiel #28
0
        public ActionResult Index()
        {
            ViewBag.Title = "Awesome Single Page Application";
            var searchRepos = new SearchRepository();
            var result      = searchRepos.GetAll();

            return(View());
        }
Beispiel #29
0
        public async Task <ActionResult> HeatMap()
        {
            var searchRepository = new SearchRepository();
            var search           = await searchRepository.GetAllSearches();


            return(View(search));
        }
Beispiel #30
0
        public QueryHotKeywordsResult QueryHotKeywords(QueryHotKeywordsParameter param)
        {
            var result     = new QueryHotKeywordsResult();
            var repository = new SearchRepository();

            result.Keywords = repository.QueryHotKeywords(param);
            return(result);
        }
Beispiel #31
0
        public ActionResult Contact(string id="NW6")
        {
            ViewBag.Message = "Your contact page.";

            var repo = new SearchRepository();

            return View(repo.Search(id));
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            List <string>        stringList       = new SearchRepository((ILogFacade) new LogFacade(typeof(SearchRepository))).AutoComplete(context.Request.QueryString["searchvalue"]);
            JavaScriptSerializer scriptSerializer = new JavaScriptSerializer();

            context.Response.Write(scriptSerializer.Serialize((object)stringList));
        }
Beispiel #33
0
 public SearchController(UserManager <User> userManager, IConfiguration config, PictureRepository pictureRepository, SearchRepository searchRepository)
 {
     _userManager       = userManager;
     _config            = config;
     _storageAccount    = CloudStorageAccount.Parse(config.GetConnectionString("BlobStorage"));
     _pictureRepository = pictureRepository;
     _searchRepository  = searchRepository;
 }
Beispiel #34
0
 public void CanSaveToRaven()
 {
     var searchRepository = new SearchRepository();
     var search = new Search
                      {
                          Term = "Bouvet",
                      };
     searchRepository.SaveSearch(search);
 }
Beispiel #35
0
        public SearchProductModel GetProd([FromBody] SearchRQModel list_rq)
        {
            Website.Instance.logger.Info($"WMS GetProd Start! B2D Xid:{list_rq.company_xid}");

            var prods = new SearchProductModel();

            prods = SearchRepository.GetProdList(list_rq);

            return(prods);
        }
Beispiel #36
0
        static void Main(string[] args)
        {
            IOfferRepository  offerRepositiry  = new OfferRepository();
            ISearchRepository searchRepository = new SearchRepository();
            List <string>     topWordsList     = GetTopWordsList();

            //CountForSingleWord(topWordsList, searchRepository);
            //CountForPairWords(topWordsList, searchRepository);
            CompareOffer(topWordsList, offerRepositiry);
        }
Beispiel #37
0
        protected SearchRepositoryQueryTestsBase()
        {
            var searchConfig = LocalConfiguration.Get().GetSection("Search");
            var logger       = Substitute.For <ILogger>();

            SearchRepository = new SearchRepository(logger);

            SeedSearchBooks(searchConfig);

            SeedBookReviewers(searchConfig);
        }
        public SearchViewModel(Search search, SearchRepository repo, NotificationViewModel notif, ItemRepository itemRepo, LogsViewModel logs, Dispatcher dispatcher)
        {
            _search = search;
            URL = SearchURL;
            AutoStart = SearchAutoStart;
            Index = SearchIndex;

            _searchRepository = repo;

            _notifVM = notif;
            sList = new SearchEngine(itemRepo, _search, logs, dispatcher);

            _notifVM.RegisterSearchEvents(sList);
        }
        public AllSearchesViewModel(Dispatcher dispatcher, string dataFile, LogsViewModel logsVM, ItemRepository itemRepo)
        {
            _dispatcher = dispatcher;
            _searchRepo = new SearchRepository(dataFile);
            _itemRepo = itemRepo;
            _logs = logsVM;

            _notifVM = new NotificationViewModel(_dispatcher);

            base.DisplayName = "All Searches View Model";

            _searchRepo.SearchAdded += new EventHandler<ModelBaseAddedEventArgs>(OnSearchAddedToRepository);
            _searchRepo.SearchRemoved += new EventHandler<ModelBaseAddedEventArgs>(OnSearchRemovedFromRepository);

            CreateAllSearches();

            foreach (SearchViewModel search in Searches)
                if(search.AutoStart) Start(search);
        }
        public void AdvancedSearchAds_WaterSportAd_WaterSportProperties_ReturnWaterSportAd()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository adRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data
                Province p1 = new Province
                {
                    Label = "p1"
                };

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "city",
                    LabelUrlPart = "city"
                };
                p1.AddCity(c);

                Category cat = new Category
                {
                    Label = "Bateau à moteur",
                    LabelUrlPart = "Bateau"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "bateau",
                    Body = "la desc du bateau",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                WaterSportType st = new WaterSportType()
                {
                    Label = "pmt"
                };

                WaterSportAd bat = new WaterSportAd
                {
                    Id = 1,
                    Title = "bateau",
                    Body = "la desc du bateau",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    CreatedBy = u,
                    Type = st
                };

                repo.Save(st);
                repo.Save(p1);
                repo.Save(c);
                repo.Save(cat);
                repo.Save(u);
                repo.Save(bat);
                repo.Save(a);

                repo.Flush();

                #endregion

                AdSearchParameters param = new AdSearchParameters
                {
                    WaterTypeId = 1
                };

                // When
                IList<SearchAdCache> result = adRepo.AdvancedSearchAds<WaterSportAd>(param);

                // Then
                Assert.AreEqual(1, result.Count);
                Assert.AreEqual(a, result[0]);
            }
        }
        public void AdvancedSearchAds_RealEstateAds_RealEstateProperties_ReturnRealEstateAd()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository adRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data
                Province p1 = new Province
                {
                    Label = "p1"
                };

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "city",
                    LabelUrlPart = "city"
                };
                p1.AddCity(c);

                Category cat = new Category
                {
                    Label = "Location",
                    LabelUrlPart = "Location"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "appart",
                    Body = "boite a chaussure",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                RealEstateType t1 = new RealEstateType
                {
                    Label = "Location"
                };

                District d = new District
                {
                    City = c,
                    Label = "Cheznous"
                };

                RealEstateAd loc = new RealEstateAd
                {
                    Id = 1,
                    Title = "appart",
                    Body = "boite a chaussure",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    CreatedBy = u,
                    Type = t1,
                    District = d,
                    RoomsNumber = 5,
                    IsFurnished = true,
                    SurfaceArea = 45
                };

                repo.Save(t1);
                repo.Save(d);
                repo.Save(p1);
                repo.Save(c);
                repo.Save(cat);
                repo.Save(u);
                repo.Save(loc);
                repo.Save(a);

                MotoBrand brand = new MotoBrand
                {
                    Label = "Suzuki"
                };

                SearchAdCache a2 = new SearchAdCache
                {
                    AdId = 2,
                    Title = "appart2",
                    Body = "boite a chaussure",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                RealEstateAd loc2 = new RealEstateAd
                {
                    Id = 2,
                    Title = "appart2",
                    Body = "boite a chaussure",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    CreatedBy = u,
                    Type = t1,
                    District = d,
                    RoomsNumber = 4,
                    IsFurnished = true,
                    SurfaceArea = 65
                };
                repo.Save(loc2);
                repo.Save(a2);

                repo.Flush();

                #endregion

                AdSearchParameters param = new AdSearchParameters
                {
                    AndSearchStrings = new String[] { "appart" },
                    MinNbRooms = 2,
                    MaxNbRooms = 4,
                    DistrictId = 1,
                    RealEstateTypeId = 1,
                    IsFurnished = true,
                    MinSurfaceArea = 60,
                    MaxSurfaceArea = 65
                };

                // When
                IList<SearchAdCache> result = adRepo.AdvancedSearchAds<RealEstateAd>(param);

                // Then
                Assert.AreEqual(1, result.Count);
                Assert.AreEqual(a2, result[0]);
            }
        }
        public void AdvancedSearchAds_MotorBoatEngineAd_MotorBoatEngineProperties_ReturnMotorBoatEngineAd()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository adRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data
                Province p1 = new Province
                {
                    Label = "p1"
                };

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "city",
                    LabelUrlPart = "city"
                };
                p1.AddCity(c);

                Category cat = new Category
                {
                    Label = "Bateau à moteur",
                    LabelUrlPart = "Bateau"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "bateau",
                    Body = "la desc du bateau",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                MotorBoatEngineType mt = new MotorBoatEngineType()
                {
                    Id = 7,
                    Label = "4 temps"
                };

                MotorBoatEngineAd bat = new MotorBoatEngineAd
                {
                    Id = 1,
                    Title = "moteur",
                    Body = "la desc du bateau",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    CreatedBy = u,
                    Price = 1000,
                    Hp = 100,
                    Year = 2005,
                    MotorType = mt
                };

                repo.Save(mt);
                repo.Save(p1);
                repo.Save(c);
                repo.Save(cat);
                repo.Save(u);
                repo.Save(bat);
                repo.Save(a);

                repo.Flush();

                #endregion

                AdSearchParameters param = new AdSearchParameters
                {
                    MotorEngineTypeId = 1,
                    MinHp = 99,
                    MaxHp = 100,
                    MinYear = 2004,
                    MaxYear = 2006
                };

                // When
                IList<SearchAdCache> result = adRepo.AdvancedSearchAds<MotorBoatEngineAd>(param);

                // Then
                Assert.AreEqual(1, result.Count);
                Assert.AreEqual(a, result[0]);
            }
        }
        public void AdvancedSearchAds_MotoAds_MotoProperties_ReturnMotoAd()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository adRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data
                Province p1 = new Province
                {
                    Label = "p1"
                };

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "city",
                    LabelUrlPart = "city"
                };
                p1.AddCity(c);

                Category cat = new Category
                {
                    Label = "Auto",
                    LabelUrlPart = "Auto"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "aveo",
                    Body = "aveo sport 1.2 16s",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                CarAd car = new CarAd
                {
                    Id = 1,
                    Title = "aveo",
                    Body = "aveo sport 1.2 16s",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    CreatedBy = u
                };

                repo.Save(p1);
                repo.Save(c);
                repo.Save(cat);
                repo.Save(u);
                repo.Save(car);
                repo.Save(a);

                Category cat2 = new Category
                {
                    Label = "Moto",
                    LabelUrlPart = "Moto"
                };

                MotoBrand brand = new MotoBrand
                {
                    Label = "Suzuki"
                };

                SearchAdCache a2 = new SearchAdCache
                {
                    AdId = 2,
                    Title = "aveo",
                    Body = "aveo sport 1.2 16s",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat2
                };

                MotoAd moto = new MotoAd
                {
                    Id = 2,
                    Title = "aveo",
                    Body = "aveo sport 1.2 16s",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat2,
                    Brand = brand,
                    EngineSize = 650,
                    CreatedBy = u
                };
                repo.Save(brand);
                repo.Save(cat2);
                repo.Save(moto);
                repo.Save(a2);

                repo.Flush();

                #endregion

                AdSearchParameters param = new AdSearchParameters
                {
                    AndSearchStrings = new String[] { "aveo" },
                    BrandId = brand.Id,
                    MinEngineSize = 250,
                    MaxEngineSize = 800
                };

                // When
                IList<SearchAdCache> result = adRepo.AdvancedSearchAds<MotoAd>(param);

                // Then
                Assert.AreEqual(1, result.Count);
                Assert.AreEqual(a2, result[0]);
            }
        }
        public void AdvancedSearchAds_Ad_MinMaxPrice_ReturnMatchingAds()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository adRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data
                Province p1 = new Province
                {
                    Label = "p1"
                };

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "city",
                    LabelUrlPart = "city"
                };
                p1.AddCity(c);

                Category cat = new Category
                {
                    Label = "Location",
                    LabelUrlPart = "Location"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "chaussure",
                    Body = "boite a chaussure",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                Ad loc = new Ad
                {
                    Id = 1,
                    Title = "chaussure",
                    Body = "boite a chaussure",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    CreatedBy = u,
                    Price = 1000
                };

                repo.Save(p1);
                repo.Save(c);
                repo.Save(cat);
                repo.Save(u);
                repo.Save(loc);
                repo.Save(a);

                SearchAdCache a2 = new SearchAdCache
                {
                    AdId = 2,
                    Title = "chaussure",
                    Body = "boite a chaussure",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                Ad loc2 = new Ad
                {
                    Id = 2,
                    Title = "chaussure",
                    Body = "boite a chaussure",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    CreatedBy = u,
                    Price = 2000
                };
                repo.Save(loc2);
                repo.Save(a2);

                repo.Flush();

                #endregion

                AdSearchParameters param = new AdSearchParameters
                {
                    MinPrice = 0,
                    MaxPrice = 1000
                };

                // When
                IList<SearchAdCache> result = adRepo.AdvancedSearchAds<Ad>(param);

                // Then
                Assert.AreEqual(1, result.Count);
                Assert.AreEqual(a, result[0]);
            }
        }
        public void SearchAds_SearchByTitleAndBodyAndString_CreateWhereAndQuery()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository adRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data
                Province p1 = new Province
                {
                    Label = "p1"
                };

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "city",
                    LabelUrlPart = "city"
                };
                p1.AddCity(c);

                Category cat = new Category
                {
                    Label = "Moto",
                    LabelUrlPart = "Moto"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "ship",
                    Body = "computer",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };
                repo.Save<Province>(p1);
                repo.Save<City>(c);
                repo.Save<Category>(cat);
                repo.Save(a);

                Province p2 = new Province
                {
                    Label = "p2"
                };
                City c2 = new City
                {
                    Label = "CherzmOi2",
                    LabelUrlPart = "city2"
                };
                p2.AddCity(c2);
                SearchAdCache a2 = new SearchAdCache
                {
                    AdId = 2,
                    Title = "ship",
                    Body = "content",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 17),
                    Category = cat
                };
                repo.Save<Province>(p2);
                repo.Save<City>(c2);
                repo.Save(a2);

                repo.Flush();

                #endregion

                // When
                IList<SearchAdCache> result = adRepo.SearchAds(new String[] { "computer", "ship" }, null, null);

                // Then
                Assert.AreEqual(1, result.Count);
                Assert.AreEqual(a, result[0]);
            }
        }
        public void CountByCategory_NoSearchString_Returnwholecount()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository searchRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data
                Province p1 = new Province
                {
                    Label = "p1"
                };

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "city",
                    LabelUrlPart = "city"
                };
                p1.AddCity(c);

                Category cat = new Category
                {
                    Label = "Voilier",
                    LabelUrlPart = "Bateau"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "bateau 1",
                    Body = "la desc du bateau",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                Category cat2 = new Category
                {
                    Label = "Bateau à moteur",
                    LabelUrlPart = "Bateau"
                };

                SearchAdCache a2 = new SearchAdCache
                {
                    AdId = 2,
                    Title = "poupou",
                    Body = "la desc du bateau",
                    City = c,
                    CreationDate = new DateTime(2012, 06, 11, 23, 52, 18),
                    Category = cat2
                };

                repo.Save(p1);
                repo.Save(c);
                repo.Save(cat);
                repo.Save(u);
                repo.Save(a);
                repo.Save(cat2);
                repo.Save(a2);

                repo.Flush();

                #endregion

                // When
                IDictionary<Category, int> result = searchRepo.CountByCategory(new String[] { "bateau" }, null);

                // Then
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual(cat2, result.First().Key);
                Assert.AreEqual(cat, result.Last().Key);
            }
        }
        public void SearchAds_SearchByTitleAndCategories()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository adRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "CherzmOi",
                    LabelUrlPart = "city"
                };

                Category cat = new Category
                {
                    Label = "Moto",
                    LabelUrlPart = "Moto"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "titre 1",
                    Body = "content",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };
                repo.Save<City>(c);
                repo.Save<Category>(cat);
                repo.Save(a);

                City c2 = new City
                {
                    Label = "CherzmOi2",
                    LabelUrlPart = "city2"
                };

                Category cat2 = new Category
                {
                    Label = "Auto",
                    LabelUrlPart = "Auto"
                };

                SearchAdCache a2 = new SearchAdCache
                {
                    AdId = 2,
                    Title = "title 2",
                    Body = "content",
                    City = c2,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 17),
                    Category = cat2
                };
                repo.Save<City>(c2);
                repo.Save<Category>(cat2);
                repo.Save(a2);

                repo.Flush();

                #endregion

                // When
                IList<SearchAdCache> result = adRepo.SearchAds(andSearchStrings: new String[] { "ti" }, categoryIds: new int[] { cat.Id, cat2.Id });

                // Then
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual(a, result[0]);
                Assert.AreEqual(a2, result[1]);
            }
        }
Beispiel #48
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName, Email = model.Email};
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    //var userProfileRepo = new UserProfileRepository();
                    //userProfileRepo.Create(new Data.Model.UserProfile
                    //{
                    //    Username = model.UserName,
                    //    Password = model.Password,
                    //    Email = model.Email,
                    //    isFacebookUser = false,
                    //    FirstName = model.FirstName,
                    //    LastName = model.LastName,
                    //    Address = model.Address,
                    //    AllowAddressVerfication = model.AllowAddressVerfication,
                    //    City = model.City,
                    //    Country = model.Country,
                    //    HomePhone = model.HomePhone,
                    //    MobilePhone = model.MobilePhone,
                    //    AllowPhoneVerfication = model.AllowPhoneVerfication,
                    //    DriversLicense = model.DriversLicense,
                    //    AllowDriverLicenseVerfication = model.AllowDriverLicenseVerfication,
                    //    DateRegistered = DateTime.UtcNow
                    //});

                    var userProfile = new Data.Model.UserProfile
                    {
                        Username = model.UserName,
                        Password = model.Password,
                        Email = model.Email,
                        isFacebookUser = false,
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        Address = model.Address,
                        AllowAddressVerfication = model.AllowAddressVerfication,
                        City = model.City,
                        Country = model.Country,
                        HomePhone = model.HomePhone,
                        MobilePhone = model.MobilePhone,
                        AllowPhoneVerfication = model.AllowPhoneVerfication,
                        DriversLicense = model.DriversLicense,
                        AllowDriverLicenseVerfication = model.AllowDriverLicenseVerfication,
                        DateRegistered = DateTime.UtcNow
                    };
                    var accountService = new AccountService();
                    await accountService.Register(userProfile);

                    if (!string.IsNullOrEmpty(model.SearchAddress))
                    {
                        var searchRepo = new SearchRepository();
                        searchRepo.AssociateAddress(model.SearchAddress, model.UserName);
                    }

                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    var mail = new MailService();
                    mail.Send(model.Email, Server.MapPath("~/EmailTemplate/Registration.html"), model.UserName);
                    
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public void AdvancedSearchAds_CarAds_CarProperties_ReturnCarAd()
        {
            ISessionFactory sessionFactory = NhibernateHelper.SessionFactory;
            Repository repo = new Repository(sessionFactory);
            SearchRepository adRepo = new SearchRepository(sessionFactory);

            using (ITransaction transaction = sessionFactory.GetCurrentSession().BeginTransaction())
            {
                // Given
                #region test data
                Province p1 = new Province
                {
                    Label = "p1"
                };

                User u = new User
                {
                    Email = "*****@*****.**",
                    Password = "******"
                };
                repo.Save<User>(u);

                City c = new City
                {
                    Label = "city",
                    LabelUrlPart = "city"
                };
                p1.AddCity(c);

                Category cat = new Category
                {
                    Label = "Auto",
                    LabelUrlPart = "Auto"
                };

                CarFuel fuel = new CarFuel
                {
                    Label = "Diesel"
                };

                VehicleBrand brand = new VehicleBrand
                {
                    Label = "Aveo"
                };

                SearchAdCache a = new SearchAdCache
                {
                    AdId = 1,
                    Title = "aveo",
                    Body = "aveo sport 1.2 16s",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                CarAd car = new CarAd
                {
                    Id = 1,
                    Title = "aveo",
                    Body = "aveo sport 1.2 16s",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    Year = 2011,
                    Kilometers = 10000,
                    IsAutomatic = true,
                    Fuel = fuel,
                    Brand = brand,
                    CreatedBy = u
                };

                repo.Save(brand);
                repo.Save(fuel);
                repo.Save(p1);
                repo.Save(c);
                repo.Save(cat);
                repo.Save(u);
                repo.Save(car);
                repo.Save(a);

                SearchAdCache a2 = new SearchAdCache
                {
                    Title = "aveo",
                    Body = "aveo sport 1.2 16s",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat
                };

                CarAd car2 = new CarAd
                {
                    Id = 1,
                    Title = "aveo",
                    Body = "aveo sport 1.2 16s",
                    City = c,
                    CreationDate = new DateTime(2012, 01, 16, 23, 52, 18),
                    Category = cat,
                    Year = 2001,
                    Kilometers = 95000,
                    Brand = brand,
                    CreatedBy = u
                };
                repo.Save(car2);
                repo.Save(a2);

                repo.Flush();

                #endregion

                AdSearchParameters param = new AdSearchParameters
                {
                    AndSearchStrings = new String[] { "aveo" },
                    MinKm = 0,
                    MaxKm = 11000,
                    MinYear = 2000,
                    MaxYear = 2012,
                    BrandId = brand.Id,
                    FueldId = fuel.Id,
                    IsAuto = true
                };

                // When
                IList<SearchAdCache> result = adRepo.AdvancedSearchAds<CarAd>(param);

                // Then
                Assert.AreEqual(1, result.Count);
                Assert.AreEqual(a, result[0]);
            }
        }
Beispiel #50
0
        static void Main(string[] args)
        {
            var index = 0;

            var m = new Model1();
            var restaurants =
                m.Resturantes.
                Where(x => x.Offline == 0
                && x.autoOffline == 0
                && x.jupiterclosed == 0
                && x.status == 0).ToList();

            var total = restaurants.Count();

            Console.WriteLine(total);

            var rep = new RestaurantRepository();
            restaurants.ForEach(f =>
            {
                rep.Insert(new RestaurantEntity
                {
                    RowKey = f.Restaurantname,
                    Id = Guid.NewGuid().ToString(),
                    PartitionKey = f.Zipcode.Trim().ToUpper(),
                    PostCode2 = f.zipcode2.Trim().ToUpper(),
                    City = f.City,
                    Email = f.Email,
                    Address = f.Address,
                    MobilePhone = f.MobilePhone,
                    InvoiceEmail = f.invoicemail,
                    Description = f.LongDescr,
                    ShortDescription = f.ShortDescr,
                    LogoUrl = "http://d30v2pzvrfyzpo.cloudfront.net/uk/images/restaurants/" + f.ID + ".gif",
                    FakeId = Convert.ToString(f.ID),
                    DeliversTo = f.Xtrazip,
                    ContactName = f.AttName,
                    ContactPhone = f.AttPhone,
                    Latitude = Convert.ToString(f.Latitude),
                    Longitude = Convert.ToString(f.Longitude),
                    LegalName = f.LegalName,
                    FoodType = GetCousine(f.CountryID, f.SecondCountryID),
                    Bank = f.banknavn,
                    SaleFee = f.Transfee.HasValue ? f.Transfee.Value : 0,
                    FakeNumVotes = f.numOfRatings.HasValue ? f.numOfRatings.Value : 0,
                    FakeRating = f.RatingStars.HasValue ? decimal.ToDouble(f.RatingStars.Value) : 0
                });

                Debug.WriteLine("Missing: " + (total - index++));
            });

            //var model2 = new Model2();
            //var zipcodes = model2.Zipcodes.Where(x => x.Deleted == 0).ToList();
            //var total = zipcodes.Count();

            //Console.WriteLine(total);

            //var repository = new PostCodeRepository();
            //index = 0;

            //zipcodes.ForEach(z =>
            //{
            //    repository.Insert(new PostCodeEntity
            //    {
            //        PostCode = z.zipcodename,
            //        Name = z.cityname,
            //        Region = GetRegion(z.RegionID)
            //    });

            //    Debug.WriteLine("Missing: " + (total - index++));
            //});

            //var prospects = new Prospect();
            //var people = prospects.Earnmoneys.ToList();

            //## Create SearchIndex
            //var rep = new RestaurantRepository();
            var repMenu = new SearchRepository();

            rep.GetAll().Where(x => x.FakeNumVotes > 20).Take(100).ToList().ForEach(x => repMenu.InsertRestaurant("NW6", x));

            Console.WriteLine("done!");
            Console.ReadLine();
        }
Beispiel #51
0
 static void Main(string[] args)
 {
     IOfferRepository offerRepositiry = new OfferRepository();
     ISearchRepository searchRepository = new SearchRepository();
     List<string> topWordsList = GetTopWordsList();
     //CountForSingleWord(topWordsList, searchRepository);
     //CountForPairWords(topWordsList, searchRepository);
     CompareOffer(topWordsList, offerRepositiry);
 }