Is it possible to Create/Update Application User in Dynamics 365 Programmatically?

By | July 6, 2018

You may have heard about the Application user in Dynamics 365. The Application user is a non-licensed and non-interactive user in the Dynamics 365 that we can use to connect to Dynamics 365 services to perform operations.

Have you come across a requirement where you need to create/update Application User programmatically and do you think it is possible?

Recently, we had a requirement where we had to create an Application User in Dynamics 365 programmatically. And, after researching it, we came to know that it is possible!

In this blog, we will illustrate how we can create/update the Application user programmatically.

Programmatically Creating or Updating Application User in Dynamics 365

While creating an Application User from Application Form manually, we have to pass the below mandatory fields.

  1. First Name
  2. Last Name
  3. Primary Email
  4. Application ID (that we get from Azure AD)

After you click on save button, the Application ID URI, Azure AD Object ID fields get auto-populated.

If you try to do the same thing using either JavaScript (Web API) or C# code (bypassing above mentioned four fields to entity object to create), you will get the following error,

“An unexpected error occurred”

While creating an Application User, we must pass the Business Unit ID field along with the fields mentioned above.

So to create an Application User, we must pass following fields to an entity object,

  1. First Name
  2. Last Name
  3. Primary Email
  4. Application ID (that we get from Azure AD)
  5. Business Unit ID

Below is the sample code that shows how to create Application User using Web API at the client side.

function createApplicationUser() {
    try {

var apiconfig = { APIUrl: Xrm.Utility.getGlobalContext().getClientUrl() + '/api/data/v9.0/' };
        var crmAPI = new CRMWebAPI(apiconfig);

        //retrieve business unit
        var buQueryOpions = {
            Select: ["businessunitid", "name"],
            Filter: "_parentbusinessunitid_value eq null"
        };

        //retrive Business Units
        crmAPI.GetList("businessunits", buQueryOpions).then(function (response) {
            if (response != null && response != undefined && response.List != null && response.List != undefined && response.List.length > 0) {

                //set Business Unit ID
                var businessUnitId = response.List[0].businessunitid;

                //create Application User
                createApplicationuser(businessUnitId, crmAPI);
            }
            else {
                alert("Root Business Unit not found");
            }
        }, function (error) {
            alert(err.responseText);
        });
    } catch (e) {
        throwError(e, functionName);
    }
}


// This function create or update the Application User
function createApplicationuser(businessUnitId, crmAPI) {
    try {
        //check if application user is already exist
        var queryOptions = {
            Select: ['systemuserid', 'applicationid'],
            Filter: 'applicationid eq XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'
        };
        var applicationUser = null;

        //retrive Applicationuser with Application ID
        crmAPI.GetList("systemusers", queryOptions).then(function (response) {

            //if Application User record is present then Update
            if (response != null && response != undefined && response.List != null && response.List != undefined && response.List.length > 0) {

                //set the Application User
                applicationUser = response.List[0];

                //crete user data object
                var user = {
                    "applicationid": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
                    "firstname": "MultiTenant",
                    "lastname": "Portal3",
                    "internalemailaddress": "multitenantportal@test.com"
                };

                //update application user
                crmAPI.Update("systemusers", applicationUser.systemuserid, user, true).then(function (result) {
                    alert("Application user updated with new details.");
                }, function (err) { alert(err.responseText);});
            }
                //check if Application User record is not present then Crete 
            else {
                //create user data object 
                var user = {
                    "applicationid": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
                    "firstname": "MultiTenant",
                    "lastname": "Portal3",
                    "internalemailaddress": "multitenantportal@test.com",
                    "businessunitid@odata.bind": "/businessunits(" + businessUnitId + ")"
                };
                //create application user
                crmAPI.Create("systemusers", user).then(function (result) {
                    alert("Application user created.");
                }, function (err) { alert(err.responseText);});
            }

        }, function (error) {
            alert(error);
        });
    } catch (error) {
        alert(error.message || error.description);
    }
}

 

Here, we first retrieved the Business Unit ID and then we passed this Business Unit ID to create the Application User along with other fields.

You can see that we are checking whether an Application User already exists with matching Application ID in the System. If matching Application User is found, then we are updating existing Application User, else we create a new Application user.

Conclusion:

It is possible to create Application user either at client side (using JavaScript) or server side (using plugin, workflow assembly or external tools). We need to make sure that we are passing all the required fields, i.e. First name, Last Name, Email Address, Application ID and Business Unit ID.

Free 70% of storage space in CRM with Attachment Management Apps!

Attach2Dynamics – Store and manage documents/attachments in cloud storage of your choice – SharePoint, Dropbox or Azure Blob Storage from within Dynamics 365 CRM.
SharePoint Security Sync – Robust and secure solution to integrate Dynamics 365 CRM and SharePoint Security Sync thereby ensuring secure access to confidential documents stored in SharePoint.

6 thoughts on “Is it possible to Create/Update Application User in Dynamics 365 Programmatically?

  1. Kiran

    Its nice we can achieve this, Can you let me know how this can be achieved using C# code.

    1. inogic

      Hi,

      You can achieve this through C# code also. You would need to create Entity object with attributes mentioned in the blog and then use service.Create and service. Update request to create and update application user in Dynamics 365 respectively. This should work.
      Refer the following link to know how to create update record in Dynamics 365, https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/org-service/sample-create-retrieve-update-delete-late-bound

      Thanks!

      1. Sachin Datey

        My Scenario is for Update, since we had created the application user without Azure AD Client App, and now the Application Id fields is showing locked.
        I tried the below C# code,

        Entity userEnt = new Entity(“systemuser”, userCollection.Entities[0].Id);
        userEnt[“applicationid”] = new Guid(“valid app id – guid”);
        userEnt[“firstname”] = “Test”;
        userEnt[“lastname”] = “User”;
        userEnt[“internalemailaddress”] = “testuser@test.com”;
        organizationProxy.Update(userEnt);

        But is is not working, the applicationid is still blank.

        1. Inogic

          In order to create or update Application User in Dynamics CRM, you must first create Azure AD Client App and you must pass Application Id, Business Unit Id, First Name, Last Name, Internal Email Address. Without Azure AD client app it won’t work.

          Thanks!

  2. Lukman H

    I’ve tried using Postman, you need to setup Authorization(OAuth 2.0), config your header and pint to /api/data/v9.0/systemusers, and look for the app user in question using GET. Take note on the systemuserid, and create another request to the same endpoint on PATCH, only this time specifically set to the respective app user i.e. /api/data/v9.0/systemusers(systemuserid_here), and I used the same user data object in your example.
    However I can’t get my application id updated, including Application ID URI and Azure AD Object ID. Did I missed anything?

Comments are closed.