Solved

GUID of a group in active directory

Posted on 2012-03-30
12
1,270 Views
Last Modified: 2012-04-06
How do I get the guid of a group in active directory - I am using this code to get the group - can it be modified to get the string guid or guid as well as the group
    Public Shared Function GetAllGroups() As DataSet
       
        Dim dsGroup As New DataSet()
        Dim dirEntry As DirectoryEntry = New DirectoryEntry("LDAP://OU=TRGET OU,OU=AN OU,DC=COMPANY,DC=com", "USER", "PASS")
        'create instance fo the direcory searcher
        Dim dirSearch As New DirectorySearcher()
        'set the search filter
        dirSearch.SearchRoot = dirEntry
        'Set the filter
        dirSearch.Filter = "(objectClass=group)" 
        'find the first instance
        Dim searchResults As SearchResultCollection = dirSearch.FindAll()
        'Create a new table object within the dataset
        Dim dtGroup As DataTable = dsGroup.Tables.Add("Groups")
        dtGroup.Columns.Add("GroupName")
        'if there are results (there should be some!!), then convert the results
        'into a dataset to be returned.
        If searchResults.Count > 0 Then
            'iterate through collection and populate the table with
            'the Group Name
            For Each Result As SearchResult In searchResults
                'set a new empty row
                Dim drGroup As DataRow = dtGroup.NewRow()
                'populate the column
                drGroup("GroupName") = Result.Properties("cn")(0)
                'append the row to the table of the dataset
                dtGroup.Rows.Add(drGroup)
            Next
        End If
        Return dsGroup
    End Function

Open in new window

0
Comment
Question by:r3nder
  • 7
  • 4
12 Comments
 
LVL 10

Assisted Solution

by:acbxyz
acbxyz earned 300 total points
ID: 37789482
Can't test it here, but this should work.
Add another column to the DataSet:
        dtGroup.Columns.Add("GroupGUID")
and populate the value:
                drGroup("GroupGUID") = Result.Properties("objectGUID")(0)


You can also use objectSid if you want.
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37790043
i found a very good(complete) article in AD, kindly see and let me know if it helps:-

http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C
0
 
LVL 6

Author Comment

by:r3nder
ID: 37792203
I keep getting System.Bytein the label i created to check to see if I got it
Why cant I get the GUID
    Public Shared Function GetAllGroups() As DataSet
        Dim dsGroup As New DataSet()
        Dim dirEntry As DirectoryEntry = New DirectoryEntry("LDAP://AD.local", "USER", "PASS")
        'create instance fo the direcory searcher
        Dim dirSearch As New DirectorySearcher()
        'set the search filter
        dirSearch.SearchRoot = dirEntry
        'Set the filter
        dirSearch.Filter = "(objectClass=group)"
        'find the first instance
        Dim searchResults As SearchResultCollection = dirSearch.FindAll()
        'Create a new table object within the dataset
        Dim dtGroup As DataTable = dsGroup.Tables.Add("Groups")
        dtGroup.Columns.Add("GroupName")
        dtGroup.Columns.Add("GroupGUID").ToString()
        'if there are results (there should be some!!), then convert the results
        'into a dataset to be returned.
        If searchResults.Count > 0 Then
            'iterate through collection and populate the table with
            'the Group Name
            For Each Result As SearchResult In searchResults
                'set a new empty row
                Dim drGroup As DataRow = dtGroup.NewRow()
                'populate the column
                drGroup("GroupName") = Result.Properties("cn")(0)
                drGroup("GroupGUID") = Result.Properties("objectGUID")(0)
                'append the row to the table of the dataset
                dtGroup.Rows.Add(drGroup)
            Next
        End If
        Return dsGroup

    End Function

Open in new window

    Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        dsGroups = GetAllGroups()
        Me.ListBox1.DataSource = dsGroups.Tables("Groups")
        Me.ListBox1.DisplayMember = "GroupName"
        ListBox1.ValueMember = "GroupGUID"
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Label1.Text = ListBox1.SelectedValue.ToString
    End Sub
End Class

Open in new window

0
 
LVL 6

Author Comment

by:r3nder
ID: 37792352
Mabe I should say is how do I  convert System.Byte[] to the GUID in string format
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37792388
try either of these:-
Result.Properties("objectGUID")(0).ToString()

or

Encoding.Ascii.GetString(byteArray);
0
 
LVL 6

Author Comment

by:r3nder
ID: 37792406
the first one showed System.Bytes[] in the label

the encoding of the text in the lablel thew an error Unable to cast object of type 'System.String' to type 'System.Byte[]'.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 6

Author Comment

by:r3nder
ID: 37792416
I even tried this (see attachment)
screenshot.jpg
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37792419
can you share your byte array???
0
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 200 total points
ID: 37792423
can you try this:-
Dim b = DirectCast(result.Properties("objectGuid")(0), Byte())
Return New Guid(b)

Open in new window


see this for reference:-
http://www.extensionmethod.net/Details.aspx?ID=299
0
 
LVL 6

Author Comment

by:r3nder
ID: 37792432
This is everything
Imports System.Data
Imports System.DirectoryServices
Imports System.Data.SqlClient
Imports System.Text

Public Class Form2
    Dim ds As DataSet
    Dim dsGroups As DataSet
Public Shared Function ConvertGuidToOctectString(objectGuid As String) As String
        Dim guid As System.Guid = New Guid(objectGuid)
        Dim byteGuid As Byte() = guid.ToByteArray()
        Dim queryGuid As String = ""
        For Each b As Byte In byteGuid
            queryGuid += "\" & b.ToString("x2")
        Next
        Return queryGuid
    End Function


        
    Public Shared Function GetAllGroups() As DataSet
        Try
            Dim dsGroup As New DataSet()
            Dim dirEntry As DirectoryEntry = New DirectoryEntry("LDAP://DC", "USER", "PASS")
            'create instance fo the direcory searcher
            Dim dirSearch As New DirectorySearcher()
            'set the search filter
            dirSearch.SearchRoot = dirEntry
            'Set the filter
            dirSearch.Filter = "(objectClass=group)"
            'find the first instance
            Dim searchResults As SearchResultCollection = dirSearch.FindAll()
            'Create a new table object within the dataset
            Dim dtGroup As DataTable = dsGroup.Tables.Add("Groups")
            dtGroup.Columns.Add("GroupName")
            dtGroup.Columns.Add("GroupGUID")
            'if there are results (there should be some!!), then convert the results
            'into a dataset to be returned.
            If searchResults.Count > 0 Then
                'iterate through collection and populate the table with
                'the Group Name
                For Each Result As SearchResult In searchResults
                    'set a new empty row
                    Dim drGroup As DataRow = dtGroup.NewRow()
                    'populate the column
                    drGroup("GroupName") = Result.Properties("cn")(0)
                    'drGroup("GroupGUID") = Result.Properties("objectGUID")(0)
                    drGroup("GroupGUID") = DirectCast(Result.Properties("objectGuid")(0), Byte())

                    'append the row to the table of the dataset
                    dtGroup.Rows.Add(drGroup)
                Next
            End If
            Return dsGroup
        Catch E As Exception
            MessageBox.Show(E.Message)
        End Try

    End Function
    Public Shared Function getSQL() As DataSet
        Try
            Dim connString As String = "server=SQLEXPRESS;database=DB; user=USER; password=PASS;trusted_connection=yes"
            Dim conn As New SqlConnection(connString)
            conn.Open()
            Dim strSQL As String = "SELECT Country,Value FROM Country"
            Dim da As New SqlDataAdapter(strSQL, conn)
            Dim ds As New DataSet
            da.Fill(ds, "Country")
            'With cbUserRegion
            '    .DataSource = ds.Tables("Country")
            '    .DisplayMember = "Country"
            '    .ValueMember = "Value"
            '    .SelectedIndex = 0
            'End With

            'With cbCountry
            '    .DataSource = ds.Tables("Country")
            '    .DisplayMember = "Country"
            '    .ValueMember = "value"
            '    .SelectedIndex = 0
            'End With
            conn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function

    Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        dsGroups = GetAllGroups()

        Me.ListBox1.DataSource = dsGroups.Tables("Groups")
        Me.ListBox1.DisplayMember = "GroupName"
        ListBox1.ValueMember = "GroupGUID"
    End Sub

    'Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

    '    Dim tGuid As Guid
    '    ' tGuid = New Guid(CType(tItem.Properties.Item("objectGUID").Value, System.Byte()))
    '    tGuid = New Guid(CType(ListBox1.SelectedValue, System.Byte()))
    '    Label1.Text = tGuid.ToString
    'End Sub

    Public Function ConvertDNtoGUID(objectDN As String) As String
        'Removed logic to check existence first

        Dim directoryObject As New DirectoryEntry(objectDN)
        Return directoryObject.Guid.ToString()
    End Function

    Private Sub ListBox1_MouseClick(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseClick

       

        Label1.Text = ListBox1.SelectedValue.ToString
 

    End Sub
    Private Function Byte2Str(ByVal gByte() As Byte) As String
        Dim X As Integer
        Dim gTmp As String = ""
        For X = 0 To gByte.Length - 1
            gTmp = gTmp & Chr(gByte(X))
        Next
        Return (gTmp)
    End Function


End Class

Open in new window

It still returns system.byte[]
0
 
LVL 6

Accepted Solution

by:
r3nder earned 0 total points
ID: 37794281
Why didnt anyone say there was a GUID class
I found the solution
For Each Result As SearchResult In searchResults
                    'set a new empty row
                    Dim drGroup As DataRow = dtGroup.NewRow()
                    'populate the column
                    drGroup("GroupName") = Result.Properties("cn")(0)
                    Dim GuidByteAr() As Byte = Result.Properties("objectGUID")(0)
                    Dim TestGuid As New Guid(GuidByteAr)
                    drGroup("GroupGUID") = TestGuid.ToString()
                    'drGroup("GroupGUID") = DirectCast(Result.Properties("objectGuid")(0), Byte())
                    'append the row to the table of the dataset
                    dtGroup.Rows.Add(drGroup)

Open in new window

0
 
LVL 6

Author Closing Comment

by:r3nder
ID: 37815470
Thanks your your help on this
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
A short article about problems I had with the new location API and permissions in Marshmallow
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now