Thursday, July 23, 2015

How to read active directory users through x++



Dynamics Ax relies on Active Directory for user authentication.You can use AD for what it is designed for: a central storage location for application data.

But how does one get to read information from the AD?  xAxaptaUserManager and  xAxaptaUserDetails class that helps us to get the AD inforation along with SID In following code snippet, I'll show you how to collect a list of all users from a specific domain, with some basic information about those users.

static void getADUsersInfo(Args _args)

{
    str                 computer = new xSession().clientComputerName();
    xAxaptaUserManager  mgr = new xAxaptaUserManager();
    xAxaptaUserDetails  usr;
    container           domainains;
    int                 d, u;
    str                 domain, login, name, sid, email;
    ;

    // iterate AD domainains

    domainains = mgr.enumeratedomains(computer);
    for (d = 1; d <= conlen(domainains); d++)
    {
        domain = conpeek(domainains, d);
        setprefix(domain);

        // iterate AD domainain users

        usr = mgr.enumerateDomainUsers(domain);
        for (u = 0; u < usr.getUserCount(); u++)
        {
            if (usr.isUserEnabled(u) && !usr.isUserExternal(u))
            {
                // get information from AD
                login = usr.getUserLogin(u);
                name = usr.getUserName(u);
                sid = usr.getUserSid(u);
                email = usr.getUserMail(u);

                // stuff happens here, you can compare AD data with AX User info


                info(strfmt("%1 - %2 - %3 - %4 - %5", domain, login, name, email, sid));

            }
        }
    }
}

Another example of getting SID through X++ using AxaptaUserManager class – getuserId()

Sometimes knowing SID of system is very much helpful specially when the user in the database has been deleted or database is migrated/upgraded incorrectly. Ofcourse, we can get the SID’s easily from the system by opening registry editor and selecting HKEY_USERS in left pane to expand it, in left pane itself you will find the SID of users.But, below is the simple code to get the SID’s of windows users using X++ Code.

static void GetUserSID(Args _args)
{
str windowsUser = ‘companyDomain\\sreenath.reddy'; // DomainName\\userId
#Aif
#File
networkALias alias;
networkDomain domain;
int pos, len;
sid userSid;
Microsoft.Dynamics.IntegrationFramework.Util util;
;
//Split the windowsUser into domain and alias
len = strlen(windowsUser);
pos = strfind(windowsUser, #FilePathDelimiter, 1,len);
domain = substr(windowsUser, 1, pos-1);
alias = substr(windowsUser, pos+1, len – pos);

new InteropPermission(InteropKind::ClrInterop).assert();
// BP Deviation Documented
util = new Microsoft.Dynamics.IntegrationFramework.Util();

//Get the Windows SID for this user
// BP Deviation Documented
userSid = util.GetUserSid(domain, alias);
CodeAccessPermission::revertAssert();

info(userSid);
}