//[Authorize(Roles = "Admin")]
 public IActionResult Index()
 {
     try
     {
         DomainUserViewModel model = new DomainUserViewModel();
         ApplicationUser     au    = new ApplicationUser();
         au.Mobile      = model.Mobile;
         au.FirstName   = model.FirstName;
         au.LastName    = model.LastName;
         au.UserName    = model.UserName;
         au.PhoneNumber = model.PhoneNumber;
         au.Id          = model.Id;
         return(View(model));
     }
     catch (Exception e)
     {
         Log.Error(e, e.Message);
         return(View("~/Views/Shared/Error.cshtml", new ErrorViewModel {
             RequestId = e.Message
         }));
     }
 }
        private List <DomainUserViewModel> FindAllADUsers(int id, string userName)// GetAllADUsers(int id, string UseName)
        {
            try
            {
                string cipherText = "";
                IQueryable <DomainSetting> domainSetting = _context.DomainSetting.Where(w => w.Id == id);

                var domain = domainSetting.Select(w => new DomainSetting
                {
                    UserName = w.UserName,
                    Server   = w.Server,
                    Title    = w.Title,
                    Password = w.Password
                }).FirstOrDefault();
                string EncryptionKey = "MAKV2SPBNI99212";
                byte[] cipherBytes   = Convert.FromBase64String(domain.Password);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV  = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                List <DomainUserViewModel> lstADUsers     = new List <DomainUserViewModel>();
                DomainUserViewModel        objSurveyUsers = new DomainUserViewModel();
                DomainSettingViewModel     SelectAll      = new DomainSettingViewModel();
                string   dcString = "";
                string   rootNode = "";
                string[] arrString;
                arrString = domain.Title.Split('.');
                if (arrString.Length == 1)
                {
                    dcString = "dc=" + domain.Title + "";
                    rootNode = arrString[0];
                }
                else
                {
                    for (int i = 0; i != arrString.Length; i++)
                    {
                        dcString += "dc=" + arrString[i].ToString() + ",";
                    }
                    if (arrString.Length == 3)
                    {
                        rootNode = arrString[1].ToString();
                    }
                    else if (arrString.Length == 2)
                    {
                        rootNode = arrString[0].ToString();
                    }
                    dcString = dcString.Substring(0, dcString.Length - 1);
                }
                try
                {
                    string DomainPath = "LDAP://" + domain.Server + "/" + dcString;
                    System.DirectoryServices.DirectoryEntry searchRoot = new System.DirectoryServices.DirectoryEntry(DomainPath);
                    searchRoot.Username = domain.UserName;
                    searchRoot.Password = cipherText;
                    DirectorySearcher search = new DirectorySearcher(searchRoot);
                    if (userName == "*")
                    {
                        search.Filter = $"(objectClass=user)";
                    }
                    else
                    {
                        userName      = userName.Split("@")[0];
                        search.Filter = $"(samaccountname=*{userName}*)";
                    }

                    search.PropertiesToLoad.Add("samaccountname");
                    search.PropertiesToLoad.Add("mail");
                    search.PropertiesToLoad.Add("usergroup");
                    search.PropertiesToLoad.Add("displayname"); //first name
                    search.PropertiesToLoad.Add("givenname");   //first name
                    search.PropertiesToLoad.Add("sn");          //first name
                    SearchResult resultFetch;


                    SearchResultCollection resultCol = search.FindAll();
                    if (resultCol != null)
                    {
                        for (int counter = 0; counter < resultCol.Count; counter++)
                        {
                            string UserNameEmailString = string.Empty;
                            resultFetch = resultCol[counter];
                            if (resultFetch.Properties.Contains("samaccountname"))
                            {
                                objSurveyUsers = new DomainUserViewModel();
                                if (resultFetch.Properties.Contains("mail"))
                                {
                                    objSurveyUsers.Email = (String)resultFetch.Properties["mail"][0];
                                }
                                else
                                {
                                    //  objSurveyUsers.Email = (String)resultFetch.Properties["samaccountname"][0] + id.ToString() + "@Pointer.com";
                                }

                                if (resultFetch.Properties.Contains("displayname"))
                                {
                                    objSurveyUsers.DisplayName = (String)resultFetch.Properties["displayname"][0];
                                }
                                else
                                {
                                    objSurveyUsers.DisplayName = (String)resultFetch.Properties["samaccountname"][0];
                                }


                                objSurveyUsers.UserName = (String)resultFetch.Properties["samaccountname"][0];

                                if (resultFetch.Properties.Contains("givenname"))
                                {
                                    objSurveyUsers.FirstName = (String)resultFetch.Properties["givenname"][0];
                                }
                                else
                                {
                                    objSurveyUsers.FirstName = (String)resultFetch.Properties["samaccountname"][0];
                                }
                                if (resultFetch.Properties.Contains("sn"))
                                {
                                    objSurveyUsers.LastName = (String)resultFetch.Properties["sn"][0];
                                }
                                else
                                {
                                    objSurveyUsers.LastName = (String)resultFetch.Properties["samaccountname"][0];
                                }
                                objSurveyUsers.dcString = dcString;
                                lstADUsers.Add(objSurveyUsers);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
                return(lstADUsers);
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                return(null);
            }
        }
        //[Authorize(Roles = "Admin")]
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> Create(DomainUserViewModel model)
        {
            try
            {
                model.message   = "";
                model.IsSuccess = false;
                bool ping = _pingLdap.Ping(model.DomainId, model.UserName);
                if (ping)
                {
                    List <DomainUser>      users            = _findAllADUsers.FindAll(model.DomainId, model.UserName);
                    ApplicationUser        applicationUser  = new ApplicationUser();
                    List <ApplicationUser> applicationUsers = new List <ApplicationUser>();
                    IdentityResult         result           = new IdentityResult();

                    if (users.Count > 0)
                    {
                        foreach (var user in users)
                        {
                            applicationUser.UserName             = user.UserName + "@" + user.dcString.Split("dc=")[1].Replace(",", ".") + user.dcString.Split(",dc=")[1];
                            applicationUser.FirstName            = user.FirstName;
                            applicationUser.LastName             = user.LastName;
                            applicationUser.Email                = user.Email;
                            applicationUser.EmailConfirmed       = true;
                            applicationUser.PhoneNumberConfirmed = true;
                            applicationUser.PhoneNumber          = "-";
                            applicationUser.Mobile               = "-";
                            applicationUser.AddedDate            = DateTime.Now;
                            applicationUsers.Add(applicationUser);
                        }

                        if (ModelState.IsValid)
                        {
                            byte[] salt = new byte[128 / 8];
                            model.PasswordHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                                                            password: "******",
                                                                            salt: salt,
                                                                            prf: KeyDerivationPrf.HMACSHA1,
                                                                            iterationCount: 10000,
                                                                            numBytesRequested: 256 / 8));

                            foreach (var applicationUser1 in applicationUsers)
                            {
                                try
                                {
                                    result = await _userManager.CreateAsync(applicationUser1, model.PasswordHash);

                                    if (result.Succeeded)
                                    {
                                        //if (await _roleManager.FindByNameAsync(model.RoleType.ToString()) == null)
                                        //{

                                        //    await _roleManager.CreateAsync(new ApplicationRole
                                        //    {
                                        //        Name = model.RoleType.ToString(),
                                        //        NormalizedName = model.RoleType.ToString().ToUpper()
                                        //    });
                                        //}

                                        //await _userManager.AddToRoleAsync(applicationUser, model.RoleType.ToString());


                                        var systemRoles = _roleManager.Roles.ToList().Where(x => x.Id == model.RoleId);

                                        var roles = systemRoles.Select(x => x.Name).FirstOrDefault();
                                        if (roles != null)
                                        {
                                            await _userManager.AddToRoleAsync(applicationUser1, roles.ToString());
                                        }

                                        if (Request.Form.Keys.Contains("SaveAndReturn"))
                                        {
                                            model.IsSuccess = true;
                                            model.message   = "Sucsses";
                                            return(View(model));
                                        }
                                    }

                                    else
                                    {
                                        var errors = result.Errors.ToList();
                                        if (errors.Count > 0)
                                        {
                                            foreach (var error in errors)
                                            {
                                                AddErrors(result);
                                            }
                                        }

                                        else
                                        {
                                            model.IsSuccess = false;
                                            model.message   = "Error";
                                            return(View(model));
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    var a = e.Message;
                                }
                            }
                        }
                    }

                    else
                    {
                        var errors = result.Errors.ToList();
                        if (errors.Count > 0)
                        {
                            foreach (var error in errors)
                            {
                                AddErrors(result);
                            }
                        }

                        else
                        {
                            model.IsSuccess = false;
                            model.message   = "Error";
                            return(View(model));
                        }
                    }
                }

                else
                {
                    ModelState.AddModelError("", "دامین غیر فعال است.!");
                }


                return(View(model));
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                return(View("~/Views/Shared/Error.cshtml", new ErrorViewModel {
                    RequestId = e.Message
                }));
            }
        }