设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

BC Morning V1806 门户 IT世界 应用开发 查看内容

Active Directory Objects and C#

2012-2-6 09:47| 发布者: Test| 查看: 1377| 评论: 0

摘要: Update : A newer version which is using .Net 3.5 System.DirectoryServices.AccountManagement I had created a new version hereIf you are wondering how to access an Active Directory Objects using C# plea ...

Update : A newer version which is using .Net 3.5 System.DirectoryServices.AccountManagement I had created a new version here

If you are wondering how to access an Active Directory Objects using C# please look at the attached code as a reference.   The code reference is nearly complete in terms of functionalities you need to Create, View and Update necessary User Information in the Active Directory.

The code is divided into several regions but here are the 5 key regions with hteir methods explained

Validate Methods

  • Login – This Method will verify if the User Account Exists By Matching both the Username and Password as well as checking if the Account is Active.
  • IsAccountActive – This will perform a logical operation on the iUserAccountControl values to see if the user Account is Enabled or Disabled.
  • IsUserValid – This Method will Attempt to log in a User Based on the Username and Password to Ensure that they have been set up within the Active Directory.  This is the basic UserName and Password check.

Search Methods

  • GetUser – This will return a DirectoryEntry Object if the User Exists
  • GetUserDataSet – This will take a Username and Query the AD for the User.  When found it will Transform the Results from the Property Collection into a Dataset.

User Account Methods

  • SetUserPassword – This Method will set the Users Password
  • EnableUserAccount – This Method will Enable a User Account
  • ExpireUserPassword – This Method will Force Expire a Users Password
  • DisableUserAccount – This Methoid will Disable the User Account
  • MoveUserAccount – Moves a User Account to a New OU Path
  • IsAccountLocked – This Method checks whether and Account is Locked
  • UnlockUserAccount – This Method will unlocks a User Account
  • IsUserExpired – This Method checks whether and Account is Expired
  • CreateNewUser – This Method will Create a new User Directory Object
  • DeleteUser – This Method will Delete an AD User based on Username.

Group Methods

  • CreateNewGroup – This Method will create a New Active Directory Group
  • AddUserToGroup – This Method will add a User to a group
  • RemoveUserFromGroup – This Method will remove a User from a Gorup
  • IsUserGroupMember – This Method will Validate whether the User is a Memeber of a Group
  • GetUserGroups – This Method will return an ArrayList of a User Group Memberships

Helper Methods

  • GetProperty – This will retreive the Specified Property Value from the Directory Entry Object
  • GetProperty_Array – This will retreive the Specified Property Value if its an Array Type from the Directory Entry object
  • GetProperty_Byte – This will retreive the Specified Property Value if its a Byte Type from the Directory Entry object
  • SetProperty – This will Set the Property of the Directory Entry Object
  • ClearProperty – This Method will Clear the Property Values

Now here are the codes.

using System;
using System.Collections;
using System.Text;
using System.DirectoryServices;
using System.Data;
using System.Configuration;

namespace ADExchangeLib
{
public class ADMethods : IDisposable
{
    DirectoryEntry oDE = null;
    DirectoryEntry oDEC = null;
    DirectorySearcher oDS = null;
    SearchResultCollection oResults = null;
    DataSet oDs = null;
    DataSet oDsUser = null;
    DataTable oTb = null;
    DataRow oRwUser = null;
    DataRow oRwResult = null;
    DataRow oNewCustomersRow = null;

    #region Private Variables

    private string sADPath = "";
    private string sADPathPrefix = "";
    private string sADUser = "";
    private string sADPassword = "";
    private string sADServer = "";
    private string sCharactersToTrim = "";

    #endregion

    #region Enumerations

    public enum ADAccountOptions
    {
        UF_TEMP_DUPLICATE_ACCOUNT = 0x0100,
        UF_NORMAL_ACCOUNT = 0x0200,
        UF_INTERDOMAIN_TRUST_ACCOUNT = 0x0800,
        UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
        UF_SERVER_TRUST_ACCOUNT = 0x2000,
        UF_DONT_EXPIRE_PASSWD = 0x10000,
        UF_SCRIPT = 0x0001,
        UF_ACCOUNTDISABLE = 0x0002,
        UF_HOMEDIR_REQUIRED = 0x0008,
        UF_LOCKOUT = 0x0010,
        UF_PASSWD_NOTREQD = 0x0020,
        UF_PASSWD_CANT_CHANGE = 0x0040,
        UF_ACCOUNT_LOCKOUT = 0X0010,
        UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
        UF_EXPIRE_USER_PASSWORD = 0x800000,
    }
    public enum GroupType : uint
    {
        UniversalGroup = 0x08,
        DomainLocalGroup = 0x04,
        GlobalGroup = 0x02,
        SecurityGroup = 0x80000000
    }

    public enum LoginResult
    {
        LOGIN_OK = 0,
        LOGIN_USER_DOESNT_EXIST,
        LOGIN_USER_ACCOUNT_INACTIVE
    }

    #endregion

    #region Methods

    public ADMethods()
    {
        sADPath = ConfigurationSettings.AppSettings["sADPath"].ToString();
        sADUser = ConfigurationSettings.AppSettings["sADUser"].ToString();
        sADPassword = ConfigurationSettings.AppSettings["sADPassword"].ToString();
        sADServer = ConfigurationSettings.AppSettings["sADServer"].ToString();
    }
    //Implement IDisposable.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool bDisposing)
    {
        if (bDisposing)
        {

        }
        // Free your own state.
        // Set large fields to null.

        sADPath = null;
        sADUser = null;
        sADPassword = null;
        sADServer = null;
        sCharactersToTrim = null;

        oDE = null;
        oDEC = null;
        oDS = null;
        oResults = null;
        oDs = null;
        oDsUser = null;
        oTb = null;
        oRwUser = null;
        oRwResult = null;
        oNewCustomersRow = null;
    }

    //Use C# Destructor Syntax for Finalization Code.
    ~ADMethods()
    {
        //Simply call Dispose(false).
        Dispose(false);
    }

    #region Validate Methods

    /// 
    /// This Method will verify if the User Account Exists
    /// By Matching both the Username and Password as well as
    /// checking if the Account is Active.
    /// 
    /// Username to Validate
    /// Password of the Username to Validate
    /// 
    public ADMethods.LoginResult Login(string sUserName, string sPassword)
    {
        //Check if the Logon exists Based on the Username and Password
        if (IsUserValid(sUserName, sPassword))
        {
            oDE = GetUser(sUserName);
            if (oDE != null)
            {
                //Check the Account Status
                int iUserAccountControl = Convert.ToInt32(oDE.Properties["userAccountControl"][0]);
                oDE.Close();

                //If the Disabled Item does not Exist then the Account is Active
                if (!IsAccountActive(iUserAccountControl))
                {
                    return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
                }
                else
                {
                    return LoginResult.LOGIN_OK;
                }

            }
            else
            {
                return LoginResult.LOGIN_USER_DOESNT_EXIST;
            }
        }
        else
        {
            return LoginResult.LOGIN_USER_DOESNT_EXIST;
        }
    }

    /// 
    /// This will perfrom a logical operation on the iUserAccountControl values
    /// to see if the user Account is Enabled or Disabled.
    /// The Flag for Determining if the Account is active is a Bitwise value (Decimal = 2)
    /// 
    /// 
    /// 
    public bool IsAccountActive(int iUserAccountControl)
    {
        int iUserAccountControl_Disabled = Convert.ToInt32(ADAccountOptions.UF_ACCOUNTDISABLE);
        int iFlagExists = iUserAccountControl & iUserAccountControl_Disabled;

        //If a Match is Found, then the Disabled Flag Exists within the Control Flags
        if (iFlagExists > 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    /// 
    /// This will perfrom a logical operation on the sUserName values
    /// to see if the user Account is Enabled or Disabled.  
    /// The Flag for Determining if the Account is active is a Bitwise value (Decimal = 2)
    /// 
    /// Username to Validate
    /// 
    public bool IsAccountActive(string sUserName)
    {
        oDE = GetUser(sUserName);
        if (oDE != null)
        {

            //to check of the Disabled option exists.
            int iUserAccountControl = Convert.ToInt32(oDE.Properties["userAccountControl"][0]);
            oDE.Close();

            //Check if the Disabled Item does not Exist then the Account is Active
            if (!IsAccountActive(iUserAccountControl))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }

    /// 
    /// This Method will Attempt to log in a User Based on the Username and Password
    /// to Ensure that they have been set up within the Active Directory.  
    /// This is the basic UserName and Password check.
    /// 
    /// Username to Validate
    /// Password of the Username to Validate
    /// 
    public bool IsUserValid(string sUserName, string sPassword)
    {
        try
        {
            oDE = GetUser(sUserName, sPassword);
            oDE.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }

    #endregion

    #region Search Methods
    /// 
    /// This will return a DirectoryEntry Object if the User Exists
    /// 
    /// Username to Get
    /// 
    public DirectoryEntry GetUser(string sUserName)
    {
        //Create an Instance of the DirectoryEntry
        oDE = GetDirectoryObject();

        //Create Instance fo the Direcory Searcher
        oDS = new DirectorySearcher();

        oDS.SearchRoot = oDE;
        //Set the Search Filter
        oDS.Filter = "(&(objectClass=user)(sAMAccountName=" + sUserName + "))";
        oDS.SearchScope = SearchScope.Subtree;
        oDS.PageSize = 10000;

        //Find the First Instance
        SearchResult oResults = oDS.FindOne();

        //If found then Return Directory Object, otherwise return Null
        if (oResults != null)
        {
            oDE = new DirectoryEntry(oResults.Path, sADUser, sADPassword, AuthenticationTypes.Secure);
            return oDE;
        }
        else
        {
            return null;
        }
    }

    /// 
    /// Override method which will perfrom query based on combination of Username and Password
    /// 
    /// Username to Get
    /// Password for the Username to Get
    /// 
    public DirectoryEntry GetUser(string sUserName, string sPassword)
    {
        //Create an Instance of the DirectoryEntry
        oDE = GetDirectoryObject(sUserName, sPassword);

        //Create Instance fo the Direcory Searcher
        oDS = new DirectorySearcher();
        oDS.SearchRoot = oDE;

        //Set the Search Filter
        oDS.Filter = "(&(objectClass=user)(sAMAccountName=" + sUserName + "))";
        oDS.SearchScope = SearchScope.Subtree;
        oDS.PageSize = 10000;

        //Find the First Instance
        SearchResult oResults = oDS.FindOne();

        //If a Match is Found, Return Directory Object, Otherwise return Null
        if (oResults != null)
        {
            oDE = new DirectoryEntry(oResults.Path, sADUser, sADPassword, AuthenticationTypes.Secure);
            return oDE;
        }
        else
        {
            return null;
        }

    }

    /// 
    /// This will take a Username and Query the AD for the User.  
    /// When found it will Transform the Results from the Property Collection into a Dataset.
    /// 
    /// Username to Get
    /// Users Dataset
    public DataSet GetUserDataSet(string sUserName)
    {
        oDE = GetDirectoryObject();

        //Create Instance fo the Direcory Searcher
        oDS = new DirectorySearcher();
        oDS.SearchRoot = oDE;

        //Set the Search Filter
        oDS.Filter = "(&(objectClass=user)(sAMAccountName=" + sUserName + "))";
        oDS.SearchScope = SearchScope.Subtree;
        oDS.PageSize = 10000;

        //Find the First Instance
        SearchResult oResults = oDS.FindOne();

        //Create Empty User Dataset
        oDsUser = CreateUserDataSet();

        //If Record is not Null, Then Populate DataSet
        if (oResults != null)
        {
            oNewCustomersRow = oDsUser.Tables["User"].NewRow();
            oNewCustomersRow = PopulateUserDataSet(oResults, oDsUser.Tables["User"]);

            oDsUser.Tables["User"].Rows.Add(oNewCustomersRow);
        }
        oDE.Close();

        return oDsUser;

    }

    /// 
    /// This Method will Return a Dataset of User Details Based on Criteria passed to the Query
    /// The criteria is in the LDAP format
    /// e.g.
    /// (sAMAccountName='Test Account Name')(sn='Test Surname')
    /// 
    /// Criteria to use for Searching
    /// Users Dataset
    public DataSet GetUsersDataSet(string sCriteria)
    {
        oDE = GetDirectoryObject();

        //Create Instance fo the Direcory Searcher
        oDS = new DirectorySearcher();
        oDS.SearchRoot = oDE;

        //Set the Search Filter
        oDS.Filter = "(&(objectClass=user)(objectCategory=person)(" + sCriteria + "))";
        oDS.SearchScope = SearchScope.Subtree;
        oDS.PageSize = 10000;

        //Find the First Instance
        oResults = oDS.FindAll();

        //Create Empty User Dataset
        oDsUser = CreateUserDataSet();

        //If Record is not Null, Then Populate DataSet
        try
        {
            if (oResults.Count > 0)
            {
                foreach (SearchResult oResult in oResults)
                {
                    oDsUser.Tables["User"].Rows.Add(PopulateUserDataSet(oResult, oDsUser.Tables["User"]));
                }
            }
        }
        catch { }

        oDE.Close();
        return oDsUser;

    }

    #endregion

    #region User Account Methods

    /// 
    /// This Method will set the Users Password based on the User Name
    /// 
    /// The Username to Set the New Password
    /// The New Password
    /// Any Messages catched by the Exception
    public void SetUserPassword(string sUserName, string sNewPassword, out string sMessage)
    {
        try
        {
            //Get Reference to User
            string LDAPDomain = "/sAMAccountName=" + sUserName + ",CN=Users," + GetLDAPDomain();
            oDE = GetDirectoryObject(LDAPDomain);
            oDE.Invoke("SetPassword"new Object[] { sNewPassword });
            oDE.CommitChanges();
            oDE.Close();
            sMessage = "";
        }
        catch (Exception ex)
        {
            sMessage = ex.Message;
        }
    }

    /// 
    /// This Method will set the Users Password based on Directory Entry Object
    /// 
    /// The Directory Entry to Set the New Password
    /// The New Password
    /// Any Messages catched by the Exception
    public void SetUserPassword(DirectoryEntry oDE, string sPassword, out string sMessage)
    {
        try
        {
            //Set The new Password
            oDE.Invoke("SetPassword"new Object[] { sPassword });
            sMessage = "";

            oDE.CommitChanges();
            oDE.Close();
        }
        catch (Exception ex)
        {
            sMessage = ex.InnerException.Message;
        }

    }

    /// 
    /// This Method will Enable a User Account Based on the Username
    /// 
    /// The Username of the Account to Enable
    public void EnableUserAccount(string sUserName)
    {
        //Get the Directory Entry fot the User and Enable the Password
        EnableUserAccount(GetUser(sUserName));
    }

    /// 
    /// This Method will Enable a User Account Based on the Directory Entry Object
    /// 
    /// The Directoy Entry Object of the Account to Enable
    public void EnableUserAccount(DirectoryEntry oDE)
    {
        oDE.Properties["userAccountControl"][0] = ADMethods.ADAccountOptions.UF_NORMAL_ACCOUNT;
        oDE.CommitChanges();
        oDE.Close();
    }

    /// 
    /// This Method will Force Expire a Users Password based on Directory Entry Object
    /// 
    /// The Directoy Entry Object of the Account to Expire
    public void ExpireUserPassword(DirectoryEntry oDE)
    {
        //Set the Password Last Set to 0, this will Expire the Password
        oDE.Properties["pwdLastSet"][0] = 0;
        oDE.CommitChanges();
        oDE.Close();
    }

    /// 
    /// This Methoid will Disable the User Account based on the Username
    /// 
    /// The Username of the Account to Disable
    public void DisableUserAccount(string sUserName)
    {
        DisableUserAccount(GetUser(sUserName));
    }

    /// 
    /// This Methoid will Disable the User Account based on the Directory Entry Object
    /// 
    /// The Directoy Entry Object of the Account to Disable
    public void DisableUserAccount(DirectoryEntry oDE)
    {
        oDE.Properties["userAccountControl"][0] = ADMethods.ADAccountOptions.UF_NORMAL_ACCOUNT | ADMethods.ADAccountOptions.UF_DONT_EXPIRE_PASSWD | ADMethods.ADAccountOptions.UF_ACCOUNTDISABLE;
        oDE.CommitChanges();
        oDE.Close();
    }

    /// 
    /// Moves a User Account to a New OU Path
    /// 
    /// Directory Entry Object of the User to Move
    /// The New Path
    public void MoveUserAccount(DirectoryEntry oDE, string sNewOUPath)
    {
        DirectoryEntry myNewPath = null;
        //Define the new Path
        myNewPath = new DirectoryEntry("LDAP://" + sADServer + "/" + sNewOUPath, sADUser, sADPassword, AuthenticationTypes.Secure);

        oDE.MoveTo(myNewPath);
        oDE.CommitChanges();
        oDE.Close();
    }

    /// 
    /// This Method checks whether and Account is Lockecd based on the Directory Entry Object
    /// 
    /// Directory Entry Object of the Account to check
    /// 
    public bool IsAccountLocked(DirectoryEntry oDE)
    {
        return Convert.ToBoolean(oDE.InvokeGet("IsAccountLocked"));
    }

    /// 
123下一页

路过

雷人

握手

鲜花

鸡蛋

相关阅读

最新评论

手机版|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-7-8 11:39 , Processed in 0.013646 second(s), 18 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

返回顶部