When I try to set Active Directory user properties, throw exception

You can post your problem related to Microsoft Visual Studio Projects here. We will try our best to help you out.
Sean
Posts:22
Joined:Sat Feb 18, 2017 9:02 am
When I try to set Active Directory user properties, throw exception

Post by Sean » Tue Mar 07, 2017 8:35 am

It`s a good day to die....

I`m trying to make & modify windows application about AD group and users.

This application works like this.

Users choose property and mapping it from source data(DB or Excel files...)

And press sync start button, that properties put into the AD User.

But When I set AD user`s properties, it throws exception like this in DirectoryEntry.CommitChanges(); block.

The directory
service cannot perform the requested operation on the RDN attribute of an object.

Sadly I`m a newbie of Active Directory, I don`t know how to solve it... Please help me.

Code is below.

Code: Select all

void CreateADUser(string ppk,string pk,DataRow row)
{
    string pass = GetPass(pk,row,LogSections.AD);
    DirectoryEntry addept = adm.FindOU(ppk);
    string sOU = adm.GetPrincipalPath(addept);
    var aduser = adm.CreateNewUser(sOU, pk, pass, pk, null, null, adm.sDomain);
    SetAdUserProperties(pk, pass, row);
    MoveUser(ppk,pk);
}



void SetAdUserProperties(string pk,string pass,DataRow row)
{
    if (row == null) return;
    List<ADMapping> MappingPatterns = GetAdMappings(Words.User,false);
    var colnames = Tool.GetColNames(row);
    var aduser = adm.GetUser(pk);
    var de=aduser.GetUnderlyingObject() as DirectoryEntry;
    foreach (var ADMap in MappingPatterns)
    {
        string val = ADMap.Mapping;
        val=Util.ReplaceColPattern(val, row);
        SetProperty(de, ADMap.CN, val);
    }
    if (!string.IsNullOrWhiteSpace(pass))
    {
       var UserPkColumn = AppConfigHelper.GetAppString(Words.SourceUserPKColumn);
       UserPkColumn = Util.GetActualColName(UserPkColumn);
       aduser.SetPassword(pass);
       QueryHelper.Update(QueryHelper.ConnectionString, Words.ShadowUserTable
                    ,new SqlParameter[] { new SqlParameter("@passwd", pass) }
                    , new SqlParameter("@"+UserPkColumn,pk));
    }

     aduser.Save();
}

public void SetProperty(DirectoryEntry oDE, string sPropertyName, object sPropertyValue)
{
    if (sPropertyValue != null && !string.IsNullOrWhiteSpace(sPropertyValue.ToString()))
    {
        if (oDE.Properties.Contains(sPropertyName))
        {
            oDE.Properties[sPropertyName].Value = sPropertyValue;
        }
        else
        {
            oDE.Properties[sPropertyName].Add(sPropertyValue);
        }
        try
        {
            oDE.CommitChanges(); //exception here.
            oDE.Close();
         }
        catch (Exception)
        {

        }

     }


  }

Post Reply