2010-10-26 59 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