public MatchModule(IRepository<Match> matchRepository, IRepository<Country> countryRepository) : base("/matches") { Get["/"] = parameters => { var matches = matchRepository.FindAll(); var resource = matches.ToArray().Select( m => new MatchResource { Id = m.Id, Date = m.Date, Team1CountryId = m.Team1.Country.Id, Team2CountryId = m.Team2.Country.Id }); return Response.AsJson(resource); }; Post["/"] = parameters => { var resource = this.Bind<MatchResource>(); var country1 = countryRepository.GetById(resource.Team1CountryId); if (country1 == null) return HttpStatusCode.BadRequest; var country2 = countryRepository.GetById(resource.Team2CountryId); if (country2 == null) return HttpStatusCode.BadRequest; var match = Match.Create( resource.Date, country1, country2); matchRepository.Add(match); return Response.AsRedirect("/matches/" + match.Id); }; Get["/{id}"] = parameters => { var match = matchRepository.GetById((int)parameters.Id); if (match == null) return HttpStatusCode.NotFound; return Response.AsJson(new { Date = match.Date, Team1 = match.Team1, Team2 = match.Team2 }); }; }
public void FindAll_Should_Return_All_Items_Which_Satisfy_Composite_Specification(IRepository<Contact, string> repository) { for (int i = 1; i <= 3; i++) { var contact = new Contact { Name = "Test User " + i }; repository.Add(contact); } var result = repository.FindAll(new Specification<Contact>(p => p.Name == "Test User 1").OrElse(new Specification<Contact>(p => p.Name == "Test User 2"))); result.Count().ShouldEqual(2); }
public void FindAll_Should_Return_All_Items_Which_Satisfy_Composite_Specification_With_Paging_And_Sort_Descending(IRepository<Contact, string> repository) { const int resultingPage = 2; const int pageSize = 2; var queryOptions = new PagingOptions<Contact>(resultingPage, pageSize, "Name", true); for (int i = 1; i <= 10; i++) { var contact = new Contact { Name = "Test User " + i }; repository.Add(contact); } IEnumerable<Contact> result = repository .FindAll(new Specification<Contact>(p => p.Name == "Test User 1") .OrElse(new Specification<Contact>(p => p.Name == "Test User 5") .OrElse(new Specification<Contact>(p => p.Name == "Test User 8"))), queryOptions); result.Count().ShouldEqual(1); queryOptions.TotalItems.ShouldEqual(3); result.First().Name.ShouldEqual("Test User 1"); }
public List <Profile> FindAll() { return(_repository.FindAll()); }
public ViewResult Index() { return(View(repository.FindAll().ToList())); }
List <Person> IPersonService.FindAll() { return(repository.FindAll()); }
public List <TimerSchedule> GetTimerScheduleByApplianceId(long id) { return(repoTimerSchedule.FindAll(x => x.ApplianceId == id).ToList()); }
public List <DichVuViewModel> GetAll() { return(_dichvuRepository.FindAll(c => c.DichVuTags) .ProjectTo <DichVuViewModel>().ToList()); }
public IEnumerable <NFLSeason> GetNFLSeasons() { return(_nflSeasonRepository.FindAll()); }
public void FindAll_Should_Return_All_Items_Which_Satisfy_Specification_With_Paging_MagicString(IRepository<Contact, string> repository) { const int resultingPage = 2; const int pageSize = 2; const int totalItems = 10; var queryOptions = new PagingOptions<Contact>(resultingPage, pageSize, "Name"); for (int i = 1; i <= totalItems; i++) { var contact = new Contact { Name = "Test User " + i, ContactTypeId = i }; repository.Add(contact); } // this fails for RavenDb because the ContactId is an int but is being used as the key, so the check on ContactId <= 5 is doing a string comparison and including ContactId = 10 as well // need to look into why this happens and how to get around it var result = repository.FindAll(new Specification<Contact>(p => p.ContactTypeId <= totalItems / 2), queryOptions); result.Count().ShouldEqual(pageSize); queryOptions.TotalItems.ShouldEqual(totalItems / 2); result.First().Name.ShouldEqual("Test User 3"); }
public List <Book> FindAll() { return(_repository.FindAll()); }
public IEnumerable <Price> Get() { _logger.LogInformation(LoggingEvents.LIST_ITEMS, "Listing all items"); return(_repo.FindAll()); }
public List <BookVO> FindAll() { return(_bookConverter.Parse(_bookRepository.FindAll())); }
public List <ProductImageViewModel> GetImages(int productId) { return(_productImageRepository.FindAll(x => x.ProductId == productId) .ProjectTo <ProductImageViewModel>().ToList()); }
public List <ProductViewModel> GetAll() { return(_productRepository.FindAll(x => x.ProductCategory).ProjectTo <ProductViewModel>().ToList()); }
public List <SchedulesVO> FindAll() { return(_converter.ParseList(_repository.FindAll())); }
public List <PersonVO> FindAll() { return(converter.ParseList(iRepository.FindAll())); }
public void Save_BonusesList_2BonusesUpdated() { IList<BonusAggregate> bonusesToUpdate; IList<BonusAggregate> updatedBonuses = new List<BonusAggregate>(); var bonusesIds = new int[2]; string newComment = "comment on " + DateTime.Now; using (var dbContext = new DatabaseContext(TestUser, TestPass)) { bonusRepository = new BonusesRepository(dbContext); bonusesToUpdate = bonusRepository.FindAll().Take(2).ToList(); bonusesToUpdate[0].Comment = newComment; bonusesToUpdate[1].Comment = newComment; bonusesIds[0] = bonusesToUpdate[0].BonusId; bonusesIds[1] = bonusesToUpdate[1].BonusId; bonusRepository.Save(bonusesToUpdate); } using (var dbContext = new DatabaseContext(TestUser, TestPass)) { bonusRepository = new BonusesRepository(dbContext); updatedBonuses.Add(bonusRepository.GetById(bonusesIds[0])); updatedBonuses.Add(bonusRepository.GetById(bonusesIds[1])); } Assert.AreEqual(updatedBonuses[0].Comment, newComment); Assert.AreEqual(updatedBonuses[1].Comment, newComment); }
public StackLoader(IRepository<Stack> stackRepository, IRepository<Instance> instanceRepository) { _stackRepository = stackRepository; _instanceRepository = instanceRepository; _repositoryInstances = new Lazy<List<Instance>>(() => _instanceRepository.FindAll().ToList()); }
public async Task <IWrappedResponse> Search(LoadingLocationSearchRequest request) { var query = _olmaLoadingLocationRepo.FindAll() .AsNoTracking(); #region security // TODO add security #endregion #region convert search request if (request.Divisions?.Count > 0) { var divisionIds = request.Divisions; query = query.Where(l => l.CustomerDivisionId != null && divisionIds.Contains((int)l.CustomerDivisionId)); } if (request.Partners?.Count > 0) { var partnerIds = request.Partners; query = query.Where(l => l.CustomerPartnerId != null && partnerIds.Contains((int)l.CustomerPartnerId)); } #endregion #region ordering query = query.OrderBy(l => l.Id); #endregion var projectedQuery = query.ProjectTo <LoadingLocation>(Mapper.ConfigurationProvider); #region Add PublicHolidays var statesDict = _olmaCountryStateRepo.FindAll().Include(c => c.PublicHolidays).ToDictionary(s => s.Id, s => s.PublicHolidays); var countriesDict = _olmaCountryRepo.FindAll().Include(c => c.PublicHolidays).ToDictionary(c => c.Id, c => c.PublicHolidays); var mappedResult = projectedQuery.ToPaginationResult(request); foreach (var loadingLocation in mappedResult.Data) { var publicHolidays = new List <PublicHoliday>(); var stateId = loadingLocation.Address.State; var countryId = loadingLocation.Address.Country; if (stateId != null && statesDict.ContainsKey((int)stateId)) { publicHolidays.AddRange(Mapper.Map <ICollection <Olma.PublicHoliday>, ICollection <PublicHoliday> >(statesDict[(int)stateId])); } if (countryId != null && countriesDict.ContainsKey((int)countryId)) { publicHolidays.AddRange(Mapper.Map <ICollection <Olma.PublicHoliday>, ICollection <PublicHoliday> >(countriesDict[(int)countryId])); } loadingLocation.PublicHolidays = publicHolidays.AsEnumerable(); } #endregion return(Ok(mappedResult)); }
public IEnumerable <ProfileTable> GetPartial(Expression <Func <ProfileTable, bool> > predicate) { return(repo.FindAll(predicate)); }
public void DoThatThing() { BusinessObject[] entities = repository.FindAll(); someOtherClass.HandleNewBizObjs(entities); }
public List <UserRole> GetCustomerRoleSimple(string customerId) { var model = _userRoleRepository.FindAll(x => x.CustomerId == customerId).ToList(); return(model); }
public ExcursiiManagementService(IRepository <Excursie, string> repo) { this.repo = repo; Excursii = new Collection <Excursie>(repo.FindAll()); ExcursiiFiltered = new Collection <Excursie>(repo.FindAll()); }
public IEnumerable <Company> FindAll() { return(_companyRepository.FindAll()); }
public void UpdateExcursii() => Excursii = new Collection <Excursie>(repo.FindAll());
public List <Person> FindAll() { return(_repository.FindAll()); }
public void FindAllWithPaging_Skip2Take3_CorrectTotalCount() { IList<BonusAggregate> notSkipedBonuses; PagedResponse<BonusAggregate> skipedBonuses; using (var dbContext = new DatabaseContext(TestUser, TestPass)) { bonusRepository = new BonusesRepository(dbContext); notSkipedBonuses = bonusRepository.FindAll(); skipedBonuses = bonusRepository.FindAllWithPaging(2, 3); } Assert.AreEqual(skipedBonuses.TotalCount, notSkipedBonuses.Count); }
public async Task <IActionResult> Index() { var categories = await _repository.FindAll <ServiceCategory>(); return(View(categories)); }
public void FindAll_noParams_SomeBonuses() { IList<BonusAggregate> bonuses; using (var dbContext = new DatabaseContext(TestUser, TestPass)) { bonusRepository = new BonusesRepository(dbContext); bonuses = bonusRepository.FindAll(); } Assert.IsNotNull(bonuses); Assert.AreNotEqual(0, bonuses.Count); }
public List <PerformanceAreaVO> FindAll() { return(_converter.ParseList(_repository.FindAll())); }
public IEnumerable <NFLWeek> GetNFLWeeks() { var currentSeason = GetCurrentNFLSeason(); return(_nflWeekRepository.FindAll(w => w.NFLSeasonId == currentSeason.NFLSeasonId).OrderBy(w => w.NFLWeekId)); }
public void FindAll_NoParams_EmployeeExists() { BonusAggregate bonusAggregate; using (var dbContext = new DatabaseContext(TestUser, TestPass)) { bonusRepository = new BonusesRepository(dbContext); bonusAggregate = bonusRepository.FindAll().First(); } Assert.IsNotNull(bonusAggregate.Employee); }
public List <BookVO> FindAll() { return(_converter.ParseList(_repository.FindAll())); }
public void Save_BonusesList_2BonusesAdded() { int numberOfItemsBeforSave; int numberOfCurrentBonuses; using (var dbContext = new DatabaseContext(TestUser, TestPass)) { bonusFactory = new BonusFactory(new EmployeesRepository(dbContext)); var bonusesList = new List<BonusAggregate> { bonusFactory.Create(GetEmployeeById(4), DateTime.Now, 100), bonusFactory.Create(GetEmployeeById(5), DateTime.Now, 90) }; bonusRepository = new BonusesRepository(dbContext); numberOfItemsBeforSave = bonusRepository.FindAll().Count(); bonusRepository.Save(bonusesList); numberOfCurrentBonuses = bonusRepository.FindAll().Count(); } Assert.AreEqual(numberOfCurrentBonuses - 2, numberOfItemsBeforSave); }
public List <BookVO> FindAll() => _converter.ParseList(_repository.FindAll());
public JsonResult GetPagedJsonBonuses(int take, int skip) { PagedResponse<BonusAggregate> bonuses; var filteredRequest = new FilteredRequest(Request.Params); using (var dbContext = new DatabaseContext()) { BonusesRepository = new BonusesRepository(dbContext); bonuses = BonusesRepository.FindAll(skip, take, filteredRequest.SortingField, filteredRequest.Direction, filteredRequest.FilterField, filteredRequest.FilterPattern); } return Json(bonuses, JsonRequestBehavior.AllowGet); }
public List <Product> GetAll() { return(_productRepository.FindAll().ToList()); }
public void FindAll_Should_Return_All_Items_Which_Satisfy_Specification(IRepository<Contact, string> repository) { for (int i = 1; i <= 3; i++) { var contact = new Contact {Name = "Test User " + i}; repository.Add(contact); } var result = repository.FindAll(new Specification<Contact>(p => p.Name == "Test User 1")); // Note: Raven doesn't like p.Name.Equals("..."); result.Count().ShouldEqual(1); }
/// <summary> /// Initializes a new instance of the <see cref="Sessions"/> class. /// </summary> /// <param name="accessRepo">Supplied through DI.</param> /// <param name="sessionRepo">Supplied through DI.</param> /// <param name="personRepo">Supplied through DI.</param> /// <param name="captureRepo">Supplied through DI.</param> /// <param name="logger">Supplied through DI.</param> /// <param name="date">Supplied through DI.</param> public Sessions( IRepository <AccessTokenSchema> accessRepo, IRepository <SessionSchema> sessionRepo, IRepository <PersonSchema> personRepo, IRepository <BsonDocument> captureRepo, ILogger logger, IDateExtra date) : base("/sessions") { this.Before += PreSecurity.CheckAccess(accessRepo, date); this.Post <PostSessions>("/", async(req, res) => { // Has to exist due to PreSecurity Check string token = req.Cookies["ExperienceCapture-Access-Token"]; var accessTokenDoc = await accessRepo.FindOne( Builders <AccessTokenSchema> .Filter .Where(a => a.Hash == PasswordHasher.Hash(token))); var filterUser = Builders <PersonSchema> .Filter.Where(p => p.InternalId == accessTokenDoc.User); var user = await personRepo .FindOne(filterUser); string shortID = Generate.GetRandomId(4); var sessionDoc = new SessionSchema { InternalId = ObjectId.GenerateNewId(), Id = shortID, User = user, // Copying user data instead of referencing so it can never change in the session CreatedAt = new BsonDateTime(date.UtcNow), Tags = new List <string>(), }; // Retry generating a short id until it is unique bool isUnique = true; do { try { sessionDoc.Id = shortID; await sessionRepo.Add(sessionDoc); isUnique = true; } catch (MongoWriteException e) { // Re-throw any other type of exception except non-unique keys if (e.WriteError.Code != 11000) { throw e; } shortID = Generate.GetRandomId(4); isUnique = false; } }while (!isUnique); // isOngoing is a proxy variable and will always start out as true sessionDoc.IsOngoing = true; sessionDoc.InternalId = null; sessionDoc.User.InternalId = null; captureRepo.Configure($"sessions.{shortID}"); // Secondary index or else Mongo will fail on large queries // It has a limit for max number of documents on properties // Without an index, see https://docs.mongodb.com/manual/reference/limits/#Sort-Operations var index = Builders <BsonDocument> .IndexKeys; var key = index.Ascending("frameInfo.realtimeSinceStartup"); await captureRepo.Index(key); string json = JsonQuery.FulfilEncoding(req.Query, sessionDoc); if (json != null) { await res.FromJson(json); return; } await res.FromBson(sessionDoc); }); this.Get <GetSessions>("/", async(req, res) => { var builder = Builders <SessionSchema> .Filter; // Note: only use `&=` for adding to the filter, // Or else the filter cannot handle multiple query string options FilterDefinition <SessionSchema> filter = builder.Empty; var startMin = new BsonDateTime(date.UtcNow.AddSeconds(-300)); // 5 minutes var closeMin = new BsonDateTime(date.UtcNow.AddSeconds(-5)); // 5 seconds var hasTags = req.Query.AsMultiple <string>("hasTags").ToList(); if (hasTags.Count > 0) { foreach (var tag in hasTags) { filter &= builder.Where(s => s.Tags.Contains(tag)); } } var lacksTags = req.Query.AsMultiple <string>("lacksTags").ToList(); if (lacksTags.Count > 0) { foreach (var tag in lacksTags) { filter &= builder.Where(s => !s.Tags.Contains(tag)); } } // Three potential options: null, true, or false if (req.Query.As <bool?>("isOngoing") != null) { bool isOngoing = req.Query.As <bool>("isOngoing"); if (isOngoing) { filter &= builder.Where(s => s.IsOpen == true) & ((builder.Eq(s => s.LastCaptureAt, BsonNull.Value) & builder.Where(s => s.CreatedAt > startMin)) | (builder.Eq(s => s.LastCaptureAt, BsonNull.Value) & builder.Where(s => s.LastCaptureAt > closeMin))); } else { filter &= builder.Where(s => s.IsOpen == false) | ((builder.Eq(s => s.LastCaptureAt, BsonNull.Value) & builder.Where(s => s.CreatedAt < startMin)) | (builder.Eq(s => s.LastCaptureAt, BsonNull.Value) & builder.Where(s => s.LastCaptureAt < closeMin))); } } var page = req.Query.As <int?>("page") ?? 1; if (page < 1) { // Page query needs to be possible res.StatusCode = Status400BadRequest; return; } var direction = req.Query.As <string>("sort"); SortDefinition <SessionSchema> sorter; if (direction == null) { sorter = Builders <SessionSchema> .Sort.Descending(s => s.CreatedAt); } else { if (Enum.TryParse(typeof(SortOptions), direction, true, out object options)) { sorter = ((SortOptions)options).ToDefinition(); } else { res.StatusCode = Status400BadRequest; return; } } var sessionDocs = await sessionRepo .FindAll(filter, sorter, page); var sessionsDocsWithOngoing = sessionDocs.Select((s) => { bool isStarted = false; if (s.LastCaptureAt != BsonNull.Value) { isStarted = true; } bool isOngoing; if (s.IsOpen) { isOngoing = (!isStarted && startMin < s.CreatedAt) || (isStarted && closeMin < s.LastCaptureAt); } else { isOngoing = false; } s.IsOngoing = isOngoing; s.InternalId = null; s.User.InternalId = null; return(s); }); var count = await sessionRepo.FindThenCount(filter); var clientValues = new SessionsResponce { // Bson documents can't start with an array like Json, so a wrapping object is used instead ContentList = sessionsDocsWithOngoing.ToList(), PageTotal = (long)Math.Ceiling((double)count / 10d), }; string json = JsonQuery.FulfilEncoding(req.Query, clientValues); if (json != null) { await res.FromJson(json); return; } await res.FromBson(clientValues); }); this.Post <PostSession>("/{id}", async(req, res) => { string shortID = req.RouteValues.As <string>("id"); var sessionDoc = await sessionRepo .FindById(shortID); if (sessionDoc == null) { res.StatusCode = Status404NotFound; return; } if (!sessionDoc.IsOpen) { res.StatusCode = Status400BadRequest; return; } BsonDocument document; if (JsonQuery.CheckDecoding(req.Query)) { using (var ms = new MemoryStream()) { await req.Body.CopyToAsync(ms); ms.Position = 0; try { document = BsonSerializer.Deserialize <BsonDocument>(ms); } catch (Exception err) { logger.LogError(err.Message); res.StatusCode = Status400BadRequest; return; } } } else { string json = await req.Body.AsStringAsync(); try { document = BsonDocument.Parse(json); } catch (Exception err) { logger.LogError(err.Message); res.StatusCode = Status400BadRequest; return; } } // Manual validation, because Fluent Validation would remove extra properties if (!document.Contains("frameInfo") || document["frameInfo"].BsonType != BsonType.Document || !document["frameInfo"].AsBsonDocument.Contains("realtimeSinceStartup") || document["frameInfo"]["realtimeSinceStartup"].BsonType != BsonType.Double) { res.StatusCode = Status400BadRequest; return; } captureRepo.Configure($"sessions.{shortID}"); await captureRepo.Add(document); var filter = Builders <SessionSchema> .Filter.Where(s => s.Id == shortID); // This lastCaptureAt is undefined on the session document until the first call of this endpoint // Export flags are reset so the session can be re-exported var update = Builders <SessionSchema> .Update .Set(s => s.LastCaptureAt, new BsonDateTime(date.UtcNow)) .Set(s => s.ExportState, ExportOptions.NotStarted); await sessionRepo.Update(filter, update); await res.FromString(); }); this.Get <GetSession>("/{id}", async(req, res) => { string shortID = req.RouteValues.As <string>("id"); var sessionDoc = await sessionRepo .FindById(shortID); if (sessionDoc == null) { res.StatusCode = Status404NotFound; return; } var startRange = new BsonDateTime(date.UtcNow.AddSeconds(-300)); // 5 minutes var closeRange = new BsonDateTime(date.UtcNow.AddSeconds(-5)); // 5 seconds bool isStarted = false; // Check if key exists if (sessionDoc.LastCaptureAt != BsonNull.Value) { isStarted = true; } bool isOngoing; if (sessionDoc.IsOpen) { isOngoing = (!isStarted && startRange.CompareTo(sessionDoc.CreatedAt) < 0) || (isStarted && closeRange.CompareTo(sessionDoc.LastCaptureAt) < 0); } else { isOngoing = false; } sessionDoc.IsOngoing = isOngoing; sessionDoc.InternalId = null; sessionDoc.User.InternalId = null; string json = JsonQuery.FulfilEncoding(req.Query, sessionDoc); if (json != null) { await res.FromJson(json); return; } await res.FromBson(sessionDoc); }); this.Delete <DeleteSession>("/{id}", async(req, res) => { string shortID = req.RouteValues.As <string>("id"); var filter = Builders <SessionSchema> .Filter.Where(s => s.Id == shortID); var sessionDoc = await sessionRepo .FindById(shortID); if (sessionDoc == null) { res.StatusCode = Status404NotFound; return; } var update = Builders <SessionSchema> .Update .Set(s => s.IsOpen, false); await sessionRepo.Update(filter, update); await res.FromString(); }); }
public List <AppRole> GetRoles() { return(_appRoleRepository.FindAll().ToList()); }
public List <RoleGroup> GetRoleGroupSimple(string roleId) { var model = _roleGroupRepository.FindAll(x => x.RoleId == roleId).ToList(); return(model); }
public void GetFirstEmployee_noParams_employee() { Employee employee; using (var dbContext = new DatabaseContext(testUser, testPass)) { employeeRepository = new EmployeesRepository(dbContext); employee = employeeRepository.FindAll().FirstOrDefault(); } Assert.IsNotNull(employee); }
// TODO: let's do content negotiation ourselves unless there is a nice // way to do it in Nancy like there seems to be for most things public CountryModule(IRepository<Domain.Country> countryRepository, CountryFactory countryFactory) : base("/countries") { Get["/"] = parameters => { var countryResources = countryRepository.FindAll() .Select(c => new Country {id = c.Id.ToString(), Name = c.Name}); var resource = countryResources.ToArray(); return Response.AsJson(resource); }; Get["/{id}"] = parameters => { var country = countryRepository.GetById((int)parameters.id); if (country == null) return HttpStatusCode.NotFound; var resource = new Country {id = country.Id.ToString(), Name = country.Name}; return Response.AsJson(resource); }; Post["/"] = parameters => { var countryResource = this.Bind<Country>(blacklistedProperties:"id"); var validationResult = this.Validate(countryResource); if (! validationResult.IsValid) { var response = Response.AsJson(validationResult.Errors); response.StatusCode = HttpStatusCode.BadRequest; return response; } var country = countryFactory.CreateCountry(countryResource.Name); countryRepository.Add(country); return Response.AsRedirect("/countries/"+country.Id); }; Put["/{id}"] = parameters => { var country = countryRepository.GetById((int) parameters.id); if (country == null) return HttpStatusCode.NotFound; // this correct for a put? should probably be some error // we don't actually support updates to countries! //country.Name = parameters.Name; return Response.AsRedirect("/countries/" + country.Id); }; Delete["/{id}"] = parameters => { var country = countryRepository.GetById((int)parameters.id); if (country == null) return HttpStatusCode.NotFound; // this correct for a put? should probably be some error countryRepository.Remove(country); return HttpStatusCode.OK; }; }