public async Task <IActionResult> Create(Progetto progetto, string progettoDaCopiare) { if (ModelState.IsValid) { _context.Add(progetto); await _context.SaveChangesAsync(); if (!string.IsNullOrEmpty(progettoDaCopiare) && !progettoDaCopiare.Equals("0")) { List <ModuliProgetto> listaCopiata = await _context.ModuliProgetto.Where(m => m.ProgettoID == int.Parse(progettoDaCopiare)).ToListAsync(); int prgNuovo = progetto.ID; foreach (var el in listaCopiata) { _context.ModuliProgetto.Add(new ModuliProgetto { ProgettoID = prgNuovo, ModuloID = el.ModuloID, Target = el.Target }); } await _context.SaveChangesAsync(); } MyLogger.Log(messaggio: $"Richiesta POST:\n\tNuovo progetto con nome {progetto.Nome}", controller: "ProgettoController", metodo: "Create"); return(RedirectToAction(nameof(Edit), new { id = progetto.ID })); } MyLogger.Log(messaggio: $"ERRORE: Richiesta POST: Richiesta malformata", controller: "ProgettoController", metodo: "Create"); return(View(progetto)); }
private void AddResponse(SurveyResponse response) { var examination = _context.Examinations.Find(response.UsedPermission.Id); if (examination == null) { throw new ActionNotPermittedException("Permission with the id " + response.UsedPermission.Id + " does not exist."); } examination.IsSurveyCompleted = true; _context.Update(examination); _context.Add(new SurveyAboutDoctor() { ExaminationId = examination.Id, AvailabilityOfDoctor = response.DoctorSurveyResponse.Availability.Value, BehaviorOfDoctor = response.DoctorSurveyResponse.Behavior.Value, GettingAdviceByDoctor = response.DoctorSurveyResponse.GivingAdvice.Value, DoctorProfessionalism = response.DoctorSurveyResponse.Professionalism.Value }); _context.Add(new SurveyAboutHospital() { ExaminationId = examination.Id, Cleanliness = response.HospitalSurveyResponse.Cleanliness.Value, Nursing = response.HospitalSurveyResponse.Nursing.Value, OverallRating = response.HospitalSurveyResponse.General.Value, SatisfiedWithDrugAndInstrument = response.HospitalSurveyResponse.MedicationAndInstrumments.Value }); _context.Add(new SurveyAboutMedicalStaff() { ExaminationId = examination.Id, BehaviorOfMedicalStaff = response.MedicalStaffSurveyResponse.Behavior.Value, EaseInObtainingFollowUpInformation = response.MedicalStaffSurveyResponse.FollowUp.Value, GettingAdviceByMedicalStaff = response.MedicalStaffSurveyResponse.GivingAdvice.Value, MedicalStaffProfessionalism = response.MedicalStaffSurveyResponse.Professionalism.Value }); }
public async Task <IActionResult> Create([Bind("ProductId,Title,Description,Price,Discount,Amount,CategoryId,SupplierId")] Product product, IFormFile MainImage, List <IFormFile> MoreImage) { if (ModelState.IsValid) { _context.Add(product); await _context.SaveChangesAsync(); //save thành công --> có mã //Main Image product.MainImage = MyTools.SaveFileToFolder(MainImage, "Products", product.ProductId.ToString()); foreach (var file in MoreImage) { var imageFullName = MyTools.SaveFileToFolder(file, "Products", product.ProductId.ToString()); var proImage = new ProductImage { ProductId = product.ProductId, FileName = imageFullName }; _context.Add(proImage); } _context.SaveChanges(); return(RedirectToAction(nameof(Index))); } ViewData["CategoryId"] = new SelectList(_context.Categories, "CategoryId", "CategoryName", product.CategoryId); ViewData["SupplierId"] = new SelectList(_context.Manufacturers, "Id", "Name", product.SupplierId); return(View(product)); }
public Room CreateRoom(RoomRequest roomRequest) { var room = new Room(); Coppier <RoomRequest, Room> .Copy(roomRequest, room); room.Cluster = dbContext.Clusters.Where(c => c.Id == roomRequest.ClusterId).FirstOrDefault(); var screenTypes = dbContext.ScreenTypes.Where(s => roomRequest.ScreenTypeIds.Contains(s.Id)).ToList(); foreach (var screen in screenTypes) { var roomScreenType = new RoomScreenType() { ScreenType = screen, Room = room, }; dbContext.Add(roomScreenType); } dbContext.Add(room); var isSuccess = Save(); if (!isSuccess) { return(null); } return(room); }
public IActionResult AddCustomer(Customer customer) { _dbContext.Add(customer); _dbContext.SaveChanges(); return(Redirect("/customers")); }
public async Task <IActionResult> Create([FromForm] AnalysisCode analysis_Code) { if (ModelState.IsValid) { bool isCodeExist = _context.AnalysisCode.Any(m => m.Code.Equals(analysis_Code.Code)); if (isCodeExist) { ModelState.AddModelError("Code", "Code Already Exists!"); return(View(analysis_Code)); //return RedirectToAction(nameof(Create), new { error = "Code exists" }); } string newJson = JsonConvert.SerializeObject(analysis_Code); bool isCodeExists = IsCodeExists(analysis_Code.Code); analysis_Code.CompanyId = 123; analysis_Code.IsUsed = true; analysis_Code.Status = analysis_Code.Status; analysis_Code.CreatedBy = _configuration.GetValue <string>("HardcodeValue:Createdby"); analysis_Code.CreatedDatetime = DateTime.UtcNow; _context.Add(analysis_Code); await _context.SaveChangesAsync(); AuditService.InsertActionLog(analysis_Code.CompanyId, analysis_Code.CreatedBy, "Create", "Analysis Code", null, newJson); return(RedirectToAction(nameof(Index))); } return(View(analysis_Code)); }
public async Task <IActionResult> Create([Bind("FacturesGenereeID,DateFactures,DateGeneration,FactureDe,AssociationID")] FacturesGeneree facturesGeneree) { if (ModelState.IsValid) { _context.Add(facturesGeneree); List <CompteurEau> compteurs = _context.CompteurEaus.Where(c => c.Actif == true && c.Client.AssociationID == facturesGeneree.AssociationID).ToList(); for (int i = 0; i < compteurs.Count(); i++) { Facture facture = new Facture(); facture.CompteurEauID = compteurs[i].CompteurEauID; facture.DateFacture = facturesGeneree.DateFactures; facture.FactureDe = facturesGeneree.FactureDe; facture.FacturesGenereeID = facturesGeneree.FacturesGenereeID; var f = await _context.Factures.OrderByDescending(m => m.FactureDe).FirstOrDefaultAsync(m => m.CompteurEauID == compteurs[i].CompteurEauID); if (f != null) { facture.ValeurCompteurPrecedente = f.ValeurCompteur; } facture.isPayee = false; _context.Add(facture); facturesGeneree.Factures.Add(facture); } await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["AssociationID"] = new SelectList(_context.Associations, "AssociationID", "AssociationID", facturesGeneree.AssociationID); return(View(facturesGeneree)); }
public async Task <IActionResult> Create([Bind("NguoiDungID,HoTen,GioiTinhID,NgaySinh,DiaChi,SDT,Email,Hinh,LoaiNgDungID,TenDangNhap,MatKhau")] NguoiDung nguoiDung, IFormFile[] myfile) { if (ModelState.IsValid) { string arr = ""; if (myfile != null) { foreach (var item in myfile) { string url = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", item.FileName); using (var f = new FileStream(url, FileMode.Create)) { item.CopyTo(f); } arr += item.FileName; } nguoiDung.Hinh = arr; } _context.Add(nguoiDung); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["GioiTinhID"] = new SelectList(_context.GioiTinhs, "GioiTinhID", "GioiTinhID", nguoiDung.GioiTinhID); ViewData["LoaiNgDungID"] = new SelectList(_context.LoaiNgDungs, "LoaiNgDungID", "LoaiNgDungID", nguoiDung.LoaiNgDungID); return(View(nguoiDung)); }
public async Task <IActionResult> Create([FromForm] ChartOfAccounts chartOfAccounts) { try { if (ModelState.IsValid) { bool isCodeExist = _context.ChartOfAccounts.Any(m => m.Code.Equals(chartOfAccounts.Code)); if (isCodeExist) { ModelState.AddModelError("Code", "Code Already Exists!"); return(View(chartOfAccounts)); //return RedirectToAction(nameof(Create), new { error = "Code exists" }); } string newJson = JsonConvert.SerializeObject(chartOfAccounts); bool isCodeExists = IsCodeExists(chartOfAccounts.Code); chartOfAccounts.CompanyId = 123; chartOfAccounts.IsUsed = true; chartOfAccounts.Status = chartOfAccounts.Status; chartOfAccounts.CreatedBy = _configuration.GetValue <string>("HardcodeValue:Createdby"); chartOfAccounts.CreatedDatetime = DateTime.UtcNow; _context.Add(chartOfAccounts); await _context.SaveChangesAsync(); AuditService.InsertActionLog(chartOfAccounts.CompanyId, chartOfAccounts.CreatedBy, "Create", "Chart Of Accounts", null, newJson); return(RedirectToAction(nameof(Index))); } return(View(chartOfAccounts)); } catch (Exception ex) { throw; } }
public long Add(T entity) { //todo:设置操作人信息 _myDbContext.Add(entity); _myDbContext.MySaveChanges(); return(entity.Id); }
public IActionResult DangKy(RegisterVM model) { if (ModelState.IsValid) { using (var transaction = _context.Database.BeginTransaction()) { try { var khachHang = _mapper.Map <KhachHang>(model); khachHang.MaNgauNhien = MyTools.GetRandom(); khachHang.MatKhau = model.MatKhau.ToSHA512Hash(khachHang.MaNgauNhien); _context.Add(khachHang); _context.SaveChanges(); //Add role for user, default Customer var userRole = new UserRole { RoleId = 4,//Khách hàng UserId = khachHang.MaKh }; _context.Add(userRole); _context.SaveChanges(); transaction.Commit(); return(RedirectToAction("DangNhap")); } catch { transaction.Rollback(); return(View()); } } } return(View()); }
public async Task<Order> CreateOrder(User user, CancellationToken cancellationToken = default) { var order = new Order(user); _context.Add(order); await _context.SaveChangesAsync(cancellationToken); return order; }
private static void Main(string[] args) { // Setup data in datbase using (var context = new MyDbContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.Add( new Friend { Name = "Bill", Location = "Here", }); context.Add( new Friend { Name = "Paul", Location = "There", }); context.SaveChanges(); } // find nearest friends using (var context = new MyDbContext()) { var firends = context.Friends.ToList(); foreach (var item in firends) { Console.WriteLine($"{item.Name} {item.Location}"); } } }
public Cluster CreateCluster(ClusterRequest clusterRequest) { Cluster cluster = new Cluster(); cluster.Name = clusterRequest.Name; cluster.Address = clusterRequest.Address; User manager = dbContext.Users.Where(u => u.Id == clusterRequest.ManagerId).FirstOrDefault(); if (manager != null) { ClusterUser clusterUser = new ClusterUser() { Cluster = cluster, User = manager, }; dbContext.Add(clusterUser); } dbContext.Add(cluster); bool isSuccess = Save(); if (!isSuccess) { return(null); } return(cluster); }
public async Task <ActionResult> CreateWExistingItem(int?userId, int?type, [FromBody] SimpleInventoryItem?inventoryItem, [FromHeader] string Authorization) { if (inventoryItem == null) { return(NoContent()); } Inventory inventory; if (userId == null) { userId = await uow.UserDb.GetPpUserIdByJWT(Authorization); } if (type != null)//Type supplied as parameter { var uow = new UnitOfWork(_context); inventory = uow.Users.GetInventoryWithUser((int)userId, FromEnumToType(type)); } else//Type is embedded in json object { inventory = await _context.Inventory.SingleAsync(i => i.InventoryId == inventoryItem.InventoryId); } if (inventory == null) { return(BadRequest()); } var item = await _context.Item.SingleAsync(i => i.ItemId == inventoryItem.ItemId); if (item == null) { return(BadRequest()); } //If mathcing item allready is added today - increment the existing: var IIattempt = await uow.InventoryItems.TryGetTodayIinventoryItem(inventory.InventoryId, item.ItemId); if (IIattempt != null) { IIattempt.Amount += inventoryItem.Amount; uow.Complete(); return(Ok("InventoryItem allerede oprettet i dag. den er opdateret")); } //Else: create new inventory item: var completeInventoryItem = new InventoryItem(inventoryItem); completeInventoryItem.Item = item; completeInventoryItem.ItemId = item.ItemId; completeInventoryItem.Inventory = inventory; completeInventoryItem.InventoryId = inventory.InventoryId; completeInventoryItem.DateAdded = DateTime.Now; _context.Add(completeInventoryItem); int result = await _context.SaveChangesAsync(); if (result > 0) { return(Accepted()); } return(BadRequest()); }
public IActionResult Purchase(ThanhToanViewModel model) { //process order KhachHang kh = null; if (!User.Identity.IsAuthenticated) { kh = new KhachHang() { HoTen = model.HoTen, Email = model.Email, DienThoai = model.DienThoai, TenDangNhap = $"KH{DateTime.Now.Ticks}", MatKhau = new Random().Next(1000, 10000).ToString() }; db.Add(kh); db.SaveChanges(); } else { kh = HttpContext.Session.Get <KhachHang>("KhachHang"); } DonHang dh = new DonHang() { MaKH = kh.MaKH, NgayDat = DateTime.Now, NguoiNhan = model.NguoiNhan, DiaChiGiao = model.DiaChiGiao, MaTrangThai = 1 }; db.Add(dh); db.SaveChanges(); ChiTietDonHang cthd = null; foreach (CartItem item in _cart.Carts) { cthd = new ChiTietDonHang { MaDH = dh.MaDH, MaHH = item.MaHh, DonGia = item.DonGia, GiamGia = item.GiamGia, SoLuong = item.SoLuong }; db.Add(cthd); } db.SaveChanges(); //hủy giỏ hàng _cart.Clear(); //chuyển trang return(View("ThongBao")); }
public async Task <IActionResult> Create([Bind("DespesaId,ParceiroId,Valor")] Responsavel responsavel) { if (ModelState.IsValid) { _context.Add(responsavel); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["DespesaId"] = new SelectList(_context.Despesa, "Id", "Id", responsavel.DespesaId); ViewData["ParceiroId"] = new SelectList(_context.Parceiro, "Id", "Id", responsavel.ParceiroId); return(View(responsavel)); }
//[Bind("Id,Group,Code,Name,Status,RegistrationNumber,GST,TinNo,SST,Address,City,PostCode,Country,State,Email,PhoneNumber,Fax,CreatedBy,CreatedDatetime,ModifiedBy,ModifeidDatetime")] public async Task <IActionResult> Create([FromForm] Supplier supplier) { //if (ModelState.IsValid) //{ supplier.CreatedBy = "Kelvin"; supplier.CreatedDatetime = DateTime.UtcNow; _context.Add(supplier); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); //} //return View(supplier); }
public async Task <IActionResult> Create([Bind("Id,Group,Code,Name,TimeZone,Status,RegistrationNumber,GST,TinNo,SST,Address,City,PostCode,Country,State,Email,PhoneNumber,Fax,CreatedBy,CreatedDatetime,ModifiedBy,ModifeidDatetime")] Companies companies) { //if (ModelState.IsValid) //{ companies.CreatedBy = "Kelvin"; companies.CreatedDatetime = DateTime.UtcNow; _context.Add(companies); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); //} //return View(companies); }
/// <summary> /// This adds a role if not present, or updates a role if is present. /// </summary> /// <param name="roleName"></param> /// <param name="description"></param> /// <param name="permissions"></param> public void AddUpdateRoleToPermissions(string roleName, string description, ICollection <Permissions> permissions) { var status = RoleToPermissions.CreateRoleWithPermissions(roleName, description, permissions, _context); if (status.IsValid) { //Note that CreateRoleWithPermissions will return a invalid status if the role is already present. _context.Add(status.Result); } else { UpdateRole(roleName, description, permissions); } }
public async Task <IActionResult> Checkout(CheckOutViewModel request) { var userId = _userService.GetUserId(); var user = await _userManager.FindByIdAsync(userId); var model = GetCheckoutViewModel(); var checkoutRequest = new CheckoutRequest() { Address = request.CheckoutModel.Address, FirstName = request.CheckoutModel.FirstName, LastName = request.CheckoutModel.LastName, Email = request.CheckoutModel.Email, Phone = request.CheckoutModel.Phone, //OrderDetails = orderDetails }; var order = new Order() { TotalMoney = model.CartItems.Sum(m => m.Price) - model.CartItems.Sum(m => m.Value_Discount), Address = checkoutRequest.Address, Receiver = checkoutRequest.FirstName + ' ' + checkoutRequest.LastName, SDT = checkoutRequest.Phone, User = user, Process = "Mới đặt" }; _context.Add(order); await _context.SaveChangesAsync(); var order_success = _context.Order.ToList().LastOrDefault(); foreach (var item in model.CartItems) { if (item.Color_Product != null) { OrderDetail orderdetail = new OrderDetail() { ID_Color_Product = item.Color_Product.ID_Color_Product, Size = item.Size, Quantity = item.Amount, ID_Order = order_success.ID_Order, }; _context.Add(orderdetail); await _context.SaveChangesAsync(); } } ClearCart(); TempData["SuccessMsg"] = "Order puschased successful"; return(RedirectToAction("HistoryOrder", "Client_Orders")); }
public async Task <IActionResult> Create([Bind("DrinkId, DrinkName, DrinkType")] Drink drink) { drink.DrinkId = await _context.Drink.MaxAsync(m => m.DrinkId) + 1; drink.IngridientsCount = 0; if (ModelState.IsValid) { _context.Add(drink); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Edit))); } return(View(drink.DrinkId)); }
public async Task <IActionResult> Success() { Bill bill = new Bill(); var kh = HttpContext.Session.Get <Customer>("Customer"); bill.BillTime = DateTime.Now; bill.CustomerID = kh.CustomerID; bill.PaymentMethod = "Paypal"; bill.Status = "Đã thanh toán"; bill.TotalAmount = Cart.Sum(p => p.TotalPrice); _context.Add(bill); await _context.SaveChangesAsync(); return(View()); }
public async Task <IActionResult> Create([Bind("MonAnID,LoaiID,TenMon,DonGia,Hinh,MoTa,GiamGia,TrangThaiID")] MonAn monAn, IFormFile[] myfile) { if (ModelState.IsValid) { string arr = ""; if (myfile != null) { foreach (var item in myfile) { string url = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", item.FileName); using (var f = new FileStream(url, FileMode.Create)) { item.CopyTo(f); } arr += item.FileName; } monAn.Hinh = arr; } _context.Add(monAn); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["LoaiID"] = new SelectList(_context.Loais, "LoaiID", "LoaiID", monAn.LoaiID); ViewData["TrangThaiID"] = new SelectList(_context.TrangThai, "TrangThaiID", "TrangThaiID", monAn.TrangThaiID); return(View(monAn)); }
public async Task <IActionResult> Register(RestaurantViewModel model) { if (ModelState.IsValid) { if (_context.Restaurant.Any(r => r.Email.Equals(model.Email))) { model.InfoMessage = "Email " + model.Email + " already in use."; } else { Restaurant dbRestaurant = model; string salt = Crypto.generateSalt(); string hasedPassword = Crypto.computeHash(model.Password, salt); dbRestaurant.Salt = salt; dbRestaurant.Password = hasedPassword; _context.Add(dbRestaurant); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } return(View(model)); }
public async Task <IActionResult> Create([Bind("ArticleId,Name,Price,Image,CategoryId")] Article article, IFormFile imageFile) { if (ModelState.IsValid) { //dodanie obrazka string filename = "images/no-images.png"; if (imageFile != null) { string Folder = _hostingEnvironment.WebRootPath; filename = "upload/" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ".jpg"; string filePath = Path.Combine(Folder, filename); using (Stream fileStream = new FileStream(filePath, FileMode.Create)) { await imageFile.CopyToAsync(fileStream); } } article.Image = filename; //-dodanie _context.Add(article); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } //ViewData["CategoryId"] = new SelectList(_context.Categories, "CategoryId", "CategoryId", article.CategoryId); //zmiana ViewData["Category"] = new SelectList(_context.Categories, "CategoryId", "Name", article.CategoryId); //zmiana return(View(article)); }
public IActionResult Create(HangHoa hh, IFormFile Hinh) { if (ModelState.IsValid) { try { var urlHinh = FileHelper.UploadFileToFolder(Hinh, "HangHoa"); hh.Hinh = urlHinh; _context.Add(hh); _context.SaveChanges(); return(RedirectToAction("Index")); } catch (Exception ex) { _logger.LogError(ex, $"Loi: {ex.Message}"); ViewBag.ThongBaoLoi = "Có lỗi"; ViewBag.DanhSachLoai = new LoaiDropDownVM(_context.Loais, "MaLoai", "TenLoai", "MaLoai"); return(View()); } } ViewBag.DanhSachLoai = new LoaiDropDownVM(_context.Loais, "MaLoai", "TenLoai", "MaLoai"); return(View()); }
public Showtime CreateShowtime(ShowtimeRequest showtimeRequest) { Showtime showtime = new Showtime(); if (showtime.Status != null) { showtime.Status = showtimeRequest.Status; } else { showtime.Status = Constants.SHOWTIME_STATUS_ACTIVE; } showtime.StartAt = DateTime.Parse(showtimeRequest.StartAt); showtime.Movie = dbContext.Movies.Where(m => m.Id == showtimeRequest.MovieId).FirstOrDefault(); if (showtime.Movie != null) { showtime.EndAt = showtime.StartAt.AddMinutes(showtime.Movie.Runtime); } showtime.BasePrice = showtimeRequest.BasePrice; showtime.Room = dbContext.Rooms.Where(r => r.Id == showtimeRequest.RoomId).FirstOrDefault(); showtime.ScreenType = dbContext.ScreenTypes.Where(st => st.Id == showtimeRequest.ScreenTypeId).FirstOrDefault(); dbContext.Add(showtime); bool isSuccess = Save(); if (!isSuccess) { return(null); } return(showtime); }
public async Task <CreatedAtActionResult> AddSong([FromBody] Song value) { var res = context.Add(value); await context.SaveChangesAsync(); return(CreatedAtAction("AddSong", "api/InternetSong", value)); }
public async Task <IActionResult> Create(ThucDon thucDon, IFormFile Ffile) { if (ModelState.IsValid) { string s = ""; if (Ffile != null) { string fileName = $"{DateTime.Now.Ticks}{Ffile.FileName}"; s = fileName; thucDon.HinhAnh = s; string fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "user", "products", fileName); using (var file = new FileStream(fullPath, FileMode.Create)) { Ffile.CopyTo(file); } } else { thucDon.HinhAnh = "download.jpg"; } _context.Add(thucDon); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["MaDungTich"] = new SelectList(_context.DungTich, "MaDungTich", "MaDungTich", thucDon.MaDungTich); ViewData["MaLoai"] = new SelectList(_context.LoaiThucDon, "MaLoai", "MaLoai", thucDon.MaLoai); ViewData["MaTH"] = new SelectList(_context.ThuongHieu, "MaTH", "MaTH", thucDon.MaTH); ViewData["MaNongDo"] = new SelectList(_context.NongDo, "MaNongDo", "MaNongDo", thucDon.MaNongDo); return(View(thucDon)); }