我正在使用 VB.NET 中的 DirectoryServices.AccountManagement 工具,特别是查找 UserPrincipal,但我需要检索该类不提供的 Department 字段。所以我实现了这个扩展类,我在这里找到了。根据那篇文章,它是从 C# 为 VB 生成的,显然没有经过真正的测试。
Imports System.DirectoryServices.AccountManagement
Public Class UserPrincipalEx
<DirectoryRdnPrefix("CN")> _
<DirectoryObjectClass("Person")> _
Inherits UserPrincipal
' Implement the constructor using the base class constructor.
Public Sub New(ByVal context As PrincipalContext)
MyBase.New(context)
End Sub
' Implement the constructor with initialization parameters.
Public Sub New(ByVal context As PrincipalContext, ByVal samAccountName As String, ByVal password As String, ByVal enabled As Boolean)
MyBase.New(context, samAccountName, password, enabled)
End Sub
' Create the "Department" property.
<DirectoryProperty("department")> _
Public Property Department() As String
Get
If ExtensionGet("department").Length <> 1 Then
Return String.Empty
End If
Return DirectCast(ExtensionGet("department")(0), String)
End Get
Set(ByVal value As String)
ExtensionSet("department", value)
End Set
End Property
' Implement the overloaded search method FindByIdentity.
Public Shared Shadows Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityValue As String) As UserPrincipalEx
Return DirectCast(FindByIdentityWithType(context, GetType(UserPrincipalEx), identityValue), UserPrincipalEx)
End Function
' Implement the overloaded search method FindByIdentity.
Public Shared Shadows Function FindByIdentity(ByVal context As PrincipalContext, ByVal identityType As IdentityType, ByVal identityValue As String) As UserPrincipalEx
Return DirectCast(FindByIdentityWithType(context, GetType(UserPrincipalEx), identityType, identityValue), UserPrincipalEx)
End Function
End Class
这一切都编译得很好,但是当我修改我的代码以使用扩展类而不是标准的 UserPrincipal 时,它不起作用。这是尝试使用扩展的代码:
Dim insPrincipalContext As New PrincipalContext(ContextType.Domain, Environment.UserDomainName, "DC=mydomain,DC=com")
Dim insUserPrincipal As New UserPrincipalEx(insPrincipalContext)
insUserPrincipal.Description = empID
Dim insPrincipalSearcher As New PrincipalSearcher()
Dim currentADUser As UserPrincipalEx
insPrincipalSearcher.QueryFilter = insUserPrincipal
Dim results As PrincipalSearchResult(Of Principal) = insPrincipalSearcher.FindAll
上面的最后一行会产生错误:
MyApp.UserPrincipalEx 类型的主体对象不能用于针对此存储的查询。
我对 vb.net 很陌生,我不确定是什么导致了这个问题。任何有关如何解决它的建议将不胜感激。