public User Save(User user) { string query = @"INSERT INTO [User] ( Username, Password, IsAdmin ) VALUES ( @Username, @Password, @IsAdmin )"; using (SqlConnection db = new SqlConnection(CONN_STR)) { if (db.State != System.Data.ConnectionState.Open) { db.Open(); } using (SqlCommand cmd = db.CreateCommand()) { cmd.CommandText = query; cmd.Parameters.AddWithValue("Username", user.Username); cmd.Parameters.AddWithValue("Password", user.Password); cmd.Parameters.AddWithValue("IsAdmin", user.IsAdmin); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT @@Identity"; user.UserID = (int)(decimal)cmd.ExecuteScalar(); } } return user; }
public List<User> FindAll() { List<User> Users = new List<User>(); string query = "SELECT * FROM [User]"; using (SqlConnection db = new SqlConnection(CONN_STR)) { if (db.State != System.Data.ConnectionState.Open) { db.Open(); } using (SqlCommand cmd = db.CreateCommand()) { cmd.CommandText = query; using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { User u = new User(); u.UserID = reader.GetInt32(reader.GetOrdinal("UserID")); u.Username = reader.GetString(reader.GetOrdinal("Username")); u.Password = reader.GetString(reader.GetOrdinal("Password")); u.IsAdmin = reader.GetBoolean(reader.GetOrdinal("IsAdmin")); Users.Add(u); } } } } return Users; }
public void Delete(User user) { string query = "DELETE FROM User"; using (SqlConnection db = new SqlConnection(CONN_STR)) { if (db.State != System.Data.ConnectionState.Open) { db.Open(); } using (SqlCommand cmd = db.CreateCommand()) { cmd.CommandText = query; cmd.ExecuteNonQuery(); } } }
public ActionResult Index(UserForm userForm) { if (ModelState.IsValid) { if (UserRepository.UsernameNotTaken(userForm.Username)) { User newUser = new User(); newUser.Username = userForm.Username; newUser.Password = userForm.Password; newUser.IsAdmin = false; newUser = UserRepository.Save(newUser); newUser.Password = "******"; Session["CurrentUser"] = newUser; return RedirectToAction("Index", "Home", new { Area = "" }); } } return View(userForm); }