public ActionResult Create([Bind(Include = "Id,Name,Address")] CompanyModel companyModel) { if (ModelState.IsValid) { db.CompanyModels.Add(companyModel); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(companyModel)); }
public ActionResult Create([Bind(Include = "Id,FirstName,LastName,Age")] EmployeeModel employeeModel) { if (ModelState.IsValid) { db.EmployeeModels.Add(employeeModel); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(employeeModel)); }
public T Create(T item) { try { dataSet.Add(item); _context.SaveChanges(); } catch (Exception ex) { throw ex; } return(item); }
public void Check_GetSportMargin_NotExist() { // Arrange var options = new DbContextOptionsBuilder <MsSqlContext>() .UseInMemoryDatabase(databaseName: "Check_GetSportMargin_NotExist") .Options; using (var context = new MsSqlContext(options)) { context.ConfigurationSportMargin.Add ( new ConfigurationSportMargin { ConfigurationId = 1, SportId = 1, MarginValue = 100 } ); context.SaveChanges(); } using (var context = new MsSqlContext(options)) { // Act var ds = new DataService(context); var sportMargin = ds.GetSportMargin_Test(2, 2); // Assert Assert.AreEqual(sportMargin, 1); } }
public bool Create(Usuario usuario, ControleAcesso controleAcesso) { DbSet <Usuario> dsUsuario = null; using (_context) { using (var dbContextTransaction = _context.Database.BeginTransaction()) { try { dsUsuario = _context.Set <Usuario>(); dsUsuario.Add(usuario); _context.SaveChanges(); string sql = "INSERT INTO[dbo].[ControleAcesso] ([login], [senha], [idUsuario]) VALUES (@login, @senha, @idUsuario)"; _context.Database.ExecuteSqlCommand(sql, new SqlParameter("@login", controleAcesso.Login), new SqlParameter("@senha", controleAcesso.Senha), new SqlParameter("@idUsuario", usuario.Id.Value)); dbContextTransaction.Commit(); return(true); } catch (Exception) { dbContextTransaction.Rollback(); } } } return(false); }
private void save_OnClick(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(nameTextBox.Text) || string.IsNullOrEmpty(nameTextBox.Text) || string.IsNullOrEmpty(surnameTextBox.Text) || string.IsNullOrEmpty(otcTextBox.Text) || string.IsNullOrEmpty(ageBox.Text)) { MessageBox.Show("Пожалуйста заполните поля!"); return; } try { using (MsSqlContext db = new MsSqlContext()) { if (!int.TryParse(ageBox.Text, out var ages) || int.Parse(ageBox.Text) > 150) { MessageBox.Show("Введите правильное значение возраста (от 1 до 150)!"); return; } MyAcc.SelectedUser.user_name = nameTextBox.Text; MyAcc.SelectedUser.user_surname = surnameTextBox.Text; MyAcc.SelectedUser.user_otc = otcTextBox.Text; MyAcc.SelectedUser.Age = int.Parse(ageBox.Text); db.Entry(MyAcc.SelectedUser).State = EntityState.Modified; db.SaveChanges(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } Close(); }
public void Check_FilterDisabledMatches() { // Arrange var options = new DbContextOptionsBuilder <MsSqlContext>() .UseInMemoryDatabase(databaseName: "Check_FilterDisabledMatches") .Options; const int ConfigId = 1; using (var context = new MsSqlContext(options)) { context.Matches.AddRange ( new Match { MatchId = 1, CategoryId = 1 }, new Match { MatchId = 2, CategoryId = 1 }, new Match { MatchId = 3, CategoryId = 1 }, new Match { MatchId = 4, CategoryId = 1 } ); context.ConfigurationMatchDisabled.AddRange ( new ConfigurationMatchDisabled { ConfigurationId = ConfigId, MatchId = 2, Match = new Match { MatchId = 2, CategoryId = 1 } }, new ConfigurationMatchDisabled { ConfigurationId = ConfigId, MatchId = 4, Match = new Match { MatchId = 4, CategoryId = 1 } } ); context.SaveChanges(); } using (var context = new MsSqlContext(options)) { // Act var ds = new DataService(context); var filterMatches = ds.FilterDisabledMatches_Test(ConfigId); // Assert Assert.AreEqual(2, filterMatches.Count()); Assert.AreEqual(1, filterMatches[0].MatchId); Assert.AreEqual(3, filterMatches[1].MatchId); } }
public ActionResult Register(RegisterModel model) { if (User.Identity.IsAuthenticated == false) { if (ModelState.IsValid) { User user = null; user = db.Users.FirstOrDefault(u => u.Email == model.Name); if (user == null) { // создаем нового пользователя byte[] bytes = Encoding.Unicode.GetBytes(model.Password); MD5CryptoServiceProvider CSP = new MD5CryptoServiceProvider(); byte[] byteHash = CSP.ComputeHash(bytes); model.Password = string.Empty; foreach (byte b in byteHash) { model.Password += string.Format("{0:x2}", b); } Role role = db.Roles.FirstOrDefault(c => c.Id == 1); model.RoleId = 1; db.Users.Add(new User { Email = model.Name, user_name = model.user_name, user_surname = model.surname, user_otc = model.otc, Password = model.Password, Age = model.Age, RoleId = model.RoleId }); db.SaveChanges(); user = db.Users.Where(u => u.Email == model.Name && u.Password == model.Password).FirstOrDefault(); if (user != null) { FormsAuthentication.SetAuthCookie(model.Name, true); return(RedirectToAction("Details")); } } else { ModelState.AddModelError("", "Пользователь с таким логином уже существует"); } } return(View(model)); } else { return(RedirectToAction("Details")); } }
private void ProcessResourceType <ResCurrentType, ResIndexStringType, ResIndexTokenType, ResIndexUriType, ResIndexReferenceType, ResIndexQuantityType, ResIndexDateTimeType>(string ResourceName) where ResCurrentType : ResourceCurrentBase <ResCurrentType, ResIndexStringType, ResIndexTokenType, ResIndexUriType, ResIndexReferenceType, ResIndexQuantityType, ResIndexDateTimeType> where ResIndexStringType : ResourceIndexString <ResCurrentType, ResIndexStringType, ResIndexTokenType, ResIndexUriType, ResIndexReferenceType, ResIndexQuantityType, ResIndexDateTimeType> where ResIndexTokenType : ResourceIndexToken <ResCurrentType, ResIndexStringType, ResIndexTokenType, ResIndexUriType, ResIndexReferenceType, ResIndexQuantityType, ResIndexDateTimeType> where ResIndexUriType : ResourceIndexUri <ResCurrentType, ResIndexStringType, ResIndexTokenType, ResIndexUriType, ResIndexReferenceType, ResIndexQuantityType, ResIndexDateTimeType> where ResIndexReferenceType : ResourceIndexReference <ResCurrentType, ResIndexStringType, ResIndexTokenType, ResIndexUriType, ResIndexReferenceType, ResIndexQuantityType, ResIndexDateTimeType> where ResIndexQuantityType : ResourceIndexQuantity <ResCurrentType, ResIndexStringType, ResIndexTokenType, ResIndexUriType, ResIndexReferenceType, ResIndexQuantityType, ResIndexDateTimeType> where ResIndexDateTimeType : ResourceIndexDateTime <ResCurrentType, ResIndexStringType, ResIndexTokenType, ResIndexUriType, ResIndexReferenceType, ResIndexQuantityType, ResIndexDateTimeType> { try { Hl7.Fhir.Serialization.FhirXmlSerializer FhirXmlSerializer = new Hl7.Fhir.Serialization.FhirXmlSerializer(); bool Running = true; while (Running) { IPyroDbContext context = new MsSqlContext(); var Query = context.Set <ResCurrentType>().Where(x => x.XmlBlob != null && x.IsDeleted == false && x.Resource == null).Take(200).ToList(); if (Query == null || Query.Count == 0) { Running = false; } else { foreach (var ResourceEntity in Query) { if (!string.IsNullOrWhiteSpace(ResourceEntity.XmlBlob)) { Resource Res = Common.Tools.FhirResourceSerializationSupport.DeSerializeFromXml(ResourceEntity.XmlBlob); byte[] ResBytes = FhirXmlSerializer.SerializeToBytes(Res); ResourceEntity.Resource = Common.Tools.GZip.GZipper.Compress(ResBytes); ResourceEntity.XmlBlob = null; context.Set <ResCurrentType>().AddOrUpdate(ResourceEntity); } } context.SaveChanges(); context.Dispose(); } } } catch (Exception Exec) { throw new Exception($"The Resource Type {ResourceName}", Exec); } }
public void UpdateScore(string studentInfoId, string classInfoId, int newScore, string course) { SqlParameter[] sql = new [] { new SqlParameter("course", course), new SqlParameter("stuInfo", studentInfoId), new SqlParameter("classInfo", classInfoId), new SqlParameter("newScore", newScore) { Direction = ParameterDirection.Output }, }; _loggerHelper.WriteInfoLog(studentInfoId + "," + classInfoId + "," + newScore + "," + course); //没搞明白为什么ExecuteSqlInterpolated可以执行却不能变更,暂时先用ExecuteSqlRaw var update = _msSqlContext.Database .ExecuteSqlRaw($"update LastClassScores set {course} = {newScore} where ClassInfoId = '{classInfoId}' and StudentsInfoId = '{studentInfoId}'"); _msSqlContext.SaveChanges(); _loggerHelper.WriteInfoLog(update); }
public void Check_GetSportMargin_Exist() { // Arrange var options = new DbContextOptionsBuilder <MsSqlContext>() .UseInMemoryDatabase(databaseName: "Check_GetSportMargin_Exist") .Options; const int ConfigId = 1; const int SportId = 1; const double MarginValue = 1.2; using (var context = new MsSqlContext(options)) { context.ConfigurationSportMargin.Add ( new ConfigurationSportMargin { ConfigurationId = ConfigId, SportId = SportId, MarginValue = MarginValue } ); context.Sports.Add(new Sport { SportId = SportId }); context.SaveChanges(); } using (var context = new MsSqlContext(options)) { // Act var ds = new DataService(context); var sportMargin = ds.GetSportMargin(ConfigId, SportId); // Assert Assert.AreEqual(sportMargin, MarginValue); } }
public void Check_EnableConfigurations() { // Arrange var options = new DbContextOptionsBuilder <MsSqlContext>() .UseInMemoryDatabase(databaseName: "Check_EnableConfigurations") .Options; using (var context = new MsSqlContext(options)) { context.Configuration.AddRange ( new Configuration { ConfigurationId = 1, IsEnabled = true }, new Configuration { ConfigurationId = 2, IsEnabled = true }, new Configuration { ConfigurationId = 3, IsEnabled = false } ); context.SaveChanges(); } using (var context = new MsSqlContext(options)) { // Act var ds = new DataService(context); var enabledConfigs = ds.EnableConfigurations; // Assert Assert.AreEqual(2, enabledConfigs.Count); Assert.AreEqual(1, enabledConfigs[0].ConfigurationId); Assert.AreEqual(2, enabledConfigs[1].ConfigurationId); } }
/// <summary> /// Seed simple data to MsSql in case it is empty. For test purposes. /// </summary> /// <param name="context">MsSQL context</param> private static void SeedMsSql(MsSqlContext context) { var product = new Product() { Measure = new Measure() { Name = "Some" }, Name = "Chocolate “Milka”", BuyingPrice = 10m, Incomes = new List<Income>() { new Income() { Quantity = 10, Date = DateTime.Now, Supermarket = new Supermarket() }, new Income() { Quantity = 10, Date = DateTime.Now, Supermarket = new Supermarket() } }, Vendor = new Vendor() { Name = "Nestle Sofia Corp.", Expenses = new List<Expense>() { new Expense() { Amount = 15m, Date = DateTime.Now }, new Expense() { Amount = 15m, Date = DateTime.Now } } } }; context.Products.AddOrUpdate(product); var product2 = new Product() { Measure = new Measure() { Name = "Some2" }, Name = "Beer “Zagorka”", BuyingPrice = 10m, Incomes = new List<Income>() { new Income() { Quantity = 10, Date = DateTime.Now, Supermarket = new Supermarket() } }, Vendor = new Vendor() { Name = "Zagorka Corp.", Expenses = new List<Expense>() { new Expense() { Amount = 120m, Date = DateTime.Now } } } }; context.Products.AddOrUpdate(product2); var product3 = new Product() { Measure = new Measure() { Name = "Some3" }, Name = "Vodka “Targovishte”", BuyingPrice = 10m, Incomes = new List<Income>() { new Income() { Quantity = 10, Date = DateTime.Now, Supermarket = new Supermarket() } }, Vendor = new Vendor() { Name = "Targovishte Bottling Company Ltd.", Expenses = new List<Expense>() { new Expense() { Amount = 200m, Date = DateTime.Now } } } }; context.Products.AddOrUpdate(product3); context.SaveChanges(); Console.WriteLine("MS SQL Server seeded with sample data."); }
public void ExportDataToMSSQLContext(MsSqlContext context) { var measures = this.oracleContext.Measures.ToList(); var products = this.oracleContext.Products.ToList(); var vendors = this.oracleContext.Vendors.ToList(); var incomes = this.oracleContext.Incomes.ToList(); var expenses = this.oracleContext.Expenses.ToList(); foreach (var measure in measures) { if (!context.Measures.Any(m => m.Name == measure.Name)) { context.Measures.Add(measure); } } foreach (var vendor in vendors) { if (!context.Vendors.Any(v => v.Name == vendor.Name)) { context.Vendors.Add(vendor); } } foreach (var product in products) { if (!context.Products.Any(p => p.Name == p.Name)) { context.Products.Add(product); } } foreach (var income in incomes) { if (!context.Incomes.Any(i => i.Date == income.Date)) { context.Incomes.Add(income); } } foreach (var expense in expenses) { if (!context.Expenses.Any(e => e.Date == expense.Date)) { context.Expenses.Add(expense); } } context.SaveChanges(); }
public void Insert(T obj) { context.Set <T>().Add(obj); context.SaveChanges(); }
public ActionResult ChangePassword(ChangePassModel model) { if (ModelState.IsValid) { User user; user = db.Users.FirstOrDefault(u => u.Email == User.Identity.Name); if (user != null) { if (user.Email == User.Identity.Name) { using (MsSqlContext db = new MsSqlContext()) { byte[] bytes = Encoding.Unicode.GetBytes(model.Password); MD5CryptoServiceProvider CSP = new MD5CryptoServiceProvider(); byte[] byteHash = CSP.ComputeHash(bytes); model.Password = string.Empty; foreach (byte b in byteHash) { model.Password += string.Format("{0:x2}", b); } if (model.Password == user.Password) { byte[] bytesnew = Encoding.Unicode.GetBytes(model.Password_new); MD5CryptoServiceProvider CSPnew = new MD5CryptoServiceProvider(); byte[] byteHashnew = CSPnew.ComputeHash(bytesnew); model.Password_new = string.Empty; foreach (byte b in byteHashnew) { model.Password_new += string.Format("{0:x2}", b); } byte[] bytesconf = Encoding.Unicode.GetBytes(model.ConfirmPassword); MD5CryptoServiceProvider CSPconf = new MD5CryptoServiceProvider(); byte[] byteHashconf = CSP.ComputeHash(bytesconf); model.ConfirmPassword = string.Empty; foreach (byte b in byteHashconf) { model.ConfirmPassword += string.Format("{0:x2}", b); } if (model.ConfirmPassword == model.Password_new) { user.Password = model.ConfirmPassword; db.Entry(user).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Details")); } } else { ModelState.AddModelError("Password", "Неверный пароль"); } } } else { return(RedirectToAction("Details")); } } } else { return(RedirectToAction("Login")); } return(View(model)); }