Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
I have registartion and login form in my project for the user can registor and log in. I have cretaed user module, view, and controller.I have faced a problem when I tried to add role on it and try to intialzie membership. I need to add a role for user and adminstrator. how do i do it? than you for your help

// in my modeule I have
C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace BootstrapPager.Models
{
    public class User
    {
        [Required]
        public virtual int Id { get; set; }
        [Required]
        [Display(Name = "First Name")]
        public virtual string FirstName { get; set; }
        [Required]
        [Display(Name = "Last Name")]
        public virtual string LastName { get; set; }
        [Required]
        [Display(Name = "Username")]
        public virtual string UserName { get; set; }

        [Required]
        [Display(Name = "Email Address")]
        [DataType(DataType.EmailAddress)]
        [RegularExpression("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$", ErrorMessage = "Please enter a valid Email Address")]
        public virtual string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public virtual string Password { get; set; }

        [Required]
        [NotMapped]
        [Display(Name = "Confirm Password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
        [Required]
        [Display(Name = "Address")]
        public string Address { get; set; }

        [Required]
        [Display(Name = "Country")]
        public string Country { get; set; } 
         [Required]
        [Display(Name = "City")]
        public string City { get; set; }
         [Required]
        [Display(Name = "State")]
        public string State { get; set; }
         [Required]
        [Display(Name = "Zip")]
        public string Zip { get; set; }





        
        //public virtual ICollection<RSVP> RSVPs { get; set; }
    }

    public class Login
    {
        [Required]
        [Display(Name = "Username")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }


}

C#
// in my conroller
<pre lang="c#">using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BootstrapPager.Models;
using Microsoft.VisualBasic;

namespace BootstrapPager.Controllers
{
    public class UserController : Controller
    {
        private EmployeeDb db = new EmployeeDb();

        //
        // GET: /User/

        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // GET: /User/Create
        
        public ActionResult Create()
        {
            //if (Session["user"] != null)
            //{
                
            //    return View();
            //}
            //else { return Content("Please Login First"); }
            return View();
        }

        //
        // POST: /User/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(User user)
        {
            if (ModelState.IsValid)
            {
                //User users = (User)db.Users.Where((a => a.Email == user.Email) || );
                //var email = from a in db.Users
                //             where a.Email == user.Email
                //             select a.Email;
                //var username = from a in db.Users
                //               where a.UserName == user.UserName
                //               select a.UserName;
               
                //if ( email.Count() == 0 && username.Count() == 0 )
                //{
                    db.Users.Add(user);
                    db.SaveChanges();
                    // return Redirect("Home/Index");
                    return RedirectToAction("Index", "Home");
            //    }
            //    else
            //    {
            //        if (email.Count() != 0)
            //            ModelState.AddModelError("Email", "Email address already exists. Try another email address.");
            //        if ( username.Count() != 0)
            //        {
            //            ModelState.AddModelError("UserName", "Username already exists. Try another username." );
            //        }
            //    }
            }

            return View(user);
        }

        public ActionResult Login()
        {
            ViewBag.login = true;
            return View();
        }

        [HttpPost]
        public ActionResult Login(Login login)
        {
            //ViewBag.login = false;
            if (ModelState.IsValid)
            {
                var user = db.Users.Where( a=>a.UserName == login.UserName && a.Password == login.Password);

                if ( user.Count() != 0 )
                {
                    User loginuser = db.Users.FirstOrDefault(a => a.UserName == login.UserName);
                    Session["login"] = "true";
                    
                    Session["username"] = login.UserName;
                    Session["userid"] = loginuser.Id; 
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewBag.login = false;
                }
            }
            else
            {
                ViewBag.login = true;
            }
            return View(login);
        }

        public ActionResult Logout()
        {
            Session["username"] = null;
            Session["userid"] = null; 
            Session["login"] = "false";
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult UserProfile( string name )
        {
           
            User user = db.Users.FirstOrDefault( a => a.UserName == name);
            return View(user);
        }

        //
        // GET: /User/Edit/5

        public ActionResult Edit(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        //
        // GET: /User/Delete/5

        public ActionResult Delete(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /User/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
Posted
Updated 1-Jun-14 1:40am
v4
Comments
[no name] 1-Jun-14 7:23am    
You did not tell us what the problem is. And whatever the problem actually is, does all of this unformatted code really have anything at all to do with your problem?
Member 10651775 1-Jun-14 8:02am    
sorry I forgeted to format it, I just formated it. the poblem is I want add rolle on the system for user and adminstartion. I tried to add but that did not work.

1 solution

In my article Drag And Drop Role Management with Asp.Net, MVC & jQuery[^] you can see how I check the role the current user has to see if they have the authority to run the action.

During the initialisation of the system you can add the roles into the database by calling a method in the global.asax Application_Start;

Obviously you would do this on the first run just to set things up. Later on you can either comment this out or do some logic checking to see if the roles or user accounts already exist.
C#
protected void Application_Start()
{

    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    //Initialise the Database
    //Database.SetInitializer(new DropCreateDatabaseAlways<TM470Project.DBContexts.DrillingDailyReportsDBContext>());
    //Database.SetInitializer(new DropCreateDatabaseAlways<TM470Project.DBContexts.KPIDailyDBContext>());


    //Initialise the user database Roles - Note:Set to true only during dev when cleaning up old roles being removed.
    InitialiseRoles(false);

    //Initialise the default SuperUser + Guest Account
    InitialiseDefaultUsers();

    //Use the new combined context for the intialiser
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TM470Project.DBContexts.CombinedDBContext>());

}


then the two methods are
C#
private void InitialiseRoles(Boolean DeleteExistingRoles)
        {

            if (DeleteExistingRoles)
            {
                //Delete All Existing Roles
                //Get list of Roles
                String[] oldRoles = Roles.GetAllRoles();

                foreach (String role in oldRoles)
                {
                    //Get all the usernames with Role
                    String[] users = Roles.GetUsersInRole(role);

                    //Remove all the users from Role
                    foreach (String user in users)
                    {
                        Roles.RemoveUserFromRole(user, role);
                    }

                    //Delete the Role
                    Roles.DeleteRole(role);

                }
            }

            //Roles list to be used by application
            String[] NewRoles = new String[] {"KPI-Daily-View","KPI-Daily-Create", "KPI-Daily-Edit", "KPI-Daily-Delete", "KPI-Losses-View","KPI-Losses-Create","KPI-Losses-Edit","KPI-Losses-Delete", "Drilling-Report-View","Drilling-Report-Create","Drilling-Report-Edit","Drilling-Report-Delete", "Admin-User-View","Admin-User-Add","Admin-User-Edit","Admin-User-Delete","Admin-User-ChangePassword", "Admin-Assets-View","Admin-Assets-Create","Admin-Assets-Edit","Admin-Assets-Delete"};

            //Check if role exists and add if not
            foreach (String role in NewRoles)
            {
                if (!Roles.RoleExists(role))
                {
                    Roles.CreateRole(role);
                }
            }
        }


You can then add the default users onto the system by doing;
C#
private void InitialiseDefaultUsers()
        {
            MembershipUser user = null;

            //Default SuperUser Account
           user = Membership.GetUser("SuperUser");
           if (user == null)
           {
               //Account does not exist
               Membership.CreateUser("SuperUser", "ThePassword","SuperUser@the-email.net");
           }

           //Check the SuperUser account has all roles
           String[] roles = Roles.GetAllRoles();
           foreach (String role in roles)
           {
               if (!(Roles.IsUserInRole("SuperUser", role)))
               {
                   Roles.AddUserToRole("SuperUser", role);
               }
           }

            //Default Guest Account
           user = Membership.GetUser("Guest");
           if (user==null)
           {
               //Account does not exist
               Membership.CreateUser("Guest", "guest-password", "guest@the-email.net");
           }

            //Add roles to Guest Account
            String[] guestRoles = new String[] {"KPI-Daily-View","KPI-Losses-View","Drilling-Report-View"};
            foreach (String role in guestRoles)
            {
                if (!(Roles.IsUserInRole("Guest", role)))
                {
                    Roles.AddUserToRole("Guest", role);
                }
            }

        }


Note: the code above is from my OU project that the drag and drop article was also based on, hence all those different roles for the different things the application was doing.
 
Share this answer
 
v2
Comments
Member 10651775 4-Jun-14 14:52pm    
thank you so much

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900