Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics 365 | Integration, Dataverse...
Answered

How to programmatically add user and assign them customer engadement license in dynamics 365 online using C#

(0) ShareShare
ReportReport
Posted on by 10

Hi All,

I have requirement to dynamically create users and assign them customer engagement license on online D365. I am able to create user in D365 systemuser entity but didn,t found way to assign them license.

is there any way to achieve this using C# code.

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Management.Automation.Runspaces;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace PowerApps.Samples
{
public partial class SampleProgram
{
static void Main(string[] args)
{
JObject azureUser = new JObject();
JObject retrievedResult;
string queryOptions = string.Empty;
string domainName = string.Empty;
try
{
Console.WriteLine("Please enter domain name...");
domainName = Console.ReadLine();

string connectionString = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;

using (HttpClient client = SampleHelpers.GetHttpClient(
connectionString,
SampleHelpers.clientId,
SampleHelpers.redirectUrl,
"v9.1"))
{

queryOptions = "systemusers?$select=domainname&$filter=domainname eq '" + domainName + "'";

HttpResponseMessage retrieveResponse = client.GetAsync(client.BaseAddress.AbsoluteUri + queryOptions,
HttpCompletionOption.ResponseHeadersRead).Result;

if (retrieveResponse.IsSuccessStatusCode) //200
{
retrievedResult = JObject.Parse(retrieveResponse.Content.ReadAsStringAsync().Result);
string outputDomainname = (string)retrievedResult.SelectToken("value[0].domainname");
Console.WriteLine("Domain: " + outputDomainname);
if (outputDomainname == null)
{
Console.WriteLine("Create new user...");

HttpRequestMessage createrequest = new HttpRequestMessage(HttpMethod.Post,
client.BaseAddress + "systemusers");

Console.WriteLine("Enter first name");
azureUser.Add("firstname", Console.ReadLine());

Console.WriteLine("Enter last name");
azureUser.Add("lastname", Console.ReadLine());

Console.WriteLine("Enter internal email address");
azureUser.Add("internalemailaddress", Console.ReadLine());

Console.WriteLine("Enter windows live email address");
azureUser.Add("windowsliveid", Console.ReadLine());

azureUser.Add("isdisabled", false);
azureUser.Add("caltype", 7);
azureUser.Add("businessunitid@odata.bind", "/businessunits(8c44c8ac-f6a3-ea11-a812-000d3a0a74cb)");

createrequest.Content = new StringContent(azureUser.ToString());
createrequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

HttpResponseMessage createResponse = client.SendAsync(createrequest, HttpCompletionOption.ResponseHeadersRead).Result;
if (createResponse.IsSuccessStatusCode)
{
string userUri = createResponse.Headers.GetValues("OData-EntityId").FirstOrDefault();

Console.WriteLine("Account created...");

JObject userUpdate = new JObject();
userUpdate.Add("islicensed", true);
userUpdate.Add("issyncwithdirectory", true);
userUpdate.Add("isintegrationuser", true);
HttpRequestMessage updaterequest = new HttpRequestMessage(new HttpMethod("PATCH"), userUri);
updaterequest.Content = new StringContent(userUpdate.ToString(), Encoding.UTF8, "application/json");

HttpResponseMessage updateresponse = client.SendAsync(updaterequest, HttpCompletionOption.ResponseContentRead).Result;
if (updateresponse.IsSuccessStatusCode)
{
Console.WriteLine("User updated...");
}
else
{
Console.WriteLine("Failed to update user for reason: {0}",
updateresponse.ReasonPhrase);

}
}
else
{
throw new Exception(string.Format("Failed to Post Records", createResponse.ReasonPhrase));
}
}
else
{
Console.WriteLine("User exists...");
}
}
else
{
Console.WriteLine("Failed to retrieve domain: {0}",
retrieveResponse.ReasonPhrase);
throw new Exception(string.Format("Failed to retrieve domain: {0}", retrieveResponse.Content));
}
}
}
catch (Exception ex)
{
SampleHelpers.DisplayException(ex);
throw ex;
}
finally
{
Console.WriteLine("Press <Enter> to exit the program.");

Console.ReadLine();
}
}
}
}

  • Sameer J Shinde Profile Picture
    Sameer J Shinde 10 on at
    RE: How to programmatically add user and assign them customer engadement license in dynamics 365 online using C#

    Graph API worked for me. Thank You..

  • Verified answer
    Linn Zaw Win Profile Picture
    Linn Zaw Win 3,405 on at
    RE: How to programmatically add user and assign them customer engadement license in dynamics 365 online using C#

    I don't think you need to create the user in Dynamics 365. If you assign the product licence and if the user is in the AAD group which has access to the environment, the D365 system user will automatically be created by the platform.

    For assigning the user with a proper licence, you might want to check out the Graph REST API.

    https://docs.microsoft.com/en-us/graph/api/user-assignlicense

    Check out the posts below to see how you can interact with Graph API in C#

    https://www.c-sharpcorner.com/article/get-all-organization-users-from-o365-using-graph-api/

    https://vincentlauzon.com/2017/01/31/using-microsoft-graph-api-to-interact-with-azure-ad/

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans