public JsonResult SaveEvent(Event e) { var status = false; using (MyDataEntities dc = new MyDataEntities()) { if (e.EventID > 0) { var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault(); if (v != null) { v.Subject = e.Subject; v.Start = e.Start; v.End = e.End; v.Description = e.Description; v.IsFullDay = e.IsFullDay; v.ThemeColor = e.ThemeColor; } else { dc.Events.Add(e); } dc.SaveChanges(); status = true; } else { dc.Events.Add(e); dc.SaveChanges(); } } return(new JsonResult { Data = new { status = status, e } }); }
public ActionResult Create([Bind(Include = "ProductName,Description,IsPublished,Quantity,Price,ImageFile,DateCreated,CreatedBy,DateModified,ModifiedBy")] Store.Data.Product product) { if (ModelState.IsValid) { db.Products.Add(product); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(product)); }
public ActionResult Save(Event ev) { bool status = false; if (ModelState.IsValid) { using (MyDataEntities dc = new MyDataEntities()) { if (ev.EventId > 0) { var v = dc.Events.Where(a => a.EventId == ev.EventId).FirstOrDefault(); if (v != null) { v.EventName = ev.EventName; v.EventLocation = ev.EventLocation; v.EventStartDate = ev.EventStartDate; v.EventEndDate = ev.EventEndDate; } } else { dc.Events.Add(ev); } dc.SaveChanges(); status = true; } } return(new JsonResult { Data = new { status = status } }); }
public void DeleteItem(int id) { db = new MyDataEntities(); var item = db.Items.Find(id); db.Items.Remove(item); db.SaveChanges(); }
public void minusAmountItem(int id, int quantity) { db = new MyDataEntities(); var item = this.getItems(id); item.Amount -= quantity; db.SaveChanges(); }
public void DeleteProducer(int id) { var producer = db.Producers.Find(id); db = new MyDataEntities(); db.Producers.Remove(producer); db.SaveChanges(); }
public ActionResult SaveData(EmpTable emp) { var context = new MyDataEntities(); context.EmpTables.Add(emp); context.SaveChanges(); return(RedirectToAction("AllEmployees")); }
public void DeleteCart(int id) { db = new MyDataEntities(); var cart = db.Carts.Find(id); db.Carts.Remove(cart); db.SaveChanges(); }
public void UpdateProducer(int id, string name) { db = new MyDataEntities(); var producer = db.Producers.Find(id); producer.Name = name; db.Entry(producer).State = System.Data.EntityState.Modified; db.SaveChanges(); }
public ActionResult CreateAddressWithUser(Store.Data.Address newAddress, int userID) { if (ModelState.IsValid) { //Populate address object with necessary values newAddress.UserID = userID; newAddress.IsBilling = true; newAddress.IsShipping = true; newAddress.DateCreated = DateTime.Now; newAddress.CreatedBy = "dbo"; newAddress.DateModified = DateTime.Now; newAddress.ModifiedBy = "dbo"; //Add the new address object to the DB and then save the DB db.Addresses.Add(newAddress); db.SaveChanges(); } //Redirect to the method: Address within this controller return(RedirectToAction("Address", "Order")); }
public void UpdateCart(int id, int quantity, int total) { db = new MyDataEntities(); var cart = db.Carts.Find(id); cart.Quantity = quantity; cart.Total = total; db.Entry(cart).State = System.Data.EntityState.Modified; db.SaveChanges(); }
public void AddProducer(string code, string name) { var producer = new Producer(); producer.Code = code; producer.Name = name; db = new MyDataEntities(); db.Producers.Add(producer); db.SaveChanges(); }
//Update the quantity after an item deletion public ActionResult UpdateItemQuantity(int newQuantity, int itemID) { //Makes sure everything is up-to-date UpdateSession(); //temporary variable holding the integer representing the User's ID (and therefore the CartID) int temporary = Convert.ToInt32(Session["UserID"].ToString()); //returns the row with the to-be-deleted ShoppingCartID var check = db.ShoppingCartProducts.Where(x => x.ShoppingCartID == temporary).Where(x => x.ShoppingCartProductID == itemID); //Grab the quantity associated with the ShoppingCartProductID decimal newSub = 0; int oldQuantity = 0; foreach (var item in check) { if (newQuantity > 0) { item.Quantity = newQuantity; newSub = Convert.ToDecimal(newQuantity * item.Product.Price); } else { oldQuantity = item.Quantity; newSub = Convert.ToDecimal(oldQuantity * item.Product.Price); } } string passThis = newSub.ToString("0.00"); //Try saving try { db.SaveChanges(); } //If saving does not work catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } return(Json(new { UpdateQuantity = newQuantity, newSubTotal = passThis, oldQuan = oldQuantity })); }
public void UpdateItem(int id, string name, int producer, int quantity, int price) { db = new MyDataEntities(); var item = db.Items.Find(id); item.Name = name; item.Producer = producer; item.Amount = quantity; item.Price = price; db.Entry(item).State = System.Data.EntityState.Modified; db.SaveChanges(); }
public void AddCart(string name, int Id_Item, int priceunit, int quantity, int total) { var cart = new Cart(); cart.Name = name; cart.PriceUnit = priceunit; cart.Quantity = quantity; cart.Total = total; cart.Id_item = Id_Item; db = new MyDataEntities(); db.Carts.Add(cart); db.SaveChanges(); }
public ActionResult Delete(string id) { MyDataEntities context = new MyDataEntities(); int empid = int.Parse(id); var record = context.EmpTables.FirstOrDefault((emp) => emp.EmpID == empid); if (record == null) { throw new Exception("No Employee found to delete"); } context.EmpTables.Remove(record); context.SaveChanges(); return(View("AllEmployees", context.EmpTables.ToList())); }
public void AddItem(string code, string name, int producer, int quantity, int price) { var item = new Item(); item.Code = code; item.Name = name; item.Producer = producer; item.Amount = quantity; item.Price = price; db = new MyDataEntities(); db.Items.Add(item); db.SaveChanges(); }
//Cambiare questo switch in base al reale nome della tabella nel database public void SavePreventive(tPreventiveDetails preventive, EnumUseful.typeOfDatabaseOperation typeOfDatabaseOperation) { switch (typeOfDatabaseOperation) { case EnumUseful.typeOfDatabaseOperation.EDIT: tPreventiveDetails PreventiveToEdit = dbEntity.tPreventiveDetails.FirstOrDefault( x => x.IdPreventivo == preventive.IdPreventivo ); if (PreventiveToEdit != null) { PreventiveToEdit.IdCliente = preventive.IdCliente; PreventiveToEdit.NumeroPreventivo = preventive.NumeroPreventivo; PreventiveToEdit.Riferimento = preventive.Riferimento; PreventiveToEdit.Allegati = preventive.Allegati; PreventiveToEdit.Oggetto = preventive.Oggetto; PreventiveToEdit.Attenzione = preventive.Attenzione; PreventiveToEdit.Durata = preventive.Durata; PreventiveToEdit.Data_ = preventive.Data_; PreventiveToEdit.Confermato = preventive.Confermato; PreventiveToEdit.Operatore = preventive.Operatore; PreventiveToEdit.AddebitoTransporto = preventive.AddebitoTransporto; PreventiveToEdit.Sconto = preventive.Sconto; PreventiveToEdit.Progetto = preventive.Progetto; PreventiveToEdit.Variazione = preventive.Variazione; PreventiveToEdit.Totale = preventive.Totale; PreventiveToEdit.Pagamento = preventive.Pagamento; PreventiveToEdit.Consegna = preventive.Consegna; PreventiveToEdit.NotaApertura = preventive.NotaApertura; PreventiveToEdit.NotaChiusura = preventive.NotaChiusura; PreventiveToEdit.NoteAndamaneto = preventive.NoteAndamaneto; PreventiveToEdit.DataInizioLavoro = preventive.DataInizioLavoro; PreventiveToEdit.NumeroCommisione = preventive.NumeroCommisione; PreventiveToEdit.Referenza = preventive.Referenza; PreventiveToEdit.Listino = preventive.Listino; } break; case EnumUseful.typeOfDatabaseOperation.CREATE: if (preventive != null) { dbEntity.tPreventiveDetails.Add(preventive); } break; } dbEntity.SaveChanges(); }
public JsonResult DeleteEvent(int eventID) { using (MyDataEntities dc = new MyDataEntities()) { var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault(); if (v != null) { dc.Events.Remove(v); dc.SaveChanges(); status = true; } } return(new JsonResult { Data = new { status = status } }); }
public void SaveCompany(tDitte Company, EnumUseful.typeOfDatabaseOperation typeOfDatabaseOperation) { switch (typeOfDatabaseOperation) { case EnumUseful.typeOfDatabaseOperation.EDIT: tDitte CompanyToEdit = dbEntity.tDitte.FirstOrDefault( x => x.IdDitta == Company.IdDitta ); if (CompanyToEdit != null) { CompanyToEdit.IdDitta = Company.IdDitta; CompanyToEdit.NomeDitta = Company.NomeDitta; CompanyToEdit.RagioneSocialeDitta = Company.RagioneSocialeDitta; CompanyToEdit.IndirizzoDitta = Company.IndirizzoDitta; CompanyToEdit.CapDitta = Company.CapDitta; CompanyToEdit.CittaDitta = Company.CittaDitta; CompanyToEdit.ProvinciaDitta = Company.ProvinciaDitta; CompanyToEdit.TelefonoDitta = Company.TelefonoDitta; CompanyToEdit.FaxDitta = Company.FaxDitta; CompanyToEdit.UrlDitta = Company.UrlDitta; CompanyToEdit.EmailDitta = Company.EmailDitta; CompanyToEdit.P_IvaDitta = Company.P_IvaDitta; CompanyToEdit.CodiceAgente = Company.CodiceAgente; CompanyToEdit.Listino = Company.Listino; CompanyToEdit.Logo = Company.Logo; } break; case EnumUseful.typeOfDatabaseOperation.CREATE: if (Company != null) { dbEntity.tDitte.Add(Company); } break; case EnumUseful.typeOfDatabaseOperation.SAVE: break; default: break; } dbEntity.SaveChanges(); }
public ActionResult Edit(EmpTable postedData) { //Create the Context object MyDataEntities context = new MyDataEntities(); //Find the matching record var rec = context.EmpTables.FirstOrDefault((e) => e.EmpID == postedData.EmpID); //Set the values to the record rec.EmpName = postedData.EmpName; rec.EmpAddress = postedData.EmpAddress; rec.EmpSalary = postedData.EmpSalary; rec.EmpPhone = postedData.EmpPhone; //Update the record to the database context.SaveChanges();//Commmit the transaction.... //Redirect to the AllEmployees Page.... return(RedirectToAction("AllEmployees")); }
public ActionResult DeleteEvent(int id) { bool status = false; using (MyDataEntities dc = new MyDataEntities()) { var v = dc.Events.Where(a => a.EventId == id).FirstOrDefault(); if (v != null) { dc.Events.Remove(v); dc.SaveChanges(); status = true; } } return(new JsonResult { Data = new { status = status } }); }
//TEST: WEBAPI_GETORDERS_TEST //Test the functionality of the WebAPI GetOrders method using test data. public void WebAPI_GetOrders_Test() { MyDataEntities db = new MyDataEntities(); OrderShippingController os = new OrderShippingController(); //ARRANGE db.SaveChanges(); List <Order> list = new List <Order>(); //This time value is equal to 1 minute and the purpose is to subtract the current time by 1 minutes and get all the orders created //within the last minute (we will only find our test order) TimeSpan time = new TimeSpan(0, 1, 0); DateTime startDate = DateTime.Now.Subtract(time); DateTime endDate = DateTime.Now; //ACT list = os.GetOrders(startDate, endDate); //ASSERT Assert.IsNotNull(list); Assert.IsInstanceOfType(list, typeof(List <Order>)); Assert.IsTrue(list.Count() == 1); }
public void SaveCustomer(tCliente cliente, EnumUseful.typeOfDatabaseOperation typeOfDatabaseOperation) { switch (typeOfDatabaseOperation) { case EnumUseful.typeOfDatabaseOperation.EDIT: tCliente CustomerToEdit = dbEntity.tCliente.FirstOrDefault(x => x.Id == cliente.Id); if (CustomerToEdit != null) { CustomerToEdit.RagioneSociale = cliente.RagioneSociale; CustomerToEdit.CodiceUniclima = cliente.CodiceUniclima; CustomerToEdit.Indirizzo = cliente.Indirizzo; CustomerToEdit.CAP = cliente.CAP; CustomerToEdit.Citta = cliente.Citta; CustomerToEdit.Provincia = cliente.Provincia; } break; case EnumUseful.typeOfDatabaseOperation.CREATE: if (cliente != null) { dbEntity.tCliente.Add(cliente); } break; } try { dbEntity.SaveChanges(); } catch (Exception ee) { Console.WriteLine(ee.Message); } }
public HttpResponseMessage UpdateOrder([FromBody] ClientOrder order) { HttpResponseMessage response; if (!IsLoggedIn()) { return(response = Request.CreateResponse(HttpStatusCode.Forbidden, "Error! You're not logged in.")); } if (String.IsNullOrEmpty(order.Number)) { ModelState.AddModelError("Number", "Please enter number"); } //var result = JsonConvert.DeserializeObject<string>(value); if (ModelState.IsValid) { using (MyDataEntities mde = new MyDataEntities()) { if (order.Status == "create") { // Create new order Order newOrder = new Order { OrderId = Guid.NewGuid(), Number = order.Number, ManagerId = new Guid(order.ManagerId), Created_date = DateTime.UtcNow, Updated_date = null, Delivery_date = order.Delivery_date, Description = order.Description }; mde.Orders.Add(newOrder); mde.SaveChanges(); response = Request.CreateResponse(HttpStatusCode.Created, order); } else { //Update exsisting order Order updatedOrder = mde.Orders.Where(o => o.OrderId.ToString().Equals(order.OrderId)).FirstOrDefault(); if (updatedOrder != null) { updatedOrder.Number = order.Number; updatedOrder.ManagerId = new Guid(order.ManagerId); updatedOrder.Updated_date = DateTime.UtcNow; updatedOrder.Description = order.Description; updatedOrder.Delivery_date = order.Delivery_date; mde.SaveChanges(); response = Request.CreateResponse(HttpStatusCode.OK, order); } else { response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Cannot find order with this guid."); } } } } else { response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error! Please try again with valid data."); } return(response); }
public void SaveUser() { //Enact a save on the DB to ensure parity between the data we work with and the state of the DB db.SaveChanges(); }
//MarkOrderShipped: /OrderShipping/MarkOrderShipped/(id) public string MarkOrderShipped(int id) { //Create an order object to hold our Order based on its ID Order initialOrder = new Order(); //Used to grab the order again after saving in order to make sure that the changes have gone through List <Order> testOrder = new List <Order>(); //o = or.GetOrderMethod(id); //Using the ID, put the specific order into our Order object initialOrder = db.Orders.Where(x => x.OrderID == id).FirstOrDefault(); //If our initial order isn't empty (it would be empty if no Order matching the ID was found) then set the Status to 3. if (initialOrder != null) { initialOrder.StatusID = 3; } //Try saving try { db.SaveChanges(); } //If saving does not work catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } //PassThis will be returned so that we can view our success/failure message string passThis = ""; //If our initialOrder is not null (Meaning we did find an order matching the OrderID) then go about checking the StatusID if (initialOrder != null) { //Grab the order from the DB, we don't want to use our old object because we want to make sure that the change has gone through testOrder = db.Orders.Where(x => x.OrderID == id).ToList(); foreach (var item in testOrder) { //Return the status ID of the order so that we can observe its value passThis = "Order Status set to: " + item.Status.StatusDescription; } } //If our initialOrder was null then it means that no Order matched the OrderID and we need to report that error to the user else { passThis = "Failure: No Order Found"; } //Return the success/failure message return(passThis); }