LDAP组织机构勾选人控件工具类

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.DirectoryServices;
using System.Collections.Generic;

public partial class ADSelectMan : System.Web.UI.Page
{
    //测试
    static string ldap = "http://www.cnblogs.com/starcrm/admin/ldap://centway.com/";
    static string dc = "DC=centway,DC=com";
    static string user = "centway\\administrator";
    static string pw = "qwe123!";
    static string rootEntry = "http://www.cnblogs.com/starcrm/admin/ldap://centway.com/ou=广汽集团, DC=centway,DC=com";
    static string entryName = "centway\\\\";

    //正式
    //static string ldap = "http://www.cnblogs.com/starcrm/admin/ldap://gagc.com.cn/";
    //static string dc = "DC=gagc,DC=com,DC=cn";
    //static string user = "gagc\\administrator";
    //static string pw = "gacit83151963!";
    //static string rootEntry = "http://www.cnblogs.com/starcrm/admin/ldap://gagc.com.cn/ou=广州汽车集团股份有限公司, DC=gagc,DC=com,DC=cn";
    //static string entryName = "gagc\\\\";

    private ADTool myad = new ADTool(ldap, dc, user, pw);   

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!base.IsPostBack)
        {           
            string uid = Convert.ToString(Page.Request.Params["uid"]);
            if (uid != string.Empty && uid != null)
            {
                string[] arrId = uid.Split(';');
                foreach (string str in arrId)
                {
                    DirectoryEntry userentry = myad.getUserEntry(str);
                    ListBox1.Items.Add(new ListItem(userentry.Name.Substring(3, userentry.Name.Length - 3), userentry.Properties["sAMAccountName"].Value.ToString()));
                }
            }
            DirectoryEntry entry = this.myad.getRootEntry(rootEntry, user, pw);           
            if (entry.SchemaClassName == "user")
            {
                entry.Properties["sAMAccountName"].Value.ToString();               
            }
            TreeNode child = new TreeNode(entry.Name.Substring(3, entry.Name.Length - 3), entry.Path);
            if (entry.SchemaClassName == "organizationalUnit")
            {
                //close
                child.ImageUrl = @"img\folder.gif";
            }
            else
            {
                child.ImageUrl = @"img\user.gif";
            }
            this.TreeView1.Nodes.Add(child);

            // 全部展开
            if (Page.Request.Params["orgs"] == "all")
            {
                TreeNode node2 = new TreeNode("tmp");
                child.ChildNodes.Add(node2);
                node2.Expanded = false;
            }

            else
            {
                TreeNode node2 = new TreeNode("orgs");
                child.ChildNodes.Add(node2);
                node2.Expanded = false;
            }

        }
    }

    // Methods
    private void addNode(TreeNode node)
    {
        string path = node.Value.Split(new char[] { ';' })[0];
        DirectoryEntry entry = new DirectoryEntry(path, user, pw);
        foreach (DirectoryEntry entry2 in entry.Children)
        {
            CreateNode(node, entry2, "tmp");
        }
    }

    /// <summary>
    /// 具有包含排除功能的节点添加
    /// </summary>
    /// <param name="node">节点</param>
    /// <param name="isInclude">true就是包含,false就是排除</param>
    /// <param name="depts">组织列表</param>
    private void addNode(TreeNode node, bool isInclude, List<string> depts)
    {
        string path = node.Value.Split(new char[] { ';' })[0];
        DirectoryEntry entry = new DirectoryEntry(path, user, pw);
        foreach (DirectoryEntry entry2 in entry.Children)
        {
            if (isInclude)
            {
                if (depts.Contains(entry2.Name.Substring(3, entry2.Name.Length - 3)))
                {
                    CreateNode(node, entry2, "tmp");
                }
            }
            else
            {
                if (!depts.Contains(entry2.Name.Substring(3, entry2.Name.Length - 3)))
                {
                    CreateNode(node, entry2, "tmp");
                }
            }
        }
    }

    //将节点添加单独作为一个方法
    private void CreateNode(TreeNode node, DirectoryEntry entr,string nodename)
    {
        string str2 = "";
        if (entr.SchemaClassName == "user" || entr.SchemaClassName == "group")
        {
            str2 = entr.Properties["sAMAccountName"].Value.ToString();
        }
        TreeNode child = new TreeNode(entr.Name.Substring(3, entr.Name.Length - 3), entr.Path);
        if ((entr.SchemaClassName == "organizationalUnit") && this.CheckBoxList1.Items[2].Selected)
        {
            //close
            child.ImageUrl = @"img\folder.gif";
            node.ChildNodes.Add(child);
        }
        else if ((entr.SchemaClassName == "user") && this.CheckBoxList1.Items[0].Selected)
        {
            child.ImageUrl = @"img\user.gif";
            //child.Value = child.Value + "%" + str2;
            child.Value = str2;
            node.ChildNodes.Add(child);
        }
        else if ((entr.SchemaClassName == "group") && this.CheckBoxList1.Items[1].Selected)
        {
            child.ImageUrl = @"img\group.gif";
            child.Value = str2;
            node.ChildNodes.Add(child);
        }
        child.Checked = node.Checked;
        child.Expanded = false;
        if ((entr.SchemaClassName == "organizationalUnit") && this.CheckBoxList1.Items[2].Selected)
        {
            TreeNode node3 = new TreeNode(nodename);
            child.ChildNodes.Add(node3);
            node3.Expanded = false;
        }

    }
   


    protected void btnAdd_Click(object sender, EventArgs e)
    {
        int num = Convert.ToInt32(Page.Request.Params["num"]);

        foreach (TreeNode node in this.TreeView1.CheckedNodes)
        {
            if (node.Text != "tmp")
            {
                ListItem item = new ListItem(node.Text, node.Value);
                if ((node.ImageUrl == @"img\user.gif") && !this.ListBox1.Items.Contains(item))
                {
                    if (num == -1)
                    {
                        this.ListBox1.Items.Add(item);
                    }
                    else
                    {
                        if (ListBox1.Items.Count < num)
                        {
                            this.ListBox1.Items.Add(item);
                        }
                    }
                }
                else if ((node.ImageUrl == @"img\group.gif") && !this.ListBox1.Items.Contains(item))
                {
                    if (num == -1)
                    {
                        this.ListBox1.Items.Add(item);
                    }
                    else
                    {
                        if (ListBox1.Items.Count < num)
                        {
                            this.ListBox1.Items.Add(item);
                        }
                    }
                }
                else if (node.ImageUrl == @"img\folder.gif")
                {
                    DirectoryEntry oU = new DirectoryEntry(node.Value, user, pw);                  
                    foreach (DirectoryEntry entry2 in this.myad.getAllUserByOU(oU))
                    {                      
                        item = new ListItem(entry2.Name.Substring(3, entry2.Name.Length - 3),entry2.Properties["sAMAccountName"].Value.ToString());
                        if (num != -1)
                        {
                            if (!this.ListBox1.Items.Contains(item) && ListBox1.Items.Count < num)
                            {
                                this.ListBox1.Items.Add(item);
                            }
                        }
                        else
                        {
                            if (!this.ListBox1.Items.Contains(item))
                            {
                                this.ListBox1.Items.Add(item);
                            }
                        }                       
                    }
                    continue;
                }
            }
        }
    }


    protected void btnDel_Click(object sender, EventArgs e)
    {
        while (this.ListBox1.SelectedItem != null)
        {
            TreeNode node = this.TreeView1.FindNode(this.ListBox1.SelectedItem.Value);
            if (node != null)
            {
                node.Checked = false;
            }
            this.ListBox1.Items.Remove(this.ListBox1.SelectedItem);
        }
    }


    protected void btnOK_Click(object sender, EventArgs e)
    {
        string strValue = "";
        string strName = "";
        foreach (ListItem item in this.ListBox1.Items)
        {
            if (strValue == "")
            {
                strValue = entryName + item.Value;
                strName = item.Text; 
            }
            else
            {
                strValue = strValue + ";" + entryName + item.Value;
                strName = strName + ";" + item.Text;
            }
        }       
        string pagetype = Convert.ToString(this.Page.Request.Params["pagetype"]);
        if (pagetype == "wl")
        {
            Page.RegisterStartupScript("js", " <script>var value = opener.document.getElementById('" + Request["aduserid"] + "').value='" + strValue + "';opener.document.getElementById('" + Request["adusername"] + "').value='" + strName + "';window.close();</script>");
        }
        else
        {
            Page.RegisterStartupScript("js", " <script>opener.document.aspnetForm." + Request["aduserid"] + ".value='" + strValue + "';opener.document.aspnetForm." + Request["adusername"] + ".value='" + strName + "';window.close();</script>");
        }
       
    }

    private void SetChildChecked(TreeNode parentNode)
    {
        foreach (TreeNode node in parentNode.ChildNodes)
        {
            node.Checked = parentNode.Checked;
            if (node.ChildNodes.Count > 0)
            {
                this.SetChildChecked(node);
            }
        }
    }

 

    protected void TreeView1_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
    {
        if ((e.Node.ChildNodes.Count == 1) && (e.Node.ChildNodes[0].Value == "tmp"))
        {
            e.Node.ChildNodes.RemoveAt(0);
            this.addNode(e.Node);
        }

        if ((e.Node.ChildNodes.Count == 1) && (e.Node.ChildNodes[0].Value == "orgs"))
        {
            e.Node.ChildNodes.RemoveAt(0);

            List<string> list=new List<string>();
            if (Page.Request.Params["orgs"] == "leader")
            {
                list.Add("公司领导");
            }
            else
            {
                string orgs = System.Web.HttpUtility.UrlDecode(this.Page.Request.Params["orgs"]);
                for (int i = 0; i < orgs.Split(',').Length; i++)
                {
                    list.Add(orgs.Split(',')[i]);
                }
            }

            if (this.Page.Request.Params["include"] == "Y")
            {
                this.addNode(e.Node, true, list);
            }
            else
            {
                this.addNode(e.Node, false, list);
            }
        }

    }


    protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// ADTool 的摘要说明
    /// </summary>
    public class ADTool
    {
        private string ldapHead = "";
        private string ldapTail = "";
        private string admin = "";
        private string adminpass = "";

        private DirectoryEntry rootEntry;

        public ADTool()
        {
            rootEntry = getRootEntry("http://www.cnblogs.com/starcrm/admin/ldap://eip.dymsc.com/DC=dymsc,DC=com", "dymsc\\spsadmin", "czjhwl9946%!");
        }

        /// <summary>
        /// 初始化AD信息
        /// </summary>
        /// <param name="lh"></param>
        /// <param name="lt"></param>
        /// <param name="ad">管理员帐号</param>
        /// <param name="adpass">管理员密码</param>
        public ADTool(string lh, string lt, string ad, string adpass)
        {
            ldapHead = lh;
            ldapTail = lt;
            admin = ad;
            adminpass = adpass;
            rootEntry = getRootEntry(ldapHead + ldapTail, admin, adminpass);
        }

        /// <summary>
        /// 获取AD根条目
        /// </summary>
        /// <param name="ldap"></param>
        /// <param name="user">管理员帐号</param>
        /// <param name="pass">管理员密码</param>
        /// <returns>条目</returns>
        public DirectoryEntry getRootEntry(string ldap, string user, string pass)
        {
            DirectoryEntry searchRoot = new DirectoryEntry(ldap, user, pass,
                    AuthenticationTypes.Secure);
            return searchRoot;
        }

        /// <summary>
        /// 获取目标路径下的条目
        /// </summary>
        /// <param name="OUpath">条目路径</param>
        /// <returns>条目</returns>
        public DirectoryEntry getOU(string OUpath)
        {
            try
            {
                DirectoryEntry searchRoot = rootEntry;
                //TODO: Replace FULL NAME with the name that you want to search for.
                DirectoryEntry ouentry = new DirectoryEntry(ldapHead + OUpath + ", " + ldapTail, admin, adminpass);
                return ouentry;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取目标组织下的条目列表
        /// </summary>
        /// <param name="OU">目标组织</param>
        /// <returns>条目列表</returns>
        public List<DirectoryEntry> getEntryByOU(DirectoryEntry OU)
        {
            List<DirectoryEntry> Entry = new List<DirectoryEntry>();

            System.Collections.IEnumerator enu = OU.Children.GetEnumerator();

            while (enu.MoveNext() == true)
            {
                DirectoryEntry entry = (DirectoryEntry)enu.Current;
                Entry.Add(entry);
            }
            return Entry;
        }


        /// <summary>
        /// 获取目标组织下指定类型的条目列表
        /// </summary>
        /// <param name="OU">目标组织</param>
        /// <returns>条目列表</returns>
        public List<DirectoryEntry> getEntryByOU(DirectoryEntry OU, string strType)
        {
            List<DirectoryEntry> Entry = new List<DirectoryEntry>();

            System.Collections.IEnumerator enu = OU.Children.GetEnumerator();

            while (enu.MoveNext() == true)
            {
                DirectoryEntry entry = (DirectoryEntry)enu.Current;
                if (entry.SchemaClassName == strType)
                {
                    Entry.Add(entry);
                }
            }
            return Entry;
        }


        /// <summary>
        /// 获取目标组织下的子组织列表
        /// </summary>
        /// <param name="OU">目标组织</param>
        /// <returns>子组织列表</returns>
        public List<DirectoryEntry> getChildrenOUByOU(DirectoryEntry OU)
        {
            return getEntryByOU(OU, "organizationalUnit");
        }

        /// <summary>
        /// 获取目标组织下的用户
        /// </summary>
        /// <param name="OU">目标组织</param>
        /// <returns>用户列表</returns>
        public List<DirectoryEntry> getUsersByOU(DirectoryEntry OU)
        {
            return getEntryByOU(OU, "user");
        }

        public List<DirectoryEntry> getAllUserByOU(DirectoryEntry OU)
        {
            List<DirectoryEntry> list = new List<DirectoryEntry>();
            IEnumerator enumerator = OU.Children.GetEnumerator();
            while (enumerator.MoveNext())
            {
                DirectoryEntry current = (DirectoryEntry)enumerator.Current;
                if (current.SchemaClassName == "user")
                {
                    list.Add(current);
                }
                else if (current.SchemaClassName == "organizationalUnit")
                {
                    foreach (DirectoryEntry entry2 in this.getAllUserByOU(current))
                    {
                        list.Add(entry2);
                    }
                    continue;
                }
            }
            return list;
        }

        /// <summary>
        /// 获取目标用户
        /// </summary>
        /// <param name="loginName">登陆名</param>
        /// <returns></returns>
        public DirectoryEntry getUserEntry(string loginName)
        {
            try
            {
                DirectoryEntry searchRoot = rootEntry;
                //TODO: Replace FULL NAME with the name that you want to search for.
                string accountname = loginName.Split('\\')[1];
                //DirectorySearcher dirSearch = new DirectorySearcher(
                //searchRoot, "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + accountname + "))");
                DirectorySearcher dirSearch = new DirectorySearcher(searchRoot, "sAMAccountName=" + accountname );
                SearchResult oSearchResult = dirSearch.FindOne();
                DirectoryEntry dirEntry = oSearchResult.GetDirectoryEntry();
                return dirEntry;
            }
            catch (Exception ex)
            {
                string strErr = ex.Message;
                return null;
            }
        }

        /// <summary>
        /// 获取目标用户隶属的用户组
        /// </summary>
        /// <param name="loginName">登陆名</param>
        /// <returns></returns>
        public ArrayList getUserGroup(string loginName)
        {
            try
            {
                ArrayList arrGroup = new ArrayList();
                DirectoryEntry searchRoot = rootEntry;
                //TODO: Replace FULL NAME with the name that you want to search for.
                string accountname = loginName.Split('\\')[1];
                DirectorySearcher dirSearch = new DirectorySearcher(
                searchRoot, "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + accountname + "))");
                SearchResult oSearchResult = dirSearch.FindOne();
                DirectoryEntry dirEntry = oSearchResult.GetDirectoryEntry();
                for (int i = 0; i < dirEntry.Properties["memberOf"].Count; i++)
                {
                    string group = dirEntry.Properties["memberOf"][i].ToString();
                    int startIndex, endIndex;
                    startIndex = group.IndexOf("=") + 1;
                    endIndex = group.IndexOf(",") - startIndex;
                    group = group.Substring(startIndex, endIndex);
                    arrGroup.Add(group);
                }
                return arrGroup;
            }
            catch (Exception ex)
            {
                string strErr = ex.Message;
                return null;
            }
        }
    }

    protected void btnUp_Click(object sender, EventArgs e)
    {
        if (ListBox1.SelectedIndex != 0 && ListBox1.SelectedIndex != -1)
        {
            int listItemIndex = ListBox1.SelectedIndex; 
            ListItem item = ListBox1.SelectedItem;
            ListBox1.Items.Remove(item);
            ListBox1.Items.Insert(listItemIndex - 1, item);    
        }
    }

    protected void btnDown_Click(object sender, EventArgs e)
    {
        if (ListBox1.SelectedIndex != ListBox1.Items.Count - 1  
            && ListBox1.SelectedIndex != -1)
        {
            int listItemIndex = ListBox1.SelectedIndex;
            ListItem item = ListBox1.SelectedItem;
            ListBox1.Items.Remove(item);
            ListBox1.Items.Insert(listItemIndex + 1, item);
        }
    }

    protected void btnTop_Click(object sender, EventArgs e)
    {
        if (ListBox1.SelectedIndex != 0 && ListBox1.SelectedIndex != -1)
        {
            int listItemIndex = ListBox1.SelectedIndex;
            ListItem item = ListBox1.SelectedItem;
            ListBox1.Items.Remove(item);
            ListBox1.Items.Insert(0, item);
        }
    }

    protected void btnBottom_Click(object sender, EventArgs e)
    {
        if (ListBox1.SelectedIndex != ListBox1.Items.Count - 1
            && ListBox1.SelectedIndex != -1)
        {
            int listItemIndex = ListBox1.SelectedIndex;
            ListItem item = ListBox1.SelectedItem;
            ListBox1.Items.Remove(item);
            ListBox1.Items.Insert(ListBox1.Items.Count, item);
        }
    }
}

posted @ 2009-09-14 14:23  昕友软件开发  阅读(209)  评论(0编辑  收藏  举报
欢迎访问我的开源项目:xyIM企业即时通讯