I have the following table in SQL Server 2008 database:
User
--------------------------------------------------------
Id Numeric(18, 0) | Identity(1, 1) PK not null
Name Nchar(20) | Not null
I'm using an ADO.NET Entity Data model to do:
MyEntities entities;
try
{
entities = new MyEntities();
if (entities.User.Count(u => u.Name == userName) == 0)
{
entities.User.AddObject(new User()
{
Name = userName
});
resultCode = 1;
entities.SaveChanges();
}
else
{
resultCode = 2;
}
}
catch
{
resultCode = 3;
}
finally
{
if (entities != null)
entities.Dispose();
}
How can I get User.Id for new User added?
If your model is configured correctly and you have Id property marked with StoreGeneratedPattern.Identity you need simply call this:
var user = new User()
{
Name = userName
};
entities.User.AddObject(user);
resultCode = 1;
entities.SaveChanges();
int id = user.Id; // it's here
Try keeping a reference to the user object. Once SaveChanges() is called, the Id should automatically be updated. Here's a modification of your code to demonstrate:
if (entities.User.Count(u => u.Name == userName) == 0)
{
User newUser = new User()
{
Name = userName
};
entities.User.AddObject(newUser);
resultCode = 1;
entities.SaveChanges();
// newUser.Id should be populated at this point.
}
Related
Heading ##[HttpPost]
public ActionResult LogIn(UserDetail user)
{
using (AdventureWorksDBEntities User = new AdventureWorksDBEntities())
{
var UserInput= User.UserDetails.Where(b => b.UserName == user.UserName && b.Password == user.Password).FirstOrDefault();
if (UserInput!=null)
{
Session["Id"] = UserInput.id.ToString();
Session["UserName"] = UserInput.UserName.ToString();
return Redirect("#");
}
else
{
ModelState.AddModelError("","Username or Password Doesn't Exist");
}
}
return View();
I want to compare user input values with the values in the database.
I'm trying to update only single property of an entity but I cannot update it.
Here is what I have done so far:
public async Task ChangePassword(string User, string Password)
{
using (var context = new abcContext())
{
var user = await context.Members.Where(c => c.UserName == User).FirstOrDefaultAsync();
var member = context.Members.Find(user.PersonID);
var coolBlog = new Member { PersonID = member.PersonID,
Password = member.Password };
context.Configuration.ValidateOnSaveEnabled = false;
context.Members.Attach(member);
context.Entry(member).Property(c => c.Password).OriginalValue = coolBlog.Password.ToString();
context.Entry(member).Property(m => m.Password).IsModified = true;
await context.SaveChangesAsync();
};
}
It is not updating password property in my database. Please guide me I have searched internet but couldn't find any appropriate solution.
You probably want this:
public async Task ChangePassword(string User, string Password)
{
using (var context = new abcContext())
{
var user = await context.Members.Where(c => c.UserName == User).FirstOrDefaultAsync();
if (user != null)
{
user.Password = Password; // do some hashing on password to not store plain password
await context.SaveChangesAsync();
}
}
}
I have simple login form without registration, because I create Admin login, who create new users. So admin login, and create new user, which can then login with that specific username and password.
So I create this controller:
public ActionResult CreateNew(Models.Users user)
{
if (ModelState.IsValid)
{
try
{
using (var dataU = new userDbEntities())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var sysUser = dataU.UsersTables.Create();
sysUser.username = user.Username;
sysUser.password = encrpPass;
sysUser.passwordSalt = crypto.Salt;
sysUser.TimeZoneId = user.TimeZoneName;
sysUser.Customer = user.Customer;
dataU.UsersTables.Add(sysUser);
dataU.SaveChanges();
return RedirectToAction("Registration", "LoginAdmin");
}
}
catch (Exception ex)
{
string error = ex.Message;
}
}
return View(user);
}
Problem is, that I can create users with same username (this is not ok!), so how to check if user with that name exists and returns, this username already exists...
thanks...
count the number of user that has the same username and add the user if the count is 0.
for example
var count = dataU.UsersTables.Count(u=>u.UserName == usernameyouwanttocheck);
if(count==0)
{
//add user
}
else
{
//alert user saying user exists
}
if I were you I would make repository and create a function that checks if the user exists or not and call that function from controller.
By help of Biplov13 I create this, which is working:
public ActionResult CreateNew(Models.Users user)
{
if (ModelState.IsValid)
{
try
{
using (var dataU = new userDbEntities())
{
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var sysUser = dataU.UsersTables.Create();
sysUser.username = user.Username;
sysUser.password = encrpPass;
sysUser.passwordSalt = crypto.Salt;
sysUser.TimeZoneId = user.TimeZoneName;
sysUser.Customer = user.Customer;
var count = dataU.UsersTables.Count(u => u.username == user.Username);
if (count == 0)
{
dataU.UsersTables.Add(sysUser);
dataU.SaveChanges();
return RedirectToAction("Registracija", "LoginAdmin");
}
else
{
// something to do if user exist...
}
}
}
}
catch (Exception ex)
{
string error = ex.Message;
}
}
return View(user);
}
I am trying to insert datas to Appointment table of my database. I did registration part of my project which works well. There are 2 tables, Patient and Appointment. After Login patients can make an appointment. Patient number comes like this
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
For appointment date and description comes from textbox. And I want to insert PatientNo from Patient table to Appointment table. For me it looks done but when I choose date and write description but I got error on this line app.PatientNo = patient.PatientNo;
An exception of type 'System.NullReferenceException' occurred in DentAppSys.dll but was not handled in user code
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Make(Models.AppModel User)
{
if (Session["UserEmail"] != null)
{
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
var app = new Appointment();
app.Date = User.Date;
app.Description = User.Description;
app.Status = "true";
app.PatientNo = patient.PatientNo;
db.Appointments.InsertOnSubmit(app);
db.SubmitChanges();
return RedirectToAction("Make", "Appointment");
}
}
else
{
return RedirectToAction("Index", "User");
}
}
}
}
and this is registration part which is working well
public ActionResult RegAndLogin(Models.RegAndLog User)
{
if (User.RegisterModel != null)
{
if (ModelState.IsValid)
{
using (var db = new MaindbModelDataContext())
{
var Person = db.Patients.FirstOrDefault(u => u.Email == User.RegisterModel.Email);
if (Person == null)
{
string Hash = BCrypt.Net.BCrypt.HashPassword(User.RegisterModel.Password);
var MyUser = new Patient();
MyUser.Name = User.RegisterModel.Firstname;
MyUser.Surname = User.RegisterModel.Lastname;
MyUser.Birthday = User.RegisterModel.Birthday;
MyUser.Email = User.RegisterModel.Email;
MyUser.Password = Hash;
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
db.Patients.InsertOnSubmit(MyUser);
db.SubmitChanges();
Session["UserEmail"] = User.RegisterModel.Email;
return RedirectToAction("Index", "Patient", User.RegisterModel);
}
else
{
ModelState.AddModelError("", "There is a user with this Email. Please enter another Email !!!");
return View();
}
}
}
else
{
ModelState.AddModelError("", "Data is incorrect !!!");
}
}
else
{
if (ModelState.IsValid && IsValid(User.LoginModel.Email, User.LoginModel.Password))
{
var TempUser = new Models.RegisterModel();
Session["UserEmail"] = User.LoginModel.Email;
using (var db = new MaindbModelDataContext())
{
var person = db.Patients.FirstOrDefault(u => u.Email == User.LoginModel.Email);
TempUser.Firstname = person.Name;
TempUser.Lastname = person.Surname;
//TempUser.RegisterModel.Birthday = (DateTime)person.BirthDate;
TempUser.Email = person.Email;
}
return RedirectToAction("Index", "Patient", TempUser);
}
else
{
ModelState.AddModelError("", "Check your E-mail or Password then try again !!!");
}
}
return View();
If you're getting a null exception on the line
app.PatientNo = patient.PatientNo;
It will be because either app or patient are null at when it's executed. I would suspect patient.
Check that patient is found correctly at the line
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
if it isn't found patient will be null.
Unit testing of the role provider to fail.
[TestMethod]
public void FindUsersInRole()
{
Mock<IUsersInRoleRepository> userInRoleMock = new Mock<IUsersInRoleRepository>();
userInRoleMock.Setup(m => m.UsersInRoles).Returns(new UsersInRole[] {
new UsersInRole { UserId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"), RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") },
new UsersInRole { UserId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"), RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") },
new UsersInRole { UserId = Guid.Parse("cccccccc-cccc-cccc-cccc-cccccccccccc"), RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") },
new UsersInRole { UserId = Guid.Parse("dddddddd-dddd-dddd-dddd-dddddddddddd"), RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") },
new UsersInRole { UserId = Guid.Parse("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"), RoleId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb") }
}.AsQueryable());
Mock<IRoleRepository> roleMock = new Mock<IRoleRepository>();
roleMock.Setup(m => m.Roles).Returns(new Role[] {
new Role { RoleId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"), RoleName = "test" },
new Role { RoleId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"), RoleName = "admin" }
}.AsQueryable());
Mock<IUserRepository> userMock = new Mock<IUserRepository>();
userMock.Setup(m => m.Users).Returns(new User[] {
new User { UserId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"), UserAccount = "abcdef" },
new User { UserId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"), UserAccount = "bcdef" },
new User { UserId = Guid.Parse("cccccccc-cccc-cccc-cccc-cccccccccccc"), UserAccount = "cdef" },
new User { UserId = Guid.Parse("dddddddd-dddd-dddd-dddd-dddddddddddd"), UserAccount = "bcdf" },
new User { UserId = Guid.Parse("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"), UserAccount = "abcde" }
}.AsQueryable());
RoleProvider target = new RoleProvider(userMock.Object, roleMock.Object, userInRoleMock.Object);
string[] result = target.FindUsersInRole("test", "cde");
Assert.AreEqual(result[0], "abcdef");
Assert.AreEqual(result[1], "bcdef");
Assert.AreEqual(result[2], "cdef");
}
Unit Test Code
string[] result = target.FindUsersInRole("test", "cde"); <-- error
FindUsersInRole - Gets an array of user names in a role where the user name contains the specified user name to match.
System.NullReferenceException is raised and try to debug.
Why NullReferenceException?
PS - FindUsersInRole (RoleProvider)
public override string[] FindUsersInRole(string roleName, string userAccountToMatch)
{
Guid roleId = roleRepository.GetRole(roleName).RoleId; // RoleId Retrun.. NullReferenceException
var roleInUsers = (from ru in usersInRoleRepository.UsersInRoles
where ru.RoleId == roleId
select ru.UserId).ToArray();
var findUserResult = (from u in userRepository.Users
where roleInUsers.Contains(u.UserId) && u.UserAccount.Contains(userAccountToMatch)
select u.UserAccount).ToArray();
return findUserResult;
}
Your cde is not a fake user in a mackUserAccount . So its return null.
try this below code string[] result = target.FindUsersInRole("test", "abcdef"); instead of
string[] result = target.FindUsersInRole("test", "cde");