C# How to add an entry to LDAP with multiple object classes
Asked Answered
T

1

7

I'm trying to create a new user record into OpenLDAP with object classes person and uidObject. The problem seems to be that with System.DirectoryServices.DirectoryEntry I've found only a way to add a new entry with one object class, but not a way to add multiple object classes.

This C# code

DirectoryEntry nRoot = new DirectoryEntry(path);
nRoot.AuthenticationType = AuthenticationTypes.None;
nRoot.Username = username;
nRoot.Password = pwd;

try
{
    DirectoryEntry newUser = nRoot.Children.Add("CN=" + "test", "person");
    newUser.Properties["cn"].Add("test");
    newUser.Properties["sn"].Add("test");
    newUser.Properties["objectClass"].Add("uidObject"); // this doesnt't make a difference
    newUser.Properties["uid"].Add("testlogin"); // this causes trouble
    newUser.CommitChanges();
}
catch (COMException ex)
{
    Console.WriteLine(ex.ErrorCode + "\t" + ex.Message);
}

...results in error:

-2147016684 The requested operation did not satisfy one or more constraints associated with the class of the object. (Exception from HRESULT: 0x80072014)

Tawana answered 23/4, 2010 at 8:43 Comment(0)
T
8

It turns out that you can add object classes after the entry has first been stored to LDAP and fetched again. So, with a simple change it works just fine!

DirectoryEntry newUser = nRoot.Children.Add("CN=" + "test", "person");
newUser.Properties["cn"].Add("test");
newUser.Properties["sn"].Add("test");
newUser.CommitChanges();

newUser.RefreshCache();
newUser.Properties["objectClass"].Add("uidObject");
newUser.Properties["uid"].Add("testlogin");
newUser.CommitChanges();
Tawana answered 23/4, 2010 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.