2010-10-26 66 views
3

我需要獲得存儲在Active Directory的數據庫中的用戶的一些信息,我有一個簡單的函數來做到這一點:SQL CLR存儲過程來查詢Active Directory

using (DirectoryEntry de = new DirectoryEntry("LDAP://ANYGIVENDOMAIN")) 
{ 
    using (DirectorySearcher adSearch = new DirectorySearcher(de)) 
    { 
     adSearch.Filter = "(sAMAccountName=jdoe)";     
     SearchResult adSearchResult = adSearch.FindOne(); 

     StringBuilder sb = new StringBuilder(); 
     sb.AppendLine(adSearchResult.Properties["displayname"][0].ToString()); 
     sb.AppendLine(adSearchResult.Properties["givenName"][0].ToString()); 
     sb.AppendLine(adSearchResult.Properties["objectSid"][0].ToString()); 
     sb.AppendLine(adSearchResult.Properties["description"][0].ToString()); 
     sb.AppendLine(adSearchResult.Properties["objectGUID"][0].ToString()); 
    } 
} 

從正在運行WinForm按我的意願做,但在SQL Server項目類型中,我無法將名稱空間System.DirectoryServices添加到引用。

任何人都知道爲什麼?

問候

JE

+0

正如旁白 - 如果我是你,我就一定要** **檢查是否一個給定的屬性存在或不; 'if(adSearchResult.Properties [「...」]!= null)....'否則,你肯定會早晚得到一些空指針異常.... – 2010-10-26 20:29:44

回答

2

參見:Supported .NET Framework Libraries

Unsupported libraries can still be called from your managed stored procedures, triggers, user-defined functions, user-defined types, and user-defined aggregates. The unsupported library must first be registered in the SQL Server database, using the CREATE ASSEMBLY statement, before it can be used in your code. Any unsupported library that is registered and run on the server should be reviewed and tested for security and reliability.

For example, the System.DirectoryServices namespace is not supported. You must register the System.DirectoryServices.dll assembly with UNSAFE permissions before you can call it from your code. The UNSAFE permission is necessary because classes in the System.DirectoryServices namespace do not meet the requirements for SAFE or EXTERNAL_ACCESS. For more information, see CLR Integration Programming Model Restrictions and CLR Integration Code Access Security .

+0

謝謝我正在調查該文件,似乎它正是我所需要的。 – JorgeEscobar 2010-10-26 19:41:17

+0

我所做的一切需要,現在我收到此錯誤:請求類型「系統的權限:用戶定義的例程或聚合GetInformationFromActiveD「 System.Security.SecurityException的執行過程中發生 一個.NET Framework錯誤。 DirectoryServices.DirectoryServicesPermission,System.DirectoryServices,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a'失敗。 System.Security.SecurityException:在StoredProcedures.getUserInfoFromActiveDirectory(SqlString用戶名,SqlString域,SqlString和說明,SqlString和顯示名稱) 權限?從winforms它的工作 – JorgeEscobar 2010-10-26 19:59:29

+0

原來,我需要使我的程序集也不安全,這使得伎倆。總結 1.將目錄服務的程序集添加爲不安全(也在數據庫中更改可信賴的權限) 2.將使用它的程序集也添加爲不安全 3.享受 希望這可以幫助其他人。 並感謝喬指出我正確的方向。 :) – JorgeEscobar 2010-10-26 20:12:34