public ActionResult DeleteRole(string RoleName, string RoleID)
       {
           ApplicationDbContext context = new ApplicationDbContext();
           DisplayManagerRoleDelete ObjRole = new DisplayManagerRoleDelete();
           ObjRole.MyRoles =  db.AspNetRoles.Where(c => c.Name.Equals(RoleName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
          
           var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
           var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
          // ObjRole.buildingmanager = db.ManagerBuilding.Where(c => c.UserID == c.Manager.ID).ToList();           
           
           List<Manager> list1 = new List<Manager>();
           List<Buildings> ListBuilding = new List<Buildings>();

          // find list all manager
           var objAllManager =  db.Manager.ToList();
          // loop through all manager
           foreach(var item in objAllManager)
           {//list of role that belong to the current user
               var ListofRoleName = userManager.GetRoles(item.AspNetUsers.Id).ToList();
              //loop through all names 
               foreach (var individualRoleName in ListofRoleName)
               {//check if the current role  matches the role passed
                   if (individualRoleName == RoleName)
                   { //if match then load manager 
                       Manager ObjManager = new Manager();
                       ObjManager = db.Manager.Find(item.AspNetUsers.Id);
                      //add manager to myManager List<>
                      // ObjRole.MyManagers.Add(ObjManager);
                       var objmb = db.ManagerBuilding.Where(c => c.UserID == item.AspNetUsers.Id).ToList();
                        foreach(var item2 in objmb)
                        {
                            ListBuilding.Add(item2.Buildings);
                        }

                      list1.Add(ObjManager);
                   }
               }
           }

           ViewBag.Managers = list1;
           ViewBag.Buildings = ListBuilding;



           return View(ObjRole);
       }
       public async Task<ActionResult> AddManager(ManagerVM model)
       {

           ApplicationDbContext context = new ApplicationDbContext();

           var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
           PasswordHasher hasher = new PasswordHasher();
          
           ApplicationUser AppUser = new ApplicationUser(){
           Id = Guid.NewGuid().ToString(),
           Email = model.Email,
           UserName = model.Username,
           SecurityStamp = Guid.NewGuid().ToString(),
           PhoneNumber = model.Phone,
           LockoutEnabled = false,
           AccessFailedCount = 0,
           PhoneNumberConfirmed = false,
           TwoFactorEnabled = false,
           EmailConfirmed = false,
           PasswordHash = hasher.HashPassword(model.Password)
          };
           string[] FullName = model.FullName.Split(new string[] {" "}, StringSplitOptions.None);
           Manager mgr = new Manager() {  
                                       ID = AppUser.Id,  
                                       FirstName=FullName[0].ToString(), 
                                       LastName = FullName[1].ToString(),  
                                       Phone = model.Phone,
                                        ClientID = model.clientID};
           db.Manager.Add(mgr); 
           context.Users.Add(AppUser);
          
           await context.SaveChangesAsync();
           await db.SaveChangesAsync();

           RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
           if(!RoleManager.RoleExists("Manager"))
           {
            var roleresult = RoleManager.Create(new IdentityRole("Manager"));
           }
           var Result = UserManager.AddToRole(AppUser.Id, "Manager");

           DisplayClientBuilding ObjDCB = new DisplayClientBuilding(){
            ManagerID = AppUser.Id, ClientID = model.clientID};

           return RedirectToAction("SelectBuilding", ObjDCB);
       }      
       public async Task<ActionResult> AddManagerTobuilding(ManagementBuilding model, ManagerVM  model2)
        {

            ViewBag.ClientID = db.Buildings.Where(b => b.ID == model.buildingID).FirstOrDefault().Clients.ID;
            ViewBag.BuildingName = db.Buildings.Where(b => b.ID == model.buildingID).FirstOrDefault().BuildingName;

            try
            {
            if (!ModelState.IsValid)
            {
                return View("ManagementBuilding", model);
            }
            ApplicationDbContext context = new ApplicationDbContext();

            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            PasswordHasher hasher = new PasswordHasher();
            var a = UserManager.FindByEmail(model2.Email);
            if (a != null)
            {
                return View("ManagementBuilding", model);
            }
            ApplicationUser AppUser = new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(),
                Email = model2.Email,
                UserName = model2.Username,
                SecurityStamp = Guid.NewGuid().ToString(),
                PhoneNumber = model2.Phone,
                LockoutEnabled = false,
                LockoutEndDateUtc= DateTime.Now.AddDays(365),
                AccessFailedCount = 0,
                PhoneNumberConfirmed = false,
                TwoFactorEnabled = false,
                EmailConfirmed = false,
                PasswordHash = hasher.HashPassword(model2.Password)
            };
            string[] FullName = model2.FullName.Split(new string[] { " " }, StringSplitOptions.None);
            Manager mgr = new Manager()
            {
                ID = AppUser.Id,
                FirstName = FullName[0].ToString(),
                LastName = FullName[1].ToString(),
                Phone = model2.Phone,
                ClientID = model2.clientID
            };
            db.Manager.Add(mgr);
            context.Users.Add(AppUser);

            await context.SaveChangesAsync();
            await db.SaveChangesAsync();

            RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            if (!RoleManager.RoleExists("Manager"))
            {var roleresult = RoleManager.Create(new IdentityRole("Manager"));}
            var Result = UserManager.AddToRole(AppUser.Id, "Manager");

            ManagerBuilding ObjManagerBuilding = new ManagerBuilding()
            {
                 BuildingID = model2.BuildingID,
                  ManagerID = mgr.ID ,
                   UserID =mgr.ID
            };

            db.ManagerBuilding.Add(ObjManagerBuilding);
            await db.SaveChangesAsync();
         

            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
            return RedirectToAction("ManagementBuilding", new { BuildingID=model2.BuildingID});
        }        
       public ActionResult RoleAddToUser(string UserName, string RoleName, string FirstName, string LastName, string Phone)
       {
          
            ApplicationDbContext context = new ApplicationDbContext();
            PointerdbEntities db = new PointerdbEntities();

            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            var CurrentUser = db.AspNetUsers.FirstOrDefault(c => c.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase));

            
            if (CurrentUser == null)
            {
                 ViewBag.Roles  = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
                
                ViewBag.clientlist = db.Clients.Select(c => new SelectListItem { Text = c.ClientName, Value = c.ID.ToString() }).ToList();
                ViewBag.ResultMessage = "There is no user with this Username !";
                return View("ManageUserRoles");
            }
            var currentUserID = CurrentUser.Id;
            var roleresult = UserManager.AddToRole(currentUserID, RoleName);
           
            ViewBag.ResultMessage = "Role created successfully !";

            var ObjisitManager = db.Manager.Find(currentUserID);
            Manager ObjManager = new Manager();
            if (ObjisitManager != null)
            {//update
                // ObjManager.ID = ObjisitManager.ID;
                //ObjManager.FirstName = ObjisitManager.FirstName;
                //ObjManager.LastName = ObjisitManager.LastName;
                //ObjManager.Phone = ObjisitManager.Phone;
                //db.Manager.Attach(ObjManager);
                //var Entry = db.Entry(ObjManager);
                //Entry.Property(c => c.FirstName).IsModified = true;
                //Entry.Property(c => c.LastName).IsModified = true;
                //Entry.Property(c => c.Phone).IsModified = true;
            }
            else 
            {//insert
                ObjManager.ID = currentUserID;
                ObjManager.FirstName = FirstName;
                ObjManager.LastName = LastName;
                ObjManager.Phone = Phone;
                db.Manager.Add(ObjManager);
                db.SaveChanges();
            }



           

           // prepopulat roles for the view dropdown
          ViewBag.Roles  = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
           ViewBag.clientlist = db.Clients.Select(c => new SelectListItem { Text = c.ClientName, Value = c.ID.ToString() }).ToList();
           return View("ManageUserRoles");
       }