Save userid on database when create new object - asp.net-mvc

I have a Controller where on the Create action I need the user ID.
Here's the controller.
public ActionResult Create(MyCreateViewModel model)
{
if (ModelState.IsValid)
{
var myobject = new MyObject
{
Attrib1 = DateTime.Now.Date,
Attrib2 = model.Etichetta,
UserId = // I need the user ID...
};
// Save the object on database...
return RedirectToAction("Index");
}
return View(model);
}
I'm using the UserProfile table provided with the SimpleMembership of MVC 4.
Which is the best practice in MVC 4 to manage the userID across the application?
Do I have to include a User attribute inside every Entity class?
Should I use a Session[] variable or what?

You can use this line to get the userId from the UserProfiles table.
var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
You can also use this function to get the users complete profile, including any custom columns you may be populating.
public static UserProfile GetUserProfile()
{
using (var db = new UsersContext())
{
var userId = WebSecurity.GetUserId
(HttpContext.Current.User.Identity.Name);
var user = db.UserProfiles
.FirstOrDefault(u => u.UserId == userId);
if (user == null)
{
//couldn't find the profile for some reason
return null;
}
return user;
}
}

Related

What's the return value of DBSet.Add(object o)

Consider the situation.
I have a userlogin table. the userlogin has the following fields.
userid(identity(1,1)), username(unique), password(string)
I have another table, userRole with following fields.
userid(fk referencing userlogin), role(string)
Now suppose I want to add an admin user to my empty application database.
What I am currently doing is:
// Check Userlogin if it contains adminuser1 as username, if not, add adminuser1 with password xyz.
UserLogin login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
context.UserLogins.Add(login);
context.SaveChanges();
// query again from database to get the userid
Userlogin user = context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password == "xyz"));
int userid = user.userid;
UserRole admin = new UserRole();
admin.userid = userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();
I want to make it a less troublesome, if we can get the userid of userRecently Added, without making another request.
I mean I want to do this if it is possible.
UserLogin login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
UserLogin user = context.UserLogins.Add(login);
UserRole admin = new UserRole();
admin.userid = user.userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();
Update
I also wanted to know if there is some way to do
context.UserLogins.Single(l => l == login);
instead of
context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password=="xyz"));
because I use the same method in large classes in many fields.
It can be different based on your needs but you can have something like:
public class UserRole
{
public int Id { get; set; }
public string role { get; set; }
}
public class UserLogin
{
public int Id { get; set; }
public string username { get; set; }
public string password { get; set; }
public UserRole Role { get; set; }
}
and then use them like:
var login = new UserLogin
{
username = "adminuser1",
password = "xyz"
};
var admin = context.UserRoles.Single(_=> _.role == "admin");
if (admin == null)
{
admin = new UserRole
{
role = "admin"
};
}
login.Role = admin;
context.UserLogins.Add(login);
context.SaveChanges();
Your models' relationship seems wrong but based on your information you can have this:
var login = context.UserLogins.Single(_ => _.username == "adminuser1");
if (login == null)
{
login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
context.UserLogins.Add(login);
context.SaveChanges();
}
else
{
// this user already exists.
}
var admin = context.UserRoles.Single(_ => _.role == "admin");
if (admin == null)
{
admin.userid = login.userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();
}
else
{
// the role already exists.
}
context.UserLogins.Single(l => l == login); would not work for you! you have to query DB based on your model key, not whole model data!
For the question
What's the return value of DBSet.Add(object o)
The answer is: it will return the same object o(i.e. without the userid). Simply because userid is an identity column and relies on the database, its value is only available after context.SaveChanges() is called. Since Add() method only registers that a change will take place after SaveChanges() is called.
For the answer to update,
Instead of using
context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password=="xyz"));
For classes that have many fields, I can check if there are any unique columns. For example. I could use, simply
context.UserLogins.Single(l => l.username == "adminuser1");
Just because, username(unique) is specified in the question.
I would rather recommend people use a single Stored Procedure. The calling of context.SaveChanges() and the context.xyz.Single() require opening database connection multiple times. For optimising performance you can use Stored Procedures, as they require only one connection per task. For more information.
Understang Performance Considerations
As I am using database first approach, I found this link also helpful.
Use Stored Procedure in Entity Framework
Thanks :)

How to Pass Value from a login Page

Hello I need help please
I am creating my first asp mvc Webpage.
I created a login and registration page connected with database.
I want to pass CustomerId from the customer that logged in to a Bookings table
So that it shows bookings related to that customer only.
Bookings table has CustomerId as a foreign key. This is what I have done so far.
public class BookingController : Controller
{
// GET: Booking
public ActionResult Index(int customerId)
{
TravelExpertsEntities bookingdb = new TravelExpertsEntities();
List<Booking> bookings = bookingdb.Bookings.Where(book =>
book.CustomerId == customerId).ToList();
return View(bookings);
}
}
}
//This is from login Controller
public ActionResult Login(Customer reg)
{
if (ModelState.IsValid)
{
var details = (from userlist in db.Customers
where userlist.UserName == reg.UserName &&
userlist.Password == reg.Password
select new
{
userlist.CustomerId,
userlist.UserName
}).ToList();
if (details.FirstOrDefault() != null)
{
Session["CustomerId"] =
details.FirstOrDefault().CustomerId;
Session["Username"] = details.FirstOrDefault().UserName;
return RedirectToAction("Index", "Booking");
}
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
}
return View(reg);
}
I was able to pull all bookings but I want to filter it with the Customer that logged in.
Replace your RedirectToAction as below, to pass customerId as parameter
var CustomerIdparam=details.FirstOrDefault().CustomerId;
RedirectToAction("Index", "Booking", new{customerId=CustomerIdparam});

Remove User from Roles in ASP.NET Identity 2.x

How can I remove User from Roles in ASP.NET Identity 2.x ?
about adding role to user there is no problem but when I want to remove a role from a user I cannot.It should be mentioned that there is no exception or error!
//POST: Admin/User/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Prefix = "")]UserViewModel userViewModel, List<int> availableRoles)
{
if (ModelState.IsValid)
{
List<int> newListOfRolesIDs = availableRoles;
List<int> oldListOfRolesIDs = UserBLL.Instance.GetRolesIDs(userViewModel.Id);
List<int> deletedList;
List<int> addedList;
var haschanged = oldListOfRolesIDs.ChangeTracking(newListOfRolesIDs, out deletedList, out addedList);
using (new EFUnitOfWorkFactory().Create())
{
if (haschanged)
{
UserBLL.Instance.InsertRoles(addedList, userViewModel.Id);
UserBLL.Instance.DeleteRoles(deletedList, userViewModel.Id);
}
await UserBLL.Instance.UpdateAsync(userViewModel);
}
//ArticleBLL.Instance.UpdatePartial(articleViewModel, m => m.Title);
return RedirectToAction("Edit");
}
return View(userViewModel);
}
Delete Role method:
public void DeleteRoles(List<int> deleteList, int? userId)
{
if (userId != null)
{
User user = UserManager.FindByIdAsync(userId.Value).Result;
foreach (var i in deleteList)
{
user.Roles.Remove(new UserRole { RoleId = i, UserId = user.Id }); // What's the problem?!
}
}
}
Insert Role method:
public void InsertRoles(List<int> insertList, int? userId)
{
if (userId != null)
{
User user = UserManager.FindByIdAsync(userId.Value).Result;
foreach (var i in insertList)
{
user.Roles.Add(new UserRole { RoleId = i, UserId = user.Id });
}
}
}
What you are looking for is the RemoveFromRoleAsync method. An example would look similar to the following:
public async Task DeleteRolesAsync(List<string> deleteList, int? userId)
{
if (userId != null)
{
foreach (var roleName in deleteList)
{
IdentityResult deletionResult = await UserManager.RemoveFromRoleAsync(userId, roleName);
}
}
}
If you already have the ID of the user, there's no need to get the user again (only if you want to make sure that the user really exists; then you have to wrap your foreach with an if-statement). The deletion methods needs the name of the role, instead of the ID, to delete the user from the role. You can use the result of the operation (in my example stored in deletionResult) to make sure that the operation was successful. Remember that the name of the user manager (in my example UserManager) can vary depending on your implementation.
I had the same issue and what I ended up using was the
RemoveFromRolesAsync(string userId, params string[] roles) Method
from the UserManager.
Using the role names in an array works.
But has an issue that is if the user is not in one of the roles in the array the user will not be removed from any roles in the array.
All or nothing.
var usr = UserManager.FindById(usrV.ID.ToString());
string[] deleteList;
deleteList= new string[1];
deleteList[0] = "Engineer";
var rresult1 = UserManager.RemoveFromRolesAsync(usr.Id, deleteList);
Hope it helps
You might want to check out this blog post. The ASP.NET team has a sample that includes adding and removing roles from a user.
ASP.NET Identity 2.0: Customizing Users and Roles

How do i insert data already present in one table into another using Entity framework

Hi I have table called Users which already has id of users who are registered.This table is in different database which is named TrackUsers. Now I am using new database called Terms which has field called ID which should take all ID's from users table and insert into this table.For this i used database first approach.
I am using ASP.NET MVC Entity framework. Below is the code I am using in controller :
public class HomeController : Controller
{
private AppMarketplaceEntities db = new AppMarketplaceEntities();
private InstallTrackerEntities db1 = new InstallTrackerEntities();
public ActionResult Index()
{
List<int> gatewayUserId = new List<int>();
using (var ctx = new InstallTrackerEntities())
{
gatewayUserId = ctx.Gateway_Users.Select(f => f.GatewayuserUID).ToList();
}
using (var ctx2 = new AppMarketplaceEntities())
{
foreach (var id in gatewayUserId)
{
ctx2.AppTerms.Add(new AppTerm() { GatewayuserUID = id });
}
db.SaveChanges();
}
return View();
}
}
}
But still GatewayUserUID is showing null in Appterms table.
Assuming you have 2 .edmx files (and therefore different dbcontexts for each database), are you looking for something like this?
List<int> userids = new List<int>();
using(var ctx = new TrackUsersEntities())
{
userids = ctx.Users.Select(f => f.UserId).ToList();
}
using(var ctx2 = new OtherDatabaseEntities())
{
foreach(var id in userids)
{
ctx2.Terms.Add(new Term() { ID = id });
}
ctx2.SaveChanges();
}
As for where to place the code, I'd put it in the Services layer (if it exists), otherwise in the Controller class.

How to properly map entities to domain models in n-tier architecture?

I created a mid-size project following Project Silk's structure. However, I have trouble mapping the entities I retrieve from my repositories into domain model objects for use in the Web project. I have posted a similar question here with all the code and haven't received the help I'm looking for.
My application's architecture follows Project Silk's very closely. The data tier holds the repositories and model POCOs. The Business Logic layer holds the services. Inside these services, we map objects from the Data Tier to the Model objects in the business layer.
internal static Model.User ToDataModelUser(User userToConvert)
{
if (userToConvert == null)
{
return null;
}
Model.User modelUser = new Model.User()
{
UserId = userToConvert.UserId,
AuthorizationId = userToConvert.AuthorizationId,
DisplayName = userToConvert.DisplayName,
Country = userToConvert.Country,
PostalCode = userToConvert.PostalCode,
HasRegistered = userToConvert.HasRegistered,
};
return modelUser;
}
internal static User ToServiceUser(Model.User dataUser)
{
if (dataUser == null)
{
return null;
}
User user = new User()
{
UserId = dataUser.UserId,
AuthorizationId = dataUser.AuthorizationId,
DisplayName = dataUser.DisplayName,
Country = dataUser.Country,
PostalCode = dataUser.PostalCode,
HasRegistered = dataUser.HasRegistered,
};
return user;
}
My question is how do I map objects like this when they have many-to-many relationships? For example, lets say a User has an ICollection Roles. That means my Role has an ICollection Users. When I'm mapping a users via ToDataModelUser or ToServiceUser, I now have a Roles property to populate. Thus the code from above will look like this:
internal static Model.User ToDataModelUser(User userToConvert)
{
if (userToConvert == null)
{
return null;
}
Model.User modelUser = new Model.User()
{
UserId = userToConvert.UserId,
AuthorizationId = userToConvert.AuthorizationId,
DisplayName = userToConvert.DisplayName,
Country = userToConvert.Country,
PostalCode = userToConvert.PostalCode,
HasRegistered = userToConvert.HasRegistered,
Roles = new Collection<Role>()
};
foreach (Role role in userToConvert.Roles)
modelUser.Roles.Add(RoleServies.ToDataModelRole(role));
return modelUser;
}
Now here comes the problem, if you look at RoleServices.ToDataModelRole(Role role) this is what you get:
internal static Model.Role ToDataModelRole(Role roleToConvert)
{
if (roleToConvert == null) return null;
Model.Role role = new Model.Role()
{
Description = roleToConvert.Description,
RoleId = roleToConvert.RoleId,
RoleName = roleToConvert.RoleName,
Users = new Collection<User>()
};
foreach (User user in roleToConvert.Users)
roleToConvert.Users.Add(UserServices.ToDataModelUser(user));
return role;
}
As you can easily see, if you run this you will get a stack overflow error b/c we will be going from User >> Role >> User >> Role >> etc.. when trying to do the mapping. If I don't map the navigation properties, I don't have access to them in the web project. I have a feeling I am totally missing something here.
You could create an overload for the ToDataModelX methods. Pass a Boolean to de/activate the loading of the subordinate object. Instead of always loading the a Role's Users, only load them when directed to do so.
internal static Model.User ToDataModelUser(User userToConvert)
{
return ToDataModelUser(userToConvert, true);
}
internal static Model.User ToDataModelUser(User userToConvert, Boolean loadRoles)
{
if (userToConvert == null)
{
return null;
}
Model.User modelUser = new Model.User()
{
....
Roles = new Collection<Role>()
};
if (loadRoles)
{
foreach (Role role in userToConvert.Roles)
modelUser.Roles.Add(RoleServies.ToDataModelRole(role, false));
}
return modelUser;
}
internal static Model.Role ToDataModelRole(Role roleToConvert)
{
return ToDataModelRole(roleToConvert, true);
}
internal static Model.Role ToDataModelRole(Role roleToConvert, Boolean loadUsers)
{
if (roleToConvert == null) return null;
Model.Role role = new Model.Role()
{
....
Users = new Collection<User>()
};
if (loadUsers)
{
foreach (User user in roleToConvert.Users)
roleToConvert.Users.Add(UserServices.ToDataModelUser(user, false));
}
return role;
}

Resources