Thursday, December 18, 2008

AD user creation

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace Microsoft.Dynamics.CreateADUser
{
    public class NewUser
    {
        string defaultNC;
        string alias;
        string fullName;
        string password;
        string ou;

        public void setDomain(string _defaultNC)
        {
            defaultNC = "DC=" + _defaultNC;
        }
        public void setAlias(string _alias)
        {
            alias = _alias;
        }
        public void setFullName(string _fullName)
        {
            fullName = _fullName;
        }
        public void setPassword(string _password)
        {
            password = _password;
        }
        public void setOu(string _ou)
        {
            ou = _ou;
        }

        public string execute()
        {
            DirectoryEntry container, user;
            string ret;

            try
            {
                //This creates the new user in the "users" container.
                //Set the sAMAccountName and the password
                container = new DirectoryEntry("LDAP://OU=" + ou + ", " + 
defaultNC + ",DC=NO");
                user = container.Children.Add("cn=" + fullName, "user");
                user.Properties["sAMAccountName"].Add(alias);
                user.CommitChanges();
                user.Invoke("SetPassword", new object[] { password });

                //This enables the new user.
                user.Properties["userAccountControl"].Value = 0x200; 
//ADS_UF_NORMAL_ACCOUNT
                user.CommitChanges();
                ret = "OK";
            }
            catch (Exception e)
            {
                ret = e.ToString();
            }
            return ret;
        }
    }
}

Just compile and put the dll-file in the client\bin folder of Ax and create 
a reference from the aot and use the class like this in Ax:

------------------------------------
static void Job1(Args _args)
{
    Microsoft.Dynamics.CreateADUser.NewUser user;
    ;
    user = new Microsoft.Dynamics.CreateADUser.NewUser();
    user.setDomain(/*yourdomain*/);
    user.setAlias(/*alias of the user you want to create*/);
    user.setFullName(/*Full name of the user*/);
    user.setPassword(/*Password*/);
    user.execute();
}

No comments:

How to identify the user that was used to change an object from AOT in AX2012

Get the object name for which we need to track these (user and date&time) information's. Login to SQL Server Management Studio an...