现在的位置: 首页 > 综合 > 正文

AD操作类[修改版]

2012年11月22日 ⁄ 综合 ⁄ 共 9540字 ⁄ 字号 评论关闭

存在的问题,给AD用户增加一个新属性提示错误“指定的目录服务属性或服务不存在”,哪位高人知道,请指点?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.DirectoryServices;

namespace Yesun.Edzh.Util
{
    /// <summary>
    /// 操作AD
    /// </summary>
    public class AD
    {
        private string _domainADsPath;
        private string _username;
        private string _password;

        public static string TYPE_ORGANIZATIONALUNIT = "organizationalUnit";
        public static string TYPE_GROUP = "group";
        public static string TYPE_USER = "user";

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="server"></param>
        /// <param name="path"></param>
        public AD(string domainADsPath, string username, string password)
        {
            this._domainADsPath = domainADsPath;
            this._username = username;
            this._password = password;
        }

        /// <summary>
        /// 读取用户
        /// </summary>
        /// <param name="domainADsPath"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="schemaClassNameToSearch"></param>
        /// <returns></returns>
        public DataTable GetUserList(string schemaClassNameToSearch)
        {
            SearchResultCollection results = ExecuteAD(schemaClassNameToSearch);
            DataTable dt = GetUserList(results);
            results.Dispose();
            return dt;
        }

        /// <summary>
        /// 给用户绑定RFID
        /// </summary>
        /// <param name="username"></param>
        /// <param name="rfid"></param>
        public void BindRfIdToADUser(string username, string rfid)
        {
            DirectoryEntry entry = ExecuteAD(TYPE_USER, username);
            if (entry != null)
            {
                //需要判断卡号是否存在
                SearchResultCollection results = ExecuteAD(TYPE_USER);
                foreach (SearchResult result in results)
                {
                    string adPath = result.Path;
                    if (adPath.IndexOf("/") < 0)
                        continue;
                    DirectoryEntry tmpEntry = result.GetDirectoryEntry();
                    if (tmpEntry.Properties["Comment"].Count > 0 && tmpEntry.Properties["Comment"][0].ToString() == rfid)
                    {
                        //卡号已经存在
                        throw new Exception("此卡号已经绑定到员工[" + tmpEntry.Properties["name"][0].ToString() + "]");
                    }
                }

                //更新
                SetProperty(entry, "Comment", rfid); //Comment 值作为RFID卡号
                entry.CommitChanges();

            }
        }

        /// <summary>
        /// 通过rfid读取AD用户信息
        /// </summary>
        /// <param name="rfid"></param>
        /// <returns></returns>
        public DirectoryEntry GetDirectoryEntryByRFID(string rfid)
        {
            SearchResultCollection results = ExecuteAD(TYPE_USER);
            foreach (SearchResult result in results)
            {
                string adPath = result.Path;
                if (adPath.IndexOf("/") < 0)
                    continue;
                DirectoryEntry tmpEntry = result.GetDirectoryEntry();
                if (tmpEntry.Properties["Comment"].Count > 0 && tmpEntry.Properties["Comment"][0].ToString() == rfid)
                {
                    return result.GetDirectoryEntry();
                }
            }
            return null;
        }

        /// <summary>
        /// 读取用户
        /// </summary>
        /// <param name="results"></param>
        /// <returns></returns>
        public DataTable GetUserList(SearchResultCollection results)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("rfid", typeof(string));
            dt.Columns.Add("username", typeof(string));
            dt.Columns.Add("password", typeof(string));
            dt.Columns.Add("path", typeof(string));
            dt.Columns.Add("displayname", typeof(string));
            dt.Columns.Add("samaccountname", typeof(string));
            dt.Columns.Add("mail", typeof(string));

           
            if (results.Count == 0)
                throw new Exception("域中没有任何用户");
            else
            {
                foreach (SearchResult result in results)
                {
                    string adPath = result.Path;
                    if (adPath.IndexOf("/") < 0)
                        continue;
                    DirectoryEntry entry = result.GetDirectoryEntry();
                    if (entry != null)
                    {
                        DataRow dr = dt.NewRow();
                        if (entry.Properties["name"].Count > 0)
                            dr["username"] = entry.Properties["name"][0].ToString();
                        if (entry.Properties["samaccountname"].Count > 0)
                            dr["samaccountname"] = entry.Properties["sAMAccountName"][0].ToString();
                        if (entry.Properties["Comment"].Count > 0)
                            dr["rfid"] = entry.Properties["Comment"][0].ToString();//暂时用这个来作为RFID
                        if (entry.Properties["displayname"].Count > 0)
                            dr["displayname"] = entry.Properties["displayname"][0].ToString();
                        if (entry.Properties["mail"].Count > 0)
                            dr["mail"] = entry.Properties["mail"][0].ToString();
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 读取组
        /// </summary>
        /// <param name="domainADsPath"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="schemaClassNameToSearch"></param>
        /// <returns></returns>
        public DataTable GetGroupList(string schemaClassNameToSearch)
        {
            SearchResultCollection results = ExecuteAD(schemaClassNameToSearch);
            DataTable dt = GetGroupList(results);
            results.Dispose();
            return dt;
        }

 

        /// <summary>
        /// 读取组
        /// </summary>
        /// <param name="results"></param>
        /// <returns></returns>
        public DataTable GetGroupList(SearchResultCollection results)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("rfid", typeof(string));
            dt.Columns.Add("username", typeof(string));
            dt.Columns.Add("password", typeof(string));
            dt.Columns.Add("path", typeof(string));
            dt.Columns.Add("displayname", typeof(string));
            dt.Columns.Add("samaccountname", typeof(string));
            dt.Columns.Add("mail", typeof(string));
            if (results.Count == 0)
                throw new Exception("域中没有任何组织结构");
            else
            {
                foreach (SearchResult result in results)
                {
                    if (result.Path.IndexOf("OU=用户") < 0)
                        continue;
                    ResultPropertyCollection propColl = result.Properties;
                    DataRow dr = dt.NewRow();
                    dr["name"] = propColl["name"][0].ToString();
                    //TODO
                }
            }
            return dt;
        }

        /// <summary>
        /// 从AD中读取数据
        /// </summary>
        /// <param name="schemaClassNameToSearch"></param>
        /// <returns></returns>
        public SearchResultCollection ExecuteAD(string schemaClassNameToSearch)
        {
            DirectorySearcher searcher = new DirectorySearcher();
            searcher.SearchRoot = new DirectoryEntry(_domainADsPath, _username, _password);
            searcher.Filter = "(objectClass=" + schemaClassNameToSearch + ")";
            searcher.SearchScope = SearchScope.Subtree;
            searcher.Sort = new SortOption("name", SortDirection.Ascending);
            searcher.PageSize = 512;

            //指对范围内的属性进行加载,以提高效率
            searcher.PropertiesToLoad.AddRange(new string[] { "name", "Path", "displayname", "samaccountname", "mail", "Comment" });
            SearchResultCollection results = searcher.FindAll();
            return results;
        }

        /// <summary>
        /// 从AD中读取数据
        /// </summary>
        /// <returns></returns>
        public DirectoryEntry ExecuteAD(string schemaClassNameToSearch, string cn)
        {
            DirectorySearcher searcher = new DirectorySearcher();
            searcher.SearchRoot = new DirectoryEntry(_domainADsPath, _username, _password, AuthenticationTypes.Delegation);
            searcher.Filter = "(&(objectClass=" + schemaClassNameToSearch + ")(cn=" + cn + "))";
            searcher.SearchScope = SearchScope.Subtree;
            searcher.Sort = new SortOption("name", SortDirection.Ascending);
            searcher.PageSize = 512;

            //指对范围内的属性进行加载,以提高效率
            searcher.PropertiesToLoad.AddRange(new string[] { "name", "Path", "displayname", "samaccountname", "mail", "Comment" });
           
            SearchResult result = searcher.FindOne();
            DirectoryEntry entry = result.GetDirectoryEntry();
            return entry;
        }

        /// <summary>
        /// 设置属性,如果不存在此属性,可以创建
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="propertyName"></param>
        /// <param name="propertyValue"></param>
        public static void SetProperty(DirectoryEntry entry, string propertyName, string propertyValue)
        {
            if (!string.IsNullOrEmpty(propertyValue))
            {
                if (entry.Properties.Contains(propertyName))
                {
                    entry.Properties[propertyName][0] = propertyValue;
                }
                else
                {
                    entry.Properties[propertyName].Add(propertyValue);
                }
            }
        }

        /// <summary>
        /// 读取属性
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetProperty(DirectoryEntry entry, string propertyName)
        {
            if (entry.Properties.Contains(propertyName))
                return entry.Properties[propertyName][0].ToString();
            else
                return String.Empty;
        }
    }

}

抱歉!评论已关闭.