Industry clouds have been a major focus area for Microsoft. The recent announcement from Microsoft on the General Availability of Microsoft cloud for financial services was much anticipated. In this post I will focus on my favorite – Microsoft cloud for Retail.

What does an industry cloud offer to business/clients? What are the tangible tools, solutions that are in a box? How can partners deliver value to clients through an industry cloud?

When I look at Microsoft Azure, AWS or Google cloud, I think of them as massive virtual worlds in which businesses of all sizes are setting up shop. If we were to extend that analogy to industry clouds then we could say that an industry cloud is equivalent to planned development city or a blueprint city.

For example a retail cloud or blueprint city tries to make the life of a retail business better by providing a set of products and solutions that help retail organizations. These tools and products allow businesses to easily collect massive amount of data that is generated through retail lifecycle processes, view customer analytics to  better understand their customers, empower their employees, and make fast paced intelligent decisions.

The cloud is a great equalizer, it gives small businesses the scale and agility at a fraction of cost. Industry cloud solution adds an additional layer of features and functionality focused towards that particular industry. Microsoft cloud for retail for example enhances the existing ecommerce and brick and mortar POS solution of retail business by adding capabilities like an AI powered recommendations and ratings application, AI powered fraud protection application, and Business 2 Business commerce model.

If you are a business, should you be looking at Industry cloud solutions seriously? The answer is yes indeed. Adopting an industry cloud not only allows you to modernize and transform your business in a short period, but also gives you access to the network of partners who are working together to enhance this industry cloud.

Finally getting to the point – what is in Microsoft cloud for Retail?

Here are the list of solutions in Retail cloud from Microsoft

  • D365 Commerce: D365 Commerce is an omnichannel commerce solution that provides all components of a retail solution to manage your brick and motor stores and your online stores. Solution components include POS software, hardware station, retail headquarters product to manage products, stores, POS devices. It also enables you to deploy a fully functional ecommerce website. The omnichannel experience enables you to provide functionality like buy online and pickup in store. The ecommerce site also provides B2B commerce to manage your distributors and partners who are selling on your behalf.
  • Ratings and review service: Azure AI powered solution allows displaying related products/services and manage feedback and interaction with consumers, automated moderation
  • D365 Fraud Protection: Protecting your online instore transactions, logins through an Azure AI powered fraud protection service
  • D365 Intelligent Order Management: D365 Commerce + Teams integration to enable multichannel fulfillment and seamless customer experience
  • Teams: Multiple apps built on top of teams that enhance employee productivity through features like, shift tracking, tasks management, vacation requests, walkie-talkie
  • Intune: Shared device setup based on employee login
  • D365 Connected Store: Dynamics PowerApp to manage store security, foot traffic analytics, setup display aisles in store and measure the effectiveness of the location/position
  • D365 Omnichannel for Customer Service: Serves as a single interaction point for your customers. Customers can reach you via chat, SMS, social channels, portals. Not certain if this is included out of the box in retail cloud but is a great solution for managing customer interaction
  • D365 Customer Insights: Unifies your customer data from across multiple channels to provide AI powered insights into your customer behavior
  • D365 Supply Chain Management: Microsoft’s enterprise ERP solution to manage supply chain, and manufacturing. Allows you to manage inventory, products, warehouses, manufacturing process and works seamless with D365 Commerce to meet your end to end consumer needs.

In subsequent blog posts, I will walk through each of the above solution components in detail plus some of the emerging trends in the retail space and how the Microsoft cloud for retail aims to help businesses implement these trends.

Here is a variation of code that creates a duplicate of all standard roles and removes the human resources related duties from these duplicated roles.

static void DuplicateAllStandardRolesAndRemoveHR(Args _args)
{
    #AOT

    int             counter;
    int             numOfRolesDuplicated;

    TreeNode        securityRolesNode;
    int             sourceSecRolesCounter;

    TreeNode        securityRole, nextSecurityRole;
    str             securityRoleName;

    TreeNode        duplicatedSecurityRole;
    str             duplicatedSecurityRoleName;

    TreeNode        duplicatedSecurityRoleDuties;
    int             duplicatedSecRoleDutiesCount;
    int             counterDup;

    TreeNode        duty, nextDuty;
    str             dutyName;

    // Initialize first security role to copy duties from
    securityRolesNode = TreeNode::findNode(#SecRolesPath);
    sourceSecRolesCounter = securityRolesNode.AOTchildNodeCount();

    securityRole = securityRolesNode.AOTfirstChild();
    for(counter = 1; counter<=sourceSecRolesCounter; counter++)
    {
        nextSecurityRole = securityRole.AOTnextSibling();
        securityRoleName = securityRole.AOTname();
        if((subStr(securityRoleName, 1, 1) != '-') &&
           (securityRoleName != 'SystemUser') &&
           (subStr(securityRoleName, 1, 3) != 'sys') &&
           (subStr(securityRoleName, 1, 6) != 'retail') &&
           (subStr(securityRoleName, 1, 4) != 'copy') &&
           (subStr(securityRoleName, 1, 3) != 'Hcm')
          )
        {
            numOfRolesDuplicated++;
            duplicatedSecurityRole = securityRole.AOTDuplicate();
            duplicatedSecurityRoleName = duplicatedSecurityRole.AOTname();
            duplicatedSecurityRoleName = subStr(duplicatedSecurityRoleName, 7, strLen(duplicatedSecurityRoleName) - 6) + 'NoHR';
            duplicatedSecurityRole.AOTsetProperty('name', duplicatedSecurityRoleName);
            duplicatedSecurityRole.AOTsave();

            duplicatedSecurityRoleDuties = TreeNode::findNode(#SecRolesPath + '\\' + duplicatedSecurityRoleName + '\\Duties');
            duplicatedSecRoleDutiesCount = duplicatedSecurityRoleDuties.AOTchildNodeCount();
            duty = duplicatedSecurityRoleDuties.AOTfirstChild();
            for(counterDup = 1; counterDup <= duplicatedSecRoleDutiesCount; counterDup++)
            {
                nextDuty = duty.AOTnextSibling();
                // Delete the duty if this starts with HCM or JMG
                dutyName = duty.AOTname();
                if((subStr(dutyName, 1, 3) == 'HCM') || (subStr(dutyName, 1, 3) == 'JMG'))
                {
                    // This duty needs to be deleted
                    duty.AOTdelete();
                }
                duty = nextDuty;
            }
            duplicatedSecurityRole.AOTsave();
        }
        securityRole = nextSecurityRole;
    }
}

Recently tasked with a mundane coding activity to create security roles based on a bunch of standard roles, i came up with a simple x++ code to help me in this activity or maybe just something to keep me awake!!

What you are trying to achieve in this code is to take all the duties that are part of a set of standard security roles and add those duties to a new security role you created. This role then becomes the starting point for further refinement.

All you need to change in this job is the calls to addDutiesFromSrcToDst method. The number of calls you will make is equal to the number of source roles and the arguments point to the source role name and destination role name. Also the new role should already exist, so just create a new role and supply it as argument.

If you want to know how to figure out the AOT name of the role based on a label name of the role then you can use the below piece of code to figure that out.

SecurityRole            securityRole;

while select * from securityRole
    order by Name
{
    info(strFmt('Name: %1, AOT Name: %2', securityRole.Name, securityRole.AotName));
}

Here is the code to merge the source role duties and add them to the new role duties node.

static void CreateNewRole(Args _args)
{
    #AOT

    int             counter, counter1;
    boolean         dutyExistsInNewRole;

    TreeNode        securityRoleDutiesNode;
    str             sourceSecRole1_DutyPath;
    int             sourceSecRole1_DutyCounter;

    TreeNode        newSecurityRoleDutiesNode;
    str             newSecRole_DutyPath;
    int             newSecRole_DutyCounter;

    TreeNode        sourceSecRole1_DutyNode;
    TreeNode        newSecRole_DutyNode;

    str             sourceDutyName;
    str             newSecDutyName;

    TreeNode        newlyAddedDuty;

    void addDutiesFromSrcToDst(str _srcPath, str _destPath)
    {
        // Initialize first security role to copy duties from
        sourceSecRole1_DutyPath = #SecRolesPath + _srcPath;
        securityRoleDutiesNode = TreeNode::findNode(sourceSecRole1_DutyPath);
        sourceSecRole1_DutyCounter = securityRoleDutiesNode.AOTchildNodeCount();

        sourceSecRole1_DutyNode = securityRoleDutiesNode.AOTfirstChild();
        for(counter = 1; counter<=sourceSecRole1_DutyCounter; counter++)
        {
            dutyExistsInNewRole = false;
            sourceDutyName = sourceSecRole1_DutyNode.AOTname();
            // Initialize the new security role\duties node
            newSecRole_DutyPath = #SecRolesPath + _destPath;
            newSecurityRoleDutiesNode = TreeNode::findNode(newSecRole_DutyPath);
            newSecRole_DutyCounter = newSecurityRoleDutiesNode.AOTchildNodeCount();
            newSecRole_DutyNode = newSecurityRoleDutiesNode.AOTfirstChild();
            for(counter1 = 1; counter1<=newSecRole_DutyCounter; counter1++)
            {
                newSecDutyName = newSecRole_DutyNode.AOTname();
                if(sourceDutyName == newSecDutyName)
                {
                    dutyExistsInNewRole = true;
                    break;
                }
                newSecRole_DutyNode = newSecRole_DutyNode.AOTnextSibling();
            }
            if(!dutyExistsInNewRole)
            {
                // Add this duty to the new role's duties node
                newlyAddedDuty = newSecurityRoleDutiesNode.AOTadd(sourceDutyName);
                newlyAddedDuty.AOTsetProperty('Name', sourceDutyName);
                newlyAddedDuty.AOTsave();
                newSecurityRoleDutiesNode.AOTsave();
                //sourceSecRole1_DutyNode.AOTinsert(newSecurityRoleDutiesNode, newSecurityRoleDutiesNode, true);
                dutyExistsInNewRole = false;
            }
            //info(strFmt('%1, %2', counter, sourceDutyName));
            sourceSecRole1_DutyNode = sourceSecRole1_DutyNode.AOTnextSibling();
        }
    }
    ;

    addDutiesFromSrcToDst('\\InventMaterialsManager\\Duties', '\\NewRole\\Duties');
    addDutiesFromSrcToDst('\\CRMMarketingCoordinator\\Duties', '\\NewRole\\Duties');
    addDutiesFromSrcToDst('\\RouteProcessEngineeringManager\\Duties', '\\NewRole\\Duties');
    addDutiesFromSrcToDst('\\ProdProductionSupervisor\\Duties', '\\NewRole\\Duties');
    addDutiesFromSrcToDst('\\SMAFieldServiceTechnician\\Duties', '\\NewRole\\Duties');
}

Sometimes there is a requirement to create a new field on a table that should be populated from a custom financial dimension values. And you want to show a lookup on the data entry form for this field that populates the data from your custom financial dimension.

To meet this requirement the following tables are important.
– DimensionFinancialTag
– DimensionAttribute
– DimensionAttributeDirCategory
– FinancialTagCategory

The list of values for your custom dimension are stored in the table DimensionFinancialTag. But this table stores custom values for all custom financial dimensions. To determine which of the records to filter out and show we will have to apply a filter on the field FinancialTagCategory. How do we figure out what is the financialtagcategory value? We do that by traversing from the DimensionAttribute table which holds a record for your financial dimension. The table DimensionAttributeDirCategory holds a link between DimensionAttribute and FinancialTagCategory. You use this table to retrieve the financialtagcategory and filter the records in the table DimensionFinancialTag.

Here is some sample code…

    SysTableLookup                      sysTableLookup;
    Query                               query;
    QueryBuildDataSource                qbdsDimensionFinancialTag;
    QueryBuildRange                     qbrFinancialTagCategory;
    ;

    #define.MyCustomFinancialDimension('MyCustomFinancialDimension')

    query = new Query();
    qbdsDimensionFinancialTag = query.addDataSource(tableNum(DimensionFinancialTag));
    qbrFinancialTagCategory = qbdsDimensionFinancialTag.addRange(fieldNum(DimensionFinancialTag, FinancialTagCategory));
    qbrFinancialTagCategory.value(strFmt('%1', DimensionAttribute::findByName(MyCustomFinancialDimension, false).financialTagCategory()));

    sysTableLookup = sysTableLookup::newParameters(tableNum(DimensionFinancialTag), this);
    sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Value), true);
    sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Description));
    sysTableLookup.addSelectionField(fieldNum(DimensionFinancialTag, FinancialTagCategory));
    sysTableLookup.parmQuery(query);

    sysTableLookup.performFormLookup();

A brief description of the tables…
DimensionAttribute: This table stores the dimension attribute name and a link to the DimensionAttributeDirCategory (basically category)
DimensionAttributeDirCategory: This table links dimension attribute with FinancialTagCategory table.
FinancialTagCategory: This table is the core table for category. Apparently it is used for grouping of custom financial dimensions. Probably a way for us to share custom financial dimension values across multiple custom financial dimensions.
DimensionFinancialTag: This tables stores the custom financial dimension values. And also a link to FinancialTagCategory identifying the category for each value.

Have you ever had a need to hide a few of your modules from all users/or a few users? Alternative you wanted to show only a few modules to all your users? To achieve this there are 2 options.

1. For basic/standard ax modules like AP, AR, budgeting etc you need to turn off/blank out the licensing code in the License information form (System administration->Setup->Licensing->License information) , feature sets tab.
2. For advanced features like Warehouse or for ISV provided solutions you can alternatively turn off the configuration key in the License configuration form (System administration->Setup->Licensing->License configuration)

For example you don’t think users in your company will use the Transportation management module. Since this an advanced feature you can take the second approach mentioned above. Go to licensing configuration and uncheck the configuration key Trade->Warehouse and Transportation management. Unfortunately there are a few side effects to this approach
– This will also turn off the advanced warehousing module
– This will in addition do a db sync and remove all Transportation management module related tables
– This feature will now be unavailable to all the users (not just a select few)

In fact both the options mentioned above have the exact same side effect. How can you get around this?

We will use the power of personalization to achieve the same effect. In AX you can decide what modules you want to see in the left nav and top address bar by using the navigation options. Here you can select/un-select the modules you want to see in the navigation. This personalization is company specific so the users can have different set of modules for different companies.

NavigationPaneOptions1

NavigationPaneOptions2

There is some coding involved but i will highlight all the code components. Let us take the example of hiding the transportation module. The idea is simple; On AX client start-up we will simulate the selection of navigation pane options and un-select the transportation module. Next we will persist this into personalization for the user. However when a user changes company they will see the module in the new company. To side step this we will also copy the personalization to other companies as well for the user. Another thing that can happen is that the user may decide to open up navigation pane options and select the module that we un-selected. To get around this we will modify the code in the Ok button to un-select it! Sneaky aren’t we!! Just remember the user will get frustrated and might complain that something is wrong or there is a bug, but hey it must have been a business decision in the first place to not grant access to the module so we should be fine.

So the code changes are as follows
– Intercept the initial AX client load in the class info, method startupPost.
– Intercept the Navigation Pane options dialog (Form SysNavPaneOptionsDialog, method OKButton: clicked)
And we are done!

Here is the code

Info class method startupPost
/*
No SYS code must exist in this method
*/
void startupPost()
{
    ModuleManager::HideTMSModule();
}

/* class ModuleManager */
/* 
1. This method hides the TMS module for all users except 3 users authorizeduser1, 
authorizeduser2, authorizeduser3. 
2. The way this does is by first retrieving all the modules by calling 
infolog.navPane().getButtons(). This returns a container with name of the module 
prefixed with 0 or 1. 1 if this module should be visible in navigation and 0 if 
it should be hidden.
3. Next the code loops through each of the buttons and looks for the name of 
the Transportation module main menu (TMS). If it finds that this module is 
enabled then it disables it if the current user is not one of the above 
listed users. You can use the same logic to hide/show this module based 
on a role the current user is assigned.
3. Once the new container is built with the modified values then the code 
persists the values back to personalization by calling 
infolog.navPane().setCurrMenuButtons() with the container as argument.
4. Finally it calls another method that copies this personalization to all 
other companies for this user - MPModuleManager::replaceNavOptionsInAllCompanies()
*/
public static void hideTMSModule()
{
    container   cont_navButtons, cont_navButtons_new;

    int i = 1;
    int j = 1;
    str aotValue;

    boolean isAdmin = false;

    #AOT
    #define.Zero('0')
    #define.MainMenuLocation('\\Menus\\MainMenu')

    if (curUserId() != 'authorizeduser1' && curUserId() != 'authorizeduser2' && curUserId() != 'authorizeduser3')
    {
        cont_navButtons = infolog.navPane().getButtons();
        cont_navButtons_new = conNull();
        j = 1;
        for(i=1; i<conLen(cont_navButtons); i++)
        {
            aotValue = conPeek(cont_navButtons, i);
            switch(aotValue)
            {
                case '1TMS':
                    aotValue = '0TMS';
                    break;
            }
            cont_navButtons_new = conIns(cont_navButtons_new, j, aotValue);
            j++;
        }
        infolog.navPane().setCurrMenuButtons(cont_navButtons_new);

        ModuleManager::replaceNavOptionsInAllCompanies();
    }
}

/*
This method copies over the navigation pane personalization option from the 
current company to all other companies, so that this module TMS is not 
available in all companies.

The code is based on standard Microsoft code in the method 
RetailSMB::SetRetailSMBAreaPagesForAllCompanies()
*/

public static void replaceNavOptionsInAllCompanies()
{
    #define.elementName('Usersetup')
    #define.designName('NavPaneOptionsButtons')

    DataArea        dataArea;
    SysLastValue    sysLastValue, sysLastValue2;

    select sysLastValue
    where
        sysLastValue.company == curext() &&
        sysLastValue.userId == curUserId() &&
        sysLastValue.elementName == #elementName &&
        sysLastValue.designName == #designName;

    if (sysLastValue)
    {
        while select id from dataArea
            where !dataArea.isVirtual && dataArea.Id != curext()
        {
            select forUpdate sysLastValue2
                where sysLastValue2.company == dataArea.Id &&
                    sysLastValue2.userId == curUserId() &&
                    sysLastValue2.elementName == #elementName &&
                    sysLastValue2.designName == #designName;

            ttsBegin;

            sysLastValue2.company = dataArea.Id;
            sysLastValue2.userId = curUserId();
            sysLastValue2.elementName = sysLastValue.elementName;
            sysLastValue2.recordType = sysLastValue.recordType;
            sysLastValue2.designName = sysLastValue.designName;
            sysLastValue2.isKernel = sysLastValue.isKernel;
            sysLastValue2.value = sysLastValue.value;

            sysLastValue2.write();

            ttsCommit;
        }
    }
}

/*
Form SysNavPaneOptionsDialog, method OKButton:clicked
*/
void clicked()
{
    container navButtons;
    int i, j;
    FormListItem item;
    str buttonInfo;
    ;

    for (i = 0 ; i < ListView.getCount();i++)
    {
        item = ListView.getItem(i);
        // walk through each element
        if (item.stateChecked())
        {
            buttonInfo = '1';
        }
        else
            buttonInfo = '0';

        if(item.data() == 'TMS')
        {
            if (curUserId() != 'authorizeduser1' && curUserId() != 'authorizeduser2' && curUserId() != 'authorizeduser3')
            {
                buttonInfo = '0';
            }
        }

        buttonInfo+= item.data();
        navButtons = conins(navButtons,i+1,buttonInfo);
    }

    for (j = 1; j <= conLen(hiddenMenuItems); j++)
    {
        buttonInfo = '0' + conPeek(hiddenMenuItems, j);
        navButtons = conins(navButtons,i+1,buttonInfo);
        i++;
    }

    infolog.navPane().setCurrMenuButtons(navButtons);

    if (RetailSMB::IsRetailSMBEnabled())
    {
        RetailSMB::SetRetailSMBAreaPagesForAllCompanies();
    }

    ModuleManager::replaceNavOptionsInAllCompanies();

    super();
}

There were a few useful resources that finally led me to this solution. Following are the related links.

http://www.mazikglobal.com/blog/hide-modules-role-ax-2012/
https://community.dynamics.com/ax/f/33/t/136277.aspx
There was another post by Mriganka Bhuyan but I am unable to locate the link.

A few other solutions that did not yield proper results
1. I tried setting a configuration key on the menu and dynamically disabling the configuration key based on the current user. For this I overrode the startupPost method of the Application class. I also tried modifying the setDefaultCompany of the Application class to achieve the same effect. However I noticed that when I call infolog.navPane().setCurrMenuButtons(), a recursive call is made back to setDefaultCompany of Application object. Which caused pure virtual function call error.
2. I also tried modifiying the SysDataAreaSelect form but that does not prevent a user from using the addressbar to change the company and so it had its own issues.
3. I tried setting the navigation pane options by using code to loop through all companies and setting the personalization, but that resulted in lot of infolog messages and unexpected behavior.

One of the new modules in AX 2012 R3 is Transportation Management System (TMS). TMS allows us to shop for transportation rates based on mileage or weight for moving goods from point A to point B. However there is not a lot of documentation available yet on this subject. In this post I will try to give a short overview of TMS.

We all learn in different ways. For example if you have to remember the parts of an engine, some (people with good memory) can look at all the parts of an engine and that would be enough. However someone like me would need to see the engine as a whole together. Looking at the way the parts interact helps me remember better. So if you are like me and you want to understand TMS then i will try to draw a mental picture of the TMS engine so that you can remember it easily.

First I will list the different parts down and next i will show you how they connect. Since there are a lot of parts and some parts have a lot of sub-components i will try to give you a 100,000 ft and 30,000 ft overview first then dive in a little bit more and explode the pieces into their sub-components.

For the sake of making this post simple I am leaving out Routes, Freight charges, Carrier fuel index etc. I will try to cover them in later posts.

100,000 Ft View
– Rate Route Workbench : The main form that allows a user to calculate a rate for transportation. You can do a rate shopping here that will list the rates from all the transportation carriers that have been setup in AX. The rate is based on your requirement which is usually say a sales order or a transfer order in moving goods from warehouse to customer or another warehouse location. The transportation charges are usually dependent on both Mileage and Weight. But since you cannot calculate on both simultaneously in AX, what you would do is make one of them constant.

Example for rate by mileage: When you want to rate by mileage you would like to keep weight constant. You can do this by saying you will send a full truck load. So if you order a full truck load then the rates are based on the number of miles the truck load of items have to be moved. What we would need to do is to populate a table (from a form in AX Client) with origin postal code, city, state and destination postal code, city, state and the miles. There is no calculation but basically based on the origin and destination of your transfer order or sales order we can pull out the miles.
MileageDetails

Example for rate by weight: When you want to rate by weight you can make mileage constant by specifying the origin and destination location. Then all you would need to do is for this combination of origin and destination fill in the rate for the different weight ranges. So the columns could be : origin postal code, destination postal code, weight <100 lbs, weight <500 lbs, weight < 1000 lbs, weight < 5000 lbs, Weight Over 5000 lbs. Once we have a table like this filled up then based on the weight of the items being shipped, origin and destination we can figure out the rate.
WeightDetails

30,000 Ft View
– Shipping carrier : Shipping carriers are the ones providing service to transport your goods. To get any rate you need to set up shipping carriers first. To get a rate from the shipping carrier you need to check the “Activate carrier rating” and the “Use carrier” check boxes.

– Service : Shipping carriers will supply services. Each shipping carrier’s service is made up of the mode of transportation, mode of delivery and the load template. When doing a rate shop the number of rates you will get back is equal to the sum of all the shipping carrier services from all shipping carriers.
ShippingCarrier

– Rate Engine : This is the heart of the entire rating process and will calculate and return a rate. We create a rate engine in AX client and set its properties to an assembly (dll) and the class within the dll that will execute the code to figure out the rate based on all other selected parameters. A rate engine is composed of a number of components including Rate Base assigner, Mileage Engine, Apportionment engine etc..
RateEngines

– Rate Master : The primary use of a rate master is to allow us to define all the origins and for each origin setup a list of destinations. If we do not setup a rate master, we will not be able to locate the rate because we cannot map an origin/destination address combination to a rate.

– Rating Profile : A rating profile defines which rate master should be used by which shipping carrier.

So how does the rating process work?

  • Getting a rate is based on your origin and destination addresses
  • Addresses are composed of Country, City, State/Province, Postal code. You can use all or only a few of these address components to identify an origin/destination
  • Setup Shipping carriers and their services because rates are given by shipping carriers
  • Next you need to set up a rate engine. The rate engine is linked to the code/logic that will be used to arrive at a rate. The rate engine will also decide which of the components of the address it should use to arrive at the origin and destination combination.
  • Next Rate Master and Rate Base have to be setup. Rate Master will allow us to set up all the possible destinations (called Rate Base assignments) and Rate base will allow us to set up all the destinations. Typically for each origin we will setup a different rate base, which will essentially give us all the origin/destination combinations.
  • Finally a rating profile will connect a shipping carrier to Rate engine and Rate master
  • The rating process is in essence a 2 step process. The first step is to identify which origin record to pick. Next, based on the origin you picked you will get a list of destinations, so you need to now pick the correct destination record from the list of destinations.
  • To re-word this in TMS terms: Loop through each rating profile setup for a carrier and for each rating profile select the rate master. Under a rate master a list of rate base assignments are setup. You now need to pick the correct rate base assignment based on the origin address details. (Each rate base assignment record has fields like origin city, origin postal code and the corresponding rate base). From the rate base assignment selected you now need to take the rate base and loop through all the rate base details setup under the rate base. Each rate base detail has columns like destination city, destination postal code etc… and finally the rate. Once you have found a matching rate base detail you can now return the rate!!!
  • Rate Base assignments point to origins
  • Rate Base details point to destinations

Core Components
– Rate Base Type : Think of Rate base type as metadata. You define the metadata for which you need to capture information. So what kind of metadata does this define? It allows you to define origin and destination address components like origin city, origin postal code, destination city, destination country etc… You can define two different types of metadata fields: “Rate base” and “Assignment“. The fields that are defined as Rate base are used in identifying the origin address components and the fields that are defined as Assignment can be used to identify the destination address components.
RateBaseType

– Rate Base : Allows you to define the list of origins and link the list of destinations to each origin.
– Break Master : This is a setup of the break-up of the Mileage or Weight. You use a break master with a destination to define the rate. For example a break master would be: <500 lbs, <1000 lbs, <10,000 lbs, Max lbs
– Rate Base Assignment : Each rate base assignment points to an origin and links to the destination. Columns we see are the fields (of FieldType Assignment) from Rate Base Type selected against the Rate Master.
– Load Template : Defines the dimension of the load and also the max weight. This is linked to a carrier service to place restrictions on which services are available for rate shopping.

Code Components
– Rate Base Assigners (Always checks the table TMSRateBaseAssignment based on criteria. Common criteria are Carrier Service code, rate master code and scheduled ship date are matched)
– BaseRateAssigner (abstract class)
– MileageRateBaseAssigner : Nothing specific
– P2PRateBaseAssigner : Additional criteria is Dimension1 is equal to city, dimension2 is state, dimension3 is postalcode and dimension4 is countryregion, return first row.
– PieceRateBaseAssigner : Additional criteria is Dimension1 is pickup postal code, dropoff postal code is between dimension2 and dimension3, dimension4 is dropoff country
– PostalZoneWeightRateBaseAssigner : Nothing specific
– RailRateBaseAssigner
– LtlRateBaseAssigner
– LtlFakRateBaseAssigner

Issues
When i try to do a Rate shop, ran into the following issues

Issue 1: Rate base assignment cannot be found
Solution: This is typically because the Rate master for the service of the carrier is not setup or a matching rate base assignment was not found. To fix this go to Rate Master setup (for the carrier) and add a new rate base assignment for that particular carrier service and your origin address (and based on your rate engine parameters).

Issue 2: Rate base detail could not be found
Solution: The rate assignment is properly picked, however the rate base detail identifying the required info is not setup for passing to the rate base to figure out the rate is not setup. Create a proper rate base detail that matches your destination address.

Issue 3: Error processing BaseRateBroker, TMSException. When i dug deeper into the exception, the error was basically because of string to numeric conversion.
Solution: This was because of the setup of Rate Base Type. The rate base type had 3 fields of field type rate base. When i used this to create a rate base, 2 of these fields get added along with all the break master fields. I specified string values for these two new fields in the details row for rate base. Changed these to numbers and it worked. These values are stored in generic fields like Dimension1, Dimension2 etc in table TMSRateBaseDetail and the way these values are interpreted depends on the rating engine being used.

I also noticed the same issue when the mileage engine was not properly defined. Rather the mileage engine parameters. I had accidentally deleted the mileage engine, so i just set it up again and defined the mileage engine parameters and it worked. Again whenever we specify an assembly and a class, we have to define the parameters (with data types) exactly as required by the class.

Issue 4: Mileage detail could not be found.
Solution: The fix for this is in the Mileage engine. In Mileage engine -> Details section -> Add a new Pick-up postal code and drop-off postal code that match your load’s from and to postal codes.

Notes
Note 1: Rate base type can be specified at multiple points so that could lead to setup confusion. For example Rate base type has to be specified when you create a rate engine, you also need to specify the rate base type in Rate Master. However the rating profile brings together Rate Engine and Rate Master together and if they have different rate base types you would get validation errors.
Note 2: You can access rating profiles directly from the rating profile link under Setup->Rating or you can also go through the Shipping Carrier link under Setup->General. Rating profiles are essentially carrier specific and the combination of the carrier services and rating profiles under a carrier will give a list of all the possible rates. (Basically rate by carrier service).
Note 3: There is a little bit of hard-coding in TMS. For example the number of possible rate base assignment and rate base detail columns are limited to a maximum of 6. There are generic columns with names from Dimension1…Dimension6.
Note 4: You create a Rate base based on a Rate Base Type. The columns displayed in rate base detail are based on the fields of type Rate base defined in the Rate Base Type. Also additional columns displayed are based on the break master that is used to create the Rate base.
Note 5: You create a Rate base assignment (under rate master) based on the Rate Base Type defined under the rate master. The columns displayed in the Rate base assignment are based on the fields of type Assignment defined in the Rate Base Type.

Summary : There is so much more that I can write, for example about how to setup the Rate base detail or how to set the correct parameters for the rate engine. The parameters of rate engine are very important as this could potentially make or break your rate shop functionality for that carrier. Also there is the question of mileage engine. I think it is too much to cover in one blog, hopefully at least this blog post gives you a good jump-start.

One AX Restore to go!

Posted: May 2, 2014 in Dynamics AX 2012
Tags:

The key to learning new things in life is “A Need” but the success of learning depends on “Desire” and “Passion”.

One of the challenges I was faced with recently was to restore the data from one AX environment to another environment. Hmm ok i agree it is not a challenge but rather a (ohhh) boring mundane task. By restore i mean, say you did some demos and testing and built up a lot of data and now you want to erase this environment so you can start a new cycle of testing. However you want to restore this data in a different environment, say from Staging to QA, so you can keep the testing scenarios you created. To handle this scenario what you would do is you just restore the business/OLTP database (MicrosoftDynamicAX) into a different environment. Ideally you should restore the Model database as well.

This activity involves a lot of things to be taken care of
– We want to preserve the access and rights of users who had access to the target environment(QA)
– We want to preserve all the Parameters in AX in target environment like Batch Server config, Help System URL, EP URL, Analysis Server URL, Report Server parameters etc.
– We would like the database restore to keep the target database’s Physical File Names and the logical names of the database files. eg. your Staging AX DB was named MicrosoftDynamicsAX_Stag with physical file names D:\MSSQL\Data\MicrosoftDynamicsAX_Stag.mdf, D:\MSSQL\Data\MicrosoftDynamicsAX_Stag.ldf and the QA was named MicrosoftDynamicsAX_QA with physical file names D:\MSSQL\Data\MicrosoftDynamicsAX_QA.mdf, D:\MSSQL\Data\MicrosoftDynamicsAX_QA.ldf. When you restore from a backup of Staging db the file names will now change. So during restore you have to change file names and after restore you have to change the Logical Name of the data files as well.

Why do something manually when we can automate it right? So i set about experimenting with PowerShell and you will find below the files that allow you to do that. All of this is parameter driven.

The PowerShell script will do the following
– Loads parameters from Parameters.txt and validates all the required parameters are present and have values
– Loads both AX and SQL PS Modules
– Exports all users and their roles in the current database and generates a PowerShell script file to recreate the users after restore
– Exports all the AX config parameters to local variables
– Extracts the current database’s physical file path and logical names of the data and log files
– Backups the existing database
– Stops AOS
– Kills all active connections to the database
– Restores the database from backup while preserving file names
– Renames the logical names of the data and log files
– Restarts AOS
– Restores AX config parameters
– Logs all activity
– Works in two modes Read Only and Read Write. When property ReadOnlyMode is set to anything other than False the script will only export users, export AX parameters, backup database, stop and start AOS. If we set it to True then in addition it will also restore db and update ax parameters.

There are few limitations of this script (which i am trying to fix)
– You have to run the script from AOS Server machine and with Admin rights (of course)
– The backup location for SQL database and the backup file to restore from, have to be local to SQL Server. Let us say your SQL Server is not on AOS Server then the backup path you specify say is D:\backup then this D drive and that folder has to exist on the SQL Server, although you are running the script from AOS Server.
– This assumes both the destination database and the source database have only one mdf and one ldf file each.
– Users exported are all assumed to be Windows users. Please feel free to update this code as you feel fit, there was no such need for me so i have left it as such.
– Updating especially Batch Server parameter in AX might fail because of duplicate rows, i am working on a fix for this

There were numerous issues that i had to resolve to get this work. And some of the most painful ones are listed below. You will understand these as you read the script
– Stop-Service/Start-Service might not work properly depending upon if you are doing this in a demo environment. In a demo environment (say Contoso) the connection between the computer and DC might not be proper and could cause these commandlets to fail.
– While restoring database the restore object’s NoRecovery property has to be set to False else your restore will just pure and misereably fail.
– During restore you need to specify the relocate files but only change the physical file path and not the logical file name.
– Logical file renaming is done later in the code after restore
– You could see issues in exporting users/roles but those can be safely ignored because the type of those users being exported are not windows users

The sources files have been inserted into this word document
SourceFiles

Main PS1 file

function validateSingleParameter($nameOfParameter)
{
    $retValueInner = 1;
    if(!$Global:Parameters.ContainsKey($nameOfParameter))
    {
        "VALIDATION FAILED::Parameter #$nameOfParameter# does not exist in the Parameters.txt file" | Out-File -FilePath $log -Append;
        $retValueInner = 0;
    }
    elseif($Global:Parameters[$nameOfParameter] -eq "")
    {
        "VALIDATION FAILED::Value for Parameter #$nameOfParameter# has not been specified in the Parameters.txt file" | Out-File -FilePath $log -Append;
        $retValueInner = 0;
    }
    return $retValueInner;
}

function validateParameters
{
    $retValue = 1;
    $retrievedValue = 0;
    
    $retrievedValue = validateSingleParameter "OutputFilePath"
    if($retValue -eq 1)
    {
        $retValue = $retrievedValue;
    }
    
    $retrievedValue = validateSingleParameter "ServerInstance"
    if($retValue -eq 1)
    {
        $retValue = $retrievedValue;
    }
    
    $retrievedValue = validateSingleParameter "Database"
    if($retValue -eq 1)
    {
        $retValue = $retrievedValue;
    }
    
    $retrievedValue = validateSingleParameter "BackupFilePath"
    if($retValue -eq 1)
    {
        $retValue = $retrievedValue;
    }
    
    $retrievedValue = validateSingleParameter "BackupFileToRestore"
    if($retValue -eq 1)
    {
        $retValue = $retrievedValue;
    }
    
    $retrievedValue = validateSingleParameter "AOSServer"
    if($retValue -eq 1)
    {
        $retValue = $retrievedValue;
    }
    
    $retrievedValue = validateSingleParameter "AOSInstance"
    if($retValue -eq 1)
    {
        $retValue = $retrievedValue;
    }
    
    $retrievedValue = validateSingleParameter "ReadOnlyMode"
    if($retValue -eq 1)
    {
        $retValue = $retrievedValue;
    }
    return $retValue;
}

#Date formatted as string to create a new folder
$dateCovertedToText = "{0:ddMMMyyyy_hhmmtt}" -f (Get-Date)

$currentWorkingDirectory = $MyInvocation.MyCommand.Path.Substring(0, $MyInvocation.MyCommand.Path.LastIndexOf("\"));
$log = $currentWorkingDirectory + "\Log_" + $dateCovertedToText + ".txt" 

#Create the log file (Overwrite if exists)
New-Item -Path $log -ItemType "File" -Force

#Load Parameters
& .\LoadParameters.ps1
"Loaded Parameters " | Out-File -FilePath $log

if(!(validateParameters))
{
    "ERROR::Parameters have not been properly defined. Stopping execution of script." | Out-File -FilePath $log -Append
    return
}

$readOnlyMode = $Global:Parameters["ReadOnlyMode"]
$server = $Global:Parameters["ServerInstance"]
$databaseName = $Global:Parameters["Database"]
$backupFileToRestore = $Global:Parameters["BackupFileToRestore"]

#Load Dynamics AX Module
& .\LoadDynamicsAXPSModule.ps1
"Loadeded AX Module " | Out-File -FilePath $log -Append

#Load AX variables
$aosServer = $Global:Parameters["AOSServer"]
$aosInstance = $Global:Parameters["AOSInstance"]

$axBatchServer = $Global:Parameters["AXBatchServer"]
$axHelpSystem = $Global:Parameters["AXHelpSystem"]
$axAnalysisServer = $Global:Parameters["AXAnalysisServer"]
$axReportServer = $Global:Parameters["AXReportServer"]
$axEPUrl = $Global:Parameters["AXEPUrl"]

#Export all users/roles and generate a ps1 file
#--------------------------------------------------
$filePath = $Global:Parameters["OutputFilePath"]
$lineToWrite = ""

New-Item $filePath -ItemType file -Force
$userList = Get-AXUser

$lineToWrite = "& .\LoadDynamicsAXPSModule.ps1"
$lineToWrite | Out-File -FilePath $filePath -Append

$lineToWrite = "& .\LoadSQLServerPSModule.ps1"
$lineToWrite | Out-File -FilePath $filePath -Append
foreach($user in $userList)
{
    if($user.AXUserId -ne "Admin")
    {
        $lineToWrite = "New-AXUser -AccountType " + $user.AccountType + " -AXUserId " + $user.AXUserId + " -Company " + $user.Company + " -UserDomain " + $user.UserDomain + " -UserName " + $user.UserName
        $lineToWrite | Out-File -FilePath $filePath -Append;

        $securityRoles = Get-AXSecurityRole -AxUserID $user.AXUserId
        foreach($securityRole in $securityRoles)
        {
            $lineToWrite = "Add-AXSecurityRoleMember -AOTName " + $securityRole.AOTName + " -AxUserID " + $user.AxUserID
            $lineToWrite | Out-File -FilePath $filePath -Append;
        }
    }
}
"Exported Users and roles to $filePath " | Out-File -FilePath $log -Append
#=====================================================
#Stop AOS
Stop-Service $aosInstance -WarningAction SilentlyContinue
"Stopped AOS instance $asoInstance on server $aosServer " | Out-File -FilePath $log -Append

#Load SQLPS Module
& .\LoadSQLServerPSModule.ps1
"Loaded SQL PS Module " | Out-File -FilePath $log -Append

#Save default parameters from the AX database
$axDBConn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$server; Initial Catalog=$databaseName; Integrated Security=SSPI")
$axDBConn.Open();

#Load Batch Server parameter
$cmd = $axDBConn.CreateCommand()
$cmd.CommandText = "Select * From SYSSERVERCONFIG"
$result = $cmd.ExecuteReader();
$dataTable = New-Object System.Data.DataTable
$dataTable.Load($result)
foreach($dataRow in $dataTable.Rows)
{
    $axBatchServer = $dataRow.SERVERID;
}
"Batch Server = #$axBatchServer#" | Out-File -FilePath $log -Append

#Load Help System parameter
$cmd = $axDBConn.CreateCommand()
$cmd.CommandText = "Select * From SYSGLOBALCONFIGURATION Where NAME = 'HelpServerLocation'"
$result = $cmd.ExecuteReader();
$dataTable = New-Object System.Data.DataTable
$dataTable.Load($result)
foreach($dataRow in $dataTable.Rows)
{
    $axHelpSystem = $dataRow.VALUE;
}
"Help System parameter = #$axHelpSystem#" | Out-File -FilePath $log -Append

#Load Analysis Server parameter
$cmd = $axDBConn.CreateCommand()
$cmd.CommandText = "Select * From BIANALYSISSERVER Where ISDEFAULT = 1"
$result = $cmd.ExecuteReader();
$dataTable = New-Object System.Data.DataTable
$dataTable.Load($result)
foreach($dataRow in $dataTable.Rows)
{
    $axAnalysisServer = $dataRow.SERVERNAME;
}
"Analysis Server parameter = #$axAnalysisServer#" | Out-File -FilePath $log -Append

#Load Report Server parameters
$cmd = $axDBConn.CreateCommand()
$cmd.CommandText = "Select * From SRSSERVERS"
$result = $cmd.ExecuteReader();
$dataTable = New-Object System.Data.DataTable
$dataTable.Load($result)
foreach($dataRow in $dataTable.Rows)
{
    $axSRS_AOSID = $dataRow.AOSID;
    $axSRS_SERVERID = $dataRow.SERVERID;
    $axSRS_SERVERURL = $dataRow.SERVERURL;
    $axSRS_AXAPTAREPORTFOLDER = $dataRow.AXAPTAREPORTFOLDER;
    $axSRS_REPORTMANAGERURL = $dataRow.REPORTMANAGERURL;
    $axSRS_SERVERINSTANCE = $dataRow.SERVERINSTANCE;
    $axSRS_CONFIGURATIONID = $dataRow.CONFIGURATIONID;
}
"Report Server Parameter AOS Id = #$axSRS_AOSID#" | Out-File -FilePath $log -Append
"Report Server Parameter Server Id = #$axSRS_SERVERID#" | Out-File -FilePath $log -Append
"Report Server Parameter Server Url = #$axSRS_SERVERURL#" | Out-File -FilePath $log -Append
"Report Server Parameter Report Folder = #$axSRS_AXAPTAREPORTFOLDER#" | Out-File -FilePath $log -Append
"Report Server Parameter Report Manager Url = #$axSRS_REPORTMANAGERURL#" | Out-File -FilePath $log -Append
"Report Server Parameter Server Instance = #$axSRS_SERVERINSTANCE#" | Out-File -FilePath $log -Append
"Report Server Parameter Configuration Id= #$axSRS_CONFIGURATIONID#" | Out-File -FilePath $log -Append

#Load EP Parameter
$cmd = $axDBConn.CreateCommand()
$cmd.CommandText = "Select * From EPGLOBALPARAMETERS"
$result = $cmd.ExecuteReader();
$dataTable = New-Object System.Data.DataTable
$dataTable.Load($result)
foreach($dataRow in $dataTable.Rows)
{
    $axEPUrl = $dataRow.SEARCHSERVERURL;
}
"EP Parameter = #$axEPUrl#" | Out-File -FilePath $log -Append

$axDBConn.Close()

$sqlSrv = New-Object Microsoft.SqlServer.Management.Smo.Server($server);
$databaseObject = New-Object Microsoft.SqlServer.Management.Smo.Database;
$databaseObject = $sqlSrv.Databases.Item($databaseName);

foreach($fileGroup in $databaseObject.FileGroups)
{
    foreach($dataFile in $fileGroup.files)
    {
        $targetMDF = $dataFile.Name;
        $targetMDFFileName = $dataFile.FileName
        break;
    }
    break;
}

foreach($logFile in $databaseObject.LogFiles)
{
    $targetLDF = $logFile.Name;
    $targetLDFFileName = $logFile.FileName
    break;
}

#Load SQL PS Module changes the directory to SQLSERVER so storing the current path and switching it back after loading the SQL Powershell module
cd $currentWorkingDirectory 

#Backup folder path
#$sqlDBBackupPath =  $Global:Parameters["BackupFilePath"] + "\" + $dateCovertedToText + "\" 
$sqlDBBackupPath =  $Global:Parameters["BackupFilePath"] + "\" 

#Backup file name with full path
#$sqlDBBackupFile =  $sqlDBBackupPath + $Global:Parameters["Database"] + ".bak"
$sqlDBBackupFile =  $sqlDBBackupPath + $Global:Parameters["Database"] + ".bak"

#Switch to SQL Server directory to get to your database. Probably could optimize this code, but just want to get this done for now
Set-Location SQLSERVER:\SQL\$server\DEFAULT\DATABASES;

#Create the backup folder path
#New-Item -Path $sqlDBBackupPath -ItemType directory
"Created a new folder for backup " | Out-File -FilePath $log -Append

#Backup the database before we do a restore
Backup-SqlDatabase -ServerInstance $Global:Parameters["ServerInstance"] -Database $Global:Parameters["Database"] -BackupFile $sqlDBBackupFile
"Database backed-up to $sqlDBBackupFile " | Out-File -FilePath $log -Append

$sqlSrv = New-Object Microsoft.SqlServer.Management.Smo.Server($server);
$databaseObject = New-Object Microsoft.SqlServer.Management.Smo.Database;
$databaseObject = $sqlSrv.Databases.Item($databaseName);

$restoreDB = New-Object Microsoft.SqlServer.Management.Smo.Restore;

#The NoRecovery when set to true results in the database status going into a Restoring mode, not good.
$restoreDB.NoRecovery = $false;
$restoreDB.ReplaceDatabase = $true;
$restoreDB.Action = "Database"
$restoreDB.PercentCompleteNotification = 5;

#$restoreDB.Devices.AddDevice($backupFileToRestore, [Microsoft.SqlServer.Management.Smo.DeviceType]::File)
$backupDevice = New-Object Microsoft.SqlServer.Management.Smo.BackupDeviceItem($backupFileToRestore, "File");
$restoreDB.Devices.Add($backupDevice);

#Selects the first item in the backup set
$restoreDB.FileNumber = 1

$restoreDetails = $restoreDB.ReadBackupHeader($sqlSrv);
$relocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile
$relocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile
$relocateData.LogicalFileName = $targetMDF
$relocateLog.LogicalFileName = $targetLDF
foreach($restoreFileItem in $restoreDB.ReadFileList($sqlSrv))
{
    switch($restoreFileItem.Type)
    {
        "D"{ $relocateData.LogicalFileName = $restoreFileItem.LogicalName; }
        default { $relocateLog.LogicalFileName = $restoreFileItem.LogicalName; }
    }
    
}
$relocateData.PhysicalFileName = $targetMDFFileName
$relocateLog.PhysicalFileName = $targetLDFFileName
$restoreDB.RelocateFiles.Add($relocateData);
$restoreDB.RelocateFiles.Add($relocateLog);
$restoreDB.Database = $databaseName

if($readOnlyMode -eq "False")
{
    #Terminate all connections to the SQL Database
    $sqlSrv.KillAllProcesses($databaseName);
}

if($readOnlyMode -eq "False")
{
    #Restore the database
    $restoreDB.SqlRestore($sqlSrv);
    "Database restored from backup file " | Out-File -FilePath $log -Append
}

if($readOnlyMode -eq "False")
{
    #We are going to modify the Logical name of the database and log file
    $sqlSrv.KillAllProcesses($databaseName);
    #Refresh the information in our SQL Server object
    $sqlSrv.Refresh();
}

#Reset the SQL Server object and the database object so that we release all connections
#Unable to change logical name of the database file if these objects are not re-initialized
$sqlSrv = New-Object Microsoft.SqlServer.Management.Smo.Server($server);
$databaseObject = New-Object Microsoft.SqlServer.Management.Smo.Database;
$databaseObject = $sqlSrv.Databases.Item($databaseName);
$databaseObject_PostRestore = New-Object Microsoft.SqlServer.Management.Smo.Database;
$databaseObject_PostRestore = $sqlSrv.Databases.Item($databaseName);

foreach($fileGroup in $databaseObject_PostRestore.FileGroups)
{
    foreach($dataFile in $fileGroup.files)
    {
        if($dataFile.Name -ne $targetMDF)
        {
            if($readOnlyMode -eq "False")
            {
                $dataFile.Rename($targetMDF);
            }
        }
        break;
    }
    break;
}

foreach($logFile in $databaseObject_PostRestore.LogFiles)
{
    if($logFile.Name -ne $targetLDF)
    {
        if($readOnlyMode -eq "False")
        {
            $logFile.Rename($targetLDF);
        }
    }
    break;
}

if($readOnlyMode -eq "False")
{
    $sqlSrv.KillAllProcesses($databaseName);
}
"Logical name of the database files has been changed " | Out-File -FilePath $log -Append

#Change working directory back to the current directory. 
#We need to do this because when we load the SQLPS module the directory is set to SQL Server
Set-Location $currentWorkingDirectory
"Changed working directory back to current working directory " | Out-File -FilePath $log -Append

#Start AOS
Start-Service $aosInstance -WarningAction SilentlyContinue
"Started AOS instance $asoInstance on server $aosServer " | Out-File -FilePath $log -Append

#We will now start updating parameters in Dynamics AX database
$axDBConn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$server; Initial Catalog=$databaseName; Integrated Security=SSPI")
$axDBConn.Open();

$cmd = $axDBConn.CreateCommand()

if($readOnlyMode -eq "False")
{
    #Update batch server record in Dynamics AX database
    $cmd.CommandText = "Update Top(1) SYSSERVERCONFIG Set SERVERID='$axBatchServer', ENABLEBATCH=1"
    $cmd.ExecuteNonQuery()

    #Update Help system parameter in Dynamics AX database
    $cmd.CommandText = "Update Top(1) SYSGLOBALCONFIGURATION Set [VALUE]='$axHelpSystem' Where NAME = 'HelpServerLocation'"
    $cmd.ExecuteNonQuery()

    #Update Analysis Server parameter in Dynamics AX database
    $cmd.CommandText = "Update Top(1) BIANALYSISSERVER Set [SERVERNAME]='$axAnalysisServer' Where ISDEFAULT = 1"
    $cmd.ExecuteNonQuery()

    #Update Report Server parameter in Dynamics AX database
    $cmd.CommandText = "Update Top(1) SRSSERVERS Set [AOSID]='$axSRS_AOSID', [SERVERID] = '$axSRS_SERVERID', [SERVERURL] = '$axSRS_SERVERURL', [AXAPTAREPORTFOLDER] = '$axSRS_AXAPTAREPORTFOLDER', [REPORTMANAGERURL] = '$axSRS_REPORTMANAGERURL', [SERVERINSTANCE] = '$axSRS_SERVERINSTANCE', [CONFIGURATIONID] = '$axSRS_CONFIGURATIONID'"
    $cmd.ExecuteNonQuery()

    #Update EP Portal parameter in Dynamics AX database
    $cmd.CommandText = "Update Top(1) EPGLOBALPARAMETERS Set [SEARCHSERVERURL]='$axEPUrl'"
    $cmd.ExecuteNonQuery()
}

#Completed all our database operations and closing connection
$axDBConn.Close()

If you are trying to migrate data from one of your development environment to another development environment, you would typically do this through a database restore. There are a number of parameters within AX you need to change after the restore.

Is there a simple way to preserve the users and their roles in the destination environment (The one being overwritten)? Yes indeed, you can use PowerShell scripts to export the users and their roles before you do the restore. Use this exported list to recreate your users.

The PowerShell script below does the following.
– Loops through and extracts all users
– For each user extracts all the roles the user is assigned
– Creates a new powershell script file which has commands to recreate the user and add them to their roles
– The path of the file is hardcoded and you might want to change that “C:\TEMP\ExportedUsers.ps1”.

 

# The below code segment has been extracted form the Management Shell to load AX modules
#----------------------------------------------------------------------------------------
function ImportAXModule($axModuleName, $disableNameChecking, $isFile)
{
    try
    {
        $outputmessage = "Importing " + $axModuleName
        Write-Output $outputmessage

        if($isFile -eq $true)
        {
            $dynamicsSetupRegKey = Get-Item "HKLM:\SOFTWARE\Microsoft\Dynamics\6.0\Setup"
            $sourceDir = $dynamicsSetupRegKey.GetValue("InstallDir")
            $axModuleName = "ManagementUtilities\" + $axModuleName + ".dll"
            $axModuleName = join-path $sourceDir $axModuleName
        }
        if($disableNameChecking -eq $true)
        {
            import-module $axModuleName -DisableNameChecking
        }
        else
        {
            import-module $axModuleName
        }
    }
    catch
    {
        $outputmessage = "Could not load file " + $axModuleName
        Write-Output $outputmessage
    }
}

$dynamicsSetupRegKey = Get-Item "HKLM:\SOFTWARE\Microsoft\Dynamics\6.0\Setup"
$sourceDir = $dynamicsSetupRegKey.GetValue("InstallDir")
$dynamicsAXModulesPath = join-path $sourceDir "ManagementUtilities\Modules"

$env:PSModulePath = $env:PSModulePath + ";" + $dynamicsAXModulesPath

ImportAXModule "AxUtilLib" $false $true

#AxUtil uses "Optimize" verb.
#Therefore we use -DisableNameChecking to suppress warning about uncommon verb being used.
ImportAXModule "AxUtilLib.PowerShell" $true $false

ImportAXModule "Microsoft.Dynamics.Administration" $false $false
ImportAXModule "Microsoft.Dynamics.AX.Framework.Management" $false $false
#----------------------------------------------------------------------------------------

# Clear the screen so you can see what is happening much more easily
cls

# Change this file path to where you want to save the generated PowerShell script
$filePath = "C:\Temp\ExportedUsers.ps1"
$lineToWrite = " "

# Deletes the file to ensure we generate a clean file
New-Item $filePath -ItemType file -Force

# Retrieve the list of users
$userList = Get-AXUser

# Loop through the user list 
foreach($user in $userList)
{
    # Writes a line to the file, this line writes a PowerShell script to create/add this user to Dynamics AX
    $lineToWrite = "New-AXUser -AccountType " + $user.AccountType + " -AXUserId " + $user.AXUserId + " -Company " + $user.Company + " -UserDomain " + $user.UserDomain + " -UserName " + $user.UserName
    $lineToWrite | Out-File -FilePath $filePath -Append;

    # Retrieve all the security roles the user is assigned to
    $securityRoles = Get-AXSecurityRole -AxUserID $user.AXUserId

    # Loop through the security roles so we can write PowerShell script to the file
    foreach($securityRole in $securityRoles)
    {
        # Writes a line to the file, this line writes a PowerShell script to add the Role to the User
        $lineToWrite = "Add-AXSecurityRoleMember -AOTName " + $securityRole.AOTName + " -AxUserID " + $user.AxUserID
        $lineToWrite | Out-File -FilePath $filePath -Append;
    }
}

 

I recently switched jobs and one of my responsibility is to build AX 2012 capability in the internal IT team. I am focusing on Dev I, II and III and as part of the weekly training I have prepared some PowerPoint presentations. I am attaching them here in case anyone finds the need to do similar training. I will continue to add any new presentations I prepare to this post.

Presentations 1 to 4 cover Dev I module.

AXDevTraining_Session1

AXDevTraining_Session2

AXDevTraining_Session3

AXDevTraining_Session4

Presentations 5 to 9 cover Dev II module

AXDevTraining_Session5

AXDevTraining_Session6

AXDevTraining_Session7

AXDevTraining_Session8

AXDevTraining_Session9

Presentation targeted towards performance and infrastructure

AXInfrastructureTraining

I was trying to create a general journal with vendor payments and settle open Vendor transactions. When the code was run manually it worked fine. However when we ran the job in a batch mode it failed with the error “Unable to cast CustVendTransOpen to VendTransOpen. This just did not make sense, so i dug through the code and realized that the error was thrown at this line

CustVendOpenTransManager::UpdateTransMarked method
if (isConfigurationkeyEnabled(configurationKeyNum(PSAPwp)) && (_custVendTransOpen.TableId == tableNum(VendTransOpen)))
{
if (_custVendTransOpen.checkPwpEnabled(_custVendTransOpen)) <<——-
……

Seems strange that _custVendTransOpen.TableId == tableNum(VendTransOpen) is true but we still get this error. Following is the signature of the method checkPwpEnabled of the table VendTransOpen:
public boolean checkPwpEnabled(VendTransOpen _custVendTransOpen)
If we call this code in a non-batch mode, then it runs fine, however when we run it in batch mode, i believe that this method is called through reflection. During the process of reflection something obviously has gone wrong and during deserialization of the parameters, the reflection code is not able to cast the value from CustVendTransOpen to VendTransOpen. To get around this i found every single occurrence of this method in code and passed in explicitly a local variable which is already cast to VendTransOpen. Basically as follows
VendTransOpen vendTransOpenLocal;
if (_custVendTransOpen.TableId == tableNum(VendTransOpen))
{
vendTransOpenLocal = _custVendTransOpen;
}

if (isConfigurationkeyEnabled(configurationKeyNum(PSAPwp)) && (_custVendTransOpen.TableId == tableNum(VendTransOpen)))
{
if (_custVendTransOpen.checkPwpEnabled(vendTransOpenLocal))

This is probably a MS defect, i just fixed it myself for now and will probably go hunting for a hotfix.