public static void createUsers(string domain, string ou, int numOfUsers) { ContextType contextType = ContextType.Domain; using (PrincipalContext ctx = new PrincipalContext(contextType, domain, ou)) { for(int i=0; i<numOfUsers; i++) { try { UserPrincipal userPrincipal = new UserPrincipal(ctx); userPrincipal.Surname = SampleData.GetSampleValueRandom(SampleData.LastNames); userPrincipal.GivenName = SampleData.GetSampleValueRandom(SampleData.FirstNames); ; userPrincipal.SamAccountName = userPrincipal.GivenName.ToLower() + "." + userPrincipal.Surname.ToLower(); userPrincipal.Name = userPrincipal.GivenName + " " + userPrincipal.Surname; userPrincipal.DisplayName = userPrincipal.GivenName + " " + userPrincipal.Surname; string pwdOfNewlyCreatedUser = "******"; userPrincipal.SetPassword(pwdOfNewlyCreatedUser); userPrincipal.Enabled = true; userPrincipal.PasswordNeverExpires = true; userPrincipal.Save(); } catch (Exception ex) { Errors.Log(ex); } } } }
//BASARSE EN ESTO PARA ARREGLAR TODO LO QUE SEA CON EL AD //Una mejor manera de hacerlo http://johnbarquin.wordpress.com/2008/06/12/servicios-de-directorio-en-net-35/ /// <summary> /// Método que se encarga de crear un usuario estudiante en Active Directory /// </summary> /// <param name="estudiante"> /// Los datos del estudiante (en un tipo Usuario) por ingresar a Active Directory /// </param> public Boolean crearEstudiante2(Usuario estudiante) { String nombre_completo = estudiante.Carnet + " " + estudiante.Nombre + " " + estudiante.Apellidos + " " + estudiante.Carrera; try { PrincipalContext contextoDominio = new PrincipalContext(ContextType.Domain, Constantes.DOM, Constantes.AD_USER, Constantes.AD_PASS); UserPrincipal usuario = new UserPrincipal(contextoDominio, estudiante.UID, estudiante.Contrasena, true); usuario.SamAccountName = estudiante.UID;// LEGACY: Cuenta de estudiante Pre-Win2000 usuario.UserPrincipalName = estudiante.UID + Constantes.DOMINIO;//Debe de contener el dominio usuario.GivenName = estudiante.Nombre; usuario.Surname = estudiante.Apellidos; usuario.DisplayName = nombre_completo; usuario.Description = "Estudiante"; usuario.HomeDirectory = getHomeDirectoryAD(estudiante); usuario.EmailAddress = estudiante.Correo; usuario.HomeDrive = "M"; usuario.PasswordNeverExpires = true; usuario.Save(); usuario.SetPassword(estudiante.Contrasena); usuario.Save(); return true; } catch (Exception e) { _conexionBD = new ManejoBD(); _conexionBD.insertarBitacoraError(e.ToString(), ""); return false; } }
public static void AddUser(SBSUser user) { UserPrincipal userPrincipal = new UserPrincipal(Context); //if (lastName != null && lastName.Length > 0) userPrincipal.Surname = user.UserName; //if (firstName != null && firstName.Length > 0) userPrincipal.GivenName = user.UserName; //if (employeeID != null && employeeID.Length > 0) // userPrincipal.EmployeeId = employeeID; //if (emailAddress != null && emailAddress.Length > 0) userPrincipal.EmailAddress = user.Email; //if (telephone != null && telephone.Length > 0) // userPrincipal.VoiceTelephoneNumber = telephone; //if (userLogonName != null && userLogonName.Length > 0) userPrincipal.SamAccountName = user.UserName; string pwdOfNewlyCreatedUser = user.PassWord; userPrincipal.SetPassword(pwdOfNewlyCreatedUser); userPrincipal.Enabled = true; userPrincipal.ExpirePasswordNow(); userPrincipal.Save(); }
private static User UserPrincipalToUser(UserPrincipal userPrincipal) { if (userPrincipal == null) throw new ArgumentNullException("userPrincipal"); // Uses most of the built-in properties available as part of the UserPrincipal Object // https://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal return new User { // ReSharper disable once PossibleInvalidOperationException // This should only be null when the context type is Machine UserId = userPrincipal.Guid.GetValueOrDefault(), UserPrincipalName = userPrincipal.UserPrincipalName, NtUserName = userPrincipal.SamAccountName, DistinguishedName = userPrincipal.DistinguishedName, AccountIsLocked = userPrincipal.IsAccountLockedOut(), AccountIsEnabled = userPrincipal.Enabled, AccountIsExpired = userPrincipal.AccountExpirationDate.HasValue && userPrincipal.AccountExpirationDate.Value <= DateTime.UtcNow, AccountWillExpire = userPrincipal.AccountExpirationDate.HasValue, AccountExpirationDate = userPrincipal.AccountExpirationDate, //PasswordIsExpired // TODO: Needs directory information to determine PasswordWillExpire = userPrincipal.PasswordNeverExpires, // TODO: This is not definitive, just a high level check //PasswordExpirationDate // TODO: Needs directory information to determine PasswordLastSetDate = userPrincipal.LastPasswordSet, FirstName = userPrincipal.GivenName, MiddleName = userPrincipal.MiddleName, LastName = userPrincipal.Surname, DisplayName = userPrincipal.DisplayName, Email = userPrincipal.EmailAddress }; }
public static bool adIsUserInAdGroupsBool(string sUserId, string sGroupOrUserListSemiColon) { //check if user has SAM acct System.DirectoryServices.AccountManagement.UserPrincipal ctx = adGetUserPrincipalBySAMAccountName(sUserId); if (ctx == null) { return(false); } //check if sUserId is in sGroupOrUserListSemiColon string[] lstGroupsAndUsers = sGroupOrUserListSemiColon.Split(new char[] { ';' }); for (int i = 0; i < lstGroupsAndUsers.Length; i++) { if (sUserId.IndexOf(lstGroupsAndUsers[i]) > -1) { return(true); } } //check if any groups is in sGroup foreach (GroupPrincipal group in ctx.GetGroups().OrderBy(x => x.Name)) { for (int i = 0; i < lstGroupsAndUsers.Length; i++) { if (group.Name == lstGroupsAndUsers[i]) { return(true); } } } return(false); }
/// <summary> /// Gets a list of enabled users in Active Directory /// </summary> /// <param name="domain"></param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public static List<Users> GetEnabledUsers() { List<Users> enabledUsers = new List<Users>(6000); using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Config.ServiceSettings.PrimaryDC, Config.ServiceSettings.Username, Config.ServiceSettings.Password)) { using (UserPrincipal up = new UserPrincipal(pc)) { up.Enabled = false; using (PrincipalSearcher ps = new PrincipalSearcher(up)) { PrincipalSearchResult<Principal> results = ps.FindAll(); foreach (Principal r in results) { enabledUsers.Add(new Users() { UserGuid = (Guid)r.Guid, DisplayName = r.DisplayName, UserPrincipalName = r.UserPrincipalName, SamAccountName = r.SamAccountName, DistinguishedName = r.DistinguishedName, IsEnabled = false }); } } } } return enabledUsers; }
/// <summary> /// To Create users /// </summary> /// <param name="txt">textbox to warnings</param> /// <param name="userLogonName">username</param> /// <param name="userPassword"></param> /// <param name="datetime">account expiration date</param> /// <returns>true if users if deleted sucessfully </returns> public void CreateUser(StringBuilder sb, string userLogonName, string userPassword) { // Creating the PrincipalContext PrincipalContext principalContext = null; principalContext = context; // Check if user object already exists in the store UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, userLogonName); if (usr == null){ // Create the new UserPrincipal object UserPrincipal userPrincipal = new UserPrincipal(context); // username userPrincipal.SamAccountName = userLogonName; // Expiring date // userPrincipal.AccountExpirationDate = datetime; //Password userPrincipal.SetPassword(userPassword); //Activate the account userPrincipal.Enabled = true; //cant change the password userPrincipal.UserCannotChangePassword = true; userPrincipal.Save(); } }
private static void Main(string[] args) { var repository = new Repository(); repository.CreateDatabase(); using (var context = new PrincipalContext(ContextType.Domain, "infotecs-nt", "lr.knowledge.base", ",jrcnfgjx")) { UserPrincipal u = new UserPrincipal(context); PrincipalSearcher search = new PrincipalSearcher(u); foreach (UserPrincipal result in search.FindAll()) { repository.AddUsers(new[] { new User() { FirstName = result.DisplayName ?? string.Empty, LastName = string.Empty, MiddleName = string.Empty, ActiveDirectoryId = @"infotecs-nt\" + result.SamAccountName, IsManager = result.IsManager() } }); Console.WriteLine(string.Format("Добавлен пользователь: {0}", result.DisplayName)); repository.Save(); } } }
public void When_Creating_Home_Directory__Then_It_Should_Have_The_Appropriate_Rights() { var username = string.Format("testUser{0}", DateTime.Now.Millisecond); var administration = new AdministrationService(); var context = new PrincipalContext(ContextType.Machine); var user = new UserPrincipal(context) { Name = username, UserCannotChangePassword = false, PasswordNeverExpires = true, }; user.SetPassword("!Password123"); user.Save(); GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, "IIS_IUSRS"); if (grp != null) { grp.Members.Add(user); grp.Save(); } Assert.IsNotNull(grp); string dir = Path.Combine(ConfigurationManager.AppSettings["HomeDirectory"], username); administration.MkDir(username, dir); bool exists = Directory.Exists(dir); Assert.IsTrue(exists); Directory.Delete(dir); user.Delete(); }
public ILdapUser CastLdapUser(UserPrincipal userPrincipal) { var _user = new LdapUser(); _user.Guid = userPrincipal.Guid.Value; _user.Sid = userPrincipal.Sid.ToString(); _user.Name = userPrincipal.Name; _user.SamAccountName = userPrincipal.SamAccountName; _user.DisplayName = userPrincipal.DisplayName; _user.Description = userPrincipal.Description; _user.DistingueshedName = userPrincipal.DistinguishedName; _user.UserPrincipalName = userPrincipal.UserPrincipalName; _user.EmployeeId = userPrincipal.EmployeeId; _user.Email = userPrincipal.EmailAddress; DirectoryEntry _userDE = GetDirectoryEntry(userPrincipal); if (_userDE != null) { var _whenCreated = GetProperty(_userDE, "whenCreated"); _user.Created = (DateTime)GetProperty(_userDE, "whenCreated"); var _whenChanged = GetProperty(_userDE, "whenChanged"); _user.Updated = (DateTime)GetProperty(_userDE, "whenChanged"); } return _user; }
public List<User> FindByName(string pattern) { UserPrincipal filterCriteria = new UserPrincipal(context); filterCriteria.Name = pattern; return FindMatching(filterCriteria); }
public bool CreateUserPrincipal() { // Create connection to domain and do a search for the user try { context = new PrincipalContext(ContextType.Domain, givenDomain); UserPrincipal tempUserPrincipal = new UserPrincipal(context); tempUserPrincipal.SamAccountName = givenUserName; // Search for user PrincipalSearcher searchUser = new PrincipalSearcher(); searchUser.QueryFilter = tempUserPrincipal; UserPrincipal foundUser = (UserPrincipal)searchUser.FindOne(); userPrincipal = foundUser; userGroups = userPrincipal.GetGroups(); return true; } catch (PrincipalServerDownException) { System.Windows.Forms.MessageBox.Show("Cannot contact the server."); return false; } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message, "Unknown Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return false; } }
public void CreateMany(string userNamePrefix, int usernameSuffix, int teamId, string password, int port, string userGroupName, string userNames, bool disablepwchange, bool pwneverexpires) { GroupPrincipal group = GroupPrincipal.FindByIdentity(context, userGroupName); string[] studentNames = userNames.Replace(Environment.NewLine, "").Split(',').Select(x => x.Trim()).ToArray(); string usernamePrefix = userNamePrefix.Replace(" ", ""); string username = usernamePrefix + usernameSuffix; string description = "Bruger oprettet med UserHelper"; string physicalPath = "C:\\inetpub\\wwwroot\\" + username + "\\"; try { for (int i = 0; i < studentNames.Length; i++) { UserPrincipal user = new UserPrincipal(context); UserManagement management = new UserManagement(user, group); //Create Windows User management.CreateLocalWindowsAccount(username, password, username, description, disablepwchange, pwneverexpires, user); management.AddUserToGroup(group, user); //Create IIS Website iis.CreateWebsite(username, "DefaultAppPool", "*:" + port + ":", physicalPath); //Create FTP Virtual Directory //txtStatusMessages.Text += iis.CreateFTPVDir("localhost", username, physicalPath, username); iis.CreateVirtualDirectory("_FTP", username, physicalPath); //create databases sql.CreateSQLLoginUserAndDatabase(username, username, password); Credentials cred = new Credentials(); cred.DatabaseUserName = username; cred.DatabasePassword = password; cred.FTPUserName = username; cred.FTPPassword = password; cred.WebsitePort = port; cred.WindowsUserGroupName = group.Name; Student student = new Student(); student.Name = studentNames[i]; student.Team = db.Teams.Find(teamId); student.Credentials = cred; db.Students.Add(student); //Change username and port for next iteration usernameSuffix++; username = usernamePrefix + usernameSuffix; physicalPath = "C:\\inetpub\\wwwroot\\" + username + "\\"; port++; } db.SaveChanges(); BatchState.State = UserProcessState.INITIAL; //done } catch (Exception) { throw; } }
/// <summary> /// List all accounts in the Active Directory /// </summary> /// <param name="domain">Domain</param> private static void ListAllAccounts(string domain) { try { // Construct context to query your Active Directory using (var context = new PrincipalContext(ContextType.Domain, domain)) { // Construct UserPrincipal object for this context var userPrincipal = new UserPrincipal(context); // Search and find every user in the system – PrincipalSearcher instance for what we need! using (var searcher = new PrincipalSearcher(userPrincipal)) { var counter = 0u; // Iterate for all users in AD foreach (var result in searcher.FindAll()) { counter++; var de = result.GetUnderlyingObject() as DirectoryEntry; var samAccountName = de.Properties["samAccountName"].Value; var active = IsUserActiveInAD(de); Console.WriteLine("{0}: {1} - {2}", counter, samAccountName, active ? "Yes" : "No"); } } } } catch (PrincipalServerDownException ex) { Console.WriteLine(string.Format("Unable to lookup domain: {0}\r\n{1}", domain, ex.ToString())); } }
static void Main(string[] args) { //string connectionEmployeeDatabase = "DSN=Test;Uid=walden;Pwd=walden"; string connectionMessagingDatabase = "Server=COS-DEV01\\SQLEXPRESS;Database=Messaging;Uid=sa;Pwd=0Griswold;"; List<EBSEmployee> employeeDataList = new List<EBSEmployee>(); EBSEmployee employeeData = new EBSEmployee(); var principalContext = new PrincipalContext(ContextType.Domain, "ct-ortho.com"); UserPrincipal userPrin = new UserPrincipal(principalContext); var searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher(); searcher.QueryFilter = userPrin; var results = searcher.FindAll(); foreach (Principal p in results) { UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, p.SamAccountName); employeeData = new EBSEmployee(); if (string.IsNullOrEmpty(userPrincipal.GivenName)) { employeeData.FirstName = string.Empty; } else { employeeData.FirstName = userPrincipal.GivenName; } if (string.IsNullOrEmpty(userPrincipal.Surname)) { employeeData.LastName = string.Empty; } else { employeeData.LastName = userPrincipal.Surname; } if (string.IsNullOrEmpty(p.SamAccountName)) { employeeData.UserName = string.Empty; } else { employeeData.UserName = p.SamAccountName; } employeeData.UserID = p.Guid.ToString(); if (CheckToSeeIfUserExists(connectionMessagingDatabase, p.Guid.ToString())) { UpdateEmployeeRecords(connectionMessagingDatabase, employeeData); } else { InsertEmployeeRecords(connectionMessagingDatabase, employeeData); } } }
public List<User> FindAllEnabledWithEmails() { UserPrincipal filterCriteria = new UserPrincipal(context); filterCriteria.Enabled = true; List<User> users = FindMatching(filterCriteria); users.RemoveAll( (User user) => user.EmailAddress == null || user.EmailAddress.Trim().Length == 0 ); return users; }
public void Init(UserPrincipal up) { this.Name = up.Name; this.Alias = up.SamAccountName; // todo ; get the domain using a clean way this.Domain = up.DistinguishedName.Split(',')[2].Substring(3); // DistinguishedName = "CN=Guillaume Grosbois,OU=UserAccounts,DC=redmond,DC=corp,DC=microsoft,DC=com" }
protected void UpdateUser(UserPrincipal up, UserInfo user) { user.Name = up.DisplayName; user.Email = up.EmailAddress; user.Active = true; foreach (var g in up.GetGroups()) { user.MemberOf.Add(g.SamAccountName); } user.ExtId = up.DistinguishedName; }
/// <summary> /// Create a local user on the machine /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <remarks>Has to be run as an Admin</remarks> public static void CreateLocalUser(string userName, string password) { DeleteLocalUser(userName); UserPrincipal newUser = new UserPrincipal(new PrincipalContext(ContextType.Machine)); newUser.SetPassword(password); newUser.Name = userName; newUser.Description = "New test User"; newUser.UserCannotChangePassword = true; newUser.PasswordNeverExpires = false; newUser.Save(); }
public Task<List<User>> GetAllUsers() { using (var ctx = _directoryContext.LoadAndConnect()) { var filter = new UserPrincipal(ctx) { DisplayName = "*", Enabled = true }; using (var search = new PrincipalSearcher(filter)) { var users = search.FindAll().OfType<UserPrincipal>().AsUserList(); return Task.FromResult(users); } } }
public List<string> GetAllUsers(string term) { using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { UserPrincipal qbeUser = new UserPrincipal(context); qbeUser.SamAccountName = "*" + term + "*"; PrincipalSearcher search = new PrincipalSearcher(qbeUser); var users = search.FindAll(); var result = users.Select(p => p.Name).ToList(); return result; } }
public UserAuthenticatorFixture() { var identity = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Machine), IdentityType.SamAccountName, "adtest"); if (identity == null) { var principal = new UserPrincipal(new PrincipalContext(ContextType.Machine)); principal.SamAccountName = "adtest"; principal.DisplayName = "ad test"; principal.Save(); principal.SetPassword("password"); } }
public void RemoveWindowsAccount(UserPrincipal user) { try { user.Delete(); BatchState.State = UserProcessState.WIN_DELETE_OK; } catch (Exception) { BatchState.State = UserProcessState.WIN_DELETE_ERROR; throw; } }
private void ListUsers() { UserPrincipal ObjectUserPrincipal = new UserPrincipal(insPrincipalContext); ObjectUserPrincipal.Name = "*"; PrincipalSearcher ObjectPrincipalSearcher = new PrincipalSearcher(); ObjectPrincipalSearcher.QueryFilter = ObjectUserPrincipal; PrincipalSearchResult<Principal> SearchResults = ObjectPrincipalSearcher.FindAll(); ADUsersComboBox.Items.Clear(); foreach (Principal p in SearchResults) { ADUsersComboBox.Items.Add(p); } }
private void buttonSearch_Click(object sender, EventArgs e) { try { if (textBoxSearch.TextLength > 0) { List<string> Domain = new List<string>(); List<Users> users = new List<Users>(); Domain.Add("prd.manulifeusa.com"); Domain.Add("MLIDDOMAIN1"); foreach(string domain in Domain) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain); UserPrincipal up = new UserPrincipal(ctx); up.DisplayName = "*" + textBoxSearch.Text + "*"; //up.SamAccountName = "*" + textBoxSearch.Text + "*"; PrincipalSearcher search = new PrincipalSearcher(up); //foreach (Principal p in search.FindAll().OrderBy(a=> a.DisplayName)) foreach (Principal p in search.FindAll()) { var FoundUser = p as UserPrincipal; Users user = new Users(); user.UserName = p.SamAccountName; user.AccountName = p.SamAccountName; user.DisplayName = FoundUser.DisplayName; user.Email = FoundUser.EmailAddress; user.LastName = FoundUser.Surname; user.FirstName = FoundUser.GivenName; user.Domain = domain; users.Add(user); } } dataGridViewUsers.DataSource = users.OrderBy(a=>a.DisplayName).ToList(); } } catch (Exception) { throw; } }
public void AddUserToGroup(GroupPrincipal group, UserPrincipal user) { //now add user to "Users" group so it displays in Control Panel try { group.Members.Add(user); group.Save(); BatchState.State = UserProcessState.WIN_GROUP_OK; } catch (Exception) { BatchState.State = UserProcessState.WIN_GROUP_ERROR; throw; } }
public List<User> FindMatching(UserPrincipal filterCriteria) { List<User> results = new List<User>(); PrincipalSearcher principalSearcher = new PrincipalSearcher(); principalSearcher.QueryFilter = filterCriteria; PrincipalSearchResult<Principal> principals = principalSearcher.FindAll(); foreach (UserPrincipal userPrincipal in principals) { results.Add(new User(userPrincipal)); } results = results ?? new List<User>(); return results; }
protected void Page_Load(object sender, EventArgs e) { if ( !IsPostBack ) { fname.Attributes.Add( "readonly", "readonly" ); lname.Attributes.Add( "readonly", "readonly" ); email.Focus(); populate(); foreach ( ListItem room in epaRoomNums ) { epaRooms.Items.Add( room ); } foreach ( ListItem room in kRoomNums ) { kRooms.Items.Add( room ); } foreach ( ListItem room in epaTrainNums ) { epaTraining.Items.Add( room ); } using ( PrincipalContext pc = new PrincipalContext( System.DirectoryServices.AccountManagement.ContextType.Domain, "ITSERVICES" ) ) { using ( UserPrincipal user = new UserPrincipal( pc ) ) { user.EmailAddress = "*"; using ( PrincipalSearcher ps = new PrincipalSearcher() ) { ps.QueryFilter = user; ((DirectorySearcher)ps.GetUnderlyingSearcher()).PageSize = 500; PrincipalSearchResult<Principal> psr = ps.FindAll(); AD_Users = new string[psr.Count()]; int i = 0; foreach ( UserPrincipal u in psr ) { AD_Users[i++] = u.EmailAddress.Split('@')[0]; } } } } //Debug_FillForm(); } }
public LocalPrincipalData CreateUser(string userName) { string rvUserName = null; string rvPassword = null; LocalPrincipalData rv = null; using (var context = new PrincipalContext(ContextType.Machine)) { bool userSaved = false; ushort tries = 0; UserPrincipal user = null; do { try { rvPassword = Membership.GeneratePassword(8, 2).ToLowerInvariant() + Membership.GeneratePassword(8, 2).ToUpperInvariant(); user = new UserPrincipal(context, userName, rvPassword, true); user.DisplayName = "Warden User " + userName; user.Save(); userSaved = true; } catch (PasswordException ex) { log.DebugException(ex); } ++tries; } while (userSaved == false && tries < 5); if (userSaved) { rvUserName = user.SamAccountName; var groupQuery = new GroupPrincipal(context, IIS_IUSRS_NAME); var searcher = new PrincipalSearcher(groupQuery); var iisUsersGroup = searcher.FindOne() as GroupPrincipal; iisUsersGroup.Members.Add(user); iisUsersGroup.Save(); rv = new LocalPrincipalData(rvUserName, rvPassword); } } return rv; }
public ActionResult GetManager() { //This came from Ignacio's code, I am assumign it is the name the user has given as a search tool var search = Request.Params["id"]; System.Diagnostics.Debug.WriteLine(search.Split(' ')[0]); System.Diagnostics.Debug.WriteLine(search.Split(' ')[1]); PrincipalContext prinCon = new PrincipalContext(ContextType.Domain); UserPrincipal query = new UserPrincipal(prinCon); query.GivenName = search.Split(' ')[0]; query.Surname = search.Split(' ')[1]; System.Diagnostics.Debug.WriteLine(query.GivenName); System.Diagnostics.Debug.WriteLine(query.Surname); PrincipalSearcher searcher = new PrincipalSearcher(query); List<String> firstName = new List<String>(); List<String> lastName = new List<String>(); List<String> userName = new List<String>(); foreach (UserPrincipal result in searcher.FindAll()) { firstName.Add(result.GivenName); lastName.Add(result.Surname); userName.Add(result.UserPrincipalName); }; //data contains an array of result users var data = new { items = new[] { new { key = 1, firstname = firstName[0], lastname = lastName[0], username = userName[0] }, new { key = 2, firstname = firstName[1], lastname = lastName[1], username = userName[1]}, new { key = 3, firstname = firstName[2], lastname = lastName[2], username = userName[2]} } }; String[] hello = new string[0]; //this should be an empty array in other words nothing found. var data1 = new { items = hello }; //just change between the two values data1 or data to see the empty array sent in bellow return Json(data, JsonRequestBehavior.AllowGet); }
public void Execute() { var queryFilter = new UserPrincipal(new PrincipalContext(ContextType.Machine), _query.UserName, _query.Password, true); var searcher = new PrincipalSearcher(queryFilter); var result = searcher.FindOne(); var response = new ConnectionResponse { Id = _query.Id }; if (result != null) { var sessionId = Guid.NewGuid(); ConnectionsStorage.Instanse.Add(sessionId); response.Accepted = true; response.SessionId = sessionId; } _responseSender.Send(response, _query.ResponseEndPoint); }
public static string returnJsonListOfAdGroupsForUserId(string sUserId) { //get list groups in List List <KeyValue> lstGroups = new List <KeyValue>(); System.DirectoryServices.AccountManagement.UserPrincipal ctx = adGetUserPrincipalBySAMAccountName(sUserId); if (ctx == null) { return(""); } foreach (GroupPrincipal group in ctx.GetGroups().OrderBy(x => x.Name)) { lstGroups.Add(new KeyValue { key = "group", value = group.Name }); } return(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(lstGroups).ToString()); }
public static string adGetUserPropertyListHtml(string sUserId) { System.DirectoryServices.AccountManagement.UserPrincipal ctx = adGetUserPrincipalBySAMAccountName(sUserId); if (ctx == null) { return(""); } string sR = "Locked = "; if (ctx.IsAccountLockedOut()) { sR += "<font color=red>****YES***</font><br>"; } else { sR += "Locked = NO<br>"; } foreach (var prop in ctx.GetType().GetProperties()) { sR += prop.Name + " = " + prop.GetValue(ctx, null) + "<br>"; } return(sR); }
public static IEnumerable <ILDAPGroup> GetAllLDAPGroups(this UserPrincipal @this) { var alreadyReturned = new HashSet <string>(); var stack = new Stack <IEnumerable <ILDAPGroup> >(); stack.Push(GetLDAPGroups(@this)); while (stack.Count > 0) { var currentEnumeration = stack.Pop(); foreach (var group in currentEnumeration) { var distinguishedName = group.DistinguishedName; if (alreadyReturned.Contains(distinguishedName)) { continue; } alreadyReturned.Add(distinguishedName); yield return(group); stack.Push(group.MemberOf); } } }
public bool Remove(UserPrincipal user) { return(Remove((Principal)user)); }
public bool Contains(UserPrincipal user) { return(Contains((Principal)user)); }
public void Add(UserPrincipal user) { Add((Principal)user); }
private static UserPrincipal _FindDomainUserBySamAccountName(string samAccoutName) { using (var context = new PrincipalContext(ContextType.Domain)) return(UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccoutName)); }
internal override void ResetAllChangeStatus() { LoadState loadState; LoadState loadState1; LoadState loadState2; LoadState loadState3; LoadState loadState4; LoadState loadState5; UserPrincipal userPrincipal = this; if (this.givenNameChanged == LoadState.Changed) { loadState = LoadState.Loaded; } else { loadState = LoadState.NotSet; } userPrincipal.givenNameChanged = loadState; UserPrincipal userPrincipal1 = this; if (this.middleNameChanged == LoadState.Changed) { loadState1 = LoadState.Loaded; } else { loadState1 = LoadState.NotSet; } userPrincipal1.middleNameChanged = loadState1; UserPrincipal userPrincipal2 = this; if (this.surnameChanged == LoadState.Changed) { loadState2 = LoadState.Loaded; } else { loadState2 = LoadState.NotSet; } userPrincipal2.surnameChanged = loadState2; UserPrincipal userPrincipal3 = this; if (this.emailAddressChanged == LoadState.Changed) { loadState3 = LoadState.Loaded; } else { loadState3 = LoadState.NotSet; } userPrincipal3.emailAddressChanged = loadState3; UserPrincipal userPrincipal4 = this; if (this.voiceTelephoneNumberChanged == LoadState.Changed) { loadState4 = LoadState.Loaded; } else { loadState4 = LoadState.NotSet; } userPrincipal4.voiceTelephoneNumberChanged = loadState4; UserPrincipal userPrincipal5 = this; if (this.employeeIDChanged == LoadState.Changed) { loadState5 = LoadState.Loaded; } else { loadState5 = LoadState.NotSet; } userPrincipal5.employeeIDChanged = loadState5; base.ResetAllChangeStatus(); }
public static MailAddress GetEmailAddress(this UserPrincipal @this) => new MailAddress(@this.EmailAddress, GetFullName(@this), Encoding.UTF8);
protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { string firstname = username.Text; string password = password1.Text; //begin temp code mgouda ohasan if (firstname == "mgouda" && password == "123456") { Utilities.IsAuthenticated = true; Utilities.UserName = firstname; Utilities.Email = firstname; Utilities.FullName = firstname; string path = VirtualPathUtility.ToAbsolute("~/models/live_doctors/DoctorsLiveSessions.aspx"); Response.Redirect(path); return; } //end temp code PrincipalContext pContxt = new PrincipalContext(ContextType.Domain, "192.168.5.50", "OU=User,DC=EKFU,DC=LOCAL", firstname, password); bool checkUser = pContxt.ValidateCredentials(firstname, password); if (checkUser == false) { pContxt = new PrincipalContext(ContextType.Domain, "192.168.5.51", "OU=User,DC=EKFU,DC=LOCAL", firstname, password); checkUser = pContxt.ValidateCredentials(firstname, password); } if (checkUser == false) { pContxt = new PrincipalContext(ContextType.Domain, "192.168.93.52", "OU=User,DC=EKFU,DC=LOCAL", firstname, password); checkUser = pContxt.ValidateCredentials(firstname, password); } if (checkUser == false) { Response.Redirect("login.aspx"); } else { PrincipalSearcher se = new PrincipalSearcher(); UserPrincipal pc = UserPrincipal.FindByIdentity(pContxt, IdentityType.SamAccountName, firstname); DirectoryEntry de = (DirectoryEntry)pc.GetUnderlyingObject(); String userType = de.Properties["employeeType"].Value.ToString(); if (userType == "staff" || userType == "faculty") { System.DirectoryServices.AccountManagement.UserPrincipal up = ((System.DirectoryServices.AccountManagement.UserPrincipal)pc); Utilities.IsAuthenticated = true; Utilities.UserName = firstname; Utilities.Email = firstname; Utilities.FullName = firstname; string path = VirtualPathUtility.ToAbsolute("~/models/live_doctors/DoctorsLiveSessions.aspx"); Response.Redirect(path); } else { Utilities.IsAuthenticated = false; Utilities.UserName = null; // todo error message not authenticated } } } }