C# search for user in AD - c#

I'm not a programmer by nature so I apologize in advance. I've searched far and wide and have found bits and pieces of 10 different ways to do one thing. What I'm trying to do seems very simple but I'm missing it...I need to search Active Directory using a first name and last name and display all users who match in a listbox. Can someone point me in the right direction, or if someone has already asked the same question link me to it? Thanks in advance!

Try something like this:-
DirectorySearcher d = new DirectorySearcher(somevalue);
d.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1}))", firstname, lastname);
Also from How to search for users in Active Directory with C#
//Create a shortcut to the appropriate Windows domain
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain,
"myDomain");
//Create a "user object" in the context
using(UserPrincipal user = new UserPrincipal(domainContext))
{
//Specify the search parameters
user.Name = "he*";
//Create the searcher
//pass (our) user object
using(PrincipalSearcher pS = new PrincipalSearcher())
{
pS.QueryFilter = user;
//Perform the search
using(PrincipalSearchResult<Principal> results = pS.FindAll())
{
//If necessary, request more details
Principal pc = results.ToList()[0];
DirectoryEntry de = (DirectoryEntry)pc.GetUnderlyingObject();
}
}
}
//Output first result of the test
MessageBox.Show(de.Properties["mail"].Value.ToString());

Of course shortly after posting I found my answer :)
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "servername","username","password");
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "fname";
qbeUser.Surname = "lname";
// qbeUser.DisplayName= "fname lname";
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach (var found in srch.FindAll())
{
lstUser.Items.Add(found.ToString());
}
here is the link: Search Users in Active Directory based on First Name, Last Name and Display Name

Related

Get the last login date for Active Directory from a list of organizational unit users in c#

I have my code done that reads all users from a organizational unit, now I need to be able to read the list all those users and display the last login of each user.
Here is the code that reads correctly all the users I need
private void btn_LastLoginUser_Click(object sender, EventArgs e)
{
GroupUsers();
}
public void GroupUsers()
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain", "OU=myEmployees,DC=myCompany,DC=com");
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.Enabled = true;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach (var found in srch.FindAll())
{
lst_Users.Items.Add(found);
}
}
I need help reading that data and now display the last login date for each user and populate it to my listbox.
FunCoder,
This should allow you to get the Last Login Date and Time from the DC. It will convert the user found to an authenticated principle which contains a number of different properties that might help with other information you might be looking for in the future.
foreach(var found in srch.FindAll())
{
var auth = found as AuthenticablePrincipal;
if(auth != null)
{
var Name = auth.Name;
var LastLogin = auth.LastLogon;
}
}

C# Active Directory Search

I have this powershell function and i want to make it as a C# function.
How can i put it into C#?
Get-ADComputer -filter {Name -Like 'myComp'} -property * | select DistinguishedName
You should be able to do this quite easily. Add a reference to System.DirectoryServices.AccountManagement and then use this code:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, 'YourDomain'))
{
ComputerPrincipal computer = ComputerPrincipal.FindByIdentity (ctx, "name");
if (computer != null)
{
// do whatever you need to do with your computer principal
string distinguishedName = computer.DistinguishedName;
}
}
Update: if you don't know your domain ........ - you can also use:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
in which case the principal context is created for the current domain you're located in.
You can use C# in the following manner
Connect to the Domain controller and get the DomainContext
Use that to look up the computer objects based on a name.
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Environment.UserDomainName)
{
using (PrincipalSearcher srch = new PrincipalSearcher(new ComputerPrincipal(ctx) { Name = "ServerName"}))
{
return srch.FindAll().Cast<ComputerPrincipal>().ToList().Select(x => x.DistinguishedName);
}
}
Above returns a list of DistinguishedNames that matches the Server Name.
All the other answers suggest using the System.DirectoryServices.AccountManagement namespace. While that will work, it is really just a wrapper around the System.DirectoryServices namespace to make things a bit easier to use. It does make things easier (sometimes) but it does so at the cost of performance.
For example, in all the examples you've been given, your code will retrieve every attribute with a value from the computer object in AD, even though you only want one attribute.
If you use DirectorySearcher, you can make the search and retrieve only that one attribute that you want:
public string GetComputerDn(string computerName) {
var searcher = new DirectorySearcher {
Filter = $"(&(objectClass=computer)(sAMAccountName={computerName}$))",
PropertiesToLoad = { "distinguishedName" } //return only the distinguishedName attribute
};
var result = searcher.FindOne();
if (result == null) return null;
return (string) result.Properties["distinguishedName"][0];
}
Note that in AD, the sAMAccountName of computer objects is what you would normally refer to as the "computer name", followed by $, which is why the filter is what it is.
Please try this:
Add reference to Active Directory Services (%programfiles%\Reference Assemblies\Microsoft\Framework.NETFramework\\System.DirectoryServices.AccountManagement.dll)
public string GetComputerName(string computerName)
{
using (var context = new PrincipalContext(ContextType.Domain, "your domain name goes here"))
{
using (var group = GroupPrincipal.FindByIdentity(context, "Active Directory Group Name goes here"))
{
var computers = #group.GetMembers(true);
return computers.FirstOrDefault(c => c.Name == computerName).DistinguishedName;
}
}
return null; // or return "Not Found"
}

searching users in active directory c# ldap

I am trying to get users who are members of a particular group in AD.
I am trying with the following filters but i am unsuccessful.
1)
DirectoryEntry entry1 = new DirectoryEntry("LDAP://DC=xxinfo,DC=com");
string query = "(&(objectCategory=person)(objectClass=user)(memberOf=CN=Guests))";
2)
objSearchADAM.Filter = "(&(ObjectClass=user)(memberOf=CN=Network Configuration perators,CN=Builtin,DC=xxxx,DC=xxinfo,DC=com))";
also, is there any way to get users using this approach?
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "group_name");
this searches the current domain, i want to search the whole forest.is there any way to initialize ctx for whole forest?
any help would be appreciated.
thank you.
Got the answer!!
used below code
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "subdomain.domain.comany.com:3268", "DC=comapny,DC=com"))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "Group_Name");
port 3268 is used to search in global catalog.

How to create an arraylist of all email addresses in an Active Directory OU in an asp.net c# web forms application?

I have read several posts, but I haven't been able to get anything to work for me. I would like to create an arraylist of all display names within the "Standard Users" OU. I will then use that arraylist to populate a dropdown list. I found the following in another thread, but it provides groups and not users within the specified OU:
public ArrayList Groups()
{
ArrayList groups = new ArrayList();
foreach (System.Security.Principal.IdentityReference group in
System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
{
groups.Add(group.Translate(typeof
(System.Security.Principal.NTAccount)).ToString());
}
return groups;
}
Can this be modified to provide the list of users in the Standard Users OU? Or should I use a different approach?
I also found this, but I get an error (red lines under 'std_users') stating 'not all code paths return a value'.
public ArrayList std_users()
{
// List of strings for your names
List<string> allUsers = new List<string>();
// create your domain context and define the OU container to search in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "myco.org", "OU=Standard Users, dc=myco, dc=org");
// define a "query-by-example" principal - here, we search for a UserPrincipal (user)
UserPrincipal qbeUser = new UserPrincipal(ctx);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach (var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
allUsers.Add(found.DisplayName);
}
}
Any help would be greatly appreciated.
I am using c#, Visual Studio 2013 and the framework is 4.5.1.
First off: STOP USING ArrayList - that type is dead since .NET 2.0 and should not be used - use List<string> (or more generally: List<T>) instead - much better for performance and usability!
You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:
public List<string> GetAllEmailsFromUsersContainer()
{
List<string> users = new List<string>();
// create your domain context and bind to the standard CN=Users
// container to get all "standard" users
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "CN=Users,dc=YourCompany,dc=com"))
{
// define a "query-by-example" principal - here, we search for a UserPrincipal
// which is not locked out, and has an e-mail address
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.IsAccountLockedOut = false;
qbeUser.EmailAddress = "*";
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
users.Add(found.EmailAddress);
}
}
return users;
}
Add return allUsers; to std_users() and let us know if that works for you.

Like search in ActiveDirectory

I am searching LDAP using the following code in C# to poll active directory for users:
DirectoryEntry entry = new DirectoryEntry(ldapPath, userName, password);
DirectorySearcher Searcher = new DirectorySearcher(entry);
Searcher.CacheResults = true;
Searcher.SearchScope = SearchScope.Subtree;
Searcher.Filter = "(&(&(objectCategory=person)(objectClass=user))
(|(samaccountname=" + userSearch.SamAccountName + "*)
(&(GivenName=" + userSearch.FirstName + "*)(SN=" + userSearch.Surname +
"*))))";
Searcher.PropertiesToLoad.AddRange(new string[] {"DisplayName", "GivenName",
"DistinguishedName","Title","manager",
"mail", "physicalDeliveryOfficeName", "DirectReports", "Company",
"Description", "SAMAccountName"});
SearchResultCollection results = Searcher.FindAll();
List<ActiveUser> activeUsers = new List<ActiveUser>();
I ran it with the input parameters userSearch.FirstName = "jo" and userSearch.LastName = "bl" and was expecting one user "Joe Bloggs", but this didn't appear in the result list. If I try this using the name textbox in Active Directory Users and Computers tool in Windows, Joe Bloggs appears as the only user in the list. I am using the correct LDAP path. Am I using the wrong filter to replicate the functionality in the windows tool? Is there a 'like' search on display name?
Any help would be appreciated.
If you're on .NET 3.5 or up, you can use a PrincipalSearcher and a "query-by-example" principal to do your searching:
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the first name (GivenName) of "Bruce"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Jo*";
qbeUser.Surname = "Bl*";
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement

Categories