public static List<string> GetDomainGroups() { List<string> listGroups = new List<string>(); try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain); GroupPrincipal qbeGroup = new GroupPrincipal(ctx); PrincipalSearcher srch = new PrincipalSearcher(qbeGroup); // find all matches foreach (var found in srch.FindAll()) { GroupPrincipal foundGroup = found as GroupPrincipal; if (foundGroup != null) { listGroups.Add(foundGroup.Name); } } return listGroups; } catch (Exception ex) { } return listGroups; }
public override void CreateRole(string roleName) { GroupPrincipal newGroup = new GroupPrincipal(GetPrincipalContext(), roleName); newGroup.IsSecurityGroup = true; newGroup.Description = roleName; newGroup.Save(); }
/// <summary> /// Agrega un grupo dados su nombre y descripción /// </summary> /// <param name="nombre">Nombre del grupo</param> /// <param name="descripción">Descripción del grupo</param> public void AgregarGrupo(string nombre, string descripción) { GroupPrincipal nuevoGrupo = new GroupPrincipal(_dominio); nuevoGrupo.Name = nombre; nuevoGrupo.Description = descripción; nuevoGrupo.Save(); nuevoGrupo.Dispose(); }
public Group(GroupPrincipal group) : this() { Description = group.Description; DisplayName = group.DisplayName; DistinguishedName = group.DistinguishedName; Guid = group.Guid.HasValue ? group.Guid.Value.ToString() : default(string); Name = group.Name; SamAccountName = group.SamAccountName; Sid = group.Sid.Value; }
/// <summary> /// Creates a new group in Active Directory /// </summary> /// <param name="sOU">The OU location you want to save your new Group</param> /// <param name="sGroupName">The name of the new group</param> /// <param name="sDescription">The description of the new group</param> /// <param name="oGroupScope">The scope of the new group</param> /// <param name="bSecurityGroup">True is you want this group to be a security group, false if you want this as a distribution group</param> /// <returns>Retruns the GroupPrincipal object</returns> public GroupPrincipal CreateNewGroup(string sOU, string sGroupName, string sDescription, GroupScope oGroupScope, bool bSecurityGroup) { PrincipalContext oPrincipalContext = GetPrincipalContext(sOU); GroupPrincipal oGroupPrincipal = new GroupPrincipal(oPrincipalContext, sGroupName); oGroupPrincipal.Description = sDescription; oGroupPrincipal.GroupScope = oGroupScope; oGroupPrincipal.IsSecurityGroup = bSecurityGroup; oGroupPrincipal.Save(); return oGroupPrincipal; }
public void ReadGroup() { // Group Principal Searcher Creation GroupPrincipal Access = new GroupPrincipal(ctx); PrincipalSearcher search = new PrincipalSearcher(Access); foreach (GroupPrincipal iter in search.FindAll()) { Console.WriteLine("{0} - {1}", iter.SamAccountName, iter.Name); } }
public IEnumerable<User> GetMembers(SharedFolder sharedFolder) { List<User> members = new List<User>(); using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["Domain"], GetClientDN())) { GroupPrincipal group = new GroupPrincipal(context, sharedFolder.Name); foreach(UserPrincipal adUser in group.Members) { members.Add(userManager.Find(adUser.SamAccountName)); } } return members; }
private void ListGroups() { GroupPrincipal ObjectGroupPrincipal = new GroupPrincipal(insPrincipalContext); ObjectGroupPrincipal.Name = "*"; PrincipalSearcher ObjectPrincipalSearcher = new PrincipalSearcher(); ObjectPrincipalSearcher.QueryFilter = ObjectGroupPrincipal; PrincipalSearchResult<Principal> SearchResults = ObjectPrincipalSearcher.FindAll(); ADGroupsComboBox.Items.Clear(); foreach (Principal p in SearchResults) { ADGroupsComboBox.Items.Add(p); } }
public AdGroup(GroupPrincipal group) { this.Description = group.Description; this.DisplayName = group.DisplayName; this.DistinguishedName = group.DistinguishedName; this.GroupScope = group.GroupScope.ToString(); this.Guid = group.Guid.ToString(); this.IsSecurityGroup = group.IsSecurityGroup; this.Members = AdMember.GetAdMembers(group.Members); this.Name = group.Name; this.SamAccountName = group.SamAccountName; this.Sid = group.Sid.Value; this.UserPrincipalName = group.UserPrincipalName; }
public static List<ListClass> GetGroupListFromAdUnit(string adQuery) { List<ListClass> list = new List<ListClass>(); var domain = new PrincipalContext(ContextType.Domain, "UN1T.GROUP", String.Format("{0}, DC=UN1T,DC=GROUP", adQuery)); GroupPrincipal groupList = new GroupPrincipal(domain, "*"); PrincipalSearcher ps = new PrincipalSearcher(groupList); foreach (var grp in ps.FindAll()) { list.Add(new ListClass() {Name =grp.Name,Id= grp.Sid.ToString()}); } return list; }
public void FindGroup(string name) { using (var principalContext = new PrincipalContext(ContextType.Domain, _options.Domain)) { var groupPrincipal = new GroupPrincipal(principalContext) { Name = name }; var searcher = new PrincipalSearcher(groupPrincipal); var searchResult = searcher.FindAll(); foreach (var group in searchResult.OfType<GroupPrincipal>()) { _output.WriteGroup(group); } } }
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 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 bool AddUserToGroup(string userName, string groupName) { bool done = false; GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName); if (group == null) { group = new GroupPrincipal(context, groupName); } UserPrincipal user = UserPrincipal.FindByIdentity(context, userName); if (user != null & group != null) { group.Members.Add(user); group.Save(); done = (user.IsMemberOf(group)); } return done; }
public void WriteGroup(GroupPrincipal group) { Console.WriteLine(group.Name); if (_showPrincipalDetails) { Console.WriteLine("\tDisplayName: "+ $"{group.DisplayName}"); Console.WriteLine("\tSid: " + $"{group.Sid}"); Console.WriteLine("\tIsSecurityGroup: " + $"{group.IsSecurityGroup}"); Console.WriteLine("\tDescription: " + $"{group.Description}"); } if (_showMembership) { Console.WriteLine("\tMembers:"); foreach (var member in group.GetMembers().ToList()) { Console.WriteLine("\t\t" + $"{member.Name} ({member.StructuralObjectClass})"); } } }
public static void createGroups(string domain, string ou, int numOfGroups) { ContextType contextType = ContextType.Domain; using (PrincipalContext ctx = new PrincipalContext(contextType, domain, ou)) { for (int i = 0; i < numOfGroups; i++) { try { GroupPrincipal groupPrincipal = new GroupPrincipal(ctx); groupPrincipal.Name = SampleData.GetSampleValueRandom(SampleData.Accounts); groupPrincipal.DisplayName = groupPrincipal.Name; groupPrincipal.Save(); } catch (Exception ex) { Errors.Log(ex); } } } }
public void WriteGroup(GroupPrincipal group) { if (!_headerWritten) { _headerWritten = true; _writer.Write("Name"); if (_options.ShowMembership) { _writer.Write(";Membership"); } _writer.WriteLine(); } _writer.Write("\"" + group.Name + "\""); if (_options.Detailed) { _writer.Write(";\"" + group.Name + "\";" + "\"" + group.DisplayName + "\";" + "\"" + group.Sid + "\";" + "\"" + group.IsSecurityGroup + "\";" + "\"" + group.Description + "\""); } if (_options.ShowMembership) { foreach(var member in group.GetMembers().Select(member => member.Name).ToList()) { _writer.Write(Environment.NewLine + "\"" + group.Name + "\";\"" + member + "\""); } } _writer.WriteLine(); }
/// <summary> /// This method adds all of the user principals in the specified group to the list of principals. /// It will also include any user principal that is a member of a group within the specified group. /// </summary> /// <param name="group">The group from which users will be added to the principal list.</param> /// <param name="principals">The list of user principals.</param> private static void AddGroupMembers(GroupPrincipal group, List<PrincipalDetails> principals) { using (PrincipalSearchResult<Principal> list = group.GetMembers()) { foreach (Principal principal in list) { UserPrincipal userPrincipal = principal as UserPrincipal; if (userPrincipal != null) { principals.Add(new PrincipalDetails(userPrincipal)); userPrincipal.Dispose(); } else { GroupPrincipal groupPrincipal = principal as GroupPrincipal; if (groupPrincipal != null) { AddGroupMembers(groupPrincipal, principals); } } } } }
// Can a Clear() operation be performed on the specified group? If not, also returns // a string containing a human-readable explanation of why not, suitable for use in an exception. internal abstract bool CanGroupBeCleared(GroupPrincipal g, out string explanationForFailure);
public void Add(GroupPrincipal group) { this.Add(group); }
internal abstract bool IsMemberOfInStore(GroupPrincipal g, Principal p);
private bool MoveNextForeign() { bool flag; do { flag = false; if (this.foreignMembers.Count <= 0) { if (this.foreignResultSet == null && this.foreignGroups.Count > 0) { GroupPrincipal item = this.foreignGroups[0]; this.foreignGroups.RemoveAt(0); this.foreignResultSet = item.GetStoreCtxToUse().GetGroupMembership(item, true); } if (this.foreignResultSet == null) { continue; } bool flag1 = this.foreignResultSet.MoveNext(); if (!flag1) { if (this.foreignGroups.Count <= 0) { this.foreignResultSet.Dispose(); this.foreignResultSet = null; } else { this.foreignResultSet.Dispose(); this.foreignResultSet = null; flag = true; } } else { this.current = null; this.currentFakePrincipal = null; this.currentForeign = null; return(true); } } else { DirectoryEntry directoryEntry = this.foreignMembers[0]; this.foreignMembers.RemoveAt(0); Principal principal = this.storeCtx.ResolveCrossStoreRefToPrincipal(directoryEntry); if (!this.recursive || principal as GroupPrincipal == null) { this.current = null; this.currentFakePrincipal = null; this.currentForeign = principal; if (this.foreignResultSet != null) { this.foreignResultSet.Dispose(); } this.foreignResultSet = null; return(true); } else { this.foreignGroups.Add((GroupPrincipal)principal); flag = true; } } }while (flag); return(false); }
public void Add(GroupPrincipal group) { Add((Principal)group); }
internal abstract bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal member, out string explanationForFailure);
public IEnumerable<SharedFolder> GetSharedFolders(User user) { List<SharedFolder> sharedFolders = new List<SharedFolder>(); using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["Domain"], GetClientDN())) { GroupPrincipal queryFilter = new GroupPrincipal(context); PrincipalSearcher searcher = new PrincipalSearcher(queryFilter); PrincipalSearchResult<Principal> results = searcher.FindAll(); foreach (GroupPrincipal result in results) { if (result.Members.Contains(context, IdentityType.SamAccountName, user.UserName)) { SharedFolder sharedFolder = new SharedFolder() { Name = result.Name, DistinguishedName = result.DistinguishedName, Path = "Shared/BI" }; sharedFolders.Add(sharedFolder); } } } return sharedFolders; }
/// <summary> /// /// </summary> public GroupPrincipalWrap(GroupPrincipal groupPrincipal) { this.groupPrincipal = groupPrincipal; }
private bool MoveNextForeign() { bool needToRetry; do { needToRetry = false; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: foreignMembers count={0}", _foreignMembers.Count); if (_foreignMembers.Count > 0) { // foreignDE is a DirectoryEntry in _this_ store representing a principal in another store DirectoryEntry foreignDE = _foreignMembers[0]; _foreignMembers.RemoveAt(0); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: foreignDE={0}", foreignDE.Path); // foreignPrincipal is a principal from _another_ store (e.g., it's backed by an ADStoreCtx) Principal foreignPrincipal = _storeCtx.ResolveCrossStoreRefToPrincipal(foreignDE); // If we're not enumerating recursively, return the principal. // If we are enumerating recursively, and it's a group, save it off for later. if (!_recursive || !(foreignPrincipal is GroupPrincipal)) { // Return the principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: setting currentForeign to {0}", foreignDE.Path); _current = null; _currentFakePrincipal = null; _currentForeign = foreignPrincipal; if (_foreignResultSet != null) { _foreignResultSet.Dispose(); } _foreignResultSet = null; return(true); } else { // Save off the group for recursive expansion, and go on to the next principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: adding {0} to foreignGroups", foreignDE.Path); _foreignGroups.Add((GroupPrincipal)foreignPrincipal); needToRetry = true; continue; } } if (_foreignResultSet == null && _foreignGroups.Count > 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: getting foreignResultSet (foreignGroups count={0})", _foreignGroups.Count); // We're expanding recursively, and either (1) we're immediately before // the recursive expansion of the first foreign group, or (2) we just completed // the recursive expansion of a foreign group, and now are moving on to the next. Debug.Assert(_recursive == true); // Pull off a foreign group to expand. GroupPrincipal foreignGroup = _foreignGroups[0]; _foreignGroups.RemoveAt(0); // Since it's a foreign group, we don't know how to enumerate its members. So we'll // ask the group, through its StoreCtx, to do it for us. Effectively, we'll end up acting // as a proxy to the foreign group's ResultSet. _foreignResultSet = foreignGroup.GetStoreCtxToUse().GetGroupMembership(foreignGroup, true); } // We're either just beginning the recursive expansion of a foreign group, or we're continuing the expansion // that we started on a previous call to MoveNext(). if (_foreignResultSet != null) { Debug.Assert(_recursive == true); bool f = _foreignResultSet.MoveNext(); if (f) { // By setting current, currentFakePrincipal, and currentForeign to null, // CurrentAsPrincipal/CurrentAsIdentityReference will know to proxy out to foreignResultSet. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: using foreignResultSet"); _current = null; _currentFakePrincipal = null; _currentForeign = null; return(true); } // Ran out of members in the foreign group, is there another foreign group remaining that we need // to expand? if (_foreignGroups.Count > 0) { // Yes, there is. Null out the foreignResultSet so we'll pull out the next foreign group // the next time around the loop. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: ran out of members, using next foreignResultSet"); _foreignResultSet.Dispose(); _foreignResultSet = null; Debug.Assert(_foreignMembers.Count == 0); needToRetry = true; } else { // No, there isn't. Nothing left to do. We set foreignResultSet to null here just // to leave things in a clean state --- it shouldn't really be necessary. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: ran out of members, nothing more to do"); _foreignResultSet.Dispose(); _foreignResultSet = null; } } }while (needToRetry); return(false); }
public UserManagement(UserPrincipal user, GroupPrincipal group) { Group = group; User = user; }
public bool Contains(GroupPrincipal group) { return(Contains((Principal)group)); }
public bool Remove(GroupPrincipal group) { return(this.Remove(group)); }
public bool Contains(GroupPrincipal group) { return(this.Contains(group)); }
// Can the given member be removed from the specified group? If not, also returns // a string containing a human-readable explanation of why not, suitable for use in an exception. internal abstract bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal member, out string explanationForFailure);
internal override bool IsMemberOfInStore(GroupPrincipal g, Principal p) { Debug.Fail("SAMStoreCtx.IsMemberOfInStore: Shouldn't be here."); return(false); }
internal abstract bool CanGroupBeCleared(GroupPrincipal g, out string explanationForFailure);
// Can a Clear() operation be performed on the specified group? If not, also returns // a string containing a human-readable explanation of why not, suitable for use in an exception. internal override bool CanGroupBeCleared(GroupPrincipal g, out string explanationForFailure) { // Always true for this type of StoreCtx explanationForFailure = null; return(true); }
internal abstract BookmarkableResultSet GetGroupMembership(GroupPrincipal g, bool recursive);
// Can the given member be removed from the specified group? If not, also returns // a string containing a human-readable explanation of why not, suitable for use in an exception. internal override bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal member, out string explanationForFailure) { // Always true for this type of StoreCtx explanationForFailure = null; return(true); }
public void LogResults() { //Create result part of report.xml XmlDocument report = new XmlDocument(); report.Load(Program._Config.reportPath); XmlNode root = report.DocumentElement.SelectSingleNode("/Report/Results"); PrincipalContext ctx = new PrincipalContext(ContextType.Machine); GroupPrincipal gPrin = new GroupPrincipal(ctx); gPrin.Name = "*"; PrincipalSearcher ps = new PrincipalSearcher(); ps.QueryFilter = gPrin; PrincipalSearchResult<Principal> results = ps.FindAll(); foreach (Principal p in results) { using (GroupPrincipal gp = (GroupPrincipal)p) { XmlElement g = report.CreateElement("Group"); g.SetAttribute("Name", gp.Name); root.AppendChild(g); foreach (Principal p1 in gp.Members) { root = report.DocumentElement.SelectSingleNode(String.Format("//Report//Results//Group[@Name='{0}']",gp.Name)); XmlElement u = report.CreateElement("Member"); u.SetAttribute("Name", p1.Name); root.AppendChild(u); root = report.DocumentElement.SelectSingleNode("/Report/Results"); } } } report.Save(Program._Config.reportPath); }
private static GroupPrincipal GetOrCreateGroup(PrincipalContext context, string groupName, string description) { GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName); if (@group == null) { @group = new GroupPrincipal(context, groupName) { // This setting does not work on earlier versions of .NET so it has been removed here // Description = description }; } return @group; }
public static List<string> GetGroupsFromAD() { List<string> retVal =new List<string>(); try { ContextType contextType = ContextType.Domain; string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; string domainName = strName.Split('\\')[0]; using (PrincipalContext ctx = new PrincipalContext(contextType, domainName)) { var searchPrinciple = new GroupPrincipal(ctx); searchPrinciple.IsSecurityGroup = true; System.DirectoryServices.AccountManagement.PrincipalSearcher search = new PrincipalSearcher(); search.QueryFilter = searchPrinciple; PrincipalSearchResult<Principal> results = search.FindAll(); StringBuilder sb = new StringBuilder(); foreach (GroupPrincipal groupPrincipal in results) { retVal.Add(domainName + "\\" + groupPrincipal.Name + ";"); } } } catch (Exception ex) { Errors.Log(ex); } return retVal; }
// Get members of group g internal abstract BookmarkableResultSet GetGroupMembership(GroupPrincipal g, bool recursive);
public bool Remove(GroupPrincipal group) { return(Remove((Principal)group)); }
internal static GroupPrincipal MakeGroup(PrincipalContext ctx) { GroupPrincipal groupPrincipal = new GroupPrincipal(ctx); groupPrincipal.unpersisted = false; return groupPrincipal; }
static internal Principal ConstructFakePrincipalFromSID( byte[] sid, PrincipalContext ctx, string serverName, NetCred credentials, string authorityName) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Utils", "ConstructFakePrincipalFromSID: Build principal for SID={0}, server={1}, authority={2}", Utils.ByteArrayToString(sid), (serverName != null ? serverName : "NULL"), (authorityName != null ? authorityName : "NULL")); Debug.Assert(ClassifySID(sid) == SidType.FakeObject); // Get the name for it string nt4Name = ""; int accountUsage = 0; string name; string domainName; int err = Utils.LookupSid(serverName, credentials, sid, out name, out domainName, out accountUsage); if (err == 0) { // If it failed, we'll just live without a name //Debug.Assert(accountUsage == 5 /*WellKnownGroup*/); nt4Name = (!String.IsNullOrEmpty(domainName) ? domainName + "\\" : "") + name; } else { GlobalDebug.WriteLineIf( GlobalDebug.Warn, "Utils", "ConstructFakePrincipalFromSID: LookupSid failed (ignoring), serverName=" + serverName + ", err=" + err); } // Since LookupAccountSid indicates all of the NT AUTHORITY, etc., SIDs are WellKnownGroups, // we'll map them all to Group. // Create a Principal object to represent it GroupPrincipal g = GroupPrincipal.MakeGroup(ctx); g.fakePrincipal = true; g.unpersisted = false; // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalDisplayName, nt4Name); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalName, name); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalSamAccountName, name); // SID IdentityClaim SecurityIdentifier sidObj = new SecurityIdentifier(Utils.ConvertSidToSDDL(sid)); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalSid, sidObj); g.LoadValueIntoProperty(PropertyNames.GroupIsSecurityGroup, true); return(g); }
private void loadActiveDirectoryGroups() { string DomainName = Environment.UserDomainName; using (var context = new PrincipalContext(ContextType.Domain, DomainName)) { using (var queryFilter = new GroupPrincipal(context)) { queryFilter.GroupScope = System.DirectoryServices.AccountManagement.GroupScope.Local; using (var searcher = new PrincipalSearcher(queryFilter)) { PrincipalSearchResult<Principal> result = searcher.FindAll(); foreach (var group in result) { activeDesktopGroups.Add(group.SamAccountName + " - Local"); } } queryFilter.GroupScope = System.DirectoryServices.AccountManagement.GroupScope.Global; using (var searcher = new PrincipalSearcher(queryFilter)) { PrincipalSearchResult<Principal> result = searcher.FindAll(); foreach (var group in result) { activeDesktopGroups.Add(group.SamAccountName + " - Global"); } } queryFilter.GroupScope = System.DirectoryServices.AccountManagement.GroupScope.Universal; using (var searcher = new PrincipalSearcher(queryFilter)) { PrincipalSearchResult<Principal> result = searcher.FindAll(); foreach (var group in result) { activeDesktopGroups.Add(group.SamAccountName + " - Universal"); } } } } }