Just another tech site

C# Active Directory


using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

List all users

static bool ListUsers()
{
    // Creating the PrincipalContext
    PrincipalContext principalContext = null;
    try
    {
        principalContext = new PrincipalContext(ContextType.Domain, "10.0.0.96", "DC=test,DC=com", "administrator", "XXXXX");
    }
    catch (Exception e)
    {
        Console.WriteLine("Failed to create PrincipalContext. Exception: " + e);
        return false;
    }

    PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
    UserPrincipal parUserPrincipal = new UserPrincipal(principalContext);
    parUserPrincipal.Name = "*";
    insPrincipalSearcher.QueryFilter = parUserPrincipal;
    var results = insPrincipalSearcher.FindAll();
    foreach (Principal p in results)
    {
        Console.WriteLine(String.Format("   SamAccountName:[{0}] ", p.SamAccountName));
    }
    return true;
}

Add a new user.
you can find the following code in the MSDN (just here as a reminder)

static bool CreateUser(string firstName, string lastName, string userLogonName, string employeeID, string emailAddress, string telephone, string address)
{
    // Creating the PrincipalContext
    PrincipalContext principalContext = null;
    try
    {
        principalContext = new PrincipalContext(ContextType.Domain, "10.0.0.96", "DC=test,DC=com", "administrator", "XXXXX");
    }
    catch (Exception e)
    {
        Console.WriteLine("Failed to create PrincipalContext. Exception: " + e);
        return false;
    }

    // Check if user object already exists in the store
    UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, userLogonName);
    if (usr != null)
    {
        Console.WriteLine(userLogonName + " already exists. Please use a different User Logon Name.");
        return false;
    }

    // Create the new UserPrincipal object
    UserPrincipal userPrincipal = new UserPrincipal(principalContext);

    if (lastName != null && lastName.Length > 0)
        userPrincipal.Surname = lastName;

    if (firstName != null && firstName.Length > 0)
        userPrincipal.GivenName = firstName;

    if (employeeID != null && employeeID.Length > 0)
        userPrincipal.EmployeeId = employeeID;

    if (emailAddress != null && emailAddress.Length > 0)
        userPrincipal.EmailAddress = emailAddress;

    if (telephone != null && telephone.Length > 0)
        userPrincipal.VoiceTelephoneNumber = telephone;

    if (userLogonName != null && userLogonName.Length > 0)
        userPrincipal.SamAccountName = userLogonName;

    string pwdOfNewlyCreatedUser = "abcde@@12345!~";
    userPrincipal.SetPassword(pwdOfNewlyCreatedUser);

    userPrincipal.Enabled = true;
    //userPrincipal.ExpirePasswordNow();

    try
    {
        userPrincipal.Save();
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception creating user object. " + e);
        return false;
    }

    /***************************************************************
        *   The below code demonstrates on how you can make a smooth 
        *   transition to DirectoryEntry from AccountManagement namespace, 
        *   for advanced operations.
        ***************************************************************/
    if (userPrincipal.GetUnderlyingObjectType() == typeof(DirectoryEntry))
    {
        DirectoryEntry entry = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
        if (address != null && address.Length > 0)
            entry.Properties["streetAddress"].Value = address;
        try
        {
            entry.CommitChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception modifying address of the user. " + e);
            return false;
        }
    }

    return true;
}

now just a small helper

public static bool IdentityTest()
{

    var current = WindowsIdentity.GetCurrent();
    Console.WriteLine(String.Format("WindowsIdentity "));
    Console.WriteLine(String.Format("    current.AuthenticationType:[{0}] ", current.AuthenticationType));
    Console.WriteLine(String.Format("    current.Groups:[{0}] ", current.Groups));
    Console.WriteLine(String.Format("    current.ImpersonationLevel:[{0}] ", current.ImpersonationLevel));
    Console.WriteLine(String.Format("    current.IsAnonymous:[{0}] ", current.IsAnonymous));
    Console.WriteLine(String.Format("    current.IsAuthenticated:[{0}] ", current.IsAuthenticated));
    Console.WriteLine(String.Format("    current.IsGuest:[{0}] ", current.IsGuest));
    Console.WriteLine(String.Format("    current.IsSystem:[{0}] ", current.IsSystem));
    Console.WriteLine(String.Format("    current.Name:[{0}] ", current.Name));
    Console.WriteLine(String.Format("    current.Owner:[{0}] ", current.Owner));
    Console.WriteLine(String.Format("    current.Token:[{0}] ", current.Token));
    Console.WriteLine(String.Format("    current.User:[{0}] ", current.User));

    return true;
}
Advertisements

Comments on: "C# Active Directory" (2)

  1. I found this code to be very useful in my project. Thanks!

  2. Yes, perfect like I wanted….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: