我試圖從活動目錄獲取管理器名稱,但在引發異常時收到錯誤「An operation error occured」。嘗試從活動目錄中檢索數據時發生操作錯誤
代碼如下:
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
try
{
var requester = properties.Web.CurrentUser;
properties.AfterProperties["Requester"] = requester;
//Get the manager name from the active directory
var domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
DirectoryEntry dir = new DirectoryEntry("LDAP://" + domain);
//Exeception occurs on this line below.
string managerName = dir.Properties["Manager"].Value.ToString();
properties.AfterProperties["Manager"] = managerName;
}
catch(Exception ex)
{
}
}
編輯 能得到這個想通了,使用下面的代碼:
try
{
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Environment.UserName);
string samAccountName = "";
if (user != null)
{
// do something here....
samAccountName = user.SamAccountName;
}
//Get the manager name from the active directory
var domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
using(DirectoryEntry dir = new DirectoryEntry("LDAP://" + domain))
{
using (DirectorySearcher ds = new DirectorySearcher(dir, "samAccountName=" + samAccountName))
{
SearchResult result = ds.FindOne();
string managerName = result.Properties["manager"][0].ToString();
}
}
}
catch (Exception ex)
{
var message = ex.Message;
}
'Properties'是你需要轉換,對於初學者 '字符串managerName =(字符串)dir.Properties對象[「Manager」]。Value.ToString();'你怎麼知道當你在catch中沒有代碼的時候真正的錯誤是什麼'var message = ex.Message;'你能發佈完整的代碼嗎?方法也使用調試器,並通過每一行驗證您確實具有有效的數據/值。 – MethodMan 2013-03-21 17:05:51
當我調試時逐步完成時,我會看到異常處於捕獲狀態時的情況。我會嘗試一下你的建議 – 2013-03-21 17:06:36
只試圖幫助Ryan我知道AD很好,而我所看到的看起來像是在你的LDAP中缺少了一些東西://你的conn中缺少'389'地址字符串 – MethodMan 2013-03-21 17:07:15