Create User in MSCRM Console Application command parameters

Recently, I am working on Production support admin tasks, Most of my tickets are raised where create of New User in the CRM Systems, to make my work easier, I developed a Console Application

This can be used for On-premise of Dynamics CRM, All you have to do is to open the command Prompt and pass the command line arguments to establish a connection with CRM.

call the console application exe file in Command prompt and pass the parameters as shown below, and hit enter

DomainName\UserID(Admin), Password, https://orgname/XRMServices/2011/Organization.svc

the console establishes Connection and Prompt for the “Username(DomainName\UserID)”, “First name” and “Last name”.

The Application checks for the User exist in CRM or not and moves foreword forĀ  User Creation,

Below is the code for it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;

namespace UserCreation
{
public class CreateUser
{
static IOrganizationService _service;
public static string _domain { get; set; }
public static string _userId { get; set; }
public static string _userName { get; set; }
public static string _firstName { get; set; }
public static string _lastName { get; set; }

static void Main(string[] args)
{
Console.WriteLine(“Getting Connection Estabilished”);
ConnectToCRM(args[0].Trim(‘,’).Trim(), args[1].Trim(‘,’).Trim(), args[2].Trim(‘,’).Trim());
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
Console.WriteLine(“EnterUserName”);
_userId = Console.ReadLine();
string[] userpath = _userId.ToString().Split(‘\\’);
_userName = userpath[1];
_domain = userpath[0];
Console.WriteLine(“EnterFirstName”);
_firstName = Console.ReadLine();
Console.WriteLine(“EnterLastName”);
_lastName = Console.ReadLine();
if (userid != Guid.Empty)
{
Console.WriteLine(“Connection Established Successfully”);
Console.ReadKey();
UserCreation();
}
}

public static void ConnectToCRM(string userName, string password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = userName;
credentials.UserName.Password = password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;
}
catch (Exception ex)
{
Console.WriteLine(“Error while connecting to CRM ” + ex.Message);
Console.ReadKey();
}
}

public static Entity GetDefaultBU()
{
// Retrieve Default Business Unit
QueryExpression businessUnitQuery = new QueryExpression
{
EntityName = “businessunit”,
ColumnSet = new ColumnSet(“businessunitid”),
Criteria =
{
Conditions =
{
new ConditionExpression(“parentbusinessunitid”,
ConditionOperator.Null)
}
}
};
return _service.RetrieveMultiple(businessUnitQuery).Entities[0];
}
public static void UserCreation()
{
var defaultBusinessUnit = GetDefaultBU();
bool existingUser = GetUserExist();
if (existingUser)
{
Console.WriteLine(“Exception: User already exist!”);
throw new Exception(“User already exist!”);
}
Entity user = new Entity(“systemuser”);

user[“domainname”] = _domain + _userName;
user[“firstname”] = _firstName;
user[“lastname”] = _lastName;
user[“businessunitid”] = new EntityReference(“businessunit”, defaultBusinessUnit.Id);
Guid userId = _service.Create(user);
Console.WriteLine(“Created a system user {0} for ‘{1}, {2}'”, userId, _lastName, _firstName);
}
//Check for User Exist

public static bool GetUserExist()
{
QueryExpression systemUserQuery = new QueryExpression
{
EntityName = “systemuser”,
ColumnSet = new ColumnSet(“systemuserid”, “domainname”, “firstname”, “lastname”),
Criteria =
{
Conditions =
{
new ConditionExpression(“domainname”,
ConditionOperator.Equal, _userId)
}
}
};
var record = _service.RetrieveMultiple(systemUserQuery);
if (record.Entities.Count > 0)
return true;
return false;
}
}
}