C# Find out status of a Dynamics 365/2016 CRM SystemUser Entity object and set to disabled


I have already talked about how to extract user information from Dynamic CRM and build a MIM 2010 Dynamics ECMA. I am going to talk about how to

  • Find out if a user is disabled or active. Each time the MIM ECMA runs I want MIM  to get the status of the Dynamics account, if someone has enabled the account of a user Terminated in HR, MIM will disable it in Dynamics.
  • Set a user to disabled

This is useful if you are building a MIM 2010 Dynamics ECMA which is connected to HR feed. If the user is Terminated, in HR then you want to be able to disable the systemuser object, free up your license and well as other security considerations.

Find out if a user is disabled.

The system user has a Boolean attribute called “IsDisabled”. This will tell you if a user is disabled or not. Note this: In CRM query, the attributes names must be all lowercase, else you get “attribute not found”. So use “isdisabled” not “IsDisabled”

C# Code

// Retrieve specified system user needed to disable/enable and add the user role.

QueryExpression query = new QueryExpression


EntityName = SystemUser.EntityLogicalName,

ColumnSet = new ColumnSet(“isdisabled”)


// Get the users

EntityCollection myusers = _service.RetrieveMultiple(query);

foreach (Entity act in myusers.Entities)




Set a user to disabled

The simple thing you would think is set IsDisabled to True or false, right? Well it will not work in Dynamics. You have to use a more wholistic approach, I think because of the inter-connectivity of an entity, its more than just setting an attribute to true or false. You have to use a method known as SetStateRequest. See the code sample below

C# Code

// Retrieve a user.

SystemUser user = _service.Retrieve(SystemUser.EntityLogicalName, _userId, new ColumnSet(new String[] { “systemuserid”, “firstname”, “lastname” })).ToEntity<SystemUser>();

if (user != null)


SetStateRequest request = new SetStateRequest()


EntityMoniker = user.ToEntityReference(),

// Sets the user to disabled.

State = new OptionSetValue(1),

// Required by request but always valued at -1 in this context.

Status = new OptionSetValue(-1)



Console.WriteLine(“User account is disabled.”);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s