CRM 2015 – how to find Statecode value

Someone asked me how to find the StateCode value on a custom entity today, so the first thing I did was to search the Hosk CRM Blog.

A lot of people get confused between Status Reason and State code, if you do then read this blog post

CRM 2013 – Understanding Status and Status Reason – think before deleting them

quick guide

  • StateCode = Status
    • controls if the record is active/inactive
  • StatusCode = Status Reason
    • Status reason is linked to the state and gives the ability to different status reasons to a status.

CRM Developers point of view

Status and Status reason are both optionsets.  Option set have an int value and a text value.  The text value is meta data and the int value is held in the database on the database field.

Default entities have two status values

State

  • Active = 0
  • Inactive = 1

Status reason have different default values

Status Reason

  • Active = 1
  • Inactive = 2

Out of the box entities State and Status Reason

Out of the box entities can (and often do) have more than two Status Reasons where as custom entities can only have two States.  Microsoft often bend the rules for the default entities because they have created functionality which needs the default entities to behave in a certain way.
It’s useful to know how custom entities work so you can then appreciate how the default entities work and have been changed.  This knowledge will help you work on the default entities because you can take advantage of the added functionality and extra status values.
Below are two examples of the extra status’s for default entities
E.g. Case/Incident
  • Active
  • Cancelled
  • Closed

Lead

  • 0 : Open
  • 1 : Qualified
  • 2 : Disqualified
You can see the full list of default entities and their Status and status reasons
Looking at the list gives you an insight to the number of default entities which make up the out of the box CRM functionality.  It will give you an idea of how each entity works and the flow of it.

State and Status reason have different default values

The key piece of information is State and Status Reason have different values and this can be confusing, usually it goes down the lines of

I know State or Status Reason Active = 0 but which one is it.

A quick way to confirm what the Status or Status reason is, is to do an advanced find and use Status or Status Reason in a conditional.  If you then click the download Fetch XML button you can see the values being used

Status active 1
Status active 2
So you know Active Status (statecode) have the value of 0

No Magic Numbers

Magic numbers in development is when developers use number values for status or any option sets but give no indication what the values mean.  This makes reading/understanding the code difficult and extremely frustrating because you often have to go and look up the values.

Wiki gives a good description of Magic numbers in code

here is a good explanation on stackoverflow – What is a magic number, and why is it bad?

Below you can see an example of magic number being used in code, what status is number 6!  If you are lucky the developer will add a comment

if (incident.StatusCode.Equals(6))
{
//do something incident cancelled
}
The use of Option set enums makes this much easier to understand.  I believe code should be self documenting through the use of well named variables, methods and classes.
if (incident.StatusCode.Equals(incident_statuscode.Canceled))
{

//do something incident cancelled

}

Don’t be lazy, create the Option Set enums and make your CRM code more readable.  I have written a blog on why you should create Enumerations for optionsets.

CRM 2013 – Create Enumerations for option sets

There is a great tool to help you called

CRM Early Bound Generator

I reviewed the tool in the link below

CRM 2013 Tool – CRM Early Bound Generator

Advertisement

CRM 2013 – Create Enumerations for option sets

What are enumerations for option sets I hear some of you thinking?

start with early bound classes.

I mentioned the benefits of early bound classes in my blog post CRM 2015 – Typescript is ready to go, definition files available on NuGet

Early bound code is creates a wrapper class round your entities.  It includes all the fields in your entity.  The benefits of early bound classes

  • No typos
  • no type errors
  • easy to read and understand code

Early bound code means a lot of the potential errors in the CRM code are found at compile time instead of run time.  The big advantage of this is most of the errors are found and fixed by the developer rather than being found by the end customer.

Microsoft have a good post – Use the early bound entity classes in code

The advantages to using early-bound entity classes is that all type references are checked at compile time. The compiled executable contains the code necessary to invoke the types’ properties, methods, and events. For more information, see Use the early-bound entity classes for create, update, and delete.

Early bound classes create an entities file which includes all the names and types of the fields

The benefit of early bound code is you remove syntax errors and bring all type errors into  compile time and not runtime, so your customers don’t see them.

You can type things like this


Contact contact = new Contact();
contact.FullName = "Marvellous Hosk"

Rather than


Entity contactEntity = New Entity()

contactEntity["Fullname"] = "Marvellous Hosk"

You will notice full name is typed incorrectly, this error would only appear when the plugin is run because the compiler cannot check the late bound code for syntax errors.

What are Enumerations for option sets?

Enumerations for option sets are what early bound code is to entities.

Creating enums for option sets helps get rid of magic numbers which is a code smell .  A magic number is where code uses a number value with no explanation what the number is.  The end result is confusing code which is hard to understand.

More reasons why magic numbers are bad

  • It’s hard to maintain
  • Difficult to understand
  • change nightmare if numbers are used in many places

CRM options set and statuses are  a classic breeding ground for magic numbers to magically spring up in code.

A kind-hearted developer who hasn’t learnt thought about using enums for optionsets might create a field called StatusReasonClosed = 9100000 or they might put a comment.

This is not a bad way but it involves manually creating the variables and brings in the possibility of different naming conventions, it’s better to automate the process and use enums.  Below you can see an example of a magic number and a enum.

if (incident.StatusCode.Equals(6))
{
//do something incident cancelled
}

or

if (incident.StatusCode.Equals(incident_statuscode.Canceled))
{

//do something incident cancelled

}

Creating the option set enums file

You have a few options for creating option set enums.  The easiest tool to use is

CRM Early Bound Generator

I reviewed the tool in the link below

CRM 2013 Tool – CRM Early Bound Generator

The screen shot below shows you why it’s great, it has a lovely GUI interface.

The option set values will create a file enums like this


[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "6.1.0001.0123")]
public enum incident_statuscode
{

[System.Runtime.Serialization.EnumMemberAttribute()]
InProgress = 1,

[System.Runtime.Serialization.EnumMemberAttribute()]
OnHold = 2,

[System.Runtime.Serialization.EnumMemberAttribute()]
WaitingforDetails = 3,

[System.Runtime.Serialization.EnumMemberAttribute()]
Researching = 4,

[System.Runtime.Serialization.EnumMemberAttribute()]
ProblemSolved = 5,

[System.Runtime.Serialization.EnumMemberAttribute()]
InformationProvided = 1000,

[System.Runtime.Serialization.EnumMemberAttribute()]
IncidentComplete = 100000000,

[System.Runtime.Serialization.EnumMemberAttribute()]
IncidentWithdrawn = 100000001,

[System.Runtime.Serialization.EnumMemberAttribute()]
Canceled = 6,

}

To use the optionset.cs file you need to copy it into your visual studio project with your CRM plugins.  You can then use the enums instead of statecode and statuscode which will make your code easier to understand.

Potential problems with Existing Option set enums

I added some status reasons, the next step was to regenerate the OptionSet.cs file with the enums in.

I did this using the CRM  early bound generator tool, I copied the file to the project in visual studio, rebuilt the project and then I got loads of errors.

The CRM early bound generator create enum with this title

new_contributionrequest_new_ContributionStatus

but the enums used in the code was like this

new_contributionrequestnew_ContributionStatus

The question was how did they previously create the optionset enums? To the internet

Searching the internet I came to the this page

Create extensions for the code generation tool

It seems Microsoft had create a class library you could call via the command line to create option set enums.

The code is bundled with the CRM SDK

SDK\SampleCode\CS\CrmSvcUtilExtensions\GeneratePicklistEnums

You have to open the project in visual studio, build it

This will then put the files into the debug\bin

SDK\SampleCode\CS\CrmSvcUtilExtensions\GeneratePicklistEnums\bin\Debug

You then need to modify the bat file called GenerateOptionSets.bat and change the url setting to point to your CRM instance (don’t forget to add the orgname of the CRM organisation you want to create the optionset enums for)

CrmSvcUtil.exe ^
/codewriterfilter:”Microsoft.Crm.Sdk.Samples.FilteringService, GeneratePicklistEnums” ^
/codecustomization:”Microsoft.Crm.Sdk.Samples.CodeCustomizationService, GeneratePicklistEnums” ^
/namingservice:”Microsoft.Crm.Sdk.Samples.NamingService, GeneratePicklistEnums” ^
/url:http://CRMSERVER/ORGNAME/XRMServices/2011/Organization.svc ^
/out:OptionSets.cs

This created the OptionSet file in the same format as the previous.

If I was starting a new project I would use the CRM early bound generator