取出AD中一個組的所有成員信息(C#實現功能配合EXT做的界面)
功能說明:
通過組名稱(AD組),取出用戶列表和用戶信息,如賬號、用戶名稱、說明、部門、職位、郵箱、OU等等AD賬號中已維護的信息。用EXT做的界面,可以導入多種格式的文件,當然用戶只是要Exsl格式就好。
先上效果圖:
1. 手工指定多個組名
2. 從列出的組名中選取、導出文件
需求背景:
之前开放的一个公共盘,一有职员需要,就申请开通权限,时间长了,人员的进进出出换了好多。有的部门管理人员也换了。出于一些原因,某天经理和yao的邮件
经理:please send the user access right for K drive to me 。
yao:是每一个用户的话,只好手工一个一个用户名列出,给一些时间才行。
经理:多做一点事情,我需要每个群组里的用户。
堂文,可否写一个小系统,通过系统方法查询出来?以后可能常要拿这些信息。(这里开始邮件有抄送给我。)
yao:很多群组下面还包括群组,是否也要列出,我导出的只有登录帐号,没有名称。
经理:也需要,因为这个清单会交给他们自己做review,哪些权限需要调整,所以只给群组的名称,别人也看不懂是什么。
我:我可以測試一下看看,道理上是可以的。另外,P盤是否也要做控制?本來只是放WSD的數據的,現在什麼東西都有.
yao:现在我只能导出帐号名,没有其他信息,如果要全名那就要一个个在AD上对了。
文,有没测试是否可以拿到我列出组的成员全名。
我:昨晚我已測試過,可以一個組一個組來列出組下邊的所有成員,成員的應有的信息都可以取到,現在只取出如下的信息,看是否是你需要的?如果是,我可以發布測試版本到服務器上。
yao:文,这些信息应该足够。
以下是一些关键代码:
取一个组下的所有成员
public DataSet GetUsersForGroup(string GroupName) { if (GroupName.IndexOf(';') > 0) { return GetUsersForGroup(GroupName.Split(new char[] { ';' })); } if (GroupName == string.Empty) return null; try { DataSet dsUser = new DataSet(); DirectoryEntry de = GetDirectoryObject(); //create instance fo the direcory searcher DirectorySearcher deSearch = new DirectorySearcher(); //set the search filter deSearch.SearchRoot = de; //deSearch.PropertiesToLoad.Add("cn"); deSearch.Filter = "(&(objectClass=group)(cn=" + GroupName + "))"; //get the group result SearchResult results = deSearch.FindOne(); DataTable tbUser = dsUser.Tables.Add("Users"); tbUser.Columns.Add("GroupName"); tbUser.Columns.Add("samaccountname"); tbUser.Columns.Add("UserName"); tbUser.Columns.Add("DisplayName"); tbUser.Columns.Add("EMailAddress"); //Create default row //DataRow rwDefaultUser = tbUser.NewRow(); //rwDefaultUser["UserName"] = "0"; //rwDefaultUser["DisplayName"] = "(Not Specified)"; //rwDefaultUser["EMailAddress"] = "(Not Specified)"; //tbUser.Rows.Add(rwDefaultUser); //if the group is valid, then continue, otherwise return a blank dataset if (results != null) { //create a link to the group object, so we can get the list of members //within the group DirectoryEntry deGroup = new DirectoryEntry(results.Path, ADUser, ADPassword, AuthenticationTypes.Secure); //assign a property collection System.DirectoryServices.PropertyCollection pcoll = deGroup.Properties; int n = pcoll["member"].Count; //if there are members fo the group, then get the details and assign to the table for (int l = 0; l < n; l++) { //create a link to the user object sot hat the FirstName, LastName and SUername can be gotten DirectoryEntry deUser = new DirectoryEntry(@"LDAP://abc.com/" + pcoll["member"][l].ToString(), ADUser, ADPassword, AuthenticationTypes.Secure); try { //set a new empty row DataRow rwUser = tbUser.NewRow(); //populate the column rwUser["GroupName"] = GroupName; rwUser["samaccountname"] = GetProperty(deUser, "samaccountname"); rwUser["UserName"] = GetProperty(deUser, "cn"); rwUser["DisplayName"] = GetProperty(deUser, "givenName") + " " + GetProperty(deUser, "sn"); rwUser["EMailAddress"] = GetProperty(deUser, "mail"); //append the row to the table of the dataset tbUser.Rows.Add(rwUser); //close the directory entry object deUser.Close(); } catch (Exception ee) { throw ee; } } de.Close(); deGroup.Close(); } if (dsUser.Tables[0].Rows.Count<=0) { DataRow rwDefaultUser = tbUser.NewRow(); rwDefaultUser["GroupName"] = GroupName; rwDefaultUser["samaccountname"] = "(Not Specified)"; rwDefaultUser["UserName"] = "(Not Specified)"; rwDefaultUser["DisplayName"] = "(Not Specified)"; rwDefaultUser["EMailAddress"] = "(Not Specified)"; tbUser.Rows.Add(rwDefaultUser); } return dsUser; } catch (Exception ee) { throw ee; } }
取指写成员的某个属性
public string GetProperty(DirectoryEntry oDE, string PropertyName) { try { if (oDE.Properties.Contains(PropertyName)) { return oDE.Properties[PropertyName][0].ToString(); } else { return string.Empty; } } catch (Exception ee) { throw ee; } }
取出多个组的所有成员
public DataSet GetUsersForGroup(string[] GroupName) { try { DataSet dsUser = new DataSet(); DataTable tbUser = dsUser.Tables.Add("Users"); tbUser.Columns.Add("GroupName"); tbUser.Columns.Add("samaccountname"); tbUser.Columns.Add("UserName"); tbUser.Columns.Add("DisplayName"); tbUser.Columns.Add("EMailAddress"); foreach (string s in GroupName) { DataSet _dsUser = GetUsersForGroup(s); for (int i = 0; i < _dsUser.Tables["Users"].Rows.Count; i++) { //set a new empty row DataRow rwUser = tbUser.NewRow(); //populate the column rwUser["GroupName"] = _dsUser.Tables["Users"].Rows[i]["GroupName"]; rwUser["samaccountname"] = _dsUser.Tables["Users"].Rows[i]["samaccountname"]; rwUser["UserName"] = _dsUser.Tables["Users"].Rows[i]["UserName"]; rwUser["DisplayName"] = _dsUser.Tables["Users"].Rows[i]["DisplayName"]; rwUser["EMailAddress"] = _dsUser.Tables["Users"].Rows[i]["EMailAddress"]; //append the row to the table of the dataset tbUser.Rows.Add(rwUser); } _dsUser = null; } return dsUser; } catch (Exception ee) { throw ee; } }
取出AD中所有的组名
public DataSet GetGroups() { try { DataSet dsGroup = new DataSet(); DirectoryEntry de = GetDirectoryObject(); //create instance fo the direcory searcher DirectorySearcher deSearch = new DirectorySearcher(); //set the search filter deSearch.SearchRoot = de; //deSearch.PropertiesToLoad.Add("cn"); deSearch.Filter = "(&(objectClass=group))"; //find the first instance SearchResultCollection results = deSearch.FindAll(); //Create a new table object within the dataset DataTable tbGroup = dsGroup.Tables.Add("Groups"); tbGroup.Columns.Add("GroupName"); //if there are results (there should be some!!), then convert the results //into a dataset to be returned. if (results.Count > 0) { //DataRow rwGroup1 = tbGroup.NewRow(); //rwGroup1["GroupName"] = "all"; //tbGroup.Rows.Add(rwGroup1); ////iterate through collection and populate the table with ////the Group Name foreach (SearchResult Result in results) { //set a new empty row DataRow rwGroup = tbGroup.NewRow(); //populate the column rwGroup["GroupName"] = Result.Properties["cn"][0]; //append the row to the table of the dataset tbGroup.Rows.Add(rwGroup); } } else { throw new Exception("需要提供AD的組或稱。"); } return dsGroup; } catch (Exception ee) { throw ee; } }
private DirectoryEntry GetDirectoryObject() { try { DirectoryEntry oDE; oDE = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure); return oDE; } catch (Exception ee) { throw ee; } }
前台页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GroupsInfoReport.aspx.cs" Inherits="GroupsInfoReport" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Xml.Xsl" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Linq" %> <%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %> <script runat="server"> private void GetGroupInfoData(object sender, DirectEventArgs e) { CoreTools.AD.ADHelper ad = new CoreTools.AD.ADHelper(); ad.ADPath = @"LDAP://abc.com/DC=abc,DC=com"; if (ddlGroup.SelectedItem.Text != "all") { if (TextField1.Text == "") { Store1.DataSource = ad.GetUsersForGroup(ddlGroup.SelectedItem.Text); } else { Store1.DataSource = ad.GetUsersForGroup(TextField1.Text); } } else { DataTable t= ad.GetGroups().Tables[0]; string[] ss = new string[t.Rows.Count-1]; for (int k = 1; k < t.Rows.Count; k++) { ss[k-1] = t.Rows[k-1][0].ToString(); } ad.GetUsersForGroup(ss); } Store1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { try { CoreTools.AD.ADHelper ad = new CoreTools.AD.ADHelper(); ad.ADPath = @"LDAP://abc.com/DC=abc,DC=com"; if (!X.IsAjaxRequest) { GroupNames.DataSource = ad.GetGroups(); GroupNames.DataBind(); if (ddlGroup.SelectedItem.Text != "all") { if (TextField1.Text == "") { Store1.DataSource = ad.GetUsersForGroup(ddlGroup.SelectedItem.Text); } else { Store1.DataSource = ad.GetUsersForGroup(TextField1.Text); } } else { string[] ss=new string[ddlGroup.Items.Count]; for (int i = 1; i < ddlGroup.Items.Count; i++) { ss[i] = ddlGroup.Items[i].Text; } ad.GetUsersForGroup(ss); } Store1.DataBind(); } } catch { } } protected void Store1_RefreshData(object sender, StoreRefreshDataEventArgs e) { CoreTools.AD.ADHelper ad = new CoreTools.AD.ADHelper(); ad.ADPath = @"LDAP://abc.com/DC=abc,DC=com"; if (ddlGroup.SelectedItem.Text != "all") { if (TextField1.Text == "") { Store1.DataSource = ad.GetUsersForGroup(ddlGroup.SelectedItem.Text); } else { Store1.DataSource = ad.GetUsersForGroup(TextField1.Text); } } else { string[] ss=new string[ddlGroup.Items.Count]; for (int i = 1; i < ddlGroup.Items.Count; i++) { ss[i] = ddlGroup.Items[i].Text; } ad.GetUsersForGroup(ss); } Store1.DataBind(); } protected void Store1_Submit(object sender, StoreSubmitDataEventArgs e) { string format = this.FormatType.Value.ToString(); XmlNode xml = e.Xml; this.Response.Clear(); switch (format) { case "xml": string strXml = xml.OuterXml; this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xml"); this.Response.AddHeader("Content-Length", strXml.Length.ToString()); this.Response.ContentType = "application/xml"; this.Response.Write(strXml); break; case "xls": this.Response.ContentType = "application/vnd.ms-excel"; this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xls"); XslCompiledTransform xtExcel = new XslCompiledTransform(); xtExcel.Load(Server.MapPath("Excel.xsl")); xtExcel.Transform(xml, null, Response.OutputStream); break; case "csv": this.Response.ContentType = "application/octet-stream"; this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.csv"); XslCompiledTransform xtCsv = new XslCompiledTransform(); xtCsv.Load(Server.MapPath("Csv.xsl")); xtCsv.Transform(xml, null, Response.OutputStream); break; } this.Response.End(); } </script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>GridPanel using DataTable with Paging and Remote Reloading - Ext.NET Examples </title> <link href="http://www.cnblogs.com/http://www.cnblogs.com/resources/css/examples.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var template = '<span style="color:{0};">{1}</span>'; var change = function (value) { return String.format(template, (value > 0) ? "green" : "red", value); }; var pctChange = function (value) { return String.format(template, (value > 0) ? "green" : "red", value + "%"); }; var exportData = function (format) { FormatType.setValue(format); var store = GridPanel1.store; store.directEventConfig.isUpload = true; var records = store.reader.readRecords(store.proxy.data).records, values = []; for (i = 0; i < records.length; i++) { var obj = {}, dataR; if (store.reader.meta.id) { obj[store.reader.meta.id] = records[i].id; } dataR = Ext.apply(obj, records[i].data); if (!Ext.isEmptyObj(dataR)) { values.push(dataR); } } store.submitData(values); store.directEventConfig.isUpload = false; }; </script> </head> <body> <form id="Form1" runat="server"> <ext:ResourceManager ID="ResourceManager1" runat="server" /> <ext:Store ID="Store1" runat="server" OnRefreshData="Store1_RefreshData" OnSubmitData="Store1_Submit"> <Reader> <ext:JsonReader> <Fields> <ext:RecordField Name="GroupName" /> <ext:RecordField Name="samaccountname" /> <ext:RecordField Name="UserName" /> <ext:RecordField Name="DisplayName" /> <ext:RecordField Name="EMailAddress" /> </Fields> </ext:JsonReader> </Reader> </ext:Store> <ext:Store ID="GroupNames" runat="server" AutoDataBind="true" remarks="GroupName"> <Reader> <ext:JsonReader> <Fields> <ext:RecordField Name="GroupName"> </ext:RecordField> </Fields> </ext:JsonReader> </Reader> </ext:Store> <ext:Hidden ID="FormatType" runat="server" /> <ext:FormPanel ID="FormPanel1" runat="server" ButtonAlign="Right" Width="605" Title="查詢條件" > <Items> <ext:ComboBox ID="ddlGroup" runat="server" AutoWidth="true" DisplayField="GroupName" FieldLabel="组名称" HideLabel="false" PageSize="10" Resizable="true" StoreID="GroupNames" Width="180" TriggerAction="All" ValueField="GroupName" > </ext:ComboBox> <ext:TextField ID="TextField1" runat="server" FieldLabel="指定组名" AutoWidth="true" > </ext:TextField> </Items> <Buttons> <ext:Button ID="btnAddNewQaItem" runat="server" Text="查詢" > <DirectEvents> <Click OnEvent="GetGroupInfoData" > <EventMask MinDelay="10000" Msg="正在從後台查詢數據..." ShowMask="true" /> </Click> </DirectEvents> </ext:Button> </Buttons> </ext:FormPanel> <ext:GridPanel ID="GridPanel1" runat="server" StoreID="Store1" Title="信息" Width="605" Height="300" AutoExpandColumn="GroupName"> <ColumnModel ID="ColumnModel1" runat="server"> <Columns> <ext:Column ColumnID="GroupName" Header="组名称" Width="75" DataIndex="GroupName"> </ext:Column> <ext:Column Header="账号" Width="75" DataIndex="samaccountname"> </ext:Column> <ext:Column Header="用户" Width="75" DataIndex="UserName" > </ext:Column> <ext:Column Header="显示名称" Width="85" DataIndex="DisplayName" > </ext:Column> <ext:Column Header="邮件" Width="105" DataIndex="EMailAddress" > </ext:Column> </Columns> </ColumnModel> <SelectionModel> <ext:RowSelectionModel ID="RowSelectionModel1" runat="server" /> </SelectionModel> <LoadMask ShowMask="true" /> <TopBar> <ext:Toolbar ID="Toolbar1" runat="server"> <Items> <ext:ToolbarFill ID="ToolbarFill1" runat="server" /> <ext:Button ID="Button1" runat="server" Text="To XML" Icon="PageCode"> <Listeners> <Click Handler="exportData('xml');" /> </Listeners> </ext:Button> <ext:Button ID="Button2" runat="server" Text="To Excel" Icon="PageExcel"> <Listeners> <Click Handler="exportData('xls');" /> </Listeners> </ext:Button> <ext:Button ID="Button3" runat="server" Text="To CSV" Icon="PageAttach"> <Listeners> <Click Handler="exportData('csv');" /> </Listeners> </ext:Button> </Items> </ext:Toolbar> </TopBar> <BottomBar> <ext:PagingToolbar ID="PagingToolbar1" runat="server" PageSize="11" StoreID="Store1" /> </BottomBar> </ext:GridPanel> </form> </body> </html>
因这是基于前一个更改AD用户密码项目的,所以不能完成的拆出来。过此时间有空写写该项目,再详细一下说说。