Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 693
  • Last Modified:

Adding a User to a Group within an OU

I am successfully creating users into an OU, but I need to add them to a group within the OU. I keep getting errors, and I think it's because I am little lost in the DirectoryEntries. Here's my code:

Dim grp As DirectoryEntry = New DirectoryEntry("LDAP://OU=SHAREPOINT")
Dim addMe As DirectoryEntry = grp.Children.Find("CN=Extranet", "group")
        If addMe.Name <> "" Then
            addMe.Invoke("Add", newUser.Path.ToString())
        End If

Thanks in advance.
0
jawhitmoyer
Asked:
jawhitmoyer
  • 10
  • 7
1 Solution
 
ihenryCommented:
I think code that's actually causing the problem isn't in any part in the code you have posted above. I'm assuming you have written your which somewhat similar to the following logic:

1. Create the user and commit change
2. Call SetPassword and commit change
3. Enable the  user and set some other attributes then commit change one last time.

Then this code (I've made a small modification to it) should works

Dim grp As DirectoryEntry = New DirectoryEntry("LDAP://OU=SHAREPOINT")
Dim addMe As DirectoryEntry = grp.Children.Find("CN=Extranet", "group")
addMe.Invoke("Add", newUser.Path.ToString()

If you're still getting problems please post the exception stack trace.

0
 
jawhitmoyerAuthor Commented:
OK. I replaced my code with yours, and put it at the very end of the routine, after setting the password, etc. I get the following message when it hits "Dim addMe as DirectoryEntry..."

System.Runtime.InteropServices.COMException occured in system.directoryservices.dll

Here's all the output:

'DefaultDomain': Loaded 'c:\windows\microsoft.net\framework\v1.1.4322\mscorlib.dll', No symbols loaded.
'AccountCreationTestbed': Loaded 'C:\Documents and Settings\jwhitmoyer\My Documents\Visual Studio Projects\AccountCreationTestbed\bin\AccountCreationTestbed.exe', Symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\system.windows.forms\1.0.5000.0__b77a5c561934e089\system.windows.forms.dll', No symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\system\1.0.5000.0__b77a5c561934e089\system.dll', No symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\system.drawing\1.0.5000.0__b03f5f7f11d50a3a\system.drawing.dll', No symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\system.directoryservices\1.0.5000.0__b03f5f7f11d50a3a\system.directoryservices.dll', No symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\microsoft.visualbasic\7.0.5000.0__b03f5f7f11d50a3a\microsoft.visualbasic.dll', No symbols loaded.
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in system.directoryservices.dll

Additional information: An operations error occurred


Unhandled Exception: System.Runtime.InteropServices.COMException (0x80072020): An operations error occurred
   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_IsContainer()
   at System.DirectoryServices.DirectoryEntries.CheckIsContainer()
   at System.DirectoryServices.DirectoryEntries.Find(String name, String schemaClassName)
   at AccountCreationTestbed.Form1.AddUserToAD() in C:\Documents and Settings\jwhitmoyer\My Documents\Visual Studio Projects\AccountCreationTestbed\Form1.vb:line 196
   at AccountCreationTestbed.Form1.Button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\jwhitmoyer\My Documents\Visual Studio Projects\AccountCreationTestbed\Form1.vb:line 130
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.ComponentManager.System.Windows.Forms.UnsafeNativeMethods+IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at AccounThe program '[3284] AccountCreationTestbed.exe' has exited with code 0 (0x0).
tCreationTestbed.Form1.Main() in C:\Documents and Settings\jwhitmoyer\My Documents\Visual Studio Projects\AccountCreationTestbed\Form1.vb:line 5
0
 
ihenryCommented:
mm..are you sure you have this object in your active directory server?
"LDAP://OU=SHAREPOINT"

I think it should look something similar to this instead
"LDAP://OU=SHAREPOINT,DC=YourDomain,DC=COM"
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
jawhitmoyerAuthor Commented:
Alright...getting closer. I added the domain info, and got past that line. Now I get an error at "addMe.Invoke..."

System.Reflection.TargetInvocationException occured at mscorlib.dll.

'DefaultDomain': Loaded 'c:\windows\microsoft.net\framework\v1.1.4322\mscorlib.dll', No symbols loaded.
'AccountCreationTestbed': Loaded 'C:\Documents and Settings\jwhitmoyer\My Documents\Visual Studio Projects\AccountCreationTestbed\bin\AccountCreationTestbed.exe', Symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\system.windows.forms\1.0.5000.0__b77a5c561934e089\system.windows.forms.dll', No symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\system\1.0.5000.0__b77a5c561934e089\system.dll', No symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\system.drawing\1.0.5000.0__b03f5f7f11d50a3a\system.drawing.dll', No symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\system.directoryservices\1.0.5000.0__b03f5f7f11d50a3a\system.directoryservices.dll', No symbols loaded.
'AccountCreationTestbed.exe': Loaded 'c:\windows\assembly\gac\microsoft.visualbasic\7.0.5000.0__b03f5f7f11d50a3a\microsoft.visualbasic.dll', No symbols loaded.
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

Additional information: Exception has been thrown by the target of an invocation.


Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.UnauthorizedAccessException: Access is denied.
   --- End of inner exception stack trace ---
   at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
   at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
   at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
   at System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)
   at AccountCreationTestbed.Form1.AddUserToAD() in C:\Documents and Settings\jwhitmoyer\My Documents\Visual Studio Projects\AccountCreationTestbed\Form1.vb:line 197
   at AccountCreationTestbed.Form1.Button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\jwhitmoyer\My Documents\Visual Studio Projects\AccountCreationTestbed\Form1.vb:line 130
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.ComponentManager.System.Windows.Forms.UnsafeNativeMethods+IMsoComponentManager.FPushMessageLoThe program '[4088] AccountCreationTestbed.exe' has exited with code 0 (0x0).
op(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at AccountCreationTestbed.Form1.Main() in C:\Documents and Settings\jwhitmoyer\My Documents\Visual Studio Projects\AccountCreationTestbed\Form1.vb:line 5
0
 
ihenryCommented:
Weird..your user account or the user account you used to bind to AD seems unable to do this task but it can set password which require higher privilege. You can do this instead?

addMe.Properties("member").Add( newUser.Properties("distinguishedName").Value )

If not I think I need to see some more of your code.
0
 
jawhitmoyerAuthor Commented:
I made the change, and I don't get any errors, but the user is not added to the group. Here's my entire Sub:

    Private Sub AddUserToAD()
        'This code adds a NEW USER to a specified OU.
        '
        'Useful in constructing LDAP "Paths":
        'cn = Computer, Contact, Container, Group, Print Queue, and User objects
        'ou = Organizational Unit
        'dc = Domain controller name (example dc=mydomain,dc=com for mydomain.com)
        'o = Domain name

        'First, connecto to the Active Directory.
        Dim sDomain As String = "gafcon"
        Dim sUsername As String = "********"
        Dim sPassword As String = "********"

        Dim dom As DirectoryEntry = New DirectoryEntry("LDAP://" & sDomain, sUsername, sPassword)

        'Connect to the specific OU
        Dim ouToAddTo As DirectoryEntry = dom.Children.Find("OU=SHAREPOINT")

        'Use the Add method to add a user in an organizationalUnit.
        Dim newUser As DirectoryEntry = ouToAddTo.Children.Add("CN=Cliff2", "User")

        'Set the core AD properties
        ' Pre-Windows 2000 Name
        newUser.Properties("sAMAccountName").Value = "Cliff2"
        ' User Logon Name
        newUser.Properties("userPrincipalName").Add("Cliff2@gafcon.local")
        ' Email
        newUser.Properties("mail").Value = "Cliff2@gafcon.local"
        ' First Name
        newUser.Properties("givenName").Add("Cliff2")
        ' Initials
        newUser.Properties("initials").Add("CS")
        ' Last Name
        newUser.Properties("sn").Add("West")
        ' Display Name
        newUser.Properties("displayName").Add("Cliff2 West")
        ' Description
        newUser.Properties("description").Add("Added by " & _
            System.Security.Principal.WindowsIdentity.GetCurrent().Name)

        'Create the account
        newUser.CommitChanges()

        'set the password for the new user
        newUser.Invoke("setPassword", "******")

        Dim userACFlags As Object = newUser.Properties("userAccountControl").Value
        newUser.Properties("userAccountControl").Value = userACFlags Or &H200 Or &H10000 Xor &H2

        'Commit the changes
        newUser.CommitChanges()

        Dim grp As DirectoryEntry = New DirectoryEntry("LDAP://OU=SHAREPOINT,DC=GAFCON,DC=LOCAL")
        Dim addMe As DirectoryEntry = grp.Children.Find("CN=Extranet", "group")
        addMe.Properties("member").Add(newUser.Properties("distinguishedName").Value)

    End Sub
0
 
jawhitmoyerAuthor Commented:
OH, and I am running the procedure using a domain admin account, so that cannot be an issue.
0
 
ihenryCommented:
add

addMe.CommitChanges()

after the last line
0
 
jawhitmoyerAuthor Commented:
That worked...the user is now in the proper group. But now the new user is DISABLED. Any thoughts as to why?
0
 
ihenryCommented:
But what I see from your code, I'm not very sure you'll get a fresh new user created, enable, with password never expire.
0
 
ihenryCommented:
:o) You have missed point no. 2 in my second post.

 newUser.Invoke("setPassword", "******")
 newUser.CommitChanges()
0
 
jawhitmoyerAuthor Commented:
I figured it out. I has to be with my group policies. I am giving you the points (very happily), but if you could tell me how to REMOVE the new user from a specific group, I would be stoked. I need to remove him from the "user" group, but to do that I need to first change the primary group to the new "Extranet" group.

Jim
0
 
ihenryCommented:
wait...are you sure you don't get any error message from this line??

newUser.Invoke("setPassword", "******")
0
 
ihenryCommented:
addMe.Properties("member").Remove(newUser.Properties("distinguishedName").Value)
0
 
ihenryCommented:
>> ...I need to remove him from the "user" group...
>> ...change the primary group to the new "Extranet" group..
Sorry, didn't read you question correctly. You need to change primary group with other group. That's the hardest part :o), can I ask you to open a new question for this. Don't worry, I'll give you a sample code for that.
0
 
ihenryCommented:
jawhitmoyer, code in the accepted answer won't be able to change primary group..
0
 
jawhitmoyerAuthor Commented:
It's on the way.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 10
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now