VB.NET adding a user to distribution list. An operations error occurred

217 views Asked by At

So this is what I've got -

Public Shared Function GetDirectoryEntry() As DirectoryEntry
    Try
        Dim entryRoot As New DirectoryEntry("LDAP://RootDSE")
        Dim Domain As String = DirectCast(entryRoot.Properties("defaultNamingContext")(0), String)

        Dim de As New DirectoryEntry()

        de.Path = "LDAP://" & Domain
        de.AuthenticationType = AuthenticationTypes.Secure

        Return de
    Catch
        Return Nothing
    End Try
End Function

Protected Sub rbAddUser_Click(sender As Object, e As EventArgs) Handles rbAddUser.Click
    AddMemberToGroup("LDAP://DOMAIN.local/CN=" & !DISTRIBUTIONNAME! & ",CN=Users,DC=DOMAIN,DC=local", "/CN=" & !SELECTEDUSER! & ",CN=Users,DC=DOMAIN,DC=local")
End Sub

Private Sub AddMemberToGroup(ByVal bindString As String, ByVal newMember As String)

    Dim ent As DirectoryEntry = GetDirectoryEntry()
    ent.Properties("member").Add(newMember)
    ent.CommitChanges()
End Sub

I hope this is easy enough for people to read, anyway the group and user are selected by the users in a table and when they click the add button I want the selected users to be adding to the selected distribution list.

when it gets to the CommitChanges() I get this error

An exception of type 'System.DirectoryServices.DirectoryServicesCOMException' occurred in System.DirectoryServices.dll but was not handled in user code Additional information: An operations error occurred.Error -2147016672

2

There are 2 answers

3
AStopher On

This is a common issue with the Process Model application pool configuration, from the official documentation:

By using the <processModel> element, you can configure many of the security, performance, health, and reliability features of application pools on IIS 7 and later.

This issue exists as CommitChanges() requires elevated privileges, and can be fixed by setting your web-application to run under NetworkManager; this can be done in two ways:

  1. Directly in your code, place the problem code inside this Using statement:

    Using HostingEnvironment.Impersonate()
        'Problem code goes here.
    End Using
    
  2. Via IIS Manager:

    1. Navigate to your website's application pool;
    2. Navigate to Advanced Settings;
    3. Scroll down to the Process Model group;
    4. Change Identity to NetworkService
0
supersteve On

I solved the error by passing through my user credentials

Private Sub AddMemberToGroup(ByVal bindString As String, ByVal newMember As String)

Dim ent As New GetDirectoryEntry(bindString)
ent.Properties("member").Add(newMember)
ent.Username = "DOMAIN\USERNAME"
ent.Password = "PASSWORD"
ent.CommitChanges()
End Sub

However my code still doesn't work, I just get no errors.