VB.NET: AD dan to'liq ismni oling

Foydalanuvchilarning "domen/usarname" identifikatori berilgan to'liq nomini olishga harakat qilyapman. Bir-biridan farqli misollarni sinab ko'rdim, lekin hech kim ishlamayapti. Visual Basic. NET 2010 dan foydalanayapman.

Dastlab VBSda quyidagi kodni topdim va VBA-ga joylashtirdim va chiroyli ishladim. Agar VB.NET-2010 da xuddi shu koddan foydalanishga harakat qilsam, bir nechta xatoliklar va LDAP yo'lini topsam, qo'lda kiritgan bo'lsam ham.

Function FindUser()
 On Error GoTo Err

 Dim objRoot As Variant
 Dim LDAPdomainName As String
 Dim UserName As String
 Dim UserDomain As String

 Dim cn As Variant
 Dim cmd As Variant
 Dim rs As Variant


UserName = VBA.Environ("UserName") ' Gets Current User
UserDomain = VBA.Environ("UserDomain") 'Gets Current User's Domain


Set objRoot = GetObject("LDAP://RootDSE")
Domain= objRoot.Get("defaultNamingContext") 



 Set cn = CreateObject("ADODB.Connection")
 Set cmd = CreateObject("ADODB.Command")
 Set rs = CreateObject("ADODB.Recordset")

 cn.Open "Provider=ADsDSOObject;"

 cmd.activeconnection = cn
 'cmd.commandtext = "SELECT ADsPath FROM 'LDAP://" & Domain & "' WHERE sAMAccountName = '" & UserName & "'"
 'To see all attributes names available, connect with Active Directory Explorer and add to Select.
 cmd.commandtext = "SELECT cn, mail  FROM 'LDAP://" & Domain & "' WHERE sAMAccountName = '" & UserName & "'"
 Set rs = cmd.Execute


 Do Until rs.EOF
    Debug.Print rs("cn") & " E-mail: " & rs("mail")
    rs.MoveNext
 Loop


Exit_Err:
 If Not rs Is Nothing Then rs.Close
 If Not cn Is Nothing Then cn.Close
 Set rs = Nothing
 Set cmd = Nothing
 Set cn = Nothing
 Exit Function

Err:
 If Err <> 0 Then
    MsgBox "Error connecting to Active Directory Database: " & Err.Description
 Else
    If Not rs.BOF And Not rs.EOF Then
        rs.MoveFirst
        MsgBox rs(0)
    Else
        MsgBox "Not Found"
    End If
 End If
 Resume Exit_Err


End Function
1
hozirgacha nimani sinab ko'rdingiz? Siz hozirgacha sinovdan o'tgan bir necha kodni kiritishingiz kerak, shuning uchun siz allaqachon o'rgangan narsalarni taklif qilmaymiz.
qo'shib qo'ydi muallif Matthieu, manba
Xullas, sinab ko'rgan narsa ishlamadi, shuning uchun ishlayotgan narsa - bu to'g'ri taklif.
qo'shib qo'ydi muallif Yatrix, manba

4 javoblar

Agar siz .NET 3.5 va undan yuqori darajada bo'lsangiz, System.DirectoryServices.AccountManagement (S.DS.AM) nom maydonini tekshiring. Bu haqda hamma narsani o'qing:

Asosan, domen kontekstini belgilashingiz va ADda foydalanuvchilar va/yoki guruhlarni osongina topishingiz mumkin:

' set up domain context
Dim ctx As New PrincipalContext(ContextType.Domain)

' find a user
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, "domain\username")

' do something here....     
If user IsNot Nothing Then
End If

' find the group in question
Dim group As GroupPrincipal = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere")

' if found....
If group IsNot Nothing Then
    ' iterate over members
    For Each p As Principal In group.GetMembers()
            ' do whatever you need to do to those members
        Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName)
    Next
End If

Yangi S.DS.AM ADda foydalanuvchilar va guruhlar bilan o'ynashni osonlashtiradi!

3
qo'shib qo'ydi
Ctx da New PrincipalContext (ContextType.Domain) sifatida Ldap istisnosiz ishlov berilmagan xato xabari topdim: "Ulanish o'rnatilishi mumkin emas."
qo'shib qo'ydi muallif Rick, manba

Nima haqida:

Imports System.DirectoryServices.AccountManagement

import      

Asosiz userFullName = String = UserPrincipal.Current.DisplayName

3
qo'shib qo'ydi

Menga 2 ta vazifalar kirdi. Buning menga yordam beradigan 2 funktsiyasi bor. Net 2.0 .net 4.0 MSDN ga tezkor qarashni boshlaganidan so'ng, bu ishi ning barcha versiyalarida ishlaydi.

2 vazifalar quyidagilardir:


'Determines your domain name
Private Function DomainName() As String
    Dim objRootDSE As New System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
    DomainName = objRootDSE.Properties("defaultNamingContext")(0)
End Function

'Will output user first name and last name. 
Public Sub ReturnUserName(ByVal UserAccountName As String)
    ' add a reference to System.DirectoryServices.dll
    Dim srch As System.DirectoryServices.DirectorySearcher
    Dim result As System.DirectoryServices.SearchResult
    Dim de, dir As System.DirectoryServices.DirectoryEntry

    de = New System.DirectoryServices.DirectoryEntry("LDAP://" & DomainName())
    srch = New System.DirectoryServices.DirectorySearcher(de)

    srch.SearchScope = SearchScope.Subtree
    srch.PropertiesToLoad.Add("givenName")
    srch.PropertiesToLoad.Add("sn")

    'Other field examples:
    'srch.PropertiesToLoad.Add("distinguishedName")
    'srch.PropertiesToLoad.Add("uid")

    ' users require both "user" and "person" filters
    ' and we also add the sAMAccountName to get the user passed.
    ' If you want to return all users in the domain remove the (sAMAccountName=" & UserAccountName & ")
    ' from the filter below.
    srch.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" & UserAccountName & "))"

    For Each result In srch.FindAll()
        dir = result.GetDirectoryEntry
        ' Properties are case sensitive!
        Debug.WriteLine(dir.Properties("givenname").Value & " " & dir.Properties("cn").Value)
    Next
End Sub

Bunga misol chaqiramiz:


Public Sub TestUserCall()
    'Returns the current logged in user.
    Call ReturnUserName(System.Security.Principal.WindowsIdentity.GetCurrent.Name)
End Sub

Ushbu misol chaqiruvni bajarish uchun 2.0 va 4.0 oralig'ida ishlaydi va shu vaqtga qadar chop etilgan barcha versiyalarda ishi ishlashi kerak.

Tegishli MSDN sahifalari quyidagilardir:

http:// /msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.name(v=VS.100).aspx

http://msdn.microsoft.com/en -us/library/94se97ay (v = VS.80) .aspx

http://msdn.microsoft. com/uz-US/library/system.directoryservices.directoryentry (v = VS.80) .aspx

http://msdn.microsoft. com/en-US/library/system.directoryservices.searchresult (v = VS.80) .aspx

1
qo'shib qo'ydi
"DomainName = objRootDSE.Properties (" defaultNamingContext ") satrida (0)" Menga COMException ishlov berilmagan xatolik yuz berdi: "Tarmoq yo'li topilmadi."
qo'shib qo'ydi muallif Rick, manba
Tarmoqdagi barcha DNS-serverlarga, to'liq hostname va hatto IP-adresiga o'zgartirish kiritishga harakat qildi, biroq shu bilan bir xil xato yuzaga keldi.
qo'shib qo'ydi muallif Rick, manba
Men Windows Server 2008 da ishlaydigan asosiy domen tekshiruvchilariga ishora qilgandim.
qo'shib qo'ydi muallif Rick, manba
Faqat sizning kompyuteringiz domen serverini qaytarib bo'lmasligi mumkin deb o'ylayman. Iltimos, "LDAP: //server.com/RootDSE" server.com bilan "LDAP://RootDSE" o'rniga domeningiz DNS-ning o'rnini almashtirishni sinab ko'ring.
qo'shib qo'ydi muallif Mako Steel, manba
DomainName() pastki qismidagi birinchi satrni Dim objRootDSE deb o'zgartiring. New System.DirectoryServices.DirectoryEntry ("LDAP: //server.com/R‌ ootDSE") server.com domen serveri DNS-xisoblanadi.
qo'shib qo'ydi muallif Mako Steel, manba
Domeningiz tekshiruvi qanday operatsion tizimi hisoblanadi? Windows Server 2003dan shubhalanishim kerakmi?
qo'shib qo'ydi muallif Mako Steel, manba
DNS serveri (serverlari) ga qarashga harakat qilyapsiz. Siz domen tekshiruvi serverida ishora qilishingiz kerak, siz buyruq buyruqni ochib, "set logonserver" ni kiritish orqali manzilingizni topishingiz mumkin, bu sizni DC ning UNC nomini berishi va server.com ning o'rniga "\\"
qo'shib qo'ydi muallif Mako Steel, manba
Hech qachon bunga hech qachon duch kelmaysan, hech kim menga nima uchun bunday bo'lishi mumkinligi haqida javob berishga o'xshaydi. Javobni taklif qiladigan boshqa xabar afsuski, bu juda jahl bilan javob beradi: social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/…
qo'shib qo'ydi muallif Mako Steel, manba

Ushbu turdagi vazifalarni bajarish uchun System.DirectoryServices nom maydonidan foydalanishingiz mumkin ( DirectoryServices LDAP uchun boshqariladigan qavatni).

Try
   ' Bind to the users container.
    Dim entry As New 
          DirectoryEntry("LDAP://CN=users,DC=fabrikam,DC=com")

    ' Create a DirectorySearcher object.
    Dim mySearcher As New DirectorySearcher(entry)

    ' Create a SearchResultCollection object to hold a collection
    ' of SearchResults returned by the FindAll method.
    Dim result As SearchResultCollection = mySearcher.FindAll()

    ' Create an object to hold a single result from the 
    ' result collection.
    Dim resEnt1 As SearchResult

    ' Get search results. For more information, 
    ' see Getting Search Results.
    ' 
    ' This sample uses Try...Catch to catch errors.
    ' Create an Exception object. For more information, 
    ' see System.Exception.

Catch Exception1 As System.Runtime.InteropServices.COMException
    Console.WriteLine(Exception1.Message)

Catch Exception2 As InvalidOperationException
    Console.WriteLine(Exception2.Message)

Catch Exception3 As NotSupportedException
    Console.WriteLine(Exception3.Message)

End Try 

You can use a search string such as "(&(objectCategory=user)(objectClass=person)(sAMAccountName=" + userId + "))" to search for a user (userID would need to be replaced with the User's ID).

Uni bir-biriga bog'lash uchun quyidagi parchani o'zgartirishingiz mumkin: barcha xususiyatlar . Keyin uni faqat foydalanuvchi nomiga qaratishga sozlashingiz mumkin.

Dim results As SearchResultCollection = Nothing

Try
    ' Bind to the users container.
    Dim path As String = "LDAP://CN=users,DC=fabrikam,DC=com"
    path = "LDAP://CN=Users,DC=strohmadom,DC=nttest,DC=microsoft,DC=com"
    Dim entry As New DirectoryEntry(path)

    ' Create a DirectorySearcher object.
    Dim mySearcher As New DirectorySearcher(entry)

    ' Set a filter for users with the name test.
    mySearcher.Filter = "(&(objectClass=user)(anr=test*))"

    ' Use the FindAll method to return objects to a SearchResultCollection.
    results = mySearcher.FindAll()

    ' Iterate through each SearchResult in the SearchResultCollection.
    Dim searchResult As SearchResult
    For Each searchResult In results
        ' Display the path of the object found.
        Console.WriteLine("Search properties for {0}", _
            searchResult.Path)

        ' Iterate through each property name in each SearchResult.
        Dim propertyKey As String
        For Each propertyKey In searchResult.Properties.PropertyNames
            ' Retrieve the value assigned to that property name 
            ' in the ResultPropertyValueCollection.
            Dim valueCollection As ResultPropertyValueCollection = searchResult.Properties(propertyKey)

            ' Iterate through values for each property name in each SearchResult.
            Dim propertyValue As Object
            For Each propertyValue In valueCollection
                ' Handle results. Be aware that the following 
                ' WriteLine() only returns readable results for 
                ' properties that are strings.
                Console.WriteLine("{0}:{1}", _
                    propertyKey, _
                    propertyValue.ToString())
            Next propertyValue
        Next propertyKey
    Next searchResult
Finally
    ' To prevent memory leaks, always call 
    ' SearchResultCollection.Dispose() manually.
    If Not results Is Nothing Then
        results.Dispose()
        results = Nothing
    End If
End Try
0
qo'shib qo'ydi
"Results = mySearcher.FindAll ()" qatorida "Tarmoq yo'li topilmadi" deb xato qilyapman. LDAP usuliga LDAP-serverni almashtirdik.
qo'shib qo'ydi muallif Rick, manba