基本信息
源码名称:AD 操作 Helper类代码下载
源码大小:3.10KB
文件格式:.zip
开发语言:C#
更新时间:2016-04-21
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍


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

namespace COM.VNet.BSS.CommonUtility
{
    public class DomainHelper
    {
        private DomainHelper(string domainName)
        {
            _domainName = domainName;
        }


        public static DomainHelper CreateActiveDirectoryConsole(string domainName, string userName, string passWord)
        {
            if (_console == null)
            {
                _console = new DomainHelper(domainName);

                _domainName = domainName;
                _userName = userName;
                _passWord = passWord;
            }
            else
            {
                if (_domainName != domainName)
                {
                    _console = new DomainHelper(domainName);

                    _domainName = domainName;
                    _userName = userName;
                    _passWord = passWord;
                }
            }

            return _console;
        }


        #region 字段
        private static DomainHelper _console;

        private static string _domainName;
        private static string _userName;
        private static string _passWord;
        #endregion


        #region 方法
        /// <summary>
        /// 根据OU的名字,获取看当前OU下面的组信息
        /// </summary>
        /// <param name="ouName">OU的名字</param>
        /// <returns></returns>
        private string[] GetGroup(string ouName)
        {
            string[] groups;

            var adRoot = GetDirectoryEntry();

            var ou = adRoot.Children.Find("OU="   ouName);

            var mySearcher = new DirectorySearcher(ou)
                {
                    Filter = ("(objectClass=group)"),
                    SearchScope = SearchScope.Subtree
                };

            //user表示用户,group表示组
            var src = mySearcher.FindAll();

            if (src.Count > 0)
            {
                groups = new string[src.Count];

                for (var i = 0; i < src.Count; i  )
                {
                    var group = src[i].GetDirectoryEntry();

                    if (group.Properties.Contains("Name"))
                    {
                        groups[i] = group.Properties["Name"][0].ToString();
                    }
                }
            }
            else
            {
                groups = null;
            }

            return groups;
        }

        private DirectoryEntry GetDirectoryEntry()
        {
            DirectoryEntry domain = string.IsNullOrEmpty(_userName) ? 
                                        new DirectoryEntry("LDAP://"   _domainName) : 
                                        new DirectoryEntry("LDAP://"   _domainName, _userName
                                                           , _passWord, AuthenticationTypes.Secure);

            return domain;
        }

        private IList<ADUserInformation> GetUsers(string groupName)
        {
            var list = new List<ADUserInformation>();

            var domain = GetDirectoryEntry();

            var domainSearcher = new DirectorySearcher(domain) {Filter = "(&(objectClass=group)(cn="   groupName   "))"};
            var group = domainSearcher.FindOne().GetDirectoryEntry();

            var sb = new StringBuilder();
            sb.Append("(|");

            using (@group)
            {
                foreach (string s in @group.Properties["member"])
                {
                    sb.AppendFormat("(distinguishedName={0})", s);
                }
            }

            sb.Append(")");

            var searchRoot = domain;

            using (searchRoot)
            {
                var ds = new DirectorySearcher(searchRoot, sb.ToString(), new[] {"Name", "SAMAccountName"});

                using (var users = ds.FindAll())
                {
                    var userlist = (from SearchResult user in users
                                    where user.Properties["SAMAccountName"].Count > 0
                                    select user);

                    list.AddRange(userlist.Select(MappingDomainUserInformation));
                }
            }
            return list;
        }

        private static ADUserInformation MappingDomainUserInformation(SearchResult user)
        {
            var groups = user.Properties["memberof"];
            var userGroups = (from object @group in groups
                             from item in @group.ToString().Split(',')
                             select item.ToString(CultureInfo.InvariantCulture).Split('=')
                                 into paris
                                 where paris.Any() && paris[0] == "CN"
                                 select paris[1]).ToList();

            var AccountName = GetDomainProperty(user, "SAMAccountName");
            var email = AccountName   "@21vianet.com";
#if DEBUG
            email = "yong.ding@hisoft.com";
#endif
            return new ADUserInformation
                {
                    AccountName = AccountName,
                    Name = GetDomainProperty(user, "DisplayName", "Name"),
                    ADPath = GetDomainProperty(user, "adspath"),
                    Groups = userGroups,
                    Email = email,
                    Phone = GetDomainProperty(user, "telephonenumber"),
                    CN = GetDomainProperty(user, "CN"),
                    OU = GetDomainProperty(user, "OU")
                };
        }

        /// <summary>
        /// 获取AD域中查询结果的Property,如果传入一个Property直接查询,如果传入两个Property ,则当第一个值为空时查询第二个值
        /// </summary>
        /// <param name="user">Ad域查询结果</param>
        /// <param name="property1">要查询的数据</param>
        /// <param name="property2">备选属性</param>
        /// <returns></returns>
        private static string GetDomainProperty(SearchResult user, string property1, string property2 = "")
        {
            string value1 = string.Empty, value2 = string.Empty;

            if (user.Properties.Contains(property1))
            {
                value1 = user.Properties[property1][0].ToString();
            }
            if (!string.IsNullOrEmpty(property2))
            {
                if (user.Properties.Contains(property2))
                {
                    value2 = user.Properties[property2][0].ToString();
                }
            }

            if (string.IsNullOrEmpty(property2))
            {
                return value1;
            }

            return !string.IsNullOrEmpty(value1) ? value1 : value2;
        }

        public string GetADUserNameForBJOE(string accountName)
        {
            var userInfo = GetUser("bj-oe", accountName);
            if (userInfo != null)
            {
                return userInfo.Name;
            }

            return string.Empty;
        }

        public ADUserInformation GetUser(string ouName, string userName)
        {
            ADUserInformation retVal = null;

            var adRoot = GetDirectoryEntry();

            var ou = adRoot.Children.Find("OU="   ouName);

            var domainSearcher = new DirectorySearcher(ou) { Filter = "(&(objectCategory=person)(objectClass=user))" };

            using (ou)
            {
                var users = domainSearcher.FindAll();
                SearchResult user = users.Cast<SearchResult>().
                    FirstOrDefault(item => item.Properties.Contains("SAMAccountName") 
                        && item.Properties["SAMAccountName"][0].ToString() == userName);

                if (user != null)
                {
                   
                    retVal = MappingDomainUserInformation(user);
                }

            }

            return retVal;
        }

        public Dictionary<string, ADUserInformation> GetAdUserList(string[] ouList)
        {
            var userList = new List<ADUserInformation>();

            string[] ous = ouList;

            if (ous.Length > 0)
            {
                var groupList = new List<string>();

                foreach (var groups in ous.Select(GetGroup).Where(groups => groups != null && groups.Length > 0))
                {
                    groupList.AddRange(groups);
                }

                foreach (var t in groupList)
                {
                    IList<ADUserInformation> users;

                    try
                    {
                        users = GetUsers(t);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    if (users != null && users.Count > 0)
                    {
                        userList.AddRange(users);
                    }
                }
            }
            else
            {
                throw new Exception("OU表中没有有效的数据!");
            }

            var userDir = new Dictionary<string, ADUserInformation>();

            foreach (var item in userList)
            {
                if (userDir.ContainsKey(item.AccountName))
                {
                    if (userDir[item.AccountName].Groups == null)
                    {
                        userDir[item.AccountName].Groups = new List<string>();
                    }

                    userDir[item.AccountName].Groups =
                            userDir[item.AccountName].Groups.Concat(item.Groups).ToList();
                }
                else
                {
                    userDir.Add(item.AccountName, item);
                }
            }

            return userDir;
        }

        public IList<ADUserInformation> GetGroupUserList(string ouName, string selectedGroupName)
        {
            var groupList = GetGroup(ouName).Where(groups => !string.IsNullOrEmpty(groups)).ToList();
            if (!groupList.Contains(selectedGroupName))
            {
                throw new Exception(string.Format("当前OU中不存在指定的组。OU:{0}  Group:{1}", ouName, selectedGroupName));
            }

            IList<ADUserInformation> userList = GetUsers(selectedGroupName);

            return userList;
        }


        public List<string> GetAdGroupList(string[] ouList)
        {
            var groupList = new List<string>();

            foreach (string[] groups in ouList.Select(GetGroup).Where(groups => groups != null && groups.Length > 0))
            {
                groupList.AddRange(groups);
            }

            return groupList;
        }


        #endregion
    }
}