我正在使用VB.NET中的DirectoryServices.AccountManagement工具,特别是找到UserPrincipal,但我需要检索该类不提供的Department字段。所以我实现了这个扩展类,我找到了here。根据该帖子,它是从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很新,我不确定是什么导致了这个问题。任何关于如何解决它的建议将不胜感激。
答案 0 :(得分:1)
我知道这是一个老问题,但我在扩展的UserPrincipal类中遇到了同样的错误。
更改
<DirectoryObjectClass("Person")> _
要:
<DirectoryObjectClass("user")> _