Hadeel e

Hadeel e

  • NA
  • 50
  • 6.8k

Generating a user profile in mvc5

Apr 21 2020 5:31 PM

In my app I have a driver users and a customer users(rider), I am trying to create a profile for each one of them. and in my driver model I have the following:


C#
  1. public class DriversModel  
  2.     {  
  3.             [Display(Name ="Id")]  
  4.             public int driverId { getset; }  
  5.   
  6.             [Display(Name = "First Name")]  
  7.             [Required(ErrorMessage = "Pleas Enter Your First Name")]  
  8.             public string firstName { getset; }  
  9.   
  10.             [Display(Name = "Last Name")]  
  11.             [Required(ErrorMessage = "Pleas Enter Your Last Name")]  
  12.             public string lastName { getset; }  
  13.   
  14.             [Display(Name = "Email Address")]  
  15.             [DataType(DataType.EmailAddress)]  
  16.             [Required(ErrorMessage = "Pleas Enter Your Email Address")]  
  17.             [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please Enater a Valid Email Address")]  
  18.             public string email { getset; }  
  19.   
  20.             [Display(Name = "Mobile Number")]  
  21.             [Required(ErrorMessage = "Pleas Enter Your Mobile Number")]  
  22.             public string phoneNumber { getset; }  
  23.   
  24.             [Display(Name = "Address")]  
  25.             [Required(ErrorMessage = "Pleas Enter Your Address")]  
  26.             public string Address { getset; }  
  27.   
  28.             [Display(Name = "City")]  
  29.             [Required(ErrorMessage = "Pleas Enter Your City")]  
  30.             public string city { getset; }  
  31.   
  32.             [Display(Name = "State")]  
  33.             [Required(ErrorMessage = "Pleas Enter Your state")]  
  34.             public string state { getset; }  
  35.   
  36.             [Display(Name = "Car")]  
  37.             [Required(ErrorMessage = "Please Identify Your Car")]  
  38.             public string car { getset; }  
  39.   
  40.             [Display(Name = "Driver's License")]   
  41.             [Required(ErrorMessage = "Please Enter Your Driver's Licende Number")]  
  42.             public string driverslicense { getset; }  
  43.   
  44.   
  45.             [Display(Name ="Profile Image")]  
  46.             [Required]  
  47.             public byte[] profileImg { getset; }  
  48.   
  49.             public string profileImgType { getset; }  
  50.   
  51.             [Display(Name = "License Image")]  
  52.             [Required]  
  53.             public byte[] licenseImg { getset; }  
  54.   
  55.             public string licenseImgType { getset; }  
  56.   
  57.            [Display(Name ="Password")]  
  58.            [DataType(DataType.Password)]  
  59.            [Required(ErrorMessage ="Please Enter a password")]  
  60.            public string PasswordHash { getset; }  
  61.   
  62.     } 

and in the customer model:

  1. public class RidersModel  
  2.     {  
  3.   
  4.        [Display(Name ="Id")]  
  5.        public int usersId { getset; }  
  6.   
  7.   
  8.         [Display(Name = "First Name")]  
  9.         [Required(ErrorMessage = "Pleas Enter Your First Name")]  
  10.         public string firstName { getset; }  
  11.   
  12.         [Display(Name = "Last Name")]  
  13.         [Required(ErrorMessage = "Pleas Enter Your Last Name")]  
  14.         public string lastName { getset; }  
  15.   
  16.         [Display(Name = "Email Address")]  
  17.         [DataType(DataType.EmailAddress)]  
  18.         [Required(ErrorMessage = "Pleas Enter Your Email Address")]  
  19.         [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please Enater a Valid Email Address")]  
  20.         public string email { getset; }  
  21.   
  22.         [Required]  
  23.         [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]  
  24.         [DataType(DataType.Password)]  
  25.         [Display(Name = "Password")]  
  26.         public string Password { getset; }  
  27.   
  28.   
  29.         [Display(Name = "Mobile Number")]  
  30.         [Required(ErrorMessage = "Pleas Enter Your Mobile Number")]  
  31.         public string mobileNumber { getset; }  
  32.   
  33.         [Display(Name = "Address")]  
  34.         [Required(ErrorMessage = "Pleas Enter Your Address")]  
  35.         public string Address { getset; }  
  36.   
  37.         [Display(Name = "City")]  
  38.         [Required(ErrorMessage = "Pleas Enter Your City")]  
  39.         public string city { getset; }  
  40.   
  41.         [Display(Name = "State")]  
  42.         [Required(ErrorMessage = "Pleas Enter Your state")]  
  43.         public string state { getset; }  
  44.   
  45.         [Display(Name = "Zip Code")]  
  46.         [Required(ErrorMessage = "Pleas Enter Your Zip Code")]  
  47.         public int zipCode { getset; }  
  48.     } 

C#

If I want to create a separate profile model for each role (customer/driver), I would include in each model what I want to save foreach user. But I don't know how would I create an action for that modelto generate all the information.?

Further, I want to have at some point the available rides to the driver so he can see which customer has requested him/her. Also, what rides the customer has requested in the customer profile.

I have a rides table in my database that has a relationship to the users/drivers table.it includes:

usersId, driversId, and Date (all as a primary key)
 
Thank You.
 

Answers (3)

1
Ahmed Abdi

Ahmed Abdi

  • 625
  • 1.7k
  • 437.2k
Apr 23 2020 2:37 AM
Sorry for late reply.
I created RoleName class and defined constant strings as role names .
  1. public class RoleName  
  2.    {  
  3.        public const string AdminRoleName = "Administrator";  
  4.        public const string DriverRoleName = "Driver";  
  5.       public const string CustomerRoleName = "Customer";  
  6.    }  
 
so when ever you are going to register driver/customer etc, just pass the rolename in AddToRole method of usermanager  to associate with them, otherwise it will be added as normal users.
  1. UserManager.AddToRole(user.Id, RoleName.DriverRoleName);
1
Ahmed Abdi

Ahmed Abdi

  • 625
  • 1.7k
  • 437.2k
Apr 22 2020 2:31 AM
Hi Hadeel.
You can create the profile(driver/customer) the same way you do when you register user in account controller. Create a viewmodels for each driver/customer and include the RegisterViewmodel defined in AccountViewmodels
  1. [HttpPost]  
  2.        [ValidateAntiForgeryToken]  
  3.        public async Task AddDriver(DriverFormViewModel viewModel)  
  4.        {  
  5.            if (ModelState.IsValid)  
  6.            {  
  7.                var user = new ApplicationUser()  
  8.                {  
  9.                    UserName = viewModel.RegisterViewModel.Email,  
  10.                    Email = viewModel.RegisterViewModel.Email,          
  11.                };  
  12.                var result = await UserManager.CreateAsync(user, viewModel.RegisterViewModel.Password);  
  13.   
  14.                if (result.Succeeded)  
  15.                {    
  16.                    UserManager.AddToRole(user.Id, RoleName.DriverRoleName);                    
  17.                    Driver driver = new Driver()  
  18.                    {  
  19.                       //populate driver  
  20.                    };  
  21.                    UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, driver.Name));  
  22.                 
  23.                    _unitOfWork.Drivers.Add(driver);  
  24.                    _unitOfWork.Complete();  
  25.                    return RedirectToAction("Index""Drivers");  
  26.                }   
  27.                this.AddErrors(result);  
  28.            }            
  29.            // If we got this far, something failed, redisplay form  
  30.            return View("DriverForm", viewModel);  
  31.        }  
 For the available riders extend the applicationuser class by adding "isAvailable" property.
 
0
Hadeel e

Hadeel e

  • 0
  • 50
  • 6.8k
Apr 22 2020 10:55 AM
Thank you so much Ahmed for replying,
Sorry I'm quite new to this type of project
 
now for having the same exist driver model, which for registration. 
Is not that going to add a new role that already exist?
 
In fact, I have added the identity after I created the project(as an existing project) so I'm using identity framework.
inthe original registration action I have the following:
  1. [HttpPost]  
  2.         public ActionResult DriversRegistration(DriversModel driver, IEnumerable<HttpPostedFileBase> images)  
  3.         {  
  4.             var profileImg = images.ElementAt(0);  
  5.             var licenseImg = images.ElementAt(1);  
  6.   
  7.   
  8.             //First check the first Image  
  9.             if (profileImg != null && profileImg.ContentLength > 0)  
  10.             {  
  11.                 driver.profileImgType = profileImg.ContentType;  
  12.                 string fileName = profileImg.FileName;  
  13.                 string pattern = @"([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";  
  14.   
  15.                 Regex rgx = new Regex(pattern);  
  16.   
  17.                 //Get the length of the image in bytes and create that array  
  18.                 driver.profileImg = new byte[profileImg.ContentLength];  
  19.   
  20.                 //fill the array of bytes with the image data  
  21.                 profileImg.InputStream.Read(driver.profileImg, 0, profileImg.ContentLength);  
  22.   
  23.                 //Need to do model state checking here, provided some code for that already  
  24.   
  25.                 ModelState.Clear();  
  26.   
  27.             }  
  28.             //Now check the second Image  
  29.             if (licenseImg != null && licenseImg.ContentLength > 0)  
  30.             {  
  31.                 driver.licenseImgType = licenseImg.ContentType;  
  32.                 string fileName = licenseImg.FileName;  
  33.                 string pattern = @"([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";  
  34.   
  35.                 Regex rgx = new Regex(pattern);  
  36.   
  37.                 //Get the length of the image in bytes and create that array  
  38.                 driver.licenseImg = new byte[licenseImg.ContentLength];  
  39.   
  40.                 //fill the array of bytes with the image data  
  41.                 licenseImg.InputStream.Read(driver.licenseImg, 0, licenseImg.ContentLength);  
  42.   
  43.                 //Need to do model state checking here, provided some code for that already  
  44.   
  45.                 ModelState.Clear();  
  46.   
  47.             }  
  48.             if (ModelState.IsValid)  
  49.             {  
  50.                 DriversTier tier = new DriversTier();  
  51.                 int newID = tier.insertDriver(driver);  
  52.                 driver.driverId = newID;  
  53.   
  54.                  
  55.                 return RedirectToAction("ThankYou""Default");  
  56.             }  
  57.             else  
  58.             {  
  59.                 return View();  
  60.             }  
  61.   
  62.   
  63.         } 
 I also have the quite same action in the admin controller:
  1. [HttpPost]  
  2.    public async Task<ActionResult> CreateDriver(DriversModel driver, IEnumerable<HttpPostedFileBase> images)  
  3.    {  
  4.   
  5.        var profileImg = images.ElementAt(0);  
  6.        var licenseImg = images.ElementAt(1);  
  7.   
  8.   
  9.        //First check the first Image  
  10.        if (profileImg != null && profileImg.ContentLength > 0)  
  11.        {  
  12.            driver.profileImgType = profileImg.ContentType;  
  13.            string fileName = profileImg.FileName;  
  14.            string pattern = @"([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";  
  15.   
  16.            Regex rgx = new Regex(pattern);  
  17.   
  18.            //Get the length of the image in bytes and create that array  
  19.            driver.profileImg = new byte[profileImg.ContentLength];  
  20.   
  21.            //fill the array of bytes with the image data  
  22.            profileImg.InputStream.Read(driver.profileImg, 0, profileImg.ContentLength);  
  23.   
  24.            //Need to do model state checking here, provided some code for that already  
  25.   
  26.            ModelState.Clear();  
  27.   
  28.        }  
  29.   
  30.        if (licenseImg != null && licenseImg.ContentLength > 0)  
  31.        {  
  32.            driver.licenseImgType = licenseImg.ContentType;  
  33.            string fileName = licenseImg.FileName;  
  34.            string pattern = @"([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";  
  35.   
  36.            Regex rgx = new Regex(pattern);  
  37.   
  38.            //Get the length of the image in bytes and create that array  
  39.            driver.licenseImg = new byte[licenseImg.ContentLength];  
  40.   
  41.            //fill the array of bytes with the image data  
  42.            licenseImg.InputStream.Read(driver.licenseImg, 0, licenseImg.ContentLength);  
  43.   
  44.            //Need to do model state checking here, provided some code for that already  
  45.   
  46.            ModelState.Clear();  
  47.   
  48.        }  
  49.        if (ModelState.IsValid)  
  50.        {  
  51.            bool processError = false;  
  52.            var userStore = new UserStore<IdentityUser>();  
  53.            var userManager = new UserManager<IdentityUser>(userStore);  
  54.            string statusMessage = "";  
  55.            IdentityUser theUser = new IdentityUser() { UserName = driver.email, Email = driver.email };  
  56.            IdentityResult theResult = await userManager.CreateAsync(theUser, driver.PasswordHash);  
  57.            DriversTier tier = new DriversTier();  
  58.            int newID = tier.insertDriver(driver);  
  59.            driver.driverId = newID;  
  60.   
  61.            if (theResult == IdentityResult.Success)  
  62.            {  
  63.              //First check to see if User Role exists.  If not create it and add user to User role.  
  64.              var roleStore = new RoleStore<IdentityRole>();  
  65.              var roleManager = new RoleManager<IdentityRole>(roleStore);  
  66.              IdentityRole theRole = await roleManager.FindByNameAsync("Driver");  
  67.   
  68.              if (theRole == null)  
  69.                {  
  70.              //The user role does not exist, create it.  
  71.               theRole = new IdentityRole("Driver");  
  72.               theResult = null;  
  73.               theResult = await roleManager.CreateAsync(theRole);  
  74.   
  75.                if (theResult == null)  
  76.                    {  
  77.                        statusMessage = string.Format("User Group Creation failed because : {0}", theResult.Errors.FirstOrDefault());  
  78.                        //Need to exit nicely here for some reason, we could not create the role with the DB  
  79.                        processError = true;  
  80.                    }  
  81.                }  
  82.   
  83.                if (!processError)  
  84.                {  
  85.                    //The role exists, now add the user to the role  
  86.                    theResult = await userManager.AddToRoleAsync(theUser.Id, "Driver");  
  87.                    statusMessage = string.Format("Identity User {0} was created successfully!<br /> {0} was added to the User group: {1}", theUser.UserName, theResult.Errors.FirstOrDefault());  
  88.                }  
  89.            }  
  90.            else  
  91.            {  
  92.                //could not create a user  
  93.                statusMessage = string.Format("User Creation failed because : {0}", theResult.Errors.FirstOrDefault());  
  94.                processError = true;  
  95.            }  
  96.   
  97.            List<IdentityUser> userList = userManager.Users.ToList<IdentityUser>();  
  98.   
  99.            return RedirectToAction("DisplayDrivers/" + driver.driverId, userList);  
  100.   
  101.        }  
  102.        else  
  103.        {  
  104.   
  105.            return View();  
  106.        }  
  107.    } 
 I know I probably missing some part. But here In the admin controller I have created the role. How would that work with your solution? Can You please explain a little further? 
Thank you.