private void button1_Click(object sender, EventArgs e)///ADD BUTTON { vehicle data = new vehicle(); ///var Model = new DatabaseEntities(); Model modelInstance = new Model(); ///.vehicle///.AddObject(TableEntityInstance); data.VehicleName = Ratehr_vec.Text; ///getting value from textbox data.RatePerhour = int.Parse(Ratehr_vec.Text); //getting value from textbox data.RatePerNightPark = int.Parse(Nightpar_vec.Text); //getting value from textbox modelInstance.vehicles.Add(data); modelInstance.SaveChanges(); int res = modelInstance.SaveChanges(); if (res > 0) { MessageBox.Show("Data Inserted Successfully"); } else { MessageBox.Show("Try Again!!!"); } }
public IHttpActionResult PutDirection(int id, Direction direction) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != direction.id) { return(BadRequest()); } db.Entry(direction).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!DirectionExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.OK)); }
public JsonResult DeleteOrder(string id) { using (var Transaction = DB.Database.BeginTransaction()) { bool check = false; try { var item = DB.Orders.Find(id); item.Status = ConstantDefine.CANCELLED; DB.Entry(item).State = EntityState.Modified; DB.SaveChanges(); var ListCart = DB.Carts.Find(item.IdCard); var ListCartItem = ListCart.CartItems; foreach (var entity in ListCartItem) { var itemBook = DB.Books.Find(entity.IdBook); itemBook.Quantity += entity.Quantity; DB.Entry(itemBook).State = EntityState.Modified; DB.SaveChanges(); } Transaction.Commit(); check = true; } catch (Exception ex) { check = false; Transaction.Rollback(); } return(Json(new { status = check })); } }
public ActionResult Create([Bind(Include = "Id,Title,EnTitle,Summary,EnSummary,ImageURL,ISBN,Price,Quantity,IdAuthor,IdPublisher,IdCategory,CreateDate,ModifiedDate,IsActive")] Book book) { if (ModelState.IsValid) { var IdNext = FindNextId(); book.Id = IdNext; book.CreateDate = DateTime.Now; string link = Server.MapPath(@"~\Assets\book-image\" + book.Id); if (!Directory.Exists(link)) { Directory.CreateDirectory(Server.MapPath(@"~\Assets\book-image\" + book.Id)); } var f = Request.Files["ImageURL"]; if (f != null && f.ContentLength > 0) { string fullPath = link + f.FileName; if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } var path = link + @"\" + f.FileName; f.SaveAs(path); book.ImageURL = @"/Assets/book-image/" + book.Id + @"/" + f.FileName; } db.Books.Add(book); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.IdAuthor = new SelectList(db.Authors, "Id", "Name", book.IdAuthor); ViewBag.IdCategory = new SelectList(db.BookCategories, "Id", "CateName", book.IdCategory); ViewBag.IdPublisher = new SelectList(db.Publishers, "Id", "Name", book.IdPublisher); return(View(book)); }
public ActionResult Create([Bind(Include = "id,id_student,id_subject,examen1,examen2,examen3,examen4")] Studentsubject studentsubject) { if (ModelState.IsValid) { Studentsubject ss2 = db.Studentsubjects.ToList().Find(value => value.id_student == studentsubject.id_student && value.id_subject == studentsubject.id_subject); if (ss2 == null) { if (studentsubject.examen1 >= 0 && studentsubject.examen1 <= 10 && studentsubject.examen2 >= 0 && studentsubject.examen2 <= 10 && studentsubject.examen3 >= 0 && studentsubject.examen3 <= 10 && studentsubject.examen4 >= 0 && studentsubject.examen4 <= 10) { db.Studentsubjects.Add(studentsubject); db.SaveChanges(); return(RedirectToAction("Index")); } else { ViewBag.error = "Error, Score must be between 0 and 10"; } } else { ViewBag.error = "Error, Student already have the score!"; } } ViewBag.id_student = new SelectList(db.Students, "id", "name", studentsubject.id_student); ViewBag.id_subject = new SelectList(db.Subjects, "id", "name_subject", studentsubject.id_subject); return(View(studentsubject)); }
public ActionResult Create([Bind(Include = "IdAccount,UserName,Password,IdRole,IsActiveAccount,IdUser,FirstName,LastName,Birthday,Email,Address,Gender,IsActiveUser,Avatar")] Register register) { using (DbContextTransaction tran = db.Database.BeginTransaction()) { try { Account account = new Account(); //Insert data to Account table account.Id = FindNextIdAccount(); account.UserName = register.UserName; account.Password = Encryptor.ToMD5(register.Password); // Encrypt Password account.IdRole = "3"; //Set default role is User account.IsActive = true; //Add to db db.Accounts.Add(account); db.SaveChanges(); User user = new User(); //Insert data to User table user.Id = account.Id; //UserID and AccountID be the same user.FirstName = register.FirstName; user.LastName = register.LastName; user.Birthday = Convert.ToDateTime(register.Birthday); //Convert birthday to MM/DD/YYYY HH:mm:ss A user.Email = register.Email; user.Address = register.Address; user.Gender = register.Gender; user.IsActive = true; //Map path Avatar string link = Server.MapPath(@"~\Assets\user-avatar\" + user.Id); // Check directory existed or not if (!Directory.Exists(link)) { Directory.CreateDirectory(Server.MapPath(@"~\Assets\user-avatar\" + user.Id)); } var f = Request.Files["Avatar"]; if (f != null && f.ContentLength > 0) { string fullPath = link + f.FileName; if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } var path = (link + @"\" + f.FileName); f.SaveAs(path); user.Avatar = (link + @"\" + f.FileName); } //Add to db db.Users.Add(user); db.SaveChanges(); //Commit transaction tran.Commit(); } catch (Exception ex) { tran.Rollback(); } } return(RedirectToAction("Login", "UserLogin")); }
public ActionResult Create(Fabricante fabricante) { context.Fabricantes.Add(fabricante); context.SaveChanges(); return(RedirectToAction("Index")); }
static void Main(string[] args) { using (var db = new Model()) { // Create Console.WriteLine("Inserting a new blog"); db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" }); db.SaveChanges(); // Read Console.WriteLine("Querying for a blog"); var blog = db.Blogs .OrderBy(b => b.BlogId) .First(); // Update Console.WriteLine("Updating the blog and adding a post"); blog.Url = "https://devblogs.microsoft.com/dotnet"; blog.Posts.Add( new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" }); db.SaveChanges(); // Delete Console.WriteLine("Delete the blog"); db.Remove(blog); db.SaveChanges(); } }
public ActionResult AddEdit(Employee Employee) { if (Employee.id == 0) { if (ModelState.IsValid) { context.Employees.Add(Employee); context.SaveChanges(); ViewBag.title = "Add Employee"; return(RedirectToAction("Index")); } return(View()); } else { Employee empToUpdate = context.Employees.Where(p => p.id == Employee.id).FirstOrDefault(); if (empToUpdate != null) { context.Entry(empToUpdate).CurrentValues.SetValues(Employee); } context.SaveChanges(); return(RedirectToAction("Index")); } }
private void Button_SaveNew_Click(object sender, RoutedEventArgs e) { bool inputIsValid = ValidateTeamInput(out DateTime startDate, out DateTime endDate); if (inputIsValid) { try { Team team = new Team { Name = TextBox_Name.Text, Description = TextBox_Description.Text, StartDate = startDate, ExpectedEnd = endDate }; model.Teams.Add(team); model.SaveChanges(); ClearTextBoxes(); DataGrid_Teams.ItemsSource = model.Teams.ToList(); } catch (Exception ex) { MessageBox.Show("Noget gik galt: " + ex.Message); } } else { MessageBox.Show("Ikke alle input felter er udfyldt korrekt."); } }
public IHttpActionResult PutStudentsubject(int id, Studentsubject studentsubject) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != studentsubject.id) { return(BadRequest()); } db.Entry(studentsubject).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!StudentsubjectExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult PutCountry(int id, [FromBody] Country newCountry) { var permission = JwtAuth.GetTokenPermission(Request.Headers.Authorization.Parameter); if ((permission & 128) <= 0) { return(BadRequest("權限不足")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var country = _db.Countries.Find(id); if (country == null) { return(NotFound()); } country.Name = newCountry.Name ?? country.Name; _db.Entry(country).State = EntityState.Modified; try { _db.SaveChanges(); return(Ok(id)); } catch (Exception e) { return(BadRequest(e.Message)); } }
public IHttpActionResult PutRoom(int id, Room room) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != room.Id) { return(BadRequest()); } db.Entry(room).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!RoomExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
private void GetItem() { IsRecorded = 1; model.Entry(this.consultation).State = EntityState.Modified; //model.Consultation.Add(this.consultation); model.SaveChanges(); }
public ActionResult Create(Categoria categoria) { context.Categorias.Add(categoria); context.SaveChanges(); return(RedirectToAction("Index")); }
public IHttpActionResult PutSalesOrderDetail(int id, SalesOrderDetail salesOrderDetail) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != salesOrderDetail.OrderDetailId) { return(BadRequest()); } _context.Entry(salesOrderDetail).State = EntityState.Modified; try { _context.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!SalesOrderDetailExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <IHttpActionResult> AssignTutorToPlacement(int TID, int PID) { // May need to do calculation of assignments based on hours being allocated Placement p = await db.Placements.FindAsync(PID); Tutor t = await db.Tutors.FindAsync(TID); if (p == null) { return(NotFound()); } if (t == null) { return(NotFound()); } //p.TutorID = TID; try { db.SaveChanges(); } catch (DbUpdateException) { return(StatusCode(HttpStatusCode.BadRequest)); } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult PutProgrami(int id, Programi programi) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != programi.ProgramId) { return(BadRequest()); } db.Entry(programi).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ProgramiExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
//ADD BTN private void button6_Click(object sender, EventArgs e) { basicCharge data = new basicCharge(); Model modelInstance = new Model(); data.OvernightStayCharge = int.Parse(Overnightchr.Text); //getting value from textbox data.ExtraKmCharge = int.Parse(extraKmchr.Text); //getting value from textbox data.DriverCharge = int.Parse(driverchr.Text); //getting value from textbox modelInstance.basicCharges.Add(data); modelInstance.SaveChanges(); int res = modelInstance.SaveChanges(); if (res > 0) { MessageBox.Show("Data Inserted Successfully"); } else { MessageBox.Show("Try Again!!!"); } }
public ActionResult Create([Bind(Include = "Id_prestamo,Fecha_entrega,Fecha_devolucion,Estado,Id_usuario,Id_cliente")] Prestamo prestamo) { foreach (var item in detalleAux) { prestamo.detallePrestamo.Add(new detallePrestamo { idLibro = item.idLibro, idPrestamo = prestamo.Id_prestamo, cantidad = item.cantidad }); } if (ModelState.IsValid) { db.Prestamo.Add(prestamo); db.SaveChanges(); foreach (var item in detalleAux) { Libro libro = db.Libro.Find(item.idLibro); libro.Cantidad = libro.Cantidad - item.cantidad; db.Entry(libro).State = EntityState.Modified; db.SaveChanges(); } detalleAux = new List <detallePrestamo>(); return(RedirectToAction("Index")); } ViewBag.Id_cliente = new SelectList(db.Cliente, "Id_cliente", "Nombre", prestamo.Id_cliente); ViewBag.Id_usuario = new SelectList(db.Usuarios, "Id_usuario", "Nombre", prestamo.Id_usuario); return(View(prestamo)); }
public IHttpActionResult PutTag(int id, [FromBody] Tag newTag) { var token = JwtAuth.GetToken(Request.Headers.Authorization.Parameter); if ((Convert.ToInt32(token["Permission"]) & 128) <= 0) { return(BadRequest("權限不足")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var tag = _db.Tags.Find(id); if (tag == null) { return(NotFound()); } tag.Name = newTag.Name ?? tag.Name; tag.Color = newTag.Color ?? tag.Color; _db.Entry(tag).State = EntityState.Modified; try { _db.SaveChanges(); } catch (Exception e) { return(BadRequest(e.Message)); } return(Ok(id)); }
public IHttpActionResult PutSubjectteacher(int id, Subjectteacher subjectteacher) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != subjectteacher.id) { return(BadRequest()); } db.Entry(subjectteacher).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!SubjectteacherExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.OK)); }
private void ADD_Click(object sender, EventArgs e) { DayPackage P = new DayPackage(); ///var Model = new DatabaseEntities(); Model MP = new Model(); ///.vehicle///.AddObject(TableEntityInstance); P.PName = Package_Name.Text; ///Ratehr_vec.Text; ;///getting value from textbox P.PDistance = int.Parse(Package_Distance.Text); //getting value from textbox P.Pcost = int.Parse(Package_Cost.Text); //getting value from textbox MP.DayPackages.Add(P); MP.SaveChanges(); int res = MP.SaveChanges(); if (res > 0) { MessageBox.Show("Data Inserted Successfully"); } else { MessageBox.Show("Try Again!!!"); } }
public ActionResult Create([Bind(Include = "Name,Duration,startingPrice,Image")] AuctionViewModel auctionView) { logger.Info("POST/Auction/Create action has been called"); if (Session["User"] == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (ModelState.IsValid) { Auction auction = new Auction(); auction.Name = auctionView.Name; auction.Duration = auctionView.Duration; auction.startingPrice = auctionView.startingPrice; if (auctionView.Image != null) { auction.Img = new byte[auctionView.Image.ContentLength]; auctionView.Image.InputStream.Read(auction.Img, 0, auctionView.Image.ContentLength); } auction.createdOn = DateTime.UtcNow; auction.State = "READY"; myDB.Auctions.Add(auction); myDB.SaveChanges(); return(RedirectToAction("UserPanel", "Accounts")); } return(View()); }
private void Button_SaveNewProject_Click(object sender, RoutedEventArgs e) { bool inputIsValid = ValidateProjectInput(out DateTime startDate, out DateTime endDate, out decimal budgetLimit); if (inputIsValid) { try { Project project = new Project { Name = TextBox_Name.Text, Description = TextBox_Description.Text, StartDate = startDate, EndDate = endDate, BudgetLimit = budgetLimit }; model.Projects.Add(project); model.SaveChanges(); ClearTextBoxes(); DataGrid_Projects.ItemsSource = model.Projects.ToList(); } catch (Exception ex) { MessageBox.Show("Noget gik galt: " + ex.Message); } } else { MessageBox.Show("Ikke alle input felter er udfyldt korrekt."); } }
public IHttpActionResult PutPlacementProvider(int id, PlacementProvider placementProvider) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != placementProvider.ProviderID) { return(BadRequest()); } db.Entry(placementProvider).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!PlacementProviderExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult PutGenre(int id, Genre genre) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != genre.GenreId) { return(BadRequest()); } _context.Entry(genre).State = EntityState.Modified; try { _context.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!GenreExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public ActionResult Create([Bind(Include = "Id,UserName,Password,IdRole,IsActive")] Account account) { if (ModelState.IsValid) { using (DbContextTransaction tran = db.Database.BeginTransaction()) { try { User user = new User(); user.Id = FindNextIdAccount(); user.IsActive = account.IsActive; account.Id = user.Id; // Auto create 1 new Id account.Password = Encryptor.ToMD5(account.Password); // Encrypt Passord db.Users.Add(user); db.Accounts.Add(account); db.SaveChanges(); tran.Commit(); return(RedirectToAction("Index")); } catch { tran.Rollback(); } } } ViewBag.IdRole = new SelectList(db.Roles, "Id", "RoleName", account.IdRole); ViewBag.Id = new SelectList(db.Users, "Id", "FirstName", account.Id); return(View(account)); }
public IHttpActionResult Putinterests(decimal id, interests interests) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != interests.id) { return(BadRequest()); } db.Entry(interests).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!interestsExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult PutPAR_MarcaNeumatico(string id, PAR_MarcaNeumatico pAR_MarcaNeumatico) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != pAR_MarcaNeumatico.Id_MarcaNeumatico) { return(BadRequest()); } db.Entry(pAR_MarcaNeumatico).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!PAR_MarcaNeumaticoExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public void Save(Model.EDEntities db) { var result = (from p in db.People where p.Login.ToUpper() == this.Login.ToUpper() select p).Count(); if (result > 0) throw new ApplicationException("Person with this login has already been registered"); var person = this.Map(); db.People.Add(person); db.SaveChanges(); this.ID = person.ID; }
public void Save(Model.EDEntities db) { var result = (from p in db.Certificates where p.SerialNumber == this.SerialNumber select p).Count(); if (result > 0) throw new ApplicationException("Person with this certificate has already been registered"); var certificate = this.Map(); db.Certificates.Add(certificate); db.SaveChanges(); this.ID = certificate.ID; }