public KeyValueResponse SetValue(KeyValue keyValue) { KeyValueResponse response; if (keyValue != null && !string.IsNullOrEmpty(keyValue.Key)) { KeyValue existingItem = null; existingItem = _context.KeyValues.Where(itm => itm.Key == keyValue.Key).FirstOrDefault(); if (existingItem != null) { //update it existingItem.Value = keyValue.Value; keyValue.LastUpdate = DateTime.UtcNow; existingItem.LastUpdate = keyValue.LastUpdate; _context.SaveChanges(); response = KeyValueResponse.Updated; } else { //just add it keyValue.LastUpdate = DateTime.UtcNow; _context.KeyValues.Add(keyValue); _context.SaveChanges(); response = KeyValueResponse.Created; } } else { response = KeyValueResponse.NotCreated; } return(response); }
public string AddDoument(DocumentViewModel document) { try { var doc = (from d in _dbContext.Documents where d.UserId == document.UserId && d.DocumentType == document.Type select d).FirstOrDefault(); if (doc != null) { _dbContext.Documents.Remove(doc); _dbContext.SaveChanges(); } Document documentToAdd = new Document() { CreateTime = DateTime.Now.ToString(), File = document.DocumentUrl, Id = (Guid.NewGuid()).ToString(), UserId = document.UserId, DocumentType = document.Type }; _dbContext.Documents.Add(documentToAdd); _dbContext.SaveChanges(); return("success"); } catch (Exception) { return("fail"); } }
public IActionResult AddCar([FromBody] CarView car) { _context.Cars.Add(new Car { Mark = car.Mark, Model = car.Model, Year = car.Year, Fuel = car.Fuel, Capacity = car.Capacity, Image = car.Image }); var dir = Directory.GetCurrentDirectory(); var ext = Path.GetExtension(car.Image); var dirSave = Path.Combine(dir, "uploads"); var imageName = Path.GetRandomFileName() + ext; var imageSaveFolder = Path.Combine(dirSave, imageName); var imagen = car.Image.LoadBase64(); imagen.Save(imageSaveFolder, ImageFormat.Jpeg); _context.SaveChanges(); return(Ok(new { message = "Was added" })); }
private static void SeedCats(EFDataContext context) { if (!context.Cats.Any()) { AppCat cat = new AppCat { Name = "Манул", Details = "Деталі про манула", Birthday = DateTime.Now, ImgUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Manoel.jpg/275px-Manoel.jpg", }; context.Cats.Add(cat); context.SaveChanges(); var firstCat = context.Cats.FirstOrDefault(); AppCatPrice price = new AppCatPrice { CatId = firstCat.Id, DateCreate = DateTime.Now, Price = 500 }; context.CatPrices.Add(price); context.SaveChanges(); } }
public IActionResult Create(Department model) { ModelState.Remove("DepartmentId"); if (ModelState.IsValid) { _dbContext.Departments.Add(model); _dbContext.SaveChanges(); return(RedirectToAction("Index")); } return(View()); }
public void UpdateDcoument(Document doc) { using (var _context = _dbContext) { var docOld = _context.documento.FirstOrDefault(doci => doci.id_interno.Equals(doc.id_interno)); var docx = _mapper.Map <documento>(doc); _dbContext.Entry(docOld).CurrentValues.SetValues(docx); //_dbContext.documento.Update(docx); _dbContext.SaveChanges(); } }
public IActionResult MyWallet() { List <Wallet> data = this._dbContext.Wallets.ToList(); _dbContext.Wallets.Add(new Wallet { BuyingPower = 15300, Investing = 12000, userID = "1" }); _dbContext.SaveChanges(); return(View(data)); }
public IActionResult Portfolio() { List <StockOwned> data = this._dbContext.StocksOwned.ToList(); _dbContext.StocksOwned.Add(new StockOwned { Name = "Amazon", userID = "1", initialInvestment = "2000", CurrentValue = "4300", numOfStocks = "4", dateBought = "01/12/2005" }); _dbContext.SaveChanges(); return(View(data)); }
public IActionResult Create(Employee model) { if (ModelState.IsValid) { _dbContext.Employees.Add(model); _dbContext.SaveChanges(); return(RedirectToAction("Index")); } this.GetModelData(); return(View()); }
public IActionResult Create(Employee model) { ModelState.Remove("EmployeeId"); if (ModelState.IsValid) { _dbContext.Employees.Add(model); _dbContext.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.Designations = _dbContext.Designations.ToList(); return(View()); }
public IActionResult ForgotPassword([FromBody] UserActivation userParam) { try { EFDataContext _dbContext = new EFDataContext(); User dbUser = _dbContext.Users .Where(u => u.EmailId == userParam.Email.ToLower()).FirstOrDefault(); if (dbUser == null) { return(Ok()); } dbUser.PasswordResetKey = CryptoUtils.GenerateRandomString(20); dbUser.PasswordResetExpiry = DateTime.UtcNow.AddHours(24); _dbContext.SaveChanges(); string resetLink = _appSettings.WebUrl + "auth/reset?email=" + dbUser.EmailId + "&key=" + dbUser.PasswordResetKey; Mail newMail = new Mail { Subject = "AgroXchange Reset Password Request", BodyHtml = string.Format("Dear {0},<p>Upon your request, we have generated a password reset key for you to set a new password for your account. Please follow the link below either by clicking it or copy-pasting it in a browser window.</p><p>If you did not request for this, don't do anything, the reset key will expire in 24 hours.</p><p><a href=\"{1}\">{1}</a></p><p>Regards</p><p>AgroXchange</p>", dbUser.FirstName + " " + dbUser.LastName, resetLink) }; newMail.AddToRecipient(dbUser.FirstName + " " + dbUser.LastName, dbUser.EmailId); _mailService.SendMail(newMail); return(Ok()); } catch (Exception ex) { if (ex is ApiException) { return(BadRequest(new { message = ex.Message })); } return(BadRequest(new { message = "Error during forgot password request. Please try again." })); } }
public IActionResult AddCar([FromBody] CarViewModels car) { var rez = new Car { Mark = car.Mark, Model = car.Model, Image = car.Image, Fuel = car.Fuel, Сapacity = car.Сapacity, Year = car.Year }; _context.Cars.Add(rez); _context.SaveChanges(); return(Ok(new { message = "Додано" })); }
public bool Insert(User_MODEL model) { using (EFDataContext dataContext = new EFDataContext()) { dataContext.User.Add(model); dataContext.SaveChanges(); return true; } }
public bool Update(MODEL.User_MODEL model) { using (EFDataContext dataContext = new EFDataContext()) { dataContext.Entry(model).State = EntityState.Modified; dataContext.SaveChanges(); return true; } }
/// <summary> /// 更新用户姓名 /// userModel 包含了已更新的Name /// </summary> /// <param name="userModel"></param> /// <returns></returns> public bool UpdateName(MODEL.User_MODEL userModel) { using (EFDataContext dataContext=new EFDataContext()) { dataContext.User.Attach(userModel); dataContext.Entry(userModel).Property(one => one.Name).IsModified = true; dataContext.SaveChanges(); return true; } }
public void Post([FromBody] Model.Employee employee) { using (EFDataContext dataContext = new EFDataContext()) { var emp = dataContext.Employee.Add(employee); dataContext.SaveChanges(); } }
public IActionResult Activate([FromBody] UserActivation userParam) { try { EFDataContext _dbContext = new EFDataContext(); User dbUser = _dbContext.Users .Where(u => u.EmailId == userParam.Email.ToLower() && u.ActivationKey == userParam.Key && !u.Activated).FirstOrDefault(); if (dbUser == null) { throw new ApiException("The email id given either does not exist or the key provided is invalid, or this user has already been activated"); } if (!dbUser.ActivationMailDate.HasValue || dbUser.ActivationMailDate.Value.AddHours(24).CompareTo(DateTime.UtcNow) < 0) { dbUser.ActivationKey = CryptoUtils.GenerateRandomString(20); dbUser.ActivationMailDate = DateTime.UtcNow; _dbContext.SaveChanges(); string activationLink = _appSettings.WebUrl + "auth/activate?email=" + dbUser.EmailId + "&key=" + dbUser.ActivationKey; Mail newMail = new Mail { Subject = "AgroXchange Account Activation", BodyHtml = string.Format("Dear {0},<p>We have generated a new activation key for you. Please verify your email address by clicking the link below or copy-pasting it in a browser window.</p><p><a href=\"{1}\">{1}</a></p><p>Regards</p><p>AgroXchange</p>", dbUser.FirstName + " " + dbUser.LastName, activationLink) }; newMail.AddToRecipient(dbUser.FirstName + " " + dbUser.LastName, dbUser.EmailId); _mailService.SendMail(newMail); throw new ApiException("It's been more than 24 hours. Your activation key has expired. We have emailed you a new one. Please follow the link in the new email to activate your account."); } else { dbUser.Activated = true; dbUser.ActivationKey = ""; _dbContext.SaveChanges(); } return(Ok()); } catch (Exception ex) { if (ex is ApiException) { return(BadRequest(new { message = ex.Message })); } return(BadRequest(new { message = "Error while activating user. Please try again." })); } }
public void InsertUser(int count, ManualResetEvent mrse) { using (var transaction = _context.Database.BeginTransaction())//https://metanit.com/sharp/entityframework/3.11.php { try { Stopwatch stopWatch = new Stopwatch();//cколько времени на добовление юзеров stopWatch.Start(); for (int i = 0; i < count; i++) { mrse.WaitOne();//приостановка потока if (CanselAsyngMetod) { //CanselAsyngMetod = false; break;// остановка добавления при нажатии отмены } AppUser appUser = new AppUser { Name = "Name" + i, DebitKredit = true, Tranіaction = DateTime.Now.AddDays(i), Details = "qqqq", Image = "Fotka" }; _context.Users.Add(appUser); _context.SaveChanges(); if (EventInsertItem != null) { EventInsertItem(i + 1);// тоже самое ниже } //EventInsertItem?.Invoke(i + 1); Debug.WriteLine("Insert user " + appUser.Id); } stopWatch.Stop(); //остановка подсчета времени на добавление в БД // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; //считает тики и переводит в формат время // Format and display the TimeSpan value. string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Debug.WriteLine("Затрачено времени на генерацию Юзеров: " + elapsedTime); if (!CanselAsyngMetod) { // Сохраняем транзакцию если флаг для отмены асинхронного добавления false transaction.Commit(); } } catch (Exception ex) { transaction.Rollback(); // Отмена транзакции } CanselAsyngMetod = false; } }
// Given[("یک دسته بندی کتاب های رمان در لیست دسته بندی کتابها وجود دارد")] private void Given() { bookCategory = new BookCategory() { Title = "کتابهای رمان" }; context.BookCategories.Add(bookCategory); context.SaveChanges(); }
public IActionResult ResetPassword([FromBody] PasswordReset userParam) { try { EFDataContext _dbContext = new EFDataContext(); User dbUser = _dbContext.Users .Where(u => u.EmailId == userParam.Email.ToLower() && u.PasswordResetKey == userParam.Key).FirstOrDefault(); if (dbUser == null) { throw new Exception(); } if (!dbUser.PasswordResetExpiry.HasValue || dbUser.PasswordResetExpiry.Value.CompareTo(DateTime.UtcNow) < 0) { throw new ApiException("Password reset key has expired. Please use the forgot password link to generate a new one."); } else { if (!dbUser.Activated) { dbUser.Activated = true; dbUser.ActivationKey = ""; } dbUser.PasswordResetExpiry = null; dbUser.PasswordResetKey = ""; UserView userView = _dbContext.Users .Where(u => u.EmailId == userParam.Email.ToLower()) .Select(u => new UserView { Id = u.UserId, EmailId = u.EmailId, FirstName = u.FirstName, LastName = u.LastName, Role = u.UserRole.RoleName }) .FirstOrDefault(); dbUser.PasswordHash = _userService.GeneratePasswordHash(userView, userParam.Password); _dbContext.SaveChanges(); Mail newMail = new Mail { Subject = "AgroXchange Password Reset Successfully", BodyHtml = string.Format("Dear {0},<p>Your new password has been successfully set for your account.</p><p>If you did not execute this, please follow the forgot password flow now to reset your password.</p><p>Regards</p><p>AgroXchange</p>", dbUser.FirstName + " " + dbUser.LastName) }; newMail.AddToRecipient(dbUser.FirstName + " " + dbUser.LastName, dbUser.EmailId); _mailService.SendMail(newMail); } return(Ok()); } catch (Exception ex) { if (ex is ApiException) { return(BadRequest(new { message = ex.Message })); } return(BadRequest(new { message = "Error while reseting password. Please try again." })); } }
/// <summary> /// 根据主键ID查找实体,然后更新其Name属性 /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <returns></returns> public bool UpdateName(int id, string name) { using (EFDataContext dataContext = new EFDataContext()) { MODEL.User_MODEL userModel = dataContext.User.Find(id); if (userModel != null) { dataContext.User.Attach(userModel); userModel.Name = name; dataContext.SaveChanges(); } return true; } }
public bool Delete(int id) { using (EFDataContext dataContext=new EFDataContext()) { MODEL.User_MODEL userModel = dataContext.User.Find(id); if (userModel != null) { dataContext.User.Remove(userModel); dataContext.SaveChanges(); return true; } return false; } }
private void btnSaveChangs_Click(object sender, RoutedEventArgs e) { us.EnableValidation = true; var usChangNew = _context.Users.SingleOrDefault(p => p.Id == MainWindow.chang_User); if (!string.IsNullOrEmpty(this.tbName.Text)) { usChangNew.Name = tbName.Text; } if (!string.IsNullOrEmpty(this.tbDetails.Text)) { usChangNew.Details = tbDetails.Text; } if (!string.IsNullOrEmpty(this.tbPrice.Text)) { this._context.AppTranzactionPrices.Add(new AppTranzactionPrice { UserId = usChangNew.Id, DateCreate = DateTime.Now, Price = decimal.Parse(this.tbPrice.Text) }); this._context.SaveChanges(); } if (!string.IsNullOrEmpty(New_FileName)) { var extension = Path.GetExtension(New_FileName); var imageName = Path.GetRandomFileName() + extension; var dir = Directory.GetCurrentDirectory(); var saveDir = Path.Combine(dir, "images"); if (!Directory.Exists(saveDir)) { Directory.CreateDirectory(saveDir); } var fileSave = Path.Combine(saveDir, imageName); File.Copy(New_FileName, fileSave); usChangNew.Image = fileSave; } if (string.IsNullOrEmpty(us.Error)) { MessageBox.Show("Ура, пошло"); _context.SaveChanges(); } else { MessageBox.Show(us.Error); } this.Close(); }
// Збереження нового кота private void SaveCat_Click(object sender, RoutedEventArgs e) { newCat.EnableValidation = true; if (string.IsNullOrEmpty(newCat.Error)) { MessageBox.Show("Додавання успішне"); var extension = Path.GetExtension(FileName); var imageName = Path.GetRandomFileName() + extension; var dir = Directory.GetCurrentDirectory(); var saveDir = Path.Combine(dir, "images"); if (!Directory.Exists(saveDir)) { Directory.CreateDirectory(saveDir); } var fileSave = Path.Combine(saveDir, imageName); File.Copy(FileName, fileSave); var cat = new AppCat { Name = tbName.Text, Gender = _gender, Birthday = (DateTime)dpDate.SelectedDate, Details = tbDetails.Text, Image = fileSave }; cat.AppCatPrices = new List <AppCatPrice> { new AppCatPrice { CatId = cat.Id, DateCreate = DateTime.Now, Price = decimal.Parse(tbPrice.Text) } }; _context.Add(cat); _context.SaveChanges(); _cats.Add(new CatVM { Id = cat.Id, Name = cat.Name, Birthday = cat.Birthday, Details = cat.Details, ImageUrl = cat.Image }); this.Close(); } else { MessageBox.Show(newCat.Error); } }
public PurcharseOrder GetPurcharseOrderNullIfClientAllowsIt(string ruc_client) { var pur_ord = _dbContext.ordenes_compra .Where(po => po.ruc_empresa_cliente == ruc_client && po.id_orden_compra == "--") .FirstOrDefault(); if (pur_ord == null) { var enterprice = _dbContext.empresas .Where(ent => ent.ruc_empresa == ruc_client && ent.sin_pedido) .FirstOrDefault(); if (enterprice == null) { return(null); } if (enterprice.ruc_empresa == null) { return(null); } OrdenesCompra null_purcharse_order = new OrdenesCompra { id_orden_compra = "--", id_tipo_moneda = "XXX", monto_orden_compra = 0, ruc_empresa_cliente = ruc_client, ruc_empresa_proveedor = null }; var temp = _dbContext.ordenes_compra .Add(null_purcharse_order); _dbContext.SaveChanges(); return(_mapper.Map <PurcharseOrder>(null_purcharse_order)); } return(_mapper.Map <PurcharseOrder>(pur_ord)); }
//[Route("update")] public IActionResult UpdateCar([FromRoute] int id, [FromBody] Car car) { var cars = _context.Cars.SingleOrDefault(x => x.Id == id); if (cars == null) { return(BadRequest(new { invalid = "Такої машини немає!" })); } cars.Mark = car.Mark; cars.Model = car.Model; cars.Year = car.Year; cars.Fuel = car.Fuel; cars.Сapacity = car.Сapacity; _context.Update(cars); _context.SaveChanges(); return(Ok(cars)); }
// Given[("تنها یک کتاب با عنوان فرگشت با دسته کتابهای علمی // و دسته سنی بیست به بالا در فهرست کتابها موجود باشد // و تنها یک عضو با سن 29 سال در فهرست اعضا موجود است")] private void Given() { bookCategory = new BookCategory() { Title = "کتابهای علمی" }; context.BookCategories.Add(bookCategory); context.SaveChanges(); book = new Book() { Title = "فرگشت", AgeRange = AgeRange.twentyToOlder, CategoryId = bookCategory.Id }; context.Books.Add(book); member = new Member() { Age = 29 }; context.Books.Add(book); context.SaveChanges(); }
private static void AddNewHorseToDisconnectedSamuraiObject() { var samurai = _context.Samurais.AsNoTracking().FirstOrDefault(s => s.Id == 23); samurai.Horse = new Horse { Name = "Mr. Ed" }; using (var newContext = new EFDataContext()) { newContext.Attach(samurai); newContext.SaveChanges(); } }
private static void ModifyingRelatedDataWhenNotTracked() { var samurai = _context.Samurais.Include(s => s.Quotes).FirstOrDefault(s => s.Id == 2); var quote = samurai.Quotes[0]; quote.Text = "Did you hear that again?"; using (var newContext = new EFDataContext()) { //newContext.Quotes.Update(quote); newContext.Entry(quote).State = EntityState.Modified; newContext.SaveChanges(); } }
public void Delete(int EmployeeID) { using (EFDataContext dataContext = new EFDataContext()) { var employee = dataContext.Employee.FirstOrDefault(emp => emp.EmployeeID == EmployeeID); if (employee != null) { dataContext.Employee.Remove(employee); } dataContext.SaveChanges(); } }
private static void AddQuoteToExistingSamuraiNotTracked(int samuraiId) { var samurai = _context.Samurais.Find(samuraiId); samurai.Quotes.Add(new Quote { Text = "Now that I saved you, will you feed me dinner?" }); using (var newContext = new EFDataContext()) { newContext.Samurais.Attach(samurai); newContext.SaveChanges(); } }
public Employee Criar(Employee entity) { try { _db.Add(entity); _db.SaveChanges(); return(entity); } catch (Exception e) { Console.WriteLine(e.Message); } return(null); }
public ActionResult Index() { _ctx = new EFDataContext(); var client = new Client("juan", "Ruiz", "brum", "095699447"); var pet = new Pet("arya", "9 meses", PetType.Cat); _ctx.Pets.Add(pet); client.Pets.Add(pet); _ctx.Clients.Add(client); _ctx.SaveChanges(); return View(); }
private static void AddQuoteToExistingSamuraiNotTracked_Easy(int samuraiId) { var quote = new Quote { Text = "Now that I saved you, will you feed me dinner again?", SamuraiId = samuraiId }; using (var newContext = new EFDataContext()) { newContext.Quotes.Add(quote); newContext.SaveChanges(); } }
// Given[("یک دسته بندی کتاب های تاریخی در لیست دسته بندی کتابها وجود دارد. // و تنها یک کتاب با عنوان جنگ جهانی دوم با، // دسته بندی کتاب های تاریخی در فهرست کتابها وجود دارد")] private void Given() { bookCategory = new BookCategory() { Title = "کتابهای تاریخی" }; context.BookCategories.Add(bookCategory); book = new Book() { Title = "جنگ جهانی دوم", Category = bookCategory, }; context.Books.Add(book); context.SaveChanges(); }
// Видалення кота з поля, на якому стоїть курсор private void btnDelete_Click(object sender, RoutedEventArgs e) { if (dgSimple.SelectedItem != null) { if (dgSimple.SelectedItem is CatVM) { var userView = dgSimple.SelectedItem as CatVM; int id = userView.Id; _idCat = id; var cat = _context.Cats.SingleOrDefault(c => c.Id == id); _context.Cats.Remove(cat); _context.SaveChanges(); } } }
public bool Delete(MODEL.User_MODEL userModel) { using (EFDataContext dataContext=new EFDataContext()) { dataContext.User.Attach(userModel); dataContext.User.Remove(userModel); dataContext.SaveChanges(); return true; } }