Search This Blog

Monday, May 23, 2022

 Create the User into ActiveDirectory

static void CreateADUSER(Args _args)

{

    System.DirectoryServices DirectoryServices;

    System.DirectoryServices.AccountManagement AccountManagement;

    System.DirectoryServices.AccountManagement.UserPrincipal up;

 

    System.DirectoryServices.AccountManagement.PrincipalContext pricipalContext;

    str networkDomain="KrishhDAX";

    InteropPermission                                               permission;

 

try

{

     permission = new InteropPermission(InteropKind::CLRInterop);

     permission.assert();

    pricipalContext = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType::Domain, "KRISHHDAX", "OU=mDK,OU=Users,OU=TestOU,DC=KrishhDAX,DC=com");

    //Sometimes we need to connect to AD using service/admin account credentials, in that case the above line of code will be as below

    //pricipalContext = new PrincipalContext(ContextType.Domain, "yourdomain.com", "OU=TestOU,DC=yourdomain,DC=com","YourAdminUser","YourAdminPassword");

    up = new System.DirectoryServices.AccountManagement.UserPrincipal(pricipalContext);

    up.set_SamAccountName("krishh");

    up.set_DisplayName("krishh Reddy");

    up.set_EmailAddress(krishh.009@KRISHHDAX.com);

    up.set_GivenName("krishh Reddy");

    up.set_UserPrincipalName(krishh.009@KRISHHDAX.com);

    up.set_Name("Krishh");

    up.set_Surname("Reddy");

    up.set_Description("User Created for testing");

    up.set_Enabled(True);

   

    up.SetPassword("KRISHHDAX#");

    up.Save();

   // info(strFmt("User Created %1",up.get_DisplayName()));

     CodeAccessPermission::revertAssert();

}

catch(Exception::CLRError)

{

       CodeAccessPermission::revertAssert();

        info(CLRInterop::getLastException().ToString());

}

}