Solved

GUID of a group in active directory

Posted on 2012-03-30
12
1,351 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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
 
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

Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes my battle tested process for setting up delegation. I use this process anywhere that I need to setup delegation. In the article I will show how it applies to Active Directory
A hard and fast method for reducing Active Directory Administrators members.
Six Sigma Control Plans
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…

719 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