设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

BCM 门户 IT世界 应用开发 查看内容

Active Directory Objects and C#

2012-2-6 09:47| 发布者: Test| 查看: 1401| 评论: 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

 
    /// 
    /// This Method will unlock a User Account based on the Directory Entry Object
    /// 
    /// Directory Entry Object of the Account to unlock
    public void UnlockUserAccount(DirectoryEntry oDE)
    {
        SetProperty(oDE, "lockoutTime""0");
    }

    /// 
    /// This Method checks whether and Account is Expired based on the Directory Entry Object
    /// 
    /// Directory Entry Object of the Account to check
    /// 
    public bool IsUserExpired(DirectoryEntry oDE)
    {
        int iDecimalValue = int.Parse(GetProperty(oDE, "userAccountControl"));
        string sBinaryValue = Convert.ToString(iDecimalValue, 2);

        //Reverse the Binary Value to get the Location for all 1's
        char[] str = sBinaryValue.ToCharArray();
        Array.Reverse(str);
        string sBinaryValueReversed = new string(str);

        //24th 1 is the Switch for the Expired Account
        if (sBinaryValueReversed.Length >= 24)
        {
            if (sBinaryValueReversed.Substring(24, 1) == "1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    }

    /// 
    /// This Method will Create a new User Directory Object
    /// 
    /// The CN of the New User
    /// 
    public DirectoryEntry CreateNewUser(string sCN)
    {
        //Set the LDAP Path so that the user will be Created under the Users Container
        string LDAPDomain = "/CN=Users," + GetLDAPDomain();

        oDE = GetDirectoryObject();
        oDEC = oDE.Children.Add("CN=" + sCN, "user");
        oDE.Close();
        return oDEC;
    }

    /// 
    /// This Method will Create a new User Directory Object based on a Username and LDAP Domain
    /// 
    /// The Username of the New User
    /// The LDAP Domain for the New User
    /// 
    public DirectoryEntry CreateNewUser(string sUserName, string sLDAPDomain)
    {
        //Set the LDAP qualification so that the user will be Created under the Users Container
        string LDAPDomain = "/CN=Users," + sLDAPDomain;
        oDE = new DirectoryEntry("LDAP://" + sADServer + "/" + sLDAPDomain, sADUser, sADPassword, AuthenticationTypes.Secure);

        oDEC = oDE.Children.Add("CN=" + sUserName, "user");
        oDE.Close();
        return oDEC;
    }

    /// 
    /// This Method will Delete an AD User based on UserNaeme. Please be careful when using this
    /// The only way you can restore this object is by Tombstone which will not
    /// Restore every details on the Directory Entry object
    /// 
    /// The Username of the Account to Delete
    /// True or False if the Delete was successfull
    public bool DeleteUser(string sUserName)
    {
        string sParentPath = GetUser(sUserName).Parent.Path;
        return DeleteUser(sUserName, sParentPath);
    }

    /// 
    /// This Method will Delete an AD User based on Username and specifying the Path. Please be careful when using this
    /// The only way you can restore this object is by Tombstone which will not
    /// Restore every details on the Directory Entry object
    /// 
    /// The Username of the Account to Delete
    /// The Path where the Useraccount is Located on LDAP
    /// 
    public bool DeleteUser(string sUserName, string sParentPath)
    {
        try
        {
            oDE = new DirectoryEntry(sParentPath, sADUser, sADPassword, AuthenticationTypes.Secure);

            oDE.Children.Remove(GetUser(sUserName));

            oDE.CommitChanges();
            oDE.Close();
            return true;
        }
        catch
        {
            return false;
        }

    }

    #endregion

    #region Group Methods

    /// 
    /// This Method will Create a New Active Directory Group
    /// 
    /// OU Location of the New Group to be Created
    /// The Group Name
    /// The Group Description
    /// The Group Type
    /// True or False whether the Group is a Security Group or a Distribution Group
    /// 
    public DirectoryEntry CreateNewGroup(string sOULocation, string sGroupName, string sDescription, GroupType oGroupTypeInput, bool bSecurityGroup)
    {
        GroupType oGroupType;

        oDE = new DirectoryEntry("LDAP://" + sADServer + "/" + sOULocation, sADUser, sADPassword, AuthenticationTypes.Secure);

        //Check if the Requested group is a Security Group or Distribution Group
        if (bSecurityGroup)
        {
            oGroupType = oGroupTypeInput | GroupType.SecurityGroup;
        }
        else
        {
            oGroupType = oGroupTypeInput;
        }
        int typeNum = (int)oGroupType;

        //Add Properties to the Group
        DirectoryEntry myGroup = oDE.Children.Add("cn=" + sGroupName, "group");
        myGroup.Properties["sAMAccountName"].Add(sGroupName);
        myGroup.Properties["description"].Add(sDescription);
        myGroup.Properties["groupType"].Add(typeNum);
        myGroup.CommitChanges();

        return myGroup;

    }

    /// 
    /// This Method will add a User Based on the Distinguished Name to an AD Group
    /// 
    /// The Users Distinguished Name
    /// The Groups Distinguished Name
    public void AddUserToGroup(string sDN, string sGroupDN)
    {
        oDE = new DirectoryEntry("LDAP://" + sADServer + "/" + sGroupDN, sADUser, sADPassword, AuthenticationTypes.Secure);

        //Adds the User to the Group
        oDE.Properties["member"].Add(sDN);
        oDE.CommitChanges();
        oDE.Close();
    }

    /// 
    /// This Method will remove a User Based on the Distinguished Name to an AD Group
    /// 
    /// The Users Distinguished Name
    /// The Groups Distinguished Name
    public void RemoveUserFromGroup(string sDN, string sGroupDN)
    {
        oDE = new DirectoryEntry("LDAP://" + sADServer + "/" + sGroupDN, sADUser, sADPassword, AuthenticationTypes.Secure);

        //Removes the User to the Group
        oDE.Properties["member"].Remove(sDN);
        oDE.CommitChanges();
        oDE.Close();
    }

    /// 
    /// This Method will Validate whether the User is a Memeber of an AD Group
    /// 
    /// The Users Distinguished Name
    /// The Groups Distinguished Name
    /// 
    public bool IsUserGroupMember(string sDN, string sGroupDN)
    {
        oDE = new DirectoryEntry("LDAP://" + sADServer + "/" + sDN, sADUser, sADPassword, AuthenticationTypes.Secure);

        string sUserName = GetProperty(oDE, "sAMAccountName");

        ArrayList oUserGroups = GetUserGroups(sUserName);
        int iGroupsCount = oUserGroups.Count;

        if (iGroupsCount != 0)
        {
            for (int i = 0; i < iGroupsCount; i++)
            {
                //Check is User is a Member of the AD Group
                if (sGroupDN == oUserGroups[i].ToString())
                {
                    return true;
                }
            }
            return false;
        }
        else
        {
            return false;
        }

    }

    /// 
    /// This Method will return an ArrayList of a User
    /// AD Group Memberships
    /// 
    /// The Username to get Group Memberships
    /// 
    public ArrayList GetUserGroups(string sUserName)
    {
        ArrayList oGroupMemberships = new ArrayList();
        return AttributeValuesMultiString("memberOf", sUserName, oGroupMemberships);
    }

    #endregion

    #region Helper Methods
    /// 
    /// This will retreive the Specified Property Value from the Directory Entry Object
    /// 
    /// The Directory Object to retrieve from
    /// The Property to retrieve
    /// 
    public string GetProperty(DirectoryEntry oDE, string sPropertyName)
    {
        if (oDE.Properties.Contains(sPropertyName))
        {
            return oDE.Properties[sPropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    /// 
    /// This will retreive the Specified Property Value if its an Array Type from the Directory Entry object
    /// 
    /// The Directory Object to retrieve from
    /// The Property to retrieve
    /// 
    public ArrayList GetProperty_Array(DirectoryEntry oDE, string sPropertyName)
    {
        ArrayList myItems = new ArrayList();
        if (oDE.Properties.Contains(sPropertyName))
        {
            for (int i = 0; i < oDE.Properties[sPropertyName].Count; i++)
            {
                myItems.Add(oDE.Properties[sPropertyName][i].ToString());
            }
            return myItems;
        }
        else
        {
            return myItems;
        }
    }

    /// 
    /// This will retreive the Specified Property Value if its a Byte Type from the Directory Entry object
    /// 
    /// The Directory Object to retrieve from
    /// The Property to retrieve
    /// 
    public byte[] GetProperty_Byte(DirectoryEntry oDE, string sPropertyName)
    {
        if (oDE.Properties.Contains(sPropertyName))
        {
            return (byte[])oDE.Properties[sPropertyName].Value;
        }
        else
        {
            return null;
        }
    }

    /// 
    /// This is an Override that will Allow a Property to be Extracted Directly
    /// from a Search Result Object
    /// 
    /// The Search Result
    /// The Property to retrieve
    /// 
    public string GetProperty(SearchResult oSearchResult, string sPropertyName)
    {
        if (oSearchResult.Properties.Contains(sPropertyName))
        {
            return oSearchResult.Properties[sPropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    /// 
    /// This will Set the Property of the Directory Entry Object
    /// 
    /// The Directory Object to Set to
    /// The Property Name
    /// The Property Value
    public void SetProperty(DirectoryEntry oDE, string sPropertyName, string sPropertyValue)
    {
        //Check if the Value is Valid
        if (sPropertyValue != string.Empty)
        {
            //Check if the Property Exists
            if (oDE.Properties.Contains(sPropertyName))
            {
                oDE.Properties[sPropertyName].Value = sPropertyValue;
                oDE.CommitChanges();
                oDE.Close();
            }
            else
            {
                oDE.Properties[sPropertyName].Add(sPropertyValue);
                oDE.CommitChanges();
                oDE.Close();
            }
        }
    }

    /// 
    /// This will Set the Property of the Directory Entry Object
    /// 
    /// The Directory Object to Set to
    /// The Property Name
    /// The Property Value
    public void SetProperty(DirectoryEntry oDE, string sPropertyName, byte[] bPropertyValue)
    {

        //Clear Binary Data if Exists
        oDE.Properties[sPropertyName].Clear();

        //Update Attribute with Binary Data from File
        oDE.Properties[sPropertyName].Add(bPropertyValue);
        oDE.CommitChanges();
        oDE.Dispose();

    }

    /// 
    /// This will Set the Property of the Directory Entry Object if its an Array Type
    /// 
    /// The Directory Object to Set to
    /// The Property Name
    /// The Property Value in Array List Type
    public void SetProperty(DirectoryEntry oDE, string sPropertyName, ArrayList aPropertyValue)
    {
        //Check if the Value is Valid
        if (aPropertyValue.Count != 0)
        {
            foreach (string sPropertyValue in aPropertyValue)
            {
                oDE.Properties[sPropertyName].Add(sPropertyValue);
                oDE.CommitChanges();
                oDE.Close();
            }
        }
    }

    /// 
    /// This Method will Clear the Property Values
    /// 
    /// The Directory Object to Set to
    /// The Property Name to be cleared
    public void ClearProperty(DirectoryEntry oDE, string sPropertyName)
    {
        //Check if the Property Exists
        if (oDE.Properties.Contains(sPropertyName))
        {
            oDE.Properties[sPropertyName].Clear();
            oDE.CommitChanges();
            oDE.Close();
        }
    }

    /// 
    /// This is an Internal Method for Retreiving a New Directory Entry Object
    /// 
    /// 
    private DirectoryEntry GetDirectoryObject()
    {
        oDE = new DirectoryEntry(sADPath, sADUser, sADPassword, AuthenticationTypes.Secure);
        return oDE;
    }

    /// 
    /// Override Function that that will Attempt a Logon based on the Username and Password
    /// 
    /// 
    /// 
    /// 
    private DirectoryEntry GetDirectoryObject(string sUserName, string sPassword)
    {
        oDE = new DirectoryEntry(sADPath, sUserName, sPassword, AuthenticationTypes.Secure);
        return oDE;
    }

    /// 
    /// This will Create the Directory Entry based on the Domain Reference
    /// 
    /// 
    /// 
    private DirectoryEntry GetDirectoryObject(string sDomainReference)
    {
        oDE = new DirectoryEntry(sADPath + sDomainReference, sADUser, sADPassword, AuthenticationTypes.Secure);
        return oDE;
    }

    /// 
    ///This will Create the Directory Entry based on the LDAP Path
    /// 
    /// 
    /// 
    public DirectoryEntry GetDirectoryObject_ByPath(string sPath)
    {
        oDE = new DirectoryEntry(sADPathPrefix + sPath, sADUser, sADPassword, AuthenticationTypes.Secure);
        return oDE;
    }

    /// 
    /// Additional Override that will Allow oObject to be Created based on the Username and Password.
    /// 
    /// 
    /// 
    /// 
    /// 
    private DirectoryEntry GetDirectoryObject(string sDomainReference, string sUserName, string sPassword)
    {
        oDE = new DirectoryEntry(sADPath + sDomainReference, sUserName, sPassword, AuthenticationTypes.Secure);
        return oDE;
    }

    /// 
    /// This will retreive the Distinguished Name from the DirectoryEntry Object
    /// 
    /// The Directory Entry Object to get the Distinguisehd Name From
    /// 
    public string GetDistinguishedName(DirectoryEntry oDE)
    {
        if (oDE.Properties.Contains("distinguishedName"))
        {
            return oDE.Properties["distinguishedName"][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }


鲜花

握手

雷人

路过

鸡蛋

相关阅读

最新评论

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

GMT-8, 2025-12-13 12:12 , Processed in 0.013476 second(s), 16 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

返回顶部