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;
_userId = Console.ReadLine();
string[] userpath = _userId.ToString().Split(‘\\’);
_userName = userpath[1];
_domain = userpath[0];
_firstName = Console.ReadLine();
_lastName = Console.ReadLine();
if (userid != Guid.Empty)
Console.WriteLine(“Connection Established Successfully”);

public static void ConnectToCRM(string userName, string password, string SoapOrgServiceUri)
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);
_service = (IOrganizationService)proxy;
catch (Exception ex)
Console.WriteLine(“Error while connecting to CRM ” + ex.Message);

public static Entity GetDefaultBU()
// Retrieve Default Business Unit
QueryExpression businessUnitQuery = new QueryExpression
EntityName = “businessunit”,
ColumnSet = new ColumnSet(“businessunitid”),
Criteria =
Conditions =
new ConditionExpression(“parentbusinessunitid”,
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;

Retrieve Entity Metadata programatically in Microsoft Dynamics 365 CRM

What Metadata does MSCRM has

MSCRM holds metadata for “Entities”

It has Metadata for fields,Relationships(one to Many, Many to One), Privileges and its Properties  i am just naming the commonly used or heard properties.

  • DisplayName
  • SchemaName
  • AttributeType
  • IsAuditEnabled
  • IsRenameable
  • IsManaged
  • IsPrimaryId

How to See EntityMetadata

One can get the metadata Information from the MetadataBrowser solution which needs to be installed in MSCRM Solutions (or)

from XRMToolbox Plugin. (or)

you can do on your own by programtically, using MSCRM SDK..

  • EntityMetadata is metadata for the entity.
  • EntityMetadata has a attributes collection which contains a list of AttributeMetadata fields.

To retrieve the Entity Metadata we need to make RetrieveEntityRequest for which the entity response is captured in the RetrieveEntityResponse by using “Execute” method from Organization Service.

Add the Namespace Microsoft.Xrm.Sdk.Metadata

The required parameters are:

  • EntityFilters(enum)
    • A filter to control how much and what data about the entity is returned .
    • EntityFilters is of type enum and has following options to select (Entity,Default,Attributes,Privileges,Relationships,All)
  • RetrieveAsIfPublished
    • Set true to include unpublished changes to Entity,
    • Setting to false includes only published changes to the Entity.

Either LogicalName or MetadataId is required to inform the request which Entity it is you wish to be returned.

below is the code it looks like

private static EntityMetadata RetriveEntityMetaData(IOrganizationService service, string entityName)
RetrieveEntityRequest req = new RetrieveEntityRequest()
EntityFilters = EntityFilters.Attributes,
LogicalName = entityName,
RetrieveAsIfPublished = true

RetrieveEntityResponse res = (RetrieveEntityResponse)service.Execute(req);
return res.EntityMetadata;

AttributeMetadata class is the base class for attributeMetaData and then there are individual attributeMetaData types

  • AttributeMetadata class
    • LookupAttributeClass
    •  DecimalAttributeClass
    •  PicklistAttributeClass
    •  StatusAttributeClass
    • All the other attribute classes

You can see the different types of attribute metadata below from base class


The below code will be used to retrieve the Attribute Metadata of the entity

var entityMetadata = RetriveEntityMetaData(_service, “contact”);
List<AttributeMetadata> FieldMetadataList = new List<AttributeMetadata>();
FieldMetadataList = entityMetadata.Attributes.ToList();

foreach (var fields in FieldMetadataList)
Console.WriteLine(string.Format(“DisplayName: {0}”,      fields.DisplayName.UserLocalizedLabel.Label));


where the Displayname retrieval is quite tricky, as there will be null values in “UserLocalizedLabel“. so it will be advised to check for null values before (fields.DisplayName.UserLocalizedLabel.Label)

Below is the output:

contact metadata

Email Router Configurations in MS-CRM 2016 On-Premise


  1. Dynamics CRM On-Premise is installed in the server. An On-premise Organization should be created in the server.
  2. Email Router Configuration Manager exe (Download link:
  3. Information regarding Mailboxes to connect to a user
  4. Server name/URL FQDN for Exchange Web Services & Version (2007/2010/2013/), or a Pop3 server address.
  • An exchange address will be in this format (http(s):// )
  • For Exchange, you can often just append the /EWS/Exchange.asmx to the address they use for Outlook Web Access.
  • If you access OWA via a URL such as Just replace /OWA with /EWS/Exchange.asmx This will look like
  • A Pop3 server would have just a format.
  1. We need User Credentials for configuring Mail boxes (usually windows credentials). Credentials will be in the format of an email address (e.g. : or domain\username.

Microsoft Dynamics CRM URL is required. When we create an organization the CRM web application will be created. URL format looks like https://CRMCompany.CompanyDomain.COM:444  or https://ipaddress:444/

Email Router Configurations on MS-CRM:

  1. Go to Settings –> Email Configurations.
  2. Click on Email Server Profile.1
  3. Click on New Button and Select POP3-SMTP Profile as Email Server Profile.
  4. Enter the following details.3
  5. Click on save and close button.
  6. Go to settings –> Email Configurations –> Mail Boxes.4
  7. Select Active mail Boxes View.
  8. Select the mail box which you want to set and double click on it, Window Opens.10
  9. Enter details and Click on Save button the form.11
  10. Click on Approve EmailNote: Mail boxes will be created from the Teams and Queues we have created, When we create an User in CRM, Provide Email address of the User. Approve the Email. Create a team in MSCRM, add Users to that team (In my case I want to configure Customer service Email , So I have Created a Team in MSCRM with Customer Service name. a Queue is automatically created and assigned to Team. Mailbox is also created against the team in MSCRM).

Setting up the Email Router

  1. Open the Email router configuration manager in the server


Configurations profile tab

  1. On Configurations profile tab, you will have to create profile for both directions (incoming and outgoing)6
  2. Click on New button, Email Router Configuration window opens
  3. Enter the following details in the window (Incoming Email Configuration)
  • Profile Name: Incoming
  • Direction: Select Incoming option from dropdown.
  • Email Server Type: Exchange (2007/2010/2013) or POP3 Email Boxes. I am selecting Exchange 2010 0r 2013 option.
  • Protocol: Select Exchange web service.
  • Authentication Type: Select Windows Authentication from dropdown for more information on Authentication types of Email Router (
  • Location : Enter the URL of Exchange server
  • Access Credentials : Select User Specified option from drop down


  1. Outgoing E-mail configuration (doing it with SMTP configurations).

Note: Configure the system as per the requirements. Below is the screen shot for outgoing email


Note: If you elect to user Exchange for the Outgoing type, you must specify what type of access credentials you are using. Select Administrator if you have an admin account that has permission to all users’ mailboxes, or if you just want to specify the credentials for one user. This can be any user, it does not have to be a Dynamics CRM admin, a windows admin, or anything like that

Deployments Tab

  1. On the Deployments Tab, you can connect to one or more deployments of Dynamics CRM, (perhaps you have a production and a test deployment, and here you can create a connection to both of them).
  • Choose what deployment type you have
  • Dynamics CRM Online if you are using Office 365, my company would be on premise, or online service provider for a 3rd party hosted installation of Dynamics CRM.
  • Enter the URL to your Dynamics CRM Organization.
  • Enter in the credentials for a user that has access to login to Dynamics CRM. This is simply to read settings from Dynamics CRM, and write them back to the system. Usually a system admin, with a full Dynamics CRM license (not just administrative license).
  • Optionally, select a default Profile for the deployment. This will set all users to use this profile in that deployment. The Profile you select will be the mailbox/server that the user(s) will send and receive from.


Users, Queues and Forward Mailboxes Tab

  1. Select your deployment and click Load Data.

Note: (Troubleshooting tip) If you get an error at this point, it is a problem with the settings on the deployments tab. Go back, and verify the URL by pasting it into a web browser, and verify the username and password by logging into Dynamics CRM with it.



2. Once the data loads, you will see all of your users that are set (on the Dynamics CRM user account inside of Dynamics CRM), to use the Email Router as either their incoming or outgoing email method.


3. Select a user, and click test Access. (If no profile is assigned because you left that blank on the deployments tab, double click the user first and assign a profile).

Note: Access Denied? Ok, here’s the catch. The user account you setup on the Configuration Profile, that’s whose mailbox you are connecting to. If the user you are testing access for, doesn’t have access to the user’s mailbox that you used (access credential), on the configuration profile, you will get an access denied, (or unable to relay) message. The email address on the user you are assigning to the profile, must match the email address of the mailbox.


4. Once Succeed, Click on Publish button.



Sandbox (Isolation) Mode in MS CRM

1         What is a Sandbox?

Sandbox is Testing or Isolated Environment where untested code will be deployed to test. It is also used in the information security. As the sandbox is meaning of filtering, When we code an application in sandbox mode. The code will get executed in the browser by limiting the Operating System API Calls. This will be helpful in stopping the malicious code to execute in the local System of the Server. This enhances the system security levels

2         MS-CRM Sandbox Understanding

Sandbox mode is introduced from 2011 MSCRM. Microsoft Dynamics CRM Provides the execution of Plugins and workflows in Isolation mode (Sandbox Mode), Dynamics CRM Collects runtime statistics of plugins and Custom workflows. If the sandbox worker process exceeds the threshold level, It will be automatically get killed by the application platform. So the plugins which are running by this worker process failed by throwing an exception. Exceptions will be found in trace files for the plugins registered in Sandbox. The above statements conclude that the Sandbox mode is recommended in secured environments, i.e. Sandbox mode (Isolation/Partial Trust) can be executed both in Online and On-Premises. None mode (Full Trust) is executed only in On-Premises.

2.1       Where can we see this Sandbox Runtime Statistics?

Plugin and Custom Workflows runtime information is captured in MSCRM Database. Search for the PluginTypeStatisticBase, Write a Select Query

“Select * from PluginTypeStatisticBase”.

This will record the Plugin Performance and runtime execution Statistics like failure or crash percentages of the Plugin.


Figure 1: PluginTypeStatasticBase Query


2.2       Find Sandbox Processing Service

Sandbox Processing Service is found in your Services .mscservices

Figure 2: MS CRM Sandbox Processing Service


Figure 3: Host and Worker Process Services

3         How Does Sandbox Plugin/Workflow Execution

  • Once the Plugin execution Context is created, the entire Context will be serialized and send it to the sandbox host process to execute the Plugin in the current Context.
  • The sandbox host process de-serializes the information and then serialize to assigned sandbox worker processes to execute the plugin
  • The sandbox worker process then de-serializes the current execution context and runs the plugin code in partial trust.
  • The returned result again shared back to the Host process.
  • The captured result in host process then sent back to the original process which raised the request for sandbox mode (w3wp.exe or CrmAsyncService.exe)

Note: Consider the plugin fired at Pre-Operation


Figure 4: Plugin Execution by w3wp Process


Figure 5: CRM Async Process Executing Custom Workflow

Note: Consider CRM Async Processes is running a workflow



4         Limitation of Sandbox Plugin/Custom Workflow

  • Only the HTTP and HTTPS protocols are allowed.
  • Access to localhost (loopback) is not permitted.
  • IP addresses cannot be used. You must use a named web address.
  • Anonymous authentication is supported and recommended.
  • Access to your local file Systems
  • Cannot be able to access the external Dlls and Dlls registered in GAC
  • Web Services cannot be accessed in the sandbox plugins

These restrictions are can be modified in server environment by editing the registry settings of the MSCRM. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM\SandboxWorkerOutboundUriPattern

The key is defined in the Regular expression format and added as a registry strings, editing the regular expression string you can take out the first three limitations (Web access). It will be in this format


External Dlls cannot be added but we can achieve this limitation by using ILMERGE tool (DLL Merger) tool.

Note: The sandbox processing service role defaults to outbound calls being enabled. If you do not want to permit outbound calls from custom code, you can disable outbound calls by setting the following registry key to 1 (DWORD) on the server that hosts the sandbox processing service role. Next, restart the Microsoft Dynamics CRM Sandbox Processing Service.

5         General Errors that Occurs in Sandbox registered Plugin/Custom Workflow

  • Attempting to use the AppDomain.CurrentDomain.AssemblyResolve event
  • Security Exception (partially trust callers)
  • IO.Path.GetTempPath() [System.Security.Permissions.EnvironmentPermissionException]
  • Any filesystem access code [System.Security.Permissions.FileIOPermissionException]
  • Attempting to use the EventLog [System.Diagnostics.EventLogPermissionException]
  • Attempting to use Isolated Storage [System.Security.Permissions.IsolatedStoragePermissionException]
  • Any references to Thread.CurrentThread caused a security failure.



6         Advantages of Sandbox Plugin

  • .Net Code Access Security feature will be working and access to file Systems and event logs will be prevented. When you want to execute the code in secure way in your server.
  • The process which executes your plugin can be killed if your plugin exceeds certain thresholds or becomes unresponsive.
  • Each organization of CRM has sandbox processes. So it is independent from organization to organization.
  • When we debug the plugin using remote debugger which is in full trust (NONE mode) will use the full resources of the Server and other users cannot perform their action on it. Sandbox uses only the Sandbox process service.
  • Azure cloud services can be implemented in the Sandbox Plugins
  • Plugin runtime execution Statistics can be recorded in MSCRM Database. Performance measuring steps can be taken in consideration from the captured outputs in DB.