Filter memberof groups of user - c#

I have manage to get a list of the users memberof groups. I want to filter the groups so i only get the groups where "Hey" is included. Something like:
GroupHeyYou,
GroupHeyThere,
GroupYouKnow,
GroupWhatThe
and only returns GroupHeyYou and GroupHeyThere
This is my function:
public List<string> GetUserGroupMemberShip()
{
DirectoryEntry de = default(DirectoryEntry); //Binding object.
DirectorySearcher ds = default(DirectorySearcher); //Search object.
SearchResult sr = default(SearchResult);
List<string> groups = new List<string>();
string logonUserName = Environment.UserName;
string logonServer = (System.Environment.GetEnvironmentVariable("logonserver")).Remove(0, 2);
string activeDirectoryPath = "LDAP://" + logonServer + "." + System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
try
{
de = new DirectoryEntry(activeDirectoryPath);
ds = new DirectorySearcher(de, "(sAMAccountName=" + logonUserName + ")");
sr = ds.FindOne();
if (null != sr)
{
DirectoryEntry deUser = new DirectoryEntry(sr.Path);
object obGroups = deUser.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
DirectoryEntry deGroups = new DirectoryEntry(ob);
groups.Add(deGroups.Name);
}
}
}
catch (Exception)
{
return null;
}
return groups;
}
how can i use a filter to do that?

var filteredGroup = groups.FindAll(item =>
{
return item.Contains("Hey");
});

Related

How can I retrieve just users from the Active Directory, not groups

I am having this code that returns list of users and groups from the Active Directory
public ArrayList GetADGroupUsers(string groupNames)
{
string[] strGrpNames = groupNames.Split(new char[] { ',' });
string strTeamList = string.Empty;
ArrayList userNames = new ArrayList();
string ADPassword = ConfigurationManager.AppSettings["ADPassword"];
IAAccess_Transaction.drms_dataaccess drmsda = new IAAccess_Transaction.drms_dataaccess();
string domainAndUsername = ConfigurationManager.AppSettings["domain"] + #"\" + ConfigurationManager.AppSettings["ADUserName"];
string decriptedADPassword = drmsda.Decrypt(ADPassword);
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, decriptedADPassword);
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
foreach (string strGrp in strGrpNames)
{
search.Filter = String.Format("(cn={0})", strGrp);
search.PropertiesToLoad.Add("member");
SearchResult result = search.FindOne();
if (result != null)
{
for (int counter = 0; counter <
result.Properties["member"].Count; counter++)
{
string user = (string)result.Properties["member"][counter];
userNames.Add(user);
}
}
}
return userNames;
}
This code retrieves BOTH, users AND group as shown on the screenshot. How can I modify this code to retrieve JUST users, NOT groups?
In order to include the nested group members, you need to lookup each entry and find out if it is a group or user. If it is a group, you can add to the groups you are already processing. Since C#/.Net doesn't have a built-in Deque class, I used LinkedList<T> instead.
public List<string> GetADGroupUsers(string groupNames) {
LinkedList<string> strGrpNames = new(groupNames.Split(','));
List<string> userNames = new();
string ADPassword = ConfigurationManager.AppSettings["ADPassword"];
string domainAndUsername = ConfigurationManager.AppSettings["domain"] + #"\" + ConfigurationManager.AppSettings["ADUserName"];
string decryptedADPassword = drmsda.Decrypt(ADPassword);
DirectoryEntry entry = new(_path, domainAndUsername, decryptedADPassword);
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher groupSearcher = new(entry);
groupSearcher.PropertiesToLoad.Add("member");
DirectorySearcher userSearcher = new(entry);
userSearcher.PropertiesToLoad.Add("groupType");
while (strGrpNames.Count > 0) {
string strGrp = strGrpNames.First();
strGrpNames.RemoveFirst();
groupSearcher.Filter = $"(cn={strGrp})";
SearchResult result = groupSearcher.FindOne();
if (result != null) {
var members = result.Properties["member"];
for (int counter = 0; counter < members.Count; ++counter) {
var user = (string)members[counter];
var userCN = user.Substring(user.IndexOf('=')+1).Substring(0,user.IndexOf(',')-3);
userSearcher.Filter = $"(cn={userCN})";
SearchResult userProperties = userSearcher.FindOne();
var userGroupType = userProperties.Properties["groupType"];
if (userGroupType != null && userGroupType.Count > 0) // group
strGrpNames.AddFirst(userCN);
else
userNames.Add(user);
}
}
}
return userNames;
}

how we can Get specfic User from Active Directory after creating new user in c#

i am creating new user in Active Directory but after creating it when i am retrieving created user the fo llowing error is coming " An operations error occurred "
following is my code
private static DirectoryEntry GetUser(string userName)
{
var de = Utility.GetDirectoryObject();
var deSearch = new DirectorySearcher
{
SearchRoot = de,
Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))",
SearchScope = SearchScope.Subtree
};
var results = deSearch.FindOne();
if (results != null)
{
de = new DirectoryEntry(results.Path, Utility.AdUser, Utility.AdPassword, AuthenticationTypes.Secure);
return de;
}
return null;
}
try this :
var deSearch = new DirectorySearcher
{
SearchRoot = de,
Filter = $"(&(objectClass=person)(sAMAccountName={userName}))",
SearchScope = SearchScope.Subtree
};

How to get a list users in Task Manager

How to get a list users in Task Manager with status?
I found only how to get a list of domain users
var usersSearcher = new ManagementObjectSearcher(#"SELECT * FROM Win32_UserAccount");
var users = usersSearcher.Get();
You can try this code to get the list of users:
var usersSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_UserAccount");
var managementObjects = usersSearcher.Get();
List<string> result = new List<string>();
foreach (ManagementObject item in managementObjects)
{
foreach (var pr in item.Properties)
{
if (pr.Name == "Caption")
{
result.Add(pr.Value?.ToString());
}
}
}
var users = result.Distinct().ToList();
Also you may try this:
var usersSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
var managementObjects = usersSearcher.Get();
List<string> allUsers = new List<string>();
foreach (ManagementObject obj in managementObjects)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
allUsers.Add(argList[1] + "\\" + argList[0]);
}
}
var result = allUsers.Distinct().ToList();

Iterate groups of user in AD and save them in list

I have a procedure that retrieves the user node out of AD:
public static void ConnectActiveDirectory()
{
List<string> lstGroups = new List<string>();
DirectoryEntry entry;
string user = "username";
string server = ConfigurationManager.AppSettings["ActiveDirectory.Server"];
entry = new DirectoryEntry(#"LDAP://" + server);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "sAMAccountName=" + user;
searcher.PropertiesToLoad.Add("MemberOf");
SearchResult result = searcher.FindOne();
}
The idea is to save all the groups in the list of strings without doing something like:
foreach (ResultPropertyValueCollection s in result.Properties.Values)
{
string groupname = null;
for (int i = 0; i < s.Count; i++)
{
dn = s[i].ToString();
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
groupname = dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1);
lstGroups.Add(groupname);
}
}
Is there any method that I can use in 'DirectorySearcher' Class?
Also, is there any way to delete the first Hashtable? the adspath one from the SearchResult object.
Instead of parsing the distinguished name by yourself, you can use the DirectoryEntry object to ask AD for the display name. For example:
var directoryEntry = new DirectoryEntry(#"LDAP://address");
var directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = "samaccountname=user";
directorySearcher.PropertiesToLoad.Add("memberOf");
var result = directorySearcher.FindOne();
foreach (var i in result.Properties["memberOf"])
{
var group = new DirectoryEntry(#"LDAP://" + i);
Console.WriteLine(group.Properties["DisplayName"]);
}

Can I create a DirectorySearcher filter using only extensionAttribute1?

I have a class using DirectorySearcher that returns results just fine based on the following optional filters:
samAccountName
givenname
sn
However, I need to create a directorysearcher that returns a user entry from AD based soley on the value of "extensionAttribute1".
Is it possible to create a filter that will search AD for a user account using only extensionAttribute1?
Here's the current code:
public static DataTable tblUserSearchResults(string searchstring, string searchproperty)
{
using (DirectoryEntry de = new DirectoryEntry(ConfigurationManager.ConnectionStrings["ADConnectionString"].ToString()))
{
//create instance of the directory searcher
using (DirectorySearcher deSearch = new DirectorySearcher())
{
//set the search filter
deSearch.SearchRoot = de;
deSearch.SearchScope = SearchScope.Subtree;
switch (searchproperty)
{
case "un":
deSearch.Filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(mail=*)(samAccountName=" + searchstring.Trim() + "*))";
break;
case "fn":
deSearch.Filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(mail=*)(givenname=" + searchstring.Trim() + "*))";
break;
case "ln":
deSearch.Filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(mail=*)(sn=" + searchstring.Trim() + "*))";
break;
default:
deSearch.Filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(mail=*)(sn=" + searchstring.Trim() + "*))";
break;
}
//get the search results
using (SearchResultCollection results = deSearch.FindAll())
{
//Create a new table object
using (DataTable tblResults = new DataTable())
{
tblResults.Columns.Add("UserID");
tblResults.Columns.Add("FirstName");
tblResults.Columns.Add("LastName");
tblResults.Columns.Add("Department");
foreach (SearchResult result in results)
{
using (DirectoryEntry de2 = result.GetDirectoryEntry())
{
if (de2.Properties["samAccountName"].Value != null)
{
DataRow dr = tblResults.NewRow();
dr["UserID"] = de2.Properties["samAccountName"].Value.ToString();
dr["FirstName"] = de2.Properties["givenname"].Value.ToString();
dr["LastName"] = de2.Properties["sn"].Value.ToString();
if (de2.Properties["department"].Value != null)
{
dr["Department"] = de2.Properties["department"].Value.ToString();
}
tblResults.Rows.Add(dr);
}
}
}
tblResults.DefaultView.Sort = "LastName asc, FirstName asc";
return tblResults;
}
}
}
}
}

Categories

Resources