2016년 8월 3일 수요일

[Dynamics] Creating AX users in Powershell


If you want to create a user in Dynamics AX 2012, you can simply use New-AXUser cmdlet and other User and role-based security cmdlets. It’s more difficult in AX 2009 and older versions, but you can utilize Business Connector to do the job. Below is an extended function that I wrote for AX 2009. It accepts a path to an exported AX configuration (to know which AX instance to use), a domain, a user name and, if required, the new AX user ID. It also supports -WhatIf and -Confirm parameters.

It automatically adds the user to the admin group, but you easily can change the script to meet your specific requirements.
Function New-AXUser
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param(
        [Parameter(Mandatory=$true)]
        [string]$ConfigFile,
        [Parameter(Mandatory=$true)]
        [string] $UserDomain,  
        [Parameter(Mandatory=$true)]
        [string]$UserName,  
        [string]$AXUserId = $UserName.Substring(0, 5)
    )
 
    #region Functions
 
    Function AddToAdminGroup
    {
        $membership = $ax.CreateAxaptaRecord('UserGroupList');
        $membership.set_Field('UserId', $AXUserId);
        $membership.set_Field('GroupId', 'Admin');
        $membership.Insert()
    }
 
    Function AxLogoff
    {
        [void]$ax.Logoff()
    }
 
    Function AxLogon
    {
        try
 {
            [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.Dynamics.BusinessConnectorNet');
            $script:ax = New-Object Microsoft.Dynamics.BusinessConnectorNet.Axapta
            $ax.Logon('', '', '', $ConfigFile)
 }
        catch
 {
            throw 'Logging to AX failed.'
        }
    }
 
    Function CreateUser
    {
        $userManager = $ax.CreateAxaptaObject('AxaptaUserManager');
 if ($userManager.Call('validateDomainUser', $UserDomain, $UserName) -eq $false)
        {
            throw error 'User cannot be created.'
        }
        else
        {
            $userDetails = $userManager.Call('getDomainUser', $UserDomain, $UserName);
            $sid = $userDetails.Call('getUserSid', 0);
            $dispName = $userDetails.Call('getUserName', 0);
 
            $user = $ax.CreateAxaptaRecord('UserInfo');
            $user.ExecuteStmt('select * from %1 where %1.Id == "Admin"')
 
            SetField $user 'Id' $AXUserId
            SetField $user 'NetworkAlias' $UserName
            SetField $user 'NetworkDomain' $UserDomain
            SetField $user 'Name' $dispName
            SetField $user 'Sid' $sid
 
            if ($PSCmdlet.ShouldProcess("Config: $ConfigFile, User ID: $AXUserId"))
            {
                $user.Insert();
                AddToAdminGroup
            }
        }
    }
 
    Function SetField
    {
        Param($axaptaRecord, [string]$fieldName, $value)
 
        $axaptaRecord.set_Field($fieldName, $value);
        Write-Verbose ($fieldName + ": " + $value)
    }
 
    Function ValidateParameters
    {
        if (!(Test-Path $ConfigFile))
        {
            throw "Configuration $ConfigFile doesn't exist"
        }
    }
 
    #endregion
 
    ValidateParameters
    AxLogon
    CreateUser
    AxLogoff
}

[Dynamics] How to clear inactive sessions from Dynamics Ax 2012

If you check the online user in Administrator Module, You may be found some session with inactive and block status. These inactive and block session are due to crashing of AX clients. These sessions are not create any problem, but possible issues with limited number of active users under Dynamics Ax license. Best approach to clear these inactive and block session form Dynamics Ax to avoid any future conflict with Licensing. All these session information is stored in "SysClientSessions" Table.

Second Problem we usually face that when we start AOS service, it take too much time change status from Starting to started. One of many reason for this phenomena that AX try to query and located any Active session in SysClientSessions. To reduce the time is to remove all session inactive from SysClientSessions table or possible remove the inactive and block session form Database.
In "SysClientSessions" Status with status 0 (Inactive), Status 2 (Ending Waiting for AOS), 3 (Ending –Block).


Perform following steps.
  1. Stop AOS service.
  2. Open SQL Server Management Studio
  3. Open any new query on Dynamics Ax Database.
  4. Run the following Query where sessions with status 0 (Inactive), Status 2 (Ending Waiting for AOS), 3 (Ending –Block).
    delete from SysClientSessions where status in(0,2,3);
  5. Restart AOS.

[Dynamics] Move AX 2012 to a different Server / Domain


As you probably know Microsoft Dynamics AX 2012 R2/R3 does not have a redeployment utility (like the Dynamics CRM deployment manager) meaning that if you want to move an AX Deployment from one domain to another – you’ll have to get your hands a little dirty.

Some important notes before we start :
  • You can use these steps also in AX 2012 – Just ignore the Modelstore database.
  • You can also use these steps to move a deployment in the same domain – ignore step 4.
  • You need to make sure that the AX installation version in the new server matches the installation
  • on the previous server.
  • I’m assuming that you have the basic required knowledge in SQL Server, your Windows Serverenvironments and of course some AX 2012 architecture understanding to do these steps

Let’s go:
  1. Open the SQL management studio and Backup your AX Databases [BusinessData Database + Modelstore Database]
    - for example: AXProd + AXProd_model
  2. Stop the AX Service on the new server and restore the databases in the new SQL server – You can restore them with different names just remember that they have to match
    – for example: AXProdNEW + AXProdNEW_model.
  3. In the SQL management studio run the following queries on the BusinessData Database (AXProdNEW):
    DELETE FROM SYSSERVERCONFIG;
    DELETE FROM SYSSERVERCONFIG;
    DELETE FROM BATCHSERVERCONFIG;

    - This will delete the batch server properties of the previous server – You should do this if the redeployment is in the same domain because the old server might be reachable by the new one and may use it as a batch server.

    DELETE FROM SYSEMAILPARAMETERS;
    - This will delete the SMTP server parameters for sending emails
    - This will delete the AOSID & SERVERID of the previous installation and will repopulate the tables with the new server name when the AX service on the new server is started.
    Also consider running:

    DELETE FROM SRSSERVERS;

    - This will clear the Reporting Services properties form – you will need to reconfigure this later if you want to redeploy the reports.

    DELETE FROM BATCHSERVERGROUP
  4. Now you need to configure your user in the AX Database in the new domain (You can skip this step if you re-deployed AX in the same domain).
    Open CMD with “Run as admin” and type:
    wmic useraccount where (name='your_windows_username' and domain='your_domain') get name,sid
    Example: wmic useraccount where (name='administrator' and domain='contoso') get name,sid
    Copy the SID to notepad.

    In the SQL management studio run the following query on the BusinessData Database (AXProdNEW):
    UPDATE USERINFO
    SET SID='your_sid', NETWORKALIAS='your_windows_username', NETWORKDOMAIN='your_domain', NAME='your_full_name'
    WHERE ID = 'Admin';


    Example:
      UPDATE USERINFO
      SET SID='S-1-5-21-916693446-2822637979-541647007-1001', NETWORKALIAS='administrator', NETWORKDOMAIN='contoso', NAME='John TheAdmin'
      WHERE ID = 'Admin';

    - This will replace the AX Admin user to your user – you can modify this query to replace other users as well, or you can later add new users from the AX GUI.
  5. Grant the AX AOS account permissions over the databases as follows:
    AXProdNEW:
      db_datareader
      db_datawriter
      db_ddladmin
      public
    AXProdNEW_model:
      public

    You can identify the AOS account by going to the services on the application server (start-> services.msc) and check the Log On tab:
    If you are using NETWORK SERVICES as the service account you will need to grant permissions to the machine$ account – Use the following query to do it.
    CREATE LOGIN [Domain\axservername$] FROM WINDOWS
  6. All done! Go to services on the application server and start the Microsoft Dynamics AX Service – it might take a few minutes for it to start. Once it’s running – you can start the application.
    If you have any issues starting the service check the server’s event log for clues, and if you have any questions – feel free to post them here and i will do my best to help you out.

Further optional steps:
  1. You should synchronize your Database to make sure everything is working properly.
  2. If you want to deploy your reports – you need to fill the Report Servers form and then run the following command from the Dynamics AX 2012 management Shell:
    Publish-AXReport –ReportName *