public static void AddStockToShops(this CompanyDbContext context, string [] lines) { foreach (var line in lines) { var colonIndex = line.IndexOf(':'); var shopName = line.Substring(0, colonIndex); var shop = context.Tenants.IgnoreQueryFilters().OfType <RetailOutlet>() .SingleOrDefault(x => x.Name == shopName); if (shop == null) { throw new ApplicationException($"Could not find a shop of name '{shopName}'"); } var eachStock = from stockAndPrice in line.Substring(colonIndex + 1).Split(',') let parts = stockAndPrice.Split('|').Select(x => x.Trim()).ToArray() select new { Name = parts[0], Price = decimal.Parse(parts[1]) }; foreach (var stock in eachStock) { var newStock = new ShopStock { Name = stock.Name, NumInStock = 5, RetailPrice = stock.Price, Shop = shop }; newStock.SetShopLevelDataKey(shop.DataKey); context.Add(newStock); } } }
public void TestDataKeyNotSetIfProvidedKeyIsNull() { //SETUP var options = SqliteInMemory.CreateOptions <CompanyDbContext>(); using (var context = new CompanyDbContext(options, new FakeGetClaimsProvider(null))) { context.Database.EnsureCreated(); var company = Company.AddTenantToDatabaseWithSaveChanges("TestCompany", PaidForModules.None, context); var shop = RetailOutlet.AddTenantToDatabaseWithSaveChanges("TestShop", company, context); var stock = new ShopStock { Name = "dress", Shop = shop }; stock.SetShopLevelDataKey("accessKey*"); context.Add(stock); context.SaveChanges(); } using (var context = new CompanyDbContext(options, new FakeGetClaimsProvider("accessKey*"))) { //ATTEMPT var stocksFiltered = context.ShopStocks.ToList(); //VERIFY stocksFiltered.Count.ShouldEqual(1); } }
public async Task <IActionResult> Post([FromBody] Employment employment) { _db.Add(employment); await _db.SaveChangesAsync(); return(Ok(employment)); }
public void TestQueryFilterWorksOnShopStock() { //SETUP var options = SqliteInMemory.CreateOptions <CompanyDbContext>(); using (var context = new CompanyDbContext(options, new FakeGetClaimsProvider("accessKey*"))) { context.Database.EnsureCreated(); var company = Company.AddTenantToDatabaseWithSaveChanges("TestCompany", PaidForModules.None, context); var shop = RetailOutlet.AddTenantToDatabaseWithSaveChanges("TestShop", company, context); context.Add(new ShopStock { Name = "dress", Shop = shop }); context.SaveChanges(); } using (var context = new CompanyDbContext(options, new FakeGetClaimsProvider("DIFF-accessKey*"))) { //ATTEMPT var stocksFiltered = context.ShopStocks.ToList(); var stocksNotFiltered = context.ShopStocks.IgnoreQueryFilters().ToList(); //VERIFY stocksFiltered.Count.ShouldEqual(0); stocksNotFiltered.Count.ShouldEqual(1); stocksNotFiltered.First().DataKey.ShouldEqual("accessKey*"); } }
public void TestQueryFilterWorksOnShopStock() { //SETUP var options = SqliteInMemory.CreateOptions <CompanyDbContext>(); using (var context = new CompanyDbContext(options, new FakeGetClaimsProvider("accessKey*"))) { context.Database.EnsureCreated(); var company = Company.AddTenantToDatabaseWithSaveChanges("TestCompany", PaidForModules.None, context); var shop = RetailOutlet.AddTenantToDatabaseWithSaveChanges("TestShop", company, context); var stock = new ShopStock { Name = "dress", NumInStock = 5, Shop = shop }; context.Add(stock); context.SaveChanges(); var utData = context.SetupSingleDtoAndEntities <SellItemDto>(); var service = new CrudServices(context, utData.ConfigAndMapper); //ATTEMPT var dto = new SellItemDto { TenantItemId = shop.TenantItemId, ShopStockId = stock.ShopStockId, NumBought = 1 }; var shopSale = service.CreateAndSave(dto); //VERIFY service.IsValid.ShouldBeTrue(service.GetAllErrors()); context.ShopSales.Count().ShouldEqual(1); context.ShopStocks.Single().NumInStock.ShouldEqual(4); } }
public async Task <IActionResult> Create([Bind("Id,Name,Desc")] ConfigurationValue configurationValue) { if (ModelState.IsValid) { _context.Add(configurationValue); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(configurationValue)); }
public async Task <IActionResult> Create([Bind("Type,Description,IsActive,IsDeleted,DeletedOn,Id,CreatedOn,ModifiedOn")] QuantityType quantityType) { if (ModelState.IsValid) { _context.Add(quantityType); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(quantityType)); }
public async Task <IActionResult> Create([Bind("ClienteId,RIF,RazonSocial")] Cliente cliente) { if (ModelState.IsValid) { _context.Add(cliente); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(cliente)); }
public CompanyDTO AddCompany(AddCompanyDTO companyDto) { var company = mapper.Map <Company>(companyDto); dbContext.Add(company); dbContext.SaveChanges(); var result = mapper.Map <CompanyDTO>(company); return(result); }
public ActionResult Create(Employee emp) { if (ModelState.IsValid) { _context.Add(emp); _context.SaveChanges(); TempData["message"] = "Employee created"; return(RedirectToAction("Index")); } ModelState.AddModelError("", "There have been errors"); return(View(emp)); }
private void AddEmployeeToDb(EmployeeViewModel model) { Employee newEmployee = new Employee { Name = model.Name, Position = model.Position, PositionEnum = model.PositionEnum, IsActive = true }; _db.Add <Employee>(newEmployee); _db.SaveChanges(); }
public async Task <IActionResult> Post([FromBody] Person person) { // NOTE TransactionSCope wouldn't work here for some reason. EF "doesn't support ambient transactions". using (var tx = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { Db.Database.BeginTransaction(System.Data.IsolationLevel.Serializable); person.EmployeeNum = BuildEmpNum(person.LastName); Db.Add(person); await Db.SaveChangesAsync(); Db.Database.CommitTransaction(); return(Ok(person)); } }
public IActionResult Index() { // 2. Create an employee instance var employee = new Employee { Name = "John", Surname = "Doe", DateOfBirth = new DateTime(1980, 10, 10) }; // 3. Add employee to context _dbContext.Add(employee); // 4. Save changes on context _dbContext.SaveChanges(); return(View()); }
protected static void AddTenantToDatabaseWithSaveChanges(TenantBase newTenant, CompanyDbContext context) { if (newTenant == null) { throw new ArgumentNullException(nameof(newTenant)); } if (!(newTenant is Company)) { if (newTenant.Parent == null) { throw new ApplicationException($"The parent cannot be null in type {newTenant.GetType().Name}."); } if (newTenant.Parent.ParentItemId == 0) { throw new ApplicationException($"The parent {newTenant.Parent.Name} must be already in the database."); } } if (context.Entry(newTenant).State != EntityState.Detached) { throw new ApplicationException($"You can't use this method to add a tenant that is already in the database."); } //We have to do this request using a transaction to make sure the DataKey is set properly using (var transaction = context.Database.BeginTransaction()) { //set up the backward link (if Parent isn't null) newTenant.Parent?._children.Add(newTenant); context.Add(newTenant); //also need to add it in case its the company // Add this to get primary key set context.SaveChanges(); //Now we can set the DataKey newTenant.SetDataKeyFromHierarchy(); context.SaveChanges(); transaction.Commit(); } }
[ValidateAntiForgeryToken] //protect against CSRF attacks public async Task <IActionResult> Kontakt(Inquiry inquiry) { var userAgent = Request.Headers["User-Agent"].ToString(); // OPTIONAL: Set version truncation to none, so full versions will be returned // By default only minor versions will be returned (e.g. X.Y) // for other options see VERSION_TRUNCATION_* constants in DeviceParserAbstract class // add using DeviceDetectorNET.Parser; DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE); var dd = new DeviceDetector(userAgent); // OPTIONAL: Set caching method // By default static cache is used, which works best within one php process (memory array caching) // To cache across requests use caching in files or memcache // add using DeviceDetectorNET.Cache; dd.SetCache(new DictionaryCache()); // OPTIONAL: If called, GetBot() will only return true if a bot was detected (speeds up detection a bit) dd.DiscardBotInformation(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) dd.SkipBotDetection(); dd.Parse(); if (dd.IsBot()) { // handle bots,spiders,crawlers,... var botInfo = dd.GetBot(); inquiry.Browser = "BOT"; inquiry.OperatingSystem = "BOT"; inquiry.Device = "BOT"; inquiry.Brand = "BOT"; inquiry.Model = "BOT"; } else { var clientInfo = dd.GetClient(); // holds information about browser, feed reader, media player, ... var osInfo = dd.GetOs(); var device = dd.GetDeviceName(); var brand = dd.GetBrandName(); var model = dd.GetModel(); inquiry.Browser = $"{clientInfo.Match.Name} ({clientInfo.Match.Version})"; inquiry.OperatingSystem = $"{osInfo.Match.Name} ({osInfo.Match.Version}) {osInfo.Match.Platform}"; var deviceResult = device == "" ? inquiry.Device = "N/A" : inquiry.Device = device; var brandResult = brand == "" ? inquiry.Brand = "N/A" : inquiry.Brand = brand; var modelResult = model == "" ? inquiry.Model = "N/A" : inquiry.Model = model; } //local Environment //OperatingSystem os = Environment.OSVersion; //var platform = os.Platform.ToString(); //var version = os.Version.ToString(); //var servicePack = os.ServicePack.ToString(); var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(); inquiry.IpAddress = remoteIpAddress; inquiry.CreatedDate = DateTime.Now; inquiry.Status = "New"; inquiry.HoursSpend = 0; inquiry.HourPrice = 400; inquiry.InvoiceNo = "N/A"; inquiry.Payment = "N/A"; if (ModelState.IsValid) { var inquiryId = await contex.Inquiries.FirstOrDefaultAsync(x => x.Id == inquiry.Id); if (inquiryId != null) { ModelState.AddModelError("", "Nastapil bland, ponow wpis."); return(View()); } //string attachmentName = "noimagecar.png"; //if (inquiry.AttachmentUpload != null) //{ // string uploadsDir = Path.Combine(webHostEnvironment.WebRootPath, "media/cars"); // attachmentName = Guid.NewGuid().ToString() + "_" + inquiry.AttachmentUpload.FileName; // string filePath = Path.Combine(uploadsDir, attachmentName); // FileStream fs = new FileStream(filePath, FileMode.Create); // await inquiry.AttachmentUpload.CopyToAsync(fs); // fs.Close(); //} //inquiry.Attachment = attachmentName; contex.Add(inquiry); await contex.SaveChangesAsync(); TempData["Success"] = "Wiadomosc zostala wyslana!"; return(RedirectToAction("Kontakt")); } return(View()); }
public void Post([FromBody] Company comp) { _context.Add(comp); _context.SaveChanges(); }
public void Post([FromBody] Employee emp) { _context.Add(emp); _context.SaveChanges(); }