static async Task Main(string[] args) { var configuration = new ConfigurationBuilder() .AddUserSecrets <Program>() .Build(); using var context = new EFContext(configuration); var jane = new User { Name = "Jane" }; var john = new User { Name = "John" }; var football = new Group { Name = "Football", Users = new List <User> { jane, john } }; var movies = new Group { Name = "Movies", Users = new List <User> { jane } }; context.AddRange(jane, john, football, movies); await context.SaveChangesAsync(); WriteLine(); var users = await context.Users.Where(u => u.Groups.Any(g => g.Name == "Movies")).ToListAsync(); foreach (var user in users) { WriteLine($"User (Movie group): {user.Name}"); } WriteLine(); var oldTimers = await context.Users.Where(u => u.Memberships.Any(m => m.CreateDate > new DateTime(2000, 1, 1))).ToListAsync(); foreach (var user in oldTimers) { WriteLine($"Old timer user: {user.Name}"); } WriteLine(); var books = await context.Books .Include(c => c.Author) .ToListAsync(); foreach (var book in books) { WriteLine($"Id: {book.Id} | Title: {book.Title} | Author: {book.Author.Name}"); } ReadKey(); }
public void TestTagKeywordsAddUpdate() { var connection = new SqliteConnection("DataSource=:memory:"); Keyword test; connection.Open(); try { var options = new DbContextOptionsBuilder <EFContext>() .UseSqlite(connection) .Options; using (var context = new EFContext(options)) { context.Database.EnsureCreated(); } using (var context = new EFContext(options)) { context.AddRange( new TagKeyword { Tag = t1, Keyword = k1 }, new TagKeyword { Tag = t2, Keyword = k1 } ); try { context.SaveChanges(); } catch (System.Exception) { throw; } } using (var context = new EFContext(options)) { var testUpdate = context.Keywords.Where(k => k.Id == 1).FirstOrDefault(); testUpdate.Name = "food1"; context.Keywords.Update(testUpdate); context.SaveChanges(); } using (var context = new EFContext(options)) { test = context.Keywords.Where(k => k.Id == 1) .Include(t => t.TagKeywords) .ThenInclude(tk => tk.Tag) .FirstOrDefault(); } Assert.Equal("food1", test.Name); Assert.Equal(2, test.TagKeywords.Count); Assert.Equal("bar", test.TagKeywords.Where(tk => tk.TagId == 1).First().Tag.Name); } finally { connection.Close(); } }
protected override async Task OneTimeSetup() { _mapper = new Mapper(new MapperConfiguration(m => { m.AddProfile <VendorProfile>(); m.AddProfile <SearchItemProfile>(); })); _vendorSearchService = new VendorSearchService(ElasticClient); var currencies = GetCurrencies(); EFContext.AddRange(currencies); EFContext.SaveChanges(); var vendors = CreateVendors(10); EFContext.AddRange(vendors); EFContext.SaveChanges(); }
private void CarregarDB() { var context = new EFContext(); context.AddRange( new Product { Id = 1, Name = "COCA COLA 2LT", Image = "", Price = 4.5 }, new Product { Id = 2, Name = "CERVEJA BRAHAMA LATA", Image = "", Price = 2.5 }, new Product { Id = 3, Name = "CERVEJA CORONA LONG NECK", Image = "", Price = 4.9 }, new Product { Id = 4, Name = "CERVEJA BRAHAMA EXTRA LONG NECK", Image = "", Price = 2.9 } ); context.SaveChanges(); }
/// <summary> /// Заповнюж БД звязками між таблицями: AspNetUser i AspNetRole /// </summary> /// <param name="context">Приймає звязок до БД типу Context</param> private static void SeedUserRoles(EFContext context) { if (context.UserRoles.Count() == 0) { context.AddRange(new List <AspNetUserRoles> { new AspNetUserRoles { UserId = 1, RoleId = 1, }, new AspNetUserRoles { UserId = 2, RoleId = 3, }, new AspNetUserRoles { UserId = 3, RoleId = 2, } }); context.SaveChanges(); } }
public void TestNeighbors() { var connection = new SqliteConnection("DataSource=:memory:"); Skill test; connection.Open(); try { var options = new DbContextOptionsBuilder <EFContext>() .UseSqlite(connection) .Options; using (var context = new EFContext(options)) { context.Database.EnsureCreated(); } using (var context = new EFContext(options)) { context.AddRange( new SkillNeighbor { Left = s1, Right = s2 }, new SkillNeighbor { Left = s1, Right = s3 }, new SkillNeighbor { Left = s1, Right = s4 }, new SkillNeighbor { Left = s2, Right = s4 } ); try { context.SaveChanges(); } catch (System.Exception) { throw; } } using (var context = new EFContext(options)) { var testUpdate = context.Skills.Where(t => t.Name == "C").FirstOrDefault(); testUpdate.Name = "food1"; context.Skills.Update(testUpdate); context.SaveChanges(); } using (var context = new EFContext(options)) { test = context.Skills.Where(t => t.Name == "food1") .Include(t => t.Rights) .ThenInclude(tn => tn.Left) .Include(t => t.Lefts) .ThenInclude(tn => tn.Right) .FirstOrDefault(); } Assert.Equal("food1", test.Name); Assert.Equal(3, test.Lefts.Count); Assert.Equal("git", test.Lefts.Where(r => r.RightId == 2).First().Right.Name); } finally { connection.Close(); } }
public void Setup() { _efContext = EFContextFactory.CreateInMemoryEFContext(); _httpServiceMock = new Mock <IHttpService>(); _adIdSettings.Url = "https://demo.ad-id.org/adid_services/{0}"; _adIdSettings.UserName = "******"; _adIdSettings.Password = "******"; _adIdSettings.BankId = "100000"; _adIdSettings.Advertiser = "PROCTER & GAMBLE"; _adIdSettings.FallbackBrandPrefix = "PGZZ"; _appSettingsMock.Setup(s => s.Value).Returns(_adIdSettings); _user = new UserIdentity { Email = "*****@*****.**", AgencyId = Guid.NewGuid(), Id = Guid.NewGuid(), BuType = BuType.Pg }; var videoId = Guid.NewGuid(); var videoContentType = new DictionaryEntry { Id = videoId, Key = "Video" }; var contentTypeMediums = new List <ContentTypeAdidMedium> { new ContentTypeAdidMedium { Id = Guid.NewGuid(), DictionaryEntry = videoContentType, DictionaryEntryId = videoId, MediaType = "Video", Medium = "TV -ALL", MediumValue = "1" }, new ContentTypeAdidMedium { Id = Guid.NewGuid(), MediaType = "Audio", Medium = "Radio -ALL", MediumValue = "43" }, new ContentTypeAdidMedium { Id = Guid.NewGuid(), MediaType = "Internet Display", Medium = "Other - Other", MediumValue = "161" }, new ContentTypeAdidMedium { Id = Guid.NewGuid(), MediaType = "Print", Medium = "ALL - Print", MediumValue = "56" } }; var agency = new Agency { Labels = new[] { "GID_100000" } }; var parent = new AbstractType { Agency = agency }; _brand = new Brand { AdIdPrefix = "1ADC" }; var project = new Project { Brand = _brand }; var cost = new Cost { Id = _costId, Parent = parent, Project = project }; _efContext.AddRange(new object[] { agency, parent, cost, _brand, project, videoContentType }); _efContext.ContentTypeAdidMedium.AddRange(contentTypeMediums); _efContext.SaveChanges(); //Unable to mock HttpContent.ReadAsStringAsync() and so Ad-Id service cannot be fully tested. _httpContentMock = new Mock <HttpContent>(); _httpResponseMessage = new HttpResponseMessage { Content = _httpContentMock.Object, StatusCode = HttpStatusCode.OK }; _httpServiceMock.Setup(h => h.PostAsync(It.IsAny <Uri>(), It.IsAny <FormUrlEncodedContent>())) .ReturnsAsync(_httpResponseMessage); _target = new AdIdService(_appSettingsMock.Object, _efContext, _activityLogMock.Object, _httpServiceMock.Object); }
public async Task RecalculateFromAgency() { //Arange var userId = Guid.NewGuid(); var roleId = Guid.NewGuid(); var agencyId = Guid.NewGuid(); var newUserGroupId = Guid.NewGuid(); var projectId = Guid.NewGuid(); var costUser = new CostUser { Id = userId, ParentId = agencyId }; var adminUser = new CostUser { Id = Guid.NewGuid(), Email = ApprovalMemberModel.BrandApprovalUserEmail }; var currentUserGroups = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; var abstractTypes = new List <AbstractType> { new AbstractType { UserGroups = currentUserGroups, Agency = new Agency(), Type = AbstractObjectType.Module.ToString() }, new AbstractType { UserGroups = currentUserGroups, Agency = new Agency(), Type = AbstractObjectType.Agency.ToString() } }; var project = new List <Project> { new Project { Id = projectId } }; var cost = new List <Cost> { new Cost { ParentId = projectId, Id = Guid.NewGuid(), UserGroups = currentUserGroups } }; _efContext.AddRange(new List <UserGroup>()); _efContext.AddRange(abstractTypes); _efContext.Add(costUser); _efContext.Add(adminUser); _efContext.AddRange(project); _efContext.AddRange(cost); _efContext.SaveChanges(); _aclClientMock.Setup(a => a.Get.GetUserGroupsForUser(costUser.Id.ToString())) .ReturnsAsync(new AclResponseObject <List <ResponseUserGroup> > { ErrorMessage = null, Response = new List <ResponseUserGroup> { new ResponseUserGroup { ExternalId = currentUserGroups.FirstOrDefault() }, new ResponseUserGroup { ExternalId = currentUserGroups.LastOrDefault() }, new ResponseUserGroup { ExternalId = newUserGroupId.ToString() } }, Status = HttpStatusCode.OK }); _aclClientMock.Setup(a => a.Get.GetObjectUserGroups(It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(new AclResponseObject <List <ResponseRole> > { ErrorMessage = null, Response = new List <ResponseRole> { new ResponseRole { ExternalId = currentUserGroups.FirstOrDefault() }, new ResponseRole { ExternalId = currentUserGroups.LastOrDefault() }, new ResponseRole { ExternalId = newUserGroupId.ToString() } }, Status = HttpStatusCode.OK }); _aclClientMock.Setup( a => a.Access.GrantAccessToObject(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(new AclResponseObject <List <ResponseUserGroup> > { ErrorMessage = null, Response = new List <ResponseUserGroup> { new ResponseUserGroup { ExternalId = newUserGroupId.ToString() } }, Status = HttpStatusCode.Created }); var agencyAbstractType = _efContext.AbstractType.Include(a => a.Agency).FirstOrDefault(a => a.Type == AbstractObjectType.Agency.ToString()); await _permissionService.GrantUserAccess <AbstractType>(roleId, agencyAbstractType.Id, costUser, BuType.Pg, userId); }
public async Task GetInsuranceUser_NorthAmericanAgency() { //Arrange var agency = new Agency(); var usa = new Country(); var northAmericanRegion = new Region(); var europeanSmo = new Smo(); var countryId = Guid.NewGuid(); var northAmericanInsuranceUserId = Guid.NewGuid(); var europeanInsuranceUserId = Guid.NewGuid(); var northAmericanRegionId = Guid.NewGuid(); var europeanSmoId = Guid.NewGuid(); var northAmericanGdamUserId = "ABC"; var europeGdamUserId = "DEF"; var northAmericanInsuranceUser = new CostUser { Id = northAmericanInsuranceUserId, GdamUserId = northAmericanGdamUserId, UserBusinessRoles = new List <UserBusinessRole> { new UserBusinessRole { BusinessRole = new BusinessRole { Key = Constants.BusinessRole.InsuranceUser, Value = Constants.BusinessRole.InsuranceUser }, ObjectType = core.Constants.AccessObjectType.Region } } }; var europeanInsuranceUser = new CostUser { Id = europeanInsuranceUserId, GdamUserId = europeGdamUserId, UserBusinessRoles = new List <UserBusinessRole> { new UserBusinessRole { BusinessRole = new BusinessRole { Key = Constants.BusinessRole.InsuranceUser, Value = Constants.BusinessRole.InsuranceUser }, ObjectType = core.Constants.AccessObjectType.Smo, } } }; agency.CountryId = countryId; agency.Country = usa; usa.Id = countryId; usa.GeoRegionId = northAmericanRegionId; var northAmericanRegionModel = new RegionModel { Name = Constants.AgencyRegion.NorthAmerica }; _regionsService.Setup(r => r.GetAsync(It.IsAny <Guid>())).ReturnsAsync(northAmericanRegionModel); northAmericanRegion.Id = northAmericanRegionId; northAmericanRegion.Key = Constants.Region.NorthAmericanArea; europeanSmo.Id = europeanSmoId; europeanSmo.Key = Constants.Smo.WesternEurope; var costUsers = new List <CostUser> { northAmericanInsuranceUser, europeanInsuranceUser }; //needed otherwise tests fail when run all together! var existingUsers = _efContext.CostUser.ToList(); _efContext.CostUser.RemoveRange(existingUsers); _efContext.AddRange(costUsers); _efContext.Smo.Add(europeanSmo); _efContext.Region.Add(northAmericanRegion); _efContext.SaveChanges(); _regionsService.Setup(a => a.GetGeoRegion(It.IsAny <Guid>())).ReturnsAsync(new RegionModel { Id = Guid.NewGuid(), Key = Constants.AgencyRegion.NorthAmerica, Name = Constants.AgencyRegion.NorthAmerica }); //Act var result = await _costUserService.GetInsuranceUsers(agency); //Assert result.Should().NotBeNull(); result.First().Should().Be(northAmericanGdamUserId); }