web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Add users to CRM online programmatically

(0) ShareShare
ReportReport
Posted on by 145

When you add a user manually in office 365, you get an email with your password etc. I want to do this process via code. Currently when  I add user to crmusing systemuser:

SystemUser user = new SystemUser{

                        DomainName = "tst1" + domain,

                        FirstName = "tst",

                        LastName = "1",                       

                        InternalEMailAddress = "test@gmail.com",

                        Address1_Telephone1 = "1111111",                       

                        IsSyncWithDirectory = true,

                        IsLicensed = true,

                        AccessMode = new OptionSetValue(0),

                        BusinessUnitId = new EntityReference

                        {

                            LogicalName = BusinessUnit.EntityLogicalName,

                            Name = BusinessUnit.EntityLogicalName,

                            Id = defaultBU.Id

                        }

                    };

 It doesn't sync with office 365 and gives an error - This is not a valid Microsoft Online Services ID for this organization

How do I create the user such that its in Office 365 and password email is generated?

Very new to CRM - please help.

 

 

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Muhammad Adeel Javaid Profile Picture
    5,580 on at

    You can add users to CRM through the following procedure:

    In the Navigation Pane, click Settings, click Administration, and then click Users.

    On the Users tab, in the Records group, click New. Or, open an existing record that you want to change.

    On the Select Business Unit page, in the Business Unit list, select a business unit. By default, Microsoft Dynamics CRM Online selects the root business unit for this field. Click Next.

    On the Select Security Roles page, select check boxes for the security roles you want to assign to the user. Hover over each to get a description of the security role. Click Next.

    On the Add Users page, enter the following:

    First Name

    Enter a first name between 1 and 50 characters. This is a required field for a user record.

    Last Name

    Enter a name between 1 and 50 characters.

    E-mail Address

    Click Add to add the user. Click Edit or Remove if that's the action you want to take. Click Next.

    On the Send E-mail Invitations page, select either Add new users and send invitations now or Add new users and do not send invitations. Click Create New Users.

  • Suggested answer
    Muhammad Adeel Javaid Profile Picture
    5,580 on at

    If you want to create an account request then the code will go like this:

    function runme() {

       SDK.SAMPLES.CreateAccountRequest();

    }

    if (typeof (SDK) == "undefined")

      { SDK = { __namespace: true }; }

          //This will establish a more unique namespace for functions in this library. This will reduce the

          // potential for functions to be overwritten due to a duplicate name when the library is loaded.

          SDK.SAMPLES = {

              _getServerUrl: function () {

                  ///<summary>

                  /// Returns the URL for the SOAP endpoint using the context information available in the form

                  /// or HTML Web resource.

                  ///</summary>

                  var OrgServicePath = "/XRMServices/2011/Organization.svc/web";

                  var serverUrl = "";

                  if (typeof GetGlobalContext == "function") {

                      var context = GetGlobalContext();

                      serverUrl = context.getServerUrl();

                  }

                  else {

                      if (typeof Xrm.Page.context == "object") {

                            serverUrl = Xrm.Page.context.getServerUrl();

                      }

                      else

                      { throw new Error("Unable to access the server URL"); }

                      }

                     if (serverUrl.match(/\/$/)) {

                          serverUrl = serverUrl.substring(0, serverUrl.length - 1);

                      }

                      return serverUrl + OrgServicePath;

                  },

              CreateAccountRequest: function () {

                  var requestMain = ""

                  requestMain += "<s:Envelope xmlns:s=\"schemas.xmlsoap.org/.../envelope\">";

                  requestMain += "  <s:Body>";

                  requestMain += "    <Execute xmlns=\"schemas.microsoft.com/.../Services\" xmlns:i=\"www.w3.org/.../XMLSchema-instance\">";

                  requestMain += "      <request i:type=\"a:CreateRequest\" xmlns:a=\"schemas.microsoft.com/.../Contracts\">";

                  requestMain += "        <a:Parameters xmlns:b=\"schemas.datacontract.org/.../System.Collections.Generic\">";

                  requestMain += "          <a:KeyValuePairOfstringanyType>";

                  requestMain += "            <b:key>Target</b:key>";

                  requestMain += "            <b:value i:type=\"a:Entity\">";

                  requestMain += "              <a:Attributes>";

                  requestMain += "                <a:KeyValuePairOfstringanyType>";

                  requestMain += "                  <b:key>name</b:key>";

                  requestMain += "                  <b:value i:type=\"c:string\" xmlns:c=\"www.w3.org/.../XMLSchema\">New Account Code</b:value>";

                  requestMain += "                </a:KeyValuePairOfstringanyType>";

                  requestMain += "                <a:KeyValuePairOfstringanyType>";

                  requestMain += "                  <b:key>address1_city</b:key>";

                  requestMain += "                  <b:value i:type=\"c:string\" xmlns:c=\"www.w3.org/.../XMLSchema\">Minneapolis</b:value>";

                  requestMain += "                </a:KeyValuePairOfstringanyType>";

                  requestMain += "              </a:Attributes>";

                  requestMain += "              <a:EntityState i:nil=\"true\" />";

                  requestMain += "              <a:FormattedValues />";

                  requestMain += "              <a:Id>00000000-0000-0000-0000-000000000000</a:Id>";

                  requestMain += "              <a:LogicalName>account</a:LogicalName>";

                  requestMain += "              <a:RelatedEntities />";

                  requestMain += "            </b:value>";

                  requestMain += "          </a:KeyValuePairOfstringanyType>";

                  requestMain += "        </a:Parameters>";

                  requestMain += "        <a:RequestId i:nil=\"true\" />";

                  requestMain += "        <a:RequestName>Create</a:RequestName>";

                  requestMain += "      </request>";

                  requestMain += "    </Execute>";

                  requestMain += "  </s:Body>";

                  requestMain += "</s:Envelope>";

                  var req = new XMLHttpRequest();

                  req.open("POST", SDK.SAMPLES._getServerUrl(), true)

                  // Responses will return XML. It isn't possible to return JSON.

                  req.setRequestHeader("Accept", "application/xml, text/xml, */*");

                  req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

                  req.setRequestHeader("SOAPAction", "schemas.microsoft.com/.../Execute");

                  var successCallback = null;

                  var errorCallback = null;

                  req.onreadystatechange = function () { SDK.SAMPLES.CreateAccountResponse(req, successCallback, errorCallback); };

                  req.send(requestMain);

              },

          CreateAccountResponse: function (req, successCallback, errorCallback) {

                  ///<summary>

                  /// Recieves the assign response

                  ///</summary>

                  ///<param name="req" Type="XMLHttpRequest">

                  /// The XMLHttpRequest response

                  ///</param>

                  ///<param name="successCallback" Type="Function">

                  /// The function to perform when an successfult response is returned.

                  /// For this message no data is returned so a success callback is not really necessary.

                  ///</param>

                  ///<param name="errorCallback" Type="Function">

                  /// The function to perform when an error is returned.

                  /// This function accepts a JScript error returned by the _getError function

                  ///</param>

                  if (req.readyState == 4) {

                  if (req.status == 200) {

                  if (successCallback != null)

                  { successCallback(); }

                  }

                  else {

                      errorCallback(SDK.SAMPLES._getError(req.responseXML));

                  }

              }

          },

          _getError: function (faultXml) {

              ///<summary>

              /// Parses the WCF fault returned in the event of an error.

              ///</summary>

              ///<param name="faultXml" Type="XML">

              /// The responseXML property of the XMLHttpRequest response.

              ///</param>

              var errorMessage = "Unknown Error (Unable to parse the fault)";

              if (typeof faultXml == "object") {

                  try {

                      var bodyNode = faultXml.firstChild.firstChild;

                      //Retrieve the fault node

                      for (var i = 0; i < bodyNode.childNodes.length; i++) {

                          var node = bodyNode.childNodes[i];

                          //NOTE: This comparison does not handle the case where the XML namespace changes

                          if ("s:Fault" == node.nodeName) {

                          for (var j = 0; j < node.childNodes.length; j++) {

                              var faultStringNode = node.childNodes[j];

                              if ("faultstring" == faultStringNode.nodeName) {

                                  errorMessage = faultStringNode.text;

                                  break;

                              }

                          }

                          break;

                      }

                  }

              }

              catch (e) { };

           }

           return new Error(errorMessage);

        },

    __namespace: true

    };

  • Suggested answer
    Muhammad Adeel Javaid Profile Picture
    5,580 on at

    Here is a link that might also be of great help for you:

    social.microsoft.com/.../f4c85318-e02a-41cd-b7a6-7c53e24e9ece

  • shwetha.vincy Profile Picture
    145 on at

    Thanks Adeel, but I want to be able to do this using code with CRM 2011 online and Office 365

  • shwetha.vincy Profile Picture
    145 on at

    I am able to create an user in CRM 2011. But the user is disabled and doesnot sync with office 365. I am creating an user - username@domain.crm.dynamics.com. The user is not AD.

  • Suggested answer
    Muhammad Adeel Javaid Profile Picture
    5,580 on at

    You can use the Create method or CreateRequest message to create all types of users. You can also create some types of users through the web application or through a data import operation.

    Create Method:

    Refer to this link:

    msdn.microsoft.com/.../microsoft.xrm.sdk.iorganizationservice.create.aspx

    CreateRequest Method:

    Refer to this link:

    msdn.microsoft.com/.../microsoft.xrm.sdk.messages.createrequest.aspx

    To create a synchronized user, set the attribute value for SystemUser.IsSyncWithDirectory to true. To create a stub user, set the value to false. After this user is created, this attribute value cannot be updated.

    When you create a synchronized user, the email address specified in the systemuser entity instance is verified in the Office 365 directory. If a user with that email address does not exist in the directory, an error is thrown.

    When you create a sync user, if a Microsoft Dynamics CRM user exists with the same WindowsLiveID, the existing user’s WindowsliveID attribute is updated as follows: _crm<#>_<WindowsLiveID>@<Domain>, where # is replaced with a number to make the value unique. To find users with conflicting IDs in the web application, you can add WindowsLiveID to the view and sort by this attribute to group all the conflicts together.

    If you attempt to create a stub user with the same WindowsLiveID as an existing synchronized user, an error is thrown.

    For more information you can refer to this link as well:

    msdn.microsoft.com/.../hh670617.aspx

  • shwetha.vincy Profile Picture
    145 on at

    Thanks guys. Guido I'll try to add the user to office 365 using code, assign a license and then add to CRM.

  • Mohammad Atif Profile Picture
    on at

    Thank you all. Please update this thread if there are more questions , if no please mark this as answered.

  • Verified answer
    shwetha.vincy Profile Picture
    145 on at

    Add the users to Office 365 and CRM online using Powershell - technet.microsoft.com/.../jj151815.aspx

    // Create Initial Session State for runspace. - import-module MSOnline

    initialSession = InitialSessionState.CreateDefault();

    initialSession.ImportPSModule(new[] { "MSOnline" });

    //credential - $O365Cred = Get-Credential

    credential = new PSCredential(_username, securePass);

    // Create command to connect office 365. - connect-msolservice -credential $O365Cred

    Command connectCommand = new Command("Connect-MsolService");

    connectCommand.Parameters.Add((new CommandParameter("Credential", credential)));

    //get lincense information and no of active and consumed ones - Get-MsolAccountSku

    Command getLicenseCommand = new Command("Get-MsolAccountSku");

    using (Runspace psRunSpace = RunspaceFactory.CreateRunspace(initialSession))

    {

    // Open runspace.

    psRunSpace.Open();

    //Iterate through each command and executes it.

    foreach (var com in new Command[] { connectCommand, getLicenseCommand })

    {

       var pipe = psRunSpace.CreatePipeline();

       pipe.Commands.Add(com);

       // Execute command and generate results and errors (if any).

       results = pipe.Invoke();

       var error = pipe.Error.ReadToEnd();

       if (error.Count > 0 && com == connectCommand)

       {

           Console.WriteLine(error[0].ToString() + "Problem in login");

           break;

       }

       if (error.Count > 0 && com == getLicenseCommand)

       {

           Console.WriteLine(error[0].ToString() + "Problem in getting licenses");

           break;

       }

       else

       {

           if (results != null && com == getLicenseCommand)

           {

               license=results[0].Properties["AccountSkuId"].Value.ToString();

               Int32.TryParse(results[0].Properties["ActiveUnits"].Value.ToString(), out totalLicenses);

               Int32.TryParse(results[0].Properties["ConsumedUnits"].Value.ToString(), out usedLicenses);

           }

       }

    }

    if (totalLicenses - usedLicenses > 0)

    {

       //create user with license - New-MsolUser -UserPrincipalName xxx@xxx.onmicrosoft.com -AlternateEmailAddresses "xxx"

       //-DisplayName "Code User" -FirstName "Code" -LastName "User" -ForceChangePassword 1 -UsageLocation "US"

       //-LicenseAssignment "xxx"

       Command createUserCommand = new Command("New-MsolUser");

       createUserCommand.Parameters.Add((new CommandParameter("UserPrincipalName", _newUserName)));

       createUserCommand.Parameters.Add((new CommandParameter("AlternateEmailAddresses", _emailAddress)));

       createUserCommand.Parameters.Add((new CommandParameter("DisplayName", _firstName + " " + _lastName)));

       createUserCommand.Parameters.Add((new CommandParameter("FirstName", _firstName)));

       createUserCommand.Parameters.Add((new CommandParameter("LastName", _lastName)));

       createUserCommand.Parameters.Add((new CommandParameter("ForceChangePassword", 1)));

       createUserCommand.Parameters.Add((new CommandParameter("UsageLocation", "US")));

       createUserCommand.Parameters.Add((new CommandParameter("LicenseAssignment", license)));

       var pipe = psRunSpace.CreatePipeline();

       pipe.Commands.Add(createUserCommand);

       // Execute command and generate results and errors (if any).

       results = pipe.Invoke();

       var error = pipe.Error.ReadToEnd();

       if (error.Count > 0)

           Console.WriteLine(error[0].ToString() + "Problem in adding user");

       else

           generatedPassword=results[0].Properties["Password"].Value.ToString();

       //send email to user with password and also add user to business unit in crm

    }

    // Close the runspace.

    psRunSpace.Close();

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans