public async Task <IActionResult> Create([Bind("Id,Name,Product_id,Imagepath")] Image imageCreateModel) { var image = new Image { Id = imageCreateModel.Id, Name = imageCreateModel.Name, Product_id = imageCreateModel.Product_id, Imagepath = imageCreateModel.Imagepath }; if (ModelState.IsValid) { _context.Add(image); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(imageCreateModel)); }
public async void OnNavigatedTo(INavigationParameters parameters) { using (var db = new DatabaseContext()) { db.Database.Migrate(); if ((await db.Blogs.CountAsync()) == 0) { db.Add(new Blog() { Rating = 5, Url = "https://mylabtw.blogspot.com/" }); db.SaveChanges(); } URL = db.Blogs.ToList().FirstOrDefault().Url; DBPath = db._databasePath; } }
public async Task <int> SaveAsync(Inventory inventory) { if (inventory.InventoryMeta == null) { inventory.InventoryMeta = new InventoryMeta(); } inventory.InventoryMeta.Modified = DateTime.UtcNow; if (inventory.InventoryMeta.Created == null) { inventory.InventoryMeta.Created = DateTime.UtcNow; } _databaseContext.Add(inventory); var id = await _databaseContext.SaveChangesAsync(); return(id); }
public IActionResult Perform(PerformExaminationModel input) { using var db = new DatabaseContext(); var pvcheck = db.PatientVisits.SingleOrDefault(x => x.PatientVisitId == input.VisitId); var pecheck = db.ExaminationsDictionary.SingleOrDefault(x => x.ExaminationDictionaryId == input.ExaminationId); if (pvcheck != null && pecheck != null && pvcheck.Status == "Registered" && pecheck.Type == 'F') { db.Add(new PhysicalExamination() { Result = input.Result, PatientVisitId = input.VisitId, ExaminationDictionaryId = input.ExaminationId }); db.SaveChanges(); return(Ok()); } return(BadRequest()); }
public void Given_Exercise_When_DeleteExerciseAsync_Then_ShouldBeTrue() { RunOnDatabase(context => { // ARRANGE DatabaseContext databaseContext = context; var exercisesRepository = new ExercisesRepository(context); databaseContext.Roles.Add(Role.Create("student")); databaseContext.SaveChanges(); var userType = databaseContext.Roles.FirstOrDefault(); databaseContext.TestTypes.Add(TestType.Create("Grila")); databaseContext.SaveChanges(); var testType = databaseContext.TestTypes.FirstOrDefault(); if (userType != null) { databaseContext.Users.Add(User.Create("Johny", "Bravo", "johnnybravo", "*****@*****.**", "#$$RR#$TED")); } databaseContext.SaveChanges(); var user = databaseContext.Users.FirstOrDefault(); if (user != null && testType != null) { databaseContext.Tests.Add(Test.Create("NumeleTestului", "DescriereaTextului", user.Id, testType.Id)); } databaseContext.SaveChanges(); var test = databaseContext.Tests.FirstOrDefault(); if (test != null) { var exercise = Exercise.Create("Problema1", test.Id); databaseContext.Add(exercise); databaseContext.SaveChanges(); // ACT var result = exercisesRepository.DeleteAsync(exercise.Id); // ASSERT result.Result.Should().Be(true); } }); }
public ActionResult SetData(Participant item) { Participant participant = new Participant() { Id = item.Id, FullName = item.FullName, EMail = item.EMail, PhoneNumber = item.PhoneNumber, TourTypeId = item.TourTypeId }; _db.Add(participant); var TourType = _db.TourTypes.Find(item.TourTypeId); TourType.Amount++; _db.SaveChanges(); return(Ok()); }
/// <inheritdoc /> public async Task <Guid> AddPicture(PictureModel pictureModel) { Guid guid = Guid.NewGuid(); var picture = new Picture() { Title = pictureModel.Title, PictureGuid = guid }; using (var memoryStream = new MemoryStream()) { await pictureModel.Picture.CopyToAsync(memoryStream); picture.ClinicPicture = memoryStream.ToArray(); _context.Add(picture); await _context.SaveChangesAsync(); } return(picture.PictureGuid); }
public Boolean Add(Account account) { Boolean testAccount = _context.Accounts.Any(acc => acc.Email == account.Email); if (testAccount) { return(false); } using (var sha256 = SHA256.Create()) { // Send a sample text to hash. var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(account.Password)); // Get the hashed string. var hash = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); account.Password = hash; } _context.Add(account); return(true); }
public async Task <IActionResult> Create(City city) { if (ModelState.IsValid) { if (city.CityId > 0) { db.Update(city); await db.SaveChangesAsync(); TempData["Message"] = "Data Update Successfully"; TempData["Status"] = "2"; } else { try { db.Add(city); await db.SaveChangesAsync(); TempData["Message"] = "Data Added Successfully"; TempData["Status"] = "1"; //ViewBag.Message = "Data Added Successfully"; //ViewBag.Status = "1"; } catch (DbUpdateConcurrencyException) { if (!CityExists(city.CityId)) { return(NotFound()); } else { throw; } } } return(RedirectToAction(nameof(Index))); } ViewData["CountryId"] = new SelectList(db.Countries, "CountryId", "Name", city.CountryId); return(View(city)); }
/// <summary> /// Creates an InMemory SQLRespository and populates with entities /// </summary> /// <param name="dbObjects"></param> public static IDataRepository CreateInMemoryTestDatabase(params object[] dbObjects) { //Get the method name of the unit test or the parent var testName = TestContext.CurrentContext.Test.FullName; if (string.IsNullOrWhiteSpace(testName)) { testName = MethodBase.GetCurrentMethod().FindParentWithAttribute <TestAttribute>().Name; } var optionsBuilder = new DbContextOptionsBuilder <DatabaseContext>().UseInMemoryDatabase(testName); optionsBuilder.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)); // show more detailed EF errors i.e. ReturnId value instead of '{ReturnId}' n the logs etc... optionsBuilder.EnableSensitiveDataLogging(); var dbContext = new DatabaseContext(optionsBuilder.Options); if (dbObjects != null && dbObjects.Length > 0) { foreach (var item in dbObjects) { var enumerable = item as IEnumerable <object>; if (enumerable == null) { dbContext.Add(item); } else { dbContext.AddRange(enumerable); } } dbContext.SaveChanges(); } var dataRepo = new SqlRepository(dbContext); return(dataRepo); }
public IActionResult Einde() { //check eerst dat alle items in Winkelmand nog bestaan in ShopItems //zonder check krijg je later bij .SaveChanges() een SQL/DB-error: //indien items in winkelmand ligt //en item wordt verwijderd uit productbeheer //en dan wordt order geplaatst -> SQL/DB-error //want ShopItem bestaat niet meer foreach (var item in _database.Winkelmandje) { var databaseitem = _databaseContext.ShopItems.SingleOrDefault(a => a.Id == item.Id); if (databaseitem == null) { Console.Write("Onbekend item in winkelmand!"); _database.Winkelmandje.Clear(); return(RedirectToAction("Index")); } } //Indien alle items winkelmand bestaan in In-memory database-ShopItems //wordt order gemaakt Order order = new Order(); _databaseContext.Add(order); _databaseContext.SaveChanges(); //orderlines maken van winkelmand-items voor dit order foreach (var item in _database.Winkelmandje) { Orderline orderline = new Orderline() { OrderId = order.Id, ShopItemId = item.Id }; _databaseContext.Orderlines.Add(orderline); _databaseContext.SaveChanges(); } return(View()); }
public async Task <IActionResult> Create(Category category) { if (ModelState.IsValid) { if (category.CategoryId > 0) { db.Update(category); await db.SaveChangesAsync(); TempData["Message"] = "Data Update Successfully"; TempData["Status"] = "2"; } else { try { db.Add(category); await db.SaveChangesAsync(); TempData["Message"] = "Data Added Successfully"; TempData["Status"] = "1"; //ViewBag.Message = "Data Added Successfully"; //ViewBag.Status = "1"; } catch (DbUpdateConcurrencyException) { if (!categoryExists(category.CategoryId)) { return(NotFound()); } else { throw; } } } return(RedirectToAction(nameof(Index))); } return(View(category)); }
public void btnSubmit_Click(Object sender, EventArgs e) { if (Page.IsValid) { using (var context = new DatabaseContext()) { Models.Project project = new Models.Project() { Title = txtTitle.Text, Description = txtDescription.Text, URL = txtURL.Text, ProjectMembers = new List <ProjectMember>() }; if (fuPoster.HasFile) { try { string filename = Guid.NewGuid().ToString() + Path.GetExtension(fuPoster.FileName); fuPoster.SaveAs(Server.MapPath("/Content/Posters/") + filename); project.Poster = filename; } catch (Exception) { } } project.ProjectMembers.Add(new ProjectMember() { Project = project, Student = context.Student .Single(s => s.ID == CurrentStudent.ID), Role = "Leader", Reflection = txtReflections.Text }); context.Add(project); context.SaveChanges(); Response.Redirect("/Pages/Controls/Student/UpdateProjects.aspx"); } } }
public async Task <IActionResult> Create([Bind("Id,Name,Password,PhoneNumber,Email")] Usuario usuario) { int flag; String temp = usuario.Email; var Usuario = _context.Usuario.FirstOrDefault(user => user.Email == temp); if (Usuario == null) { if (ModelState.IsValid) { _context.Add(usuario); await _context.SaveChangesAsync(); return(RedirectToAction("GoToIndex", "Home", new { flag = 3 })); } } flag = 0; ViewBag.flag = flag; return(View(usuario)); }
public IActionResult Create(Product model) { var product = new Product() { Description = model.Description, Title = model.Title, ImageUrl = model.ImageUrl, Price = model.Price, Quantity = model.Quantity, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; _databaseContext.Add(product); _databaseContext.SaveChanges(); _cacheClient.RemoveAllCache(); return(Ok(new { status = 200, message = "Product has been created" })); }
protected void Button3_Click(object sender, EventArgs e) { using (var context = new DatabaseContext()) { Models.Reply Replies = new Models.Reply(); Replies.Text = txtReply.Text; // Reply itself Replies.Parent = context.Parent.Single(p => p.ID == (Session["Account"] as Models.Parent).ID); // Checks to see if you are a parent (FromID) Replies.Mentor = context.Mentor.Single(m => m.Name.Equals(ddl_Mentor.SelectedValue)); // To know the mentor Replies.Message = context.Message.Single(n => n.Text.Equals(ddl_Message.SelectedValue)); // For the message they reply to context.Add(Replies); // INSERT into the database context.SaveChanges(); } Response.Redirect("Messages.aspx?Title= " + txtReply.Text); }
public IActionResult CollectData(CollectDataModel input) // zebranie danych z pirometru { using var db = new DatabaseContext(); if (input.PyrometerId > 0 && input.MaterialEmissivity > 0 && input.MaterialName != null) // jesli id i emisyjnosc wieksza od 0 i nazwa materialu inna niz null { db.Add(new Measurement() // dodanie rekordu do bazy danych { PyrometerId = input.PyrometerId, MaterialName = input.MaterialName, MaterialEmissivity = input.MaterialEmissivity, ObjectTemperature = input.ObjectTemperature, AmbientTemperature = input.AmbientTemperature, MeasurementDate = DateTime.Now.ToString() }); db.SaveChanges(); // zapis zmian return(Ok()); } return(BadRequest()); }
public async Task <IActionResult> Create([Bind("Id,CompanyName,Password,PhoneNumber,Email,NIT")] Empresa empresa) { int flag; String temp = empresa.Email; var Empresa = _context.Empresa.FirstOrDefault(empresa => empresa.Email == temp); if (Empresa == null) { if (ModelState.IsValid) { _context.Add(empresa); await _context.SaveChangesAsync(); return(RedirectToAction("GoToIndex", "Home", new { flag = 3 })); } } flag = 0; ViewBag.flag = flag; return(View(empresa)); }
public async Task <ActionResult <IEnumerable <Run> > > Seed() { var locations = new List <string> { "Vinoy Park", "Disney World", "Weedon", "Sawgrass", "Gandy", "Fort De Soto" }; for (int i = 0; i < 5; i++) { var run = new Run { Location = locations.OrderBy(o => Guid.NewGuid()).First(), Distance = new Random().Next(2, 14), When = DateTime.Now.AddDays(0 - i).AddHours(new Random().Next(0, 12)) }; _context.Add(run); } await _context.SaveChangesAsync(); return(Ok()); }
public void Create(string name, string password) { Validate.NotNullOrBlank(name, "Name cannot be blank."); Validate.NotNullOrBlank(password, "Password cannot be blank."); Validate.ShouldThrow <UserNotExistsException>(() => { Find(name); }, "User " + name + " already exists."); ValidatePassword(password); var hashedPassword = _passwordHash.Hash(password); var user = new User { Name = name, PasswordHash = hashedPassword }; _databaseContext.Add(user); _databaseContext.SaveChanges(); }
public IActionResult Order(OrderExaminationModel input) { using var db = new DatabaseContext(); var pecheck = db.ExaminationsDictionary.SingleOrDefault(x => x.ExaminationDictionaryId == input.ExaminationTypeId); if (db.PatientVisits.SingleOrDefault(x => x.PatientVisitId == input.VisitId) != null && pecheck.Type == 'L') { db.Add(new LaboratoryExamination() { PatientVisitId = input.VisitId, DoctorComment = input.DoctorComment, OrderDate = DateTime.Now, Status = "Ordered", ExaminationDictionaryId = input.ExaminationTypeId }); db.SaveChanges(); return(Ok()); } return(BadRequest()); }
public T Add <T>(T newItem) where T : class, IBaseEntity { if (newItem == null) { return(null); } try { _model.Add(newItem); _model.SaveChanges(); return(newItem); } catch (Exception e) { Console.WriteLine(e); return(null); } }
public IActionResult Post(ManualItemDto model) { if (model.ManualItemId > 0) { var entityInDb = _db.ManualItems.FirstOrDefault(mi => mi.ManualItemId == model.ManualItemId); _mapper.Map(model, entityInDb); _db.SaveChanges(); } else { var entity = new ManualItem(); //_mapper.Map(model, entity); _utilities.AutoMap(ref entity, model); _db.Add(entity); _db.SaveChanges(); model.ManualItemId = entity.ManualItemId; } return(Ok(model)); }
protected void Button2_Click(object sender, EventArgs e) { using (var context = new DatabaseContext()) { Message messages = new Message(); messages.Title = txtTitle.Text; // Message Title messages.Text = txtMessage.Text; // Message itself messages.Parent = context.Parent.Single(p => p.ID == (Session["Account"] as Models.Parent).ID); // Checks to see if you are a parent (FromID) messages.Mentor = context.Mentor.Single(m => m.Name.Equals(ddl_Mentor.SelectedValue)); // Sends to the mentor (ToID) context.Add(messages); // INSERTS into the Database context.SaveChanges(); } Response.Redirect("Messages.aspx?Title= " + txtTitle.Text + "Messages.aspx?Message= " + txtMessage.Text); // Redirect }
public IActionResult calculo(Invoice invoice) { Console.WriteLine("calculo"); Random random = new Random(); int num = random.Next(); invoice.Num = num; int subt = invoice.producto * invoice.cantidad; invoice.SubTotal = subt; double total = Math.Round(subt * 1.18, 2); invoice.Total = total; _context.Add(invoice); _context.SaveChanges(); return(View(invoice)); }
/// <summary> /// Creates a section. /// </summary> public async Task <bool> CreateSectionAsync( string classroomName, Section section, IModelErrorCollection errors) { var classroom = await LoadClassroomAsync(classroomName); section.ClassroomId = classroom.Id; if (!await _sectionValidator.ValidateSectionAsync(section, errors)) { return(false); } _dbContext.Add(section); await _dbContext.SaveChangesAsync(); return(true); }
public async Task <IActionResult> Create([Bind("Username,Password,Email,Birthdate")] Users users) { if (ModelState.IsValid) { Users tmp_user = (Users)_context.Users.SingleOrDefault(currUser => users.Username == currUser.Username); if (tmp_user == null) { _context.Add(users); ModelState.AddModelError("Register", ""); await _context.SaveChangesAsync(); return(RedirectToAction("Login", "Users")); } else { ModelState.AddModelError("Register", "User name already exist"); } } return(View(users)); }
public async Task <IActionResult> Create(Availability Model) { string UserMail = _UserManager.GetUserEmail(this.User); try { if (ModelState.IsValid) { Model.MedicKey = _UserManager.GetMedicKeyByEmail(UserMail); _Context.Add(Model); await _Context.SaveChangesAsync(); } return(RedirectToAction("Configure", "Availability")); } catch (Exception e) { Console.Write(e); return(RedirectToAction("Create", "Availability")); } }
public async Task <IActionResult> Create([Bind("Id,Date_start,Date_end,Description,Name")] Promotion promotion) { var promo = new Promotion { Id = promotion.Id, Date_start = promotion.Date_start, Date_end = promotion.Date_end, Description = promotion.Description, Name = promotion.Name }; if (ModelState.IsValid) { _context.Add(promo); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(promotion)); }
private static void Save(DatabaseContext context) { Product squeakyBone = new Product() { Name = "Squeaky Dog Bone", Price = 4.99M }; context.Products.Add(squeakyBone); Product tennisBalls = new Product() { Name = "Tennis Ball 3-Pack", Price = 9.99M }; context.Add(tennisBalls); context.SaveChanges(); }
public Timeline Add(Timeline timeline) { using (DatabaseContext context = new DatabaseContext()) { ContentItem contentItem = new ContentItem() { ParentId = 1, BeginDate = timeline.BeginDate, EndDate = timeline.EndDate, HasChildren = true, Title = timeline.Title, Description = timeline.Description, PictureURLs = new string[1] }; contentItem = context.AddContentItem<MSSQL.Entities.ContentItem, ContentItem>(contentItem); timeline.RootContentItemId = contentItem.Id; return context.Add<MSSQL.Entities.Timeline, Timeline>(timeline, new string[] { "Id", "Timestamp" }); } }